text:
package org.pentaho.di.core.logging;

import org.pentaho.di.core.Const;

import java.util.Collections;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.LinkedList;

/**
 * This class keeps the last N lines in a buffer
 *
 * @author matt
 *
 */
public class LoggingBuffer {
  private String name;

  private List<BufferLine> buffer;

  private int bufferSize;

  private KettleLogLayout layout;

  private List<KettleLoggingEventListener> eventListeners;

  public LoggingBuffer( int bufferSize ) {
    this.bufferSize = bufferSize;
    buffer = Collections.synchronizedList( new LinkedList<BufferLine>() );
    layout = new KettleLogLayout( true );
    eventListeners = Collections.synchronizedList( new ArrayList<KettleLoggingEventListener>() );
  }

  /**
   * @return the number (sequence, 1..N) of the last log line. If no records are present in the buffer, 0 is returned.
   */
  public int getLastBufferLineNr() {
    synchronized ( buffer ) {
      if ( buffer.size() > 0 ) {
        return buffer.get( buffer.size() - 1 ).getNr();
      } else {
        return 0;
      }
    }
  }

  /**
   *
   * @param channelId
   *          channel IDs to grab
   * @param includeGeneral
   *          include general log lines
   * @param from
   * @param to
   * @return
   */
  public List<KettleLoggingEvent> getLogBufferFromTo( List<String> channelId, boolean includeGeneral, int from,
    int to ) {
    List<KettleLoggingEvent> lines = new ArrayList<KettleLoggingEvent>();

    synchronized ( buffer ) {
      for ( BufferLine line : buffer ) {
        if ( line.getNr() > from && line.getNr() <= to ) {
          Object payload = line.getEvent().getMessage();
          if ( payload instanceof LogMessage ) {
            LogMessage message = (LogMessage) payload;

            // Typically, the log channel id is the one from the transformation or job running currently.
            // However, we also want to see the details of the steps etc.
            // So we need to look at the parents all the way up if needed...
            //
            boolean include = channelId == null;

            // See if we should include generic messages
            //
            if ( !include ) {
              LoggingObjectInterface loggingObject =
                LoggingRegistry.getInstance().getLoggingObject( message.getLogChannelId() );

              if ( loggingObject != null
                && includeGeneral && LoggingObjectType.GENERAL.equals( loggingObject.getObjectType() ) ) {
                include = true;
              }

              // See if we should include a certain channel id (zero, one or more)
              //
              if ( !include ) {
                for ( String id : channelId ) {
                  if ( message.getLogChannelId().equals( id ) ) {
                    include = true;
                    break;
                  }
                }
              }
            }

            if ( include ) {

              try {
                // String string = layout.format(line.getEvent());
                lines.add( line.getEvent() );
              } catch ( Exception e ) {
                e.printStackTrace();
              }
            }
          }
        }
      }
    }

    return lines;
  }

  /**
   *
   * @param parentLogChannelId
   *          the parent log channel ID to grab
   * @param includeGeneral
   *          include general log lines
   * @param from
   * @param to
   * @return
   */
  public List<KettleLoggingEvent> getLogBufferFromTo( String parentLogChannelId, boolean includeGeneral, int from,
    int to ) {

    // Typically, the log channel id is the one from the transformation or job running currently.
    // However, we also want to see the details of the steps etc.
    // So we need to look at the parents all the way up if needed...
    //
    List<String> childIds = LoggingRegistry.getInstance().getLogChannelChildren( parentLogChannelId );

    return getLogBufferFromTo( childIds, includeGeneral, from, to );
  }

  public StringBuffer getBuffer( String parentLogChannelId, boolean includeGeneral, int startLineNr, int endLineNr ) {
    StringBuffer stringBuffer = new StringBuffer( 10000 );

    List<KettleLoggingEvent> events =
      getLogBufferFromTo( parentLogChannelId, includeGeneral, startLineNr, endLineNr );
    for ( KettleLoggingEvent event : events ) {
      stringBuffer.append( layout.format( event ) ).append( Const.CR );
    }

    return stringBuffer;
  }

  public StringBuffer getBuffer( String parentLogChannelId, boolean includeGeneral ) {
    return getBuffer( parentLogChannelId, includeGeneral, 0 );
  }

  public StringBuffer getBuffer( String parentLogChannelId, boolean includeGeneral, int startLineNr ) {
    return getBuffer( parentLogChannelId, includeGeneral, startLineNr, getLastBufferLineNr() );
  }

  public StringBuffer getBuffer() {
    return getBuffer( null, true );
  }

  public void close() {
  }

  public void doAppend( KettleLoggingEvent event ) {
    synchronized ( buffer ) {
      buffer.add( new BufferLine( event ) );
      while ( bufferSize > 0 && buffer.size() > bufferSize ) {
        buffer.remove( 0 );
      }
    }
  }

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

  public String getName() {
    return name;
  }

  public void setLayout( KettleLogLayout layout ) {
    this.layout = layout;
  }

  public KettleLogLayout getLayout() {
    return layout;
  }

  public boolean requiresLayout() {
    return true;
  }

  public void clear() {
    buffer.clear();
  }

  /**
   * @return the maximum number of lines that this buffer contains, 0 or lower means: no limit
   */
  public int getMaxNrLines() {
    return bufferSize;
  }

  /**
   * @param maxNrLines
   *          the maximum number of lines that this buffer should contain, 0 or lower means: no limit
   */
  public void setMaxNrLines( int maxNrLines ) {
    this.bufferSize = maxNrLines;
  }

  /**
   * @return the nrLines
   */
  public int getNrLines() {
    return buffer.size();
  }

  /**
   * Removes all rows for the channel with the specified id
   *
   * @param id
   *          the id of the logging channel to remove
   */
  public void removeChannelFromBuffer( String id ) {
    synchronized ( buffer ) {
      Iterator<BufferLine> iterator = buffer.iterator();
      while ( iterator.hasNext() ) {
        BufferLine bufferLine = iterator.next();
        Object payload = bufferLine.getEvent().getMessage();
        if ( payload instanceof LogMessage ) {
          LogMessage message = (LogMessage) payload;
          if ( id.equals( message.getLogChannelId() ) ) {
            iterator.remove();
          }
        }
      }
    }
  }

  public int size() {
    return buffer.size();
  }

  public void removeGeneralMessages() {
    synchronized ( buffer ) {
      Iterator<BufferLine> iterator = buffer.iterator();
      while ( iterator.hasNext() ) {
        BufferLine bufferLine = iterator.next();
        Object payload = bufferLine.getEvent().getMessage();
        if ( payload instanceof LogMessage ) {
          LogMessage message = (LogMessage) payload;
          LoggingObjectInterface loggingObject =
            LoggingRegistry.getInstance().getLoggingObject( message.getLogChannelId() );
          if ( loggingObject != null && LoggingObjectType.GENERAL.equals( loggingObject.getObjectType() ) ) {
            iterator.remove();
          }
        }
      }
    }
  }

  public Iterator<BufferLine> getBufferIterator() {
    return buffer.iterator();
  }

  /**
   * It looks like this method is not used in the project.
   */
  @Deprecated
  public String dump() {
    StringBuilder buf = new StringBuilder( 50000 );
    synchronized ( buffer ) {
      for ( BufferLine line : buffer ) {
        Object payload = line.getEvent().getMessage();
        if ( payload instanceof LogMessage ) {
          LogMessage message = (LogMessage) payload;
          // LoggingObjectInterface loggingObject =
          // LoggingRegistry.getInstance().getLoggingObject(message.getLogChannelId());
          buf
            .append( message.getLogChannelId()
              + "\t" + message.getSubject() + "\t" + message.getMessage() + "\n" );
        }

      }
    }
    return buf.toString();
  }

  public void removeBufferLines( List<BufferLine> linesToRemove ) {
    buffer.removeAll( linesToRemove );
  }

  public List<BufferLine> getBufferLinesBefore( long minTimeBoundary ) {
    List<BufferLine> linesToRemove = new ArrayList<BufferLine>();
    synchronized ( buffer ) {
      for ( Iterator<BufferLine> i = buffer.iterator(); i.hasNext(); ) {
        BufferLine bufferLine = i.next();
        if ( bufferLine.getEvent().timeStamp < minTimeBoundary ) {
          linesToRemove.add( bufferLine );
        } else {
          break;
        }
      }
    }
    return linesToRemove;
  }

  public void addLogggingEvent( KettleLoggingEvent loggingEvent ) {
    doAppend( loggingEvent );
    synchronized ( eventListeners ) {
      for ( KettleLoggingEventListener listener : eventListeners ) {
        listener.eventAdded( loggingEvent );
      }
    }
  }

  public void addLoggingEventListener( KettleLoggingEventListener listener ) {
    eventListeners.add( listener );
  }

  public void removeLoggingEventListener( KettleLoggingEventListener listener ) {
    eventListeners.remove( listener );
  }
}


text:
import express = require('express');
import fs = require('fs');
import jsonmocker = require("./JSONMocker");jsonmocker;
import JSONMocker = jsonmocker.JSONMocker;
import Pool = jsonmocker.Pool;
import logger = require("./ExpressLogger");logger;
import Logger = logger.ExpressLogger;

export
interface IExpressMockerConfig
{
	port: number;
	quiet: boolean;
	statics?:IExpressMockerStatic[];
	adminAuth?:IExpressMockerBasicAuth;
	defaultRoutes:IExpressMockerRoute[];
}

export
interface IExpressMockerStatic
{
	route:string;
	directory:string;
}

export
interface IExpressMockerBasicAuth
{
	login:string;
	password:string;
}

export
interface IExpressMockerRoute
{
	active:boolean;
	id: string;
	verb:string;
	route:string;
	response:IExpressMockerResponse;
	hidden?:boolean;
	basicAuth?:IExpressMockerBasicAuth;
	routeParams?: IExpressMockerRouteParams;
}

export
interface IExpressMockerResponse
{
	source:string;
	headers?:IExpressMockerResponseHeaders
}
export
interface IExpressMockerRouteParams {
	name: string;
	value: string;
	description: string;
}
export
interface IExpressMockerResponseHeaders
{
	[index: string]: any;
}

export
interface IJSONGenResult
{
	result:string;
	directResponse:boolean;
	mime?:string;
}

export
enum ExpressMockerResponseType
{
	DATA_URL,
	FILE,
	JSON_GEN
}

function mix(...rest):Object
{
	var i:number
		,total:number
		,j:string
		,newObj:Object = {};

	for(i = 0, total = arguments.length; i < total; i++)
	{
		for(j in arguments[i])
		{
			if(arguments[i].hasOwnProperty(j)) { newObj[j] = arguments[i][j]; }
		}
	}
	return newObj;
}

import http = require("http");

//TODO Find updated express.d.ts

interface ICloseable
{
	close();
}
export
class ExpressMocker
{
	private express:express.Express;
	private expressListener:ICloseable; // TODO fix express.d.ts to correctly anotate this
	private config:IExpressMockerConfig;
	private configPath:string;
	private JSONMockerPool:Pool<JSONMocker> = new Pool<JSONMocker>( JSONMocker, 100 );
	constructor(private npmDir:string, private rootDir:string ){}

	public loadConfig( path:string ):ExpressMocker
	{
		this.configPath = path;

		this.config = JSON.parse( <string><any>fs.readFileSync(path,'utf8'));

		//config.json file route
		var adminRoute:IExpressMockerRoute = {
			id:this.shash('/express-mocker/config.json'),
			hidden:true,
			active:true,
			verb: "get",
			route: "/express-mocker/config.json",
			response:
			{
				source: "config.json"
			}

		}

		// set same config.json basicAuth access privileges
		if( this.config.adminAuth ){ adminRoute.basicAuth = this.config.adminAuth; }

		// add admin routes
		this.config.defaultRoutes.push( adminRoute );

		// set quiet mode
		Logger.quiet = this.config.quiet;

		return this;
	}

	public setPort( port:number ):ExpressMocker
	{
		if( this.config && port!=0 ) this.config.port = port;
		return this;
	}

	public getPort():number
	{
		return this.config.port;
	}
	public setQuiet( mode:boolean ):ExpressMocker
	{
		if( Logger.quiet != mode  ){ Logger.quiet = mode; }
		return this;
	}

	public createServer():ExpressMocker
	{
		this.express = express();
		this.express.use(express.urlencoded());
		this.express.use(express.json());
		this.express.use(this.corsMiddleware.bind(this));
		this.express.use(express.static(__dirname ))

		// error that raises when port is already in use
		process.on('uncaughtException',(err:any) => {
			if(err.errno === 'EADDRINUSE')
				Logger.error('Port', this.config.port, 'is alrready in use!!');
			else
				Logger.error(err);
			process.exit(1);
		});

		this.configureRoutes();
		this.configureAdmin();
		this.configureStatics();
		this.expressListener = <ICloseable>this.express.listen( this.config.port );
		Logger.success('[Express Mocker] Starting server [ @pid:',process.pid,'] at port:', this.config.port );
		return this;
	}

	private configureStatics():void
	{
		if( this.config.statics )
		{
			this.config.statics.map( ( staticDir:IExpressMockerStatic )=>{
				if ( fs.existsSync(this.rootDir + staticDir.directory) )
				{
					Logger.success('Mapping route:',staticDir.route, 'to:', this.rootDir + staticDir.directory );
					this.express.use( staticDir.route, express.static( this.rootDir + staticDir.directory) );
				}
				else
				{
					Logger.error('Error Mapping route:',staticDir.route, 'to:', this.rootDir + staticDir.directory );
				}
			});
		}
	}

	private configureAdmin():void
	{

		this.express.get('/express-mocker/stop-server', ( req:express.Request, res:express.Response )=>{
			res.send('{"code":100}');
			Logger.success('Closing..');
			this.expressListener.close();
		});

		this.express.post('/express-mocker/update', ( req:express.Request, res:express.Response )=>{

			fs.writeFileSync(this.configPath, JSON.stringify(req.body.config, null, 4),'utf8');
			res.writeHead(200, {"Content-Type": "application/json"});
			res.end('{"code":100}');
		});

		this.express.all("/express-mocker/reload", ( req:express.Request, res:express.Response )=>{

			// wipe out all the old routes, or express will get confused.
			var verbs = Object.keys(this.express.routes);
			verbs.map((verb)=>{
				this.express.routes[verb] = [];
			});
			this.loadConfig( this.configPath );
			this.configureRoutes();
			this.configureAdmin();
			this.configureStatics();
			Logger.info('Server Reload Completed.');
			res.writeHead(200, {"Content-Type": "application/json"});
			res.end('{"configPath": "' + this.configPath + '", "reloaded": "true"}');
		});

		this.config.adminAuth && this.express.get
		(
			'/express-mocker/*',
			express.basicAuth((username,password,callback)=>
			{
				var result = ((username === this.config.adminAuth.login) && (password === this.config.adminAuth.password));
				callback(null, result);
			}),
			(req, res, next)=>{ next(); }
		);
		// default admin code is located at (installed pkg dir)/bin/www
		this.express.use( '/express-mocker', express.static( this.npmDir+'/www' ) );
	}

	private configureRoutes():void
	{
		//add all active routes
		this.config.defaultRoutes.map( (e:IExpressMockerRoute) =>{ if( e.active || e.hidden ) this.addRoute( e ) } );
	}

	private addRoute( route:IExpressMockerRoute ):void
	{
		// hide logging of internal routes
		if(!route.hidden) Logger.info('Add route', route.verb.toUpperCase(), route.route )

		// add routing
		this.express[route.verb]( route.route,( req:express.Request, res:express.Response )=>{this.sendResponse(req, res, route)} );
	}

	private sendResponse( req:express.Request, res:express.Response, route:IExpressMockerRoute ):void
	{
		Logger.info('Processing route:', route.route );
		var isDataUrlRegExp:RegExp = /^data:(.+\/(.+));base64,(.*)$/
			,isJsonGeneratorFileRegExp:RegExp = /\.json-mk$/
			,source = route.response.source
			,isFileDataUrlEncoded:boolean = isDataUrlRegExp.test( source )
			,isJsonGeneratorFile:boolean = isJsonGeneratorFileRegExp.test( source )
			,isFile:boolean = !isFileDataUrlEncoded;

		switch( true )
		{
			// source response is in dataURL format
			case isFileDataUrlEncoded:
				var dataUrlInfo:RegExpExecArray = isDataUrlRegExp.exec( source )
					,mime:string = dataUrlInfo[1];

				// if response is a JSONMocker file
				if( mime != "application/json-mock" )
				{
					// send the mine/base64 response from the buffer
					var buffer:NodeBuffer = Base64.decodeBuffer( dataUrlInfo[3] );
					var len = Buffer.byteLength( buffer.toString('utf8') ,'utf8');
					this.sendContentLength( res, mime, len );
					res.send( buffer );
				}
				else
				{
					var outputBuffer:string = Base64.decode( dataUrlInfo[3]);
					// process JSONMock template from the base64 encoded buffer
					var jsonGenResult:IJSONGenResult = this.parseJSONGen( outputBuffer, route, req, res );
					var len = Buffer.byteLength( jsonGenResult.result ,'utf8');
					this.sendContentLength( res, jsonGenResult.directResponse? jsonGenResult.mime : "application/json", len,'utf8' );
					res.send( jsonGenResult.result );
				}

			break;

			// is a local JSONMocker file
			case  isJsonGeneratorFile:

				// read the file from disk
				fs.readFile(this.rootDir+'/express-mocker/'+source, {encoding: "utf8"}, (err: ErrnoException, data: NodeBuffer)=>
				{
					if (err){ throw err; }
					res.header('Content-Type', "application/json");
					// process JSONMock template from the contents of the file
					res.send( this.parseJSONGen( data.toString('utf8'), route, req, res).result );
				});

				break;

			// default send file
			default:

				//let express serve the file 4 us ;-)
				res.sendfile(source, { root: this.rootDir+'/express-mocker' });
				break;

		}
	}

	private parseJSONGen( data:string, route:IExpressMockerRoute, req:express.Request, res:express.Response ):IJSONGenResult
	{

		var dataUrlRegExp:RegExp = /^data:(.+\/(.+));base64,(.*)$/;
		var jsonmocker:JSONMocker = this.JSONMockerPool.pop();
		var template:{ $content?:string } = jsonmocker.parseTemplate( data, mix( req.params, req.body ) );
		this.JSONMockerPool.push( jsonmocker );
		// check if a direct output template is provided
		if (template.$content && dataUrlRegExp.test(template.$content) && ( Object.keys(JSON.parse(JSON.stringify(template))).length == 1))
		{
			var dataUrlInfo:RegExpExecArray = dataUrlRegExp.exec(template.$content);
			var output:string = Base64.decode( dataUrlInfo[3] );
			return {
				result:output,
				directResponse:true,
				mime:dataUrlInfo[1]
			};
		}
		return {
			result:JSON.stringify(template),
			directResponse:false
		}

	}

	private sendContentLength( res:express.Response, contentType:string, len:number ,charset:string='' ):void
	{
		res.header('Cache-Control', 'no-cache');
		res.header('Content-Type', contentType + (charset !="" ? '; charset='+charset:'') );
		res.header('Content-Length', len.toString() );
	}

	private corsMiddleware( req:express.Request, res:express.Response, next:Function ):void
	{
		res.header('Access-Control-Allow-Origin', "*");
		res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
		res.header('Access-Control-Allow-Headers', 'Content-Type');
		next();
	}

	// HELPERS

	private shash(string:string):string
	{
		var value:number = 0;
		for (var i:number = 0; i < string.length; i++)
		{
			var cc:number = string.charCodeAt(i) + 96;
			value = ((value * 27) + cc) % 9999999999999999;
		}
		return value.toString(16).toUpperCase();
	}

}

class Base64
{
	static encode( stringToEncode:string ):string
	{
		return new Buffer( stringToEncode, 'utf8' ).toString('base64');
	}

	static decode( buffer:string ):string
	{
		return new Buffer( buffer, 'base64').toString('utf8');
	}
	static decodeBuffer( buffer:string ):NodeBuffer
	{
		return new Buffer( buffer, 'base64');
	}
}

redpajama_set_name: RedPajamaGithub


text:
<!--

    Licensed to the Apache Software Foundation (ASF) under one
    or more contributor license agreements.  See the NOTICE file
    distributed with this work for additional information
    regarding copyright ownership.  The ASF licenses this file
    to you 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.

-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <packaging>pom</packaging>
  <parent>
    <groupId>org.apache.pulsar</groupId>
    <artifactId>pulsar</artifactId>
    <version>2.4.0-SNAPSHOT</version>
  </parent>

  <artifactId>pulsar-functions</artifactId>
  <name>Pulsar Functions :: Parent</name>

  <modules>
    <module>proto</module>
    <module>api-java</module>
    <module>java-examples</module>
    <module>utils</module>
    <module>instance</module>
    <module>runtime</module>
    <module>runtime-all</module>
    <module>worker</module>
    <module>secrets</module>
    <module>windowing</module>
  </modules>

</project>


text:
const Emissor = require('sk/particles/Emissor')
const random = require('sk/random')

class RectEmissor extends Emissor {
  constructor(width=0, height=0) {
    super()

    this._width = width
    this._height = height
  }

  get width() { return this._width }
  set width(v) { this._width = v }

  get height() { return this._height }
  set height(v) { this._height = !!v }

  create() {
    return {
      x: random.polar(this._width/2),
      y: random.polar(this._height/2),
    }
  }
}

module.exports = RectEmissor


text:
<?xml version='1.0' encoding='UTF-8'?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:wsa="http://www.w3.org/2005/08/addressing">
    <soapenv:Body>
        <m0:getQuote xmlns:m0="http://services.samples">
            <m0:request>
                <m0:symbol>IBM</m0:symbol>
            </m0:request>
        </m0:getQuote>
    </soapenv:Body>
</soapenv:Envelope>


text:
package dynamic;

public class CuttingaRod {
    /*
     * Given a rod of length n inches and an array of prices that contains
     * prices of all pieces of size smaller than n. Determine the maximum value
     * obtainable by cutting up the rod and selling the pieces.
     */

    int cutRod(int price[], int n) {
        int[] val = new int[n + 1];
        val[0] = 0;
        int i, j;

        // Build the table val[] in bottom up manner and return the last entry
        // from the table
        for (i = 1; i <= n; i++) {
            int max_val = Integer.MIN_VALUE;
            for (j = 0; j < i; j++)
                max_val = Math.max(max_val, price[j] + val[i - j - 1]);
            val[i] = max_val;
        }

        return val[n];
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub

    }

}


text:
package appstate

import (
	"bytes"
	"crypto/sha256"
	"encoding/json"
	"fmt"

	"google.golang.org/protobuf/proto"

	waBinary "go.mau.fi/whatsmeow/binary"
	waProto "go.mau.fi/whatsmeow/binary/proto"
	"go.mau.fi/whatsmeow/store"
	"go.mau.fi/whatsmeow/util/cbcutil"
)

// PatchList represents a decoded response to getting app state patches from the WhatsApp servers.
type PatchList struct {
	Name           WAPatchName
	HasMorePatches bool
	Patches        []*waProto.SyncdPatch
	Snapshot       *waProto.SyncdSnapshot
}

// DownloadExternalFunc is a function that can download a blob of external app state patches.
type DownloadExternalFunc func(*waProto.ExternalBlobReference) ([]byte, error)

func parseSnapshotInternal(collection *waBinary.Node, downloadExternal DownloadExternalFunc) (*waProto.SyncdSnapshot, error) {
	snapshotNode := collection.GetChildByTag("snapshot")
	rawSnapshot, ok := snapshotNode.Content.([]byte)
	if snapshotNode.Tag != "snapshot" || !ok {
		return nil, nil
	}
	var snapshot waProto.ExternalBlobReference
	err := proto.Unmarshal(rawSnapshot, &snapshot)
	if err != nil {
		return nil, fmt.Errorf("failed to unmarshal snapshot: %w", err)
	}
	var rawData []byte
	rawData, err = downloadExternal(&snapshot)
	if err != nil {
		return nil, fmt.Errorf("failed to download external mutations: %w", err)
	}
	var downloaded waProto.SyncdSnapshot
	err = proto.Unmarshal(rawData, &downloaded)
	if err != nil {
		return nil, fmt.Errorf("failed to unmarshal mutation list: %w", err)
	}
	return &downloaded, nil
}

func parsePatchListInternal(collection *waBinary.Node, downloadExternal DownloadExternalFunc) ([]*waProto.SyncdPatch, error) {
	patchesNode := collection.GetChildByTag("patches")
	patchNodes := patchesNode.GetChildren()
	patches := make([]*waProto.SyncdPatch, 0, len(patchNodes))
	for i, patchNode := range patchNodes {
		rawPatch, ok := patchNode.Content.([]byte)
		if patchNode.Tag != "patch" || !ok {
			continue
		}
		var patch waProto.SyncdPatch
		err := proto.Unmarshal(rawPatch, &patch)
		if err != nil {
			return nil, fmt.Errorf("failed to unmarshal patch #%d: %w", i+1, err)
		}
		if patch.GetExternalMutations() != nil && downloadExternal != nil {
			var rawData []byte
			rawData, err = downloadExternal(patch.GetExternalMutations())
			if err != nil {
				return nil, fmt.Errorf("failed to download external mutations: %w", err)
			}
			var downloaded waProto.SyncdMutations
			err = proto.Unmarshal(rawData, &downloaded)
			if err != nil {
				return nil, fmt.Errorf("failed to unmarshal mutation list: %w", err)
			} else if len(downloaded.GetMutations()) == 0 {
				return nil, fmt.Errorf("didn't get any mutations from download")
			}
			patch.Mutations = downloaded.Mutations
		}
		patches = append(patches, &patch)
	}
	return patches, nil
}

// ParsePatchList will decode an XML node containing app state patches, including downloading any external blobs.
func ParsePatchList(node *waBinary.Node, downloadExternal DownloadExternalFunc) (*PatchList, error) {
	collection := node.GetChildByTag("sync", "collection")
	ag := collection.AttrGetter()
	snapshot, err := parseSnapshotInternal(&collection, downloadExternal)
	if err != nil {
		return nil, err
	}
	patches, err := parsePatchListInternal(&collection, downloadExternal)
	if err != nil {
		return nil, err
	}
	list := &PatchList{
		Name:           WAPatchName(ag.String("name")),
		HasMorePatches: ag.OptionalBool("has_more_patches"),
		Patches:        patches,
		Snapshot:       snapshot,
	}
	return list, ag.Error()
}

type patchOutput struct {
	RemovedMACs [][]byte
	AddedMACs   []store.AppStateMutationMAC
	Mutations   []Mutation
}

func (proc *Processor) decodeMutations(mutations []*waProto.SyncdMutation, out *patchOutput, validateMACs bool) error {
	for i, mutation := range mutations {
		keyID := mutation.GetRecord().GetKeyId().GetId()
		keys, err := proc.getAppStateKey(keyID)
		if err != nil {
			return fmt.Errorf("failed to get key %X to decode mutation: %w", keyID, err)
		}
		content := mutation.GetRecord().GetValue().GetBlob()
		content, valueMAC := content[:len(content)-32], content[len(content)-32:]
		if validateMACs {
			expectedValueMAC := generateContentMAC(mutation.GetOperation(), content, keyID, keys.ValueMAC)
			if !bytes.Equal(expectedValueMAC, valueMAC) {
				return fmt.Errorf("failed to verify mutation #%d: %w", i+1, ErrMismatchingContentMAC)
			}
		}
		iv, content := content[:16], content[16:]
		plaintext, err := cbcutil.Decrypt(keys.ValueEncryption, iv, content)
		if err != nil {
			return fmt.Errorf("failed to decrypt mutation #%d: %w", i+1, err)
		}
		var syncAction waProto.SyncActionData
		err = proto.Unmarshal(plaintext, &syncAction)
		if err != nil {
			return fmt.Errorf("failed to unmarshal mutation #%d: %w", i+1, err)
		}
		indexMAC := mutation.GetRecord().GetIndex().GetBlob()
		if validateMACs {
			expectedIndexMAC := concatAndHMAC(sha256.New, keys.Index, syncAction.Index)
			if !bytes.Equal(expectedIndexMAC, indexMAC) {
				return fmt.Errorf("failed to verify mutation #%d: %w", i+1, ErrMismatchingIndexMAC)
			}
		}
		var index []string
		err = json.Unmarshal(syncAction.GetIndex(), &index)
		if err != nil {
			return fmt.Errorf("failed to unmarshal index of mutation #%d: %w", i+1, err)
		}
		if mutation.GetOperation() == waProto.SyncdMutation_REMOVE {
			out.RemovedMACs = append(out.RemovedMACs, indexMAC)
		} else if mutation.GetOperation() == waProto.SyncdMutation_SET {
			out.AddedMACs = append(out.AddedMACs, store.AppStateMutationMAC{
				IndexMAC: indexMAC,
				ValueMAC: valueMAC,
			})
		}
		out.Mutations = append(out.Mutations, Mutation{
			Operation: mutation.GetOperation(),
			Action:    syncAction.GetValue(),
			Index:     index,
			IndexMAC:  indexMAC,
			ValueMAC:  valueMAC,
		})
	}
	return nil
}

func (proc *Processor) storeMACs(name WAPatchName, currentState HashState, out *patchOutput) {
	err := proc.Store.AppState.PutAppStateVersion(string(name), currentState.Version, currentState.Hash)
	if err != nil {
		proc.Log.Errorf("Failed to update app state version in the database: %v", err)
	}
	err = proc.Store.AppState.DeleteAppStateMutationMACs(string(name), out.RemovedMACs)
	if err != nil {
		proc.Log.Errorf("Failed to remove deleted mutation MACs from the database: %v", err)
	}
	err = proc.Store.AppState.PutAppStateMutationMACs(string(name), currentState.Version, out.AddedMACs)
	if err != nil {
		proc.Log.Errorf("Failed to insert added mutation MACs to the database: %v", err)
	}
}

func (proc *Processor) validateSnapshotMAC(name WAPatchName, currentState HashState, keyID, expectedSnapshotMAC []byte) (keys ExpandedAppStateKeys, err error) {
	keys, err = proc.getAppStateKey(keyID)
	if err != nil {
		err = fmt.Errorf("failed to get key %X to verify patch v%d MACs: %w", keyID, currentState.Version, err)
		return
	}
	snapshotMAC := currentState.generateSnapshotMAC(name, keys.SnapshotMAC)
	if !bytes.Equal(snapshotMAC, expectedSnapshotMAC) {
		err = fmt.Errorf("failed to verify patch v%d: %w", currentState.Version, ErrMismatchingLTHash)
	}
	return
}

func (proc *Processor) decodeSnapshot(name WAPatchName, ss *waProto.SyncdSnapshot, initialState HashState, validateMACs bool, newMutationsInput []Mutation) (newMutations []Mutation, currentState HashState, err error) {
	currentState = initialState
	currentState.Version = ss.GetVersion().GetVersion()

	encryptedMutations := make([]*waProto.SyncdMutation, len(ss.GetRecords()))
	for i, record := range ss.GetRecords() {
		encryptedMutations[i] = &waProto.SyncdMutation{
			Operation: waProto.SyncdMutation_SET.Enum(),
			Record:    record,
		}
	}

	var warn []error
	warn, err = currentState.updateHash(encryptedMutations, func(indexMAC []byte, maxIndex int) ([]byte, error) {
		return nil, nil
	})
	if len(warn) > 0 {
		proc.Log.Warnf("Warnings while updating hash for %s: %+v", name, warn)
	}
	if err != nil {
		err = fmt.Errorf("failed to update state hash: %w", err)
		return
	}

	if validateMACs {
		_, err = proc.validateSnapshotMAC(name, currentState, ss.GetKeyId().GetId(), ss.GetMac())
		if err != nil {
			return
		}
	}

	var out patchOutput
	out.Mutations = newMutationsInput
	err = proc.decodeMutations(encryptedMutations, &out, validateMACs)
	if err != nil {
		err = fmt.Errorf("failed to decode snapshot of v%d: %w", currentState.Version, err)
		return
	}
	proc.storeMACs(name, currentState, &out)
	newMutations = out.Mutations
	return
}

// DecodePatches will decode all the patches in a PatchList into a list of app state mutations.
func (proc *Processor) DecodePatches(list *PatchList, initialState HashState, validateMACs bool) (newMutations []Mutation, currentState HashState, err error) {
	currentState = initialState
	var expectedLength int
	if list.Snapshot != nil {
		expectedLength = len(list.Snapshot.GetRecords())
	}
	for _, patch := range list.Patches {
		expectedLength += len(patch.GetMutations())
	}
	newMutations = make([]Mutation, 0, expectedLength)

	if list.Snapshot != nil {
		newMutations, currentState, err = proc.decodeSnapshot(list.Name, list.Snapshot, currentState, validateMACs, newMutations)
		if err != nil {
			return
		}
	}

	for _, patch := range list.Patches {
		version := patch.GetVersion().GetVersion()
		currentState.Version = version
		var warn []error
		warn, err = currentState.updateHash(patch.GetMutations(), func(indexMAC []byte, maxIndex int) ([]byte, error) {
			for i := maxIndex - 1; i >= 0; i-- {
				if bytes.Equal(patch.Mutations[i].GetRecord().GetIndex().GetBlob(), indexMAC) {
					value := patch.Mutations[i].GetRecord().GetValue().GetBlob()
					return value[len(value)-32:], nil
				}
			}
			// Previous value not found in current patch, look in the database
			return proc.Store.AppState.GetAppStateMutationMAC(string(list.Name), indexMAC)
		})
		if len(warn) > 0 {
			proc.Log.Warnf("Warnings while updating hash for %s: %+v", list.Name, warn)
		}
		if err != nil {
			err = fmt.Errorf("failed to update state hash: %w", err)
			return
		}

		if validateMACs {
			var keys ExpandedAppStateKeys
			keys, err = proc.validateSnapshotMAC(list.Name, currentState, patch.GetKeyId().GetId(), patch.GetSnapshotMac())
			if err != nil {
				return
			}
			patchMAC := generatePatchMAC(patch, list.Name, keys.PatchMAC)
			if !bytes.Equal(patchMAC, patch.GetPatchMac()) {
				err = fmt.Errorf("failed to verify patch v%d: %w", version, ErrMismatchingPatchMAC)
				return
			}
		}

		var out patchOutput
		out.Mutations = newMutations
		err = proc.decodeMutations(patch.GetMutations(), &out, validateMACs)
		if err != nil {
			return
		}
		proc.storeMACs(list.Name, currentState, &out)
		newMutations = out.Mutations
	}
	return
}


text:
import React, { PureComponent, cloneElement, isValidElement, Children } from 'react';
import PropTypes from 'prop-types';
import cn from 'classnames';

/**
 * The `IconSeparator` component is a simple helper component to render some text and
 * an icon with some space between them while centering the text. The icon can either
 * come before or after the text.
 */
export default class IconSeparator extends PureComponent {
  static propTypes = {
    /**
     * An optional style to apply.
     */
    style: PropTypes.object,

    /**
     * An optional className to apply.
     */
    className: PropTypes.string,

    /**
     * An optional style to apply to the label.
     */
    labelStyle: PropTypes.object,

    /**
     * An optional className to apply to the label.
     */
    labelClassName: PropTypes.string,

    /**
     * The label to display.
     */
    label: PropTypes.node.isRequired,

    /**
     * The icon to display.
     */
    children: PropTypes.node.isRequired,

    /**
     * Boolean if the icon should appear before or after the text
     */
    iconBefore: PropTypes.bool,

    /**
     * The component to be rendered as.
     */
    component: PropTypes.oneOfType([
      PropTypes.string,
      PropTypes.func,
    ]).isRequired,
  };

  static defaultProps = {
    component: 'div',
  };

  render() {
    const {
      className,
      labelStyle,
      labelClassName,
      component,
      label,
      iconBefore,
      children,
      ...props
    } = this.props;

    let text;
    if (isValidElement(label)) {
      const labelProps = Children.only(label).props;
      text = cloneElement(label, {
        className: cn('md-icon-text', labelClassName, labelProps.className),
        style: { ...labelStyle, ...labelProps.style },
      });
    } else {
      text = {label};
    }

    const Component = component;

    return (
      <Component {...props} className={cn('md-icon-separator', className)}>
        {iconBefore && children}
        {text}
        {!iconBefore && children}
      </Component>
    );
  }
}


text:
package esa_test

import (
	"os"
	"testing"

	"github.com/k0kubun/pp"
	"github.com/yuichiro-h/go-esa"
)

func TestGetTeamPostStartgazars(t *testing.T) {
	client := esa.New(&esa.Config{AccessToken: os.Getenv("ESA_ACCESS_TOKEN")})
	res, err := client.GetTeamPostStarGazers("coto-coto", 2387, &esa.GetTeamPostStargazersRequest{})
	if err != nil {
		t.Error(err)
	}
	t.Log(pp.Sprint(res))
}

func TestCreateTeamPostStar(t *testing.T) {
	client := esa.New(&esa.Config{AccessToken: os.Getenv("ESA_ACCESS_TOKEN")})
	err := client.CreateTeamPostStar("coto-coto", 2387, &esa.CreateTeamPostStarRequest{
		Body: esa.String("go-esa"),
	})
	if err != nil {
		t.Error(err)
	}
}


text:
using Microsoft.CodeAnalysis;

namespace Analyzers.AnalyzersMetadata.DiagnosticTitles
{
    public static class EnumDiagnosticTitles
    {
        public static readonly LocalizableString DefaultLabelShouldBeTheLast = "Default switch label";
        public static readonly LocalizableString MergeSwitchSectionsWithEquivalentContent = "Merge switch sections";
        public static readonly LocalizableString SwitchOnEnumMustHandleAllCases = "Populate switch";
    }
}


text:
package infodynamics.measures.continuous.gaussian;

import infodynamics.measures.continuous.TransferEntropyCalculator;
import infodynamics.measures.continuous.TransferEntropyCalculatorMultiVariate;
import infodynamics.measures.continuous.TransferEntropyCalculatorMultiVariateViaCondMutualInfo;
import infodynamics.measures.continuous.TransferEntropyCalculatorViaCondMutualInfo;
import infodynamics.utils.AnalyticNullDistributionComputer;
import infodynamics.utils.ChiSquareMeasurementDistribution;

/**
 *
Computes the differential transfer entropy (TE) between two multivariate
 *  double[][] time-series of observations
 *  (implementing {@link TransferEntropyCalculatorMultiVariate}),
 *  assuming that the probability distribution function for these observations is
 *  a multivariate Gaussian distribution.
 *  TE was defined by Schreiber, extended to multivariate source
 *  and destination by Lizier et al. (2011), and
 *  Kaiser and Schreiber showed how to compute
 *  TE via Gaussian assumption.
 *  This estimator is realised here by plugging in
 *  {@link ConditionalMutualInfoCalculatorMultiVariateGaussian}
 *  as the calculator into the parent class {@link TransferEntropyCalculatorMultiVariateViaCondMutualInfo}.

 *
 *
That is, this class implements a multivariate TE calculator using model of
 * Gaussian variables with linear interactions, making it equivalent
 * (up to a multiplicative constant) to the multivariate Granger causality (see Barnett et al below).
 *

 *
 *
Usage is as per the paradigm outlined for {@link TransferEntropyCalculatorMultiVariate},
 * with:
 *

 *
The constructor step being a simple call to {@link #TransferEntropyCalculatorMultiVariateGaussian()}.

 *
{@link #setProperty(String, String)} allowing properties defined for both
 * 		{@link TransferEntropyCalculator#setProperty(String, String)} and
 *      {@link ConditionalMutualInfoCalculatorMultiVariateGaussian#setProperty(String, String)}
 *      as outlined
 *      in {@link TransferEntropyCalculatorViaCondMutualInfo#setProperty(String, String)}).

 *
The user can call {@link #setCovariance(double[][], int)}
 *     instead of supplying observations via {@link #setObservations(double[][], double[][])} or
 *     {@link #addObservations(double[][], double[][])} etc.

 *
Computed values are in nats, not bits!

 *
Additional method {@link #computeSignificance()} to compute null distribution analytically.

 *

 *

 *
 *
References:

 *

 *
T. Schreiber,
 * "Measuring information transfer",
 *  Physical Review Letters 85 (2) pp.461-464, 2000.

 *
J.T. Lizier, J. Heinzle, A. Horstmann, J.-D. Haynes, M. Prokopenko,
 *
 *  "Multivariate information-theoretic measures reveal directed information
 *  structure and task relevant changes in fMRI connectivity",
 *  Journal of Computational Neuroscience, vol. 30, pp. 85-107, 2011.

 *
L. Barnett, A. B. Barrett, A. K. Seth,
 *  "Granger Causality and Transfer Entropy Are Equivalent for Gaussian Variables",
 *  Physical Review Letters 103 (23) 238701, 2009;

 *
A. Kaiser, T. Schreiber,
 *  "Information transfer in continuous processes",
 *  Physica D, Vol. 166, No. 1-2., pp. 43-62 (2002).

 *

 *
 * @author Joseph Lizier, email,
 * www
 * @see TransferEntropyCalculatorMultiVariate
 */
public class TransferEntropyCalculatorMultiVariateGaussian
	extends TransferEntropyCalculatorMultiVariateViaCondMutualInfo
	implements AnalyticNullDistributionComputer {

	/**
	 * Name of the Gaussian conditional MI calculator we will use
	 */
	public static final String COND_MI_CALCULATOR_GAUSSIAN = ConditionalMutualInfoCalculatorMultiVariateGaussian.class.getName();

	/**
	 * Creates a new instance of the Gaussian-estimate style transfer entropy calculator
	 *
	 * @throws ClassNotFoundException
	 * @throws IllegalAccessException
	 * @throws InstantiationException
	 *
	 */
	public TransferEntropyCalculatorMultiVariateGaussian() throws InstantiationException, IllegalAccessException, ClassNotFoundException {
		super(COND_MI_CALCULATOR_GAUSSIAN);
	}

	/**
	 *
Set the joint covariance of the distribution for which we will compute the
	 *  transfer entropy.

	 *
	 *
Note that without setting any observations, you cannot later
	 *  call {@link #computeLocalOfPreviousObservations()}, and without
	 *  providing the means of the variables, you cannot later call
	 *  {@link #computeLocalUsingPreviousObservations(double[][], double[][])}.

	 *
	 * @param covariance joint covariance matrix of the multivariate
	 *  source, dest, dest history
	 *  variables, considered together.
	 * @param numObservations the number of observations that the covariance
	 *  was determined from. This is used for later significance calculations
	 * @throws Exception for covariance matrix not matching the expected dimensions,
	 *  being non-square, asymmetric or non-positive definite
	 */
	public void setCovariance(double[][] covariance, int numObservations) throws Exception {
		((ConditionalMutualInfoCalculatorMultiVariateGaussian) condMiCalc).
				setCovariance(covariance, numObservations);
	}

	/**
	 * Generate an analytic distribution of what the TE would look like,
	 * under a null hypothesis that our variables had no relation
	 * (in the context of the conditional value).
	 * This is performed without bootstrapping (which is done in
	 * {@link #computeSignificance(int, int)} and {@link #computeSignificance(int, int[][])}).
	 * The method is implemented using the corresponding method of the
	 *  underlying {@link ConditionalMutualInfoCalculatorMultiVariateGaussian}
	 *
	 *
See Section II.E "Statistical significance testing" of
	 * the JIDT paper below, and the other papers referenced in
	 * {@link AnalyticNullDistributionComputer#computeSignificance()}
	 * (in particular Geweke),
	 * for a description of how this is done for TE and conditional MI.
	 * Basically, the null distribution is a chi-square distribution.
	 *

	 *
	 * @return ChiSquareMeasurementDistribution object which describes
	 * the proportion of TE scores from the null distribution
	 *  which have higher or equal conditional MIs to our actual value.
	 * @see {@link ConditionalMutualInfoCalculatorMultiVariateGaussian#computeSignificance()}
	 * @see "J.T. Lizier, 'JIDT: An information-theoretic
	 *    toolkit for studying the dynamics of complex systems', 2014."
	 * @throws Exception
	 */
	public ChiSquareMeasurementDistribution computeSignificance()
			throws Exception {
		return ((ConditionalMutualInfoCalculatorMultiVariateGaussian) condMiCalc).computeSignificance();
	}
}


text:
package org.apache.flink.connector.file.table;

import org.apache.flink.table.data.GenericRowData;
import org.apache.flink.table.data.RowData;
import org.apache.flink.table.data.utils.JoinedRowData;
import org.apache.flink.types.RowKind;

import org.junit.jupiter.api.Test;

import java.util.Arrays;
import java.util.List;

import static org.junit.jupiter.api.Assertions.assertEquals;

/** Tests for {@link JoinedRowData}. */
class EnrichedRowDataTest {

    @Test
    void testEnrichedRow() {
        final List<String> completeRowFields =
                Arrays.asList(
                        "fixedRow1",
                        "mutableRow1",
                        "mutableRow3",
                        "mutableRow2",
                        "fixedRow2",
                        "mutableRow4");
        final List<String> mutableRowFields =
                Arrays.asList("mutableRow1", "mutableRow2", "mutableRow3", "mutableRow4");
        final List<String> fixedRowFields = Arrays.asList("fixedRow1", "fixedRow2");

        final RowData fixedRowData = GenericRowData.of(1L, 2L);
        final EnrichedRowData enrichedRowData =
                EnrichedRowData.from(
                        fixedRowData, completeRowFields, mutableRowFields, fixedRowFields);
        final RowData mutableRowData = GenericRowData.of(3L, 4L, 5L, 6L);
        enrichedRowData.replaceMutableRow(mutableRowData);

        assertEquals(RowKind.INSERT, enrichedRowData.getRowKind());
        assertEquals(6, enrichedRowData.getArity());
        assertEquals(1L, enrichedRowData.getLong(0));
        assertEquals(3L, enrichedRowData.getLong(1));
        assertEquals(5L, enrichedRowData.getLong(2));
        assertEquals(4L, enrichedRowData.getLong(3));
        assertEquals(2L, enrichedRowData.getLong(4));
        assertEquals(6L, enrichedRowData.getLong(5));

        final RowData newMutableRowData = GenericRowData.of(7L, 8L, 9L, 10L);
        enrichedRowData.replaceMutableRow(newMutableRowData);

        assertEquals(1L, enrichedRowData.getLong(0));
        assertEquals(7L, enrichedRowData.getLong(1));
        assertEquals(9L, enrichedRowData.getLong(2));
        assertEquals(8L, enrichedRowData.getLong(3));
        assertEquals(2L, enrichedRowData.getLong(4));
        assertEquals(10L, enrichedRowData.getLong(5));
    }
}


text:
"""Provide the RedditorList class."""
from ..reddit.redditor import Redditor
from .base import BaseList

class RedditorList(BaseList):
    """A list of Redditors. Works just like a regular list."""

    CHILD_ATTRIBUTE = 'children'

    @staticmethod
    def _convert(reddit, data):
        """Return a :class:`.Redditor` instance from the data."""
        return Redditor(reddit, data['name'])


text:
class Admin::AApisController < Admin::AdminBaseController
  # skip_before_action :verify_authenticity_token

  def index
    @apis = select_readable(Api.order(:name))
    render layout: 'admin'
  end

  def create
    return unless user_can(:create, @create_hash)
    render layout: 'admin'
  end

  def edit
    return unless user_can(:update, @model)
    render layout: 'admin'
  end

  def set_model
    find_model_by_params(Api)
    @api = @model if @model.instance_of?(Api)
  end
end


text:
/* eslint no-param-reassign: 1 */
/* eslint no-undef: 1 */
/* global PlasticalSettings */
// External dependencies
import React, { Component } from 'react';

// Internal dependencies
import validate from 'utils/validate';
import { getDate, getTime } from 'utils/content-mixin';

const now = new Date(Date.now());
const d = new Date();
const milli = d.valueOf();

class EventForm extends Component {
  constructor(props) {
    super(props);
    this.state = {
      deadline: this.props.deadline,
      deadline_comp: this.props.deadlineComp,
      reason: 'attendance',
      built: now.toISOString(),
      verify: validate.verifyString(),
      language: this.props.locale.lang,
      post_id: this.props.postId,
      event_name: this.props.name,
      event_startdate: this.props.startdate,
      error_first_name: false,
      error_last_name: false,
      error_email: false,
      error_job_title: false,
      error_company: false,
      error_address: false,
      error_verify: false,
      errors: false,
      errorMessage: false,
      successMessage: false
    }
    this.handleSubmit = this.handleSubmit.bind(this);
    this.handleChange = this.handleChange.bind(this);
    this.handleErrors = this.handleErrors.bind(this);
    this.onBlur = this.onBlur.bind(this);
    this.onKeyPress = this.onKeyPress.bind(this);
    this.onSubmit = this.onSubmit.bind(this);
  }

  onKeyPress(e) {
    this.validation(e);
  }

  onBlur(e) {
    this.validation(e);
  }

  onSubmit(e) {
    e.preventDefault();
    e.persist(); // We need this for the callback after a registration is posted.
    this.validation(e);
    this.setState({ isSubmitting: true });

    const keys = ['post_id', 'reason', 'first_name', 'last_name', 'email', 'job_title', 'company', 'address', 'verify', 'built', 'language', 'event_name', 'event_startdate'];

    const rawValues = {};
    keys.map((key) => {
      if (e.target[key]) {
        rawValues[key] = e.target[key].value.trim();
      }
    });

    const values = {};
    values.post_id = rawValues.post_id;
    values.reason = rawValues.reason;
    values.first_name = rawValues.first_name;
    values.last_name = rawValues.last_name;
    values.email = rawValues.email;
    values.job_title = rawValues.job_title;
    values.company = rawValues.company;
    values.address = rawValues.address;
    values.verify = rawValues.verify;
    values.built = rawValues.built;
    values.language = rawValues.language;
    values.event_name = rawValues.event_name;
    values.event_startdate = rawValues.event_startdate;
    values.submit = true;

    if (this.state.errors) {
      this.handleErrors();
    } else {
      const submission = this.handleSubmit(values);
      submission.then((res) => {
        // No idea what happened.
        if (!res) {
          return;
        }
        this.setState({
          isSubmitting: false,
          deadline: this.props.deadline,
          reason: 'attendance',
          built: now.toISOString(),
          verify: validate.verifyString(),
          language: this.props.locale.lang,
          post_id: this.props.postId,
          event_name: this.props.name,
          event_startdate: this.props.startdate,
        });
        if (res.result === 'ok') {
          // Clear the details form
          e.target.first_name.value = '';
          e.target.last_name.value = '';
          e.target.email.value = '';
          e.target.job_title.value = '';
          e.target.company.value = '';
          e.target.address.value = '';
          e.target.submit.value = false;
          this.setState({
            successMessage: `${this.props.intl.formatMessage({ id: 'event.success_message' })}, ${res.name}`
          });
        } else {
          this.handleErrors();
        }

        if (res.result === 'ko') {
          this.handleErrors();
        }
      });
    }
  }

  validation(e) {
    if (e.target.name === 'first_name') {
      this.setState({ error_first_name: validate.validateName(e.target.value) });
    }
    if (e.target.name === 'last_name') {
      this.setState({ error_last_name: validate.validateName(e.target.value) });
    }
    if (e.target.name === 'email') {
      this.setState({ error_email: validate.validateEmail(e.target.value) });
    }
    if (e.target.name === 'job_title') {
      this.setState({ error_job_title: validate.validateNoHTML(e.target.value) });
    }
    if (e.target.name === 'company') {
      this.setState({ error_company: validate.validateNoHTML(e.target.value) });
    }
    if (e.target.name === 'address') {
      this.setState({ error_address: validate.validateMinLength(e.target.value, 3) || validate.validateNoHTML(e.target.value) });
    }
    if (e.target.name === 'verify') {
      this.setState({ error_verify: validate.validateIsEmpty(e.target.value) });
    }
    if (
      this.state.error_first_name ||
      this.state.error_last_name ||
      this.state.error_email ||
      this.state.error_job_title ||
      this.state.error_company ||
      this.state.error_address ||
      this.state.error_verify
    ) {
      this.setState({ errors: true });
    } else {
      this.setState({ errors: false });
    }
  }

  handleErrors() {
    this.setState({ errorMessage: this.props.intl.formatMessage({ id: 'event.error_message' }) });
    setTimeout(() => {
      this.setState({ errorMessage: false });
    }, 5000);
  }

  // Helper to submit the comment with nonce header
  handleSubmit(values) {
    const url = `${SiteSettings.endpoint}content/themes/plastical/contact/contact-proc.php`;
    const headers = {
      Accept: 'application/json',
      'X-WP-Nonce': SiteSettings.nonce,
      'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
    };
    /* eslint arrow-body-style: 1 */
    return fetch(url, {
      method: 'POST',
      headers,
      body: JSON.stringify(values)
    }).then(response => {
      return response.text();
    }).then(result => {
      let json;
      try {
        json = JSON.parse(result);
      } catch (e) {
        /* eslint no-throw-literal: 1 */
        throw { message: text, code: response.status };
      }
      return json;
    });
  }

  handleChange(e) {
    this.setState({ verify: e.target.value });
  }

  renderForm() {
    const intl = this.props.intl;
    const successMessage = this.state.successMessage ?
{this.state.successMessage}
 : null;
    const errorMessage = this.state.errorMessage ?
{this.state.errorMessage}
 : null;
    return (

{intl.formatMessage({ id: 'event.deadline' })} {this.state.deadline}

        <form onSubmit={this.onSubmit}>
          {successMessage}
          {errorMessage}

            {intl.formatMessage({ id: 'event.first_name' })} *
            <input id="first-name" className={(this.state.error_first_name) ? 'error' : ''} name="first_name" type="text" onBlur={this.onBlur} onKeyPress={this.onKeyPress} aria-required="true" required="required" placeholder={intl.formatMessage({ id: 'event.first_name_ph' })} />
            {(this.state.error_first_name) ? {intl.formatMessage({ id: 'event.first_name_err' })} : null}

            {intl.formatMessage({ id: 'event.last_name' })} *
            <input id="last-name" className={(this.state.error_last_name) ? 'error' : ''} name="last_name" type="text" onBlur={this.onBlur} onKeyPress={this.onKeyPress} aria-required="true" required="required" placeholder={intl.formatMessage({ id: 'event.last_name_ph' })} />
            {(this.state.error_last_name) ? {intl.formatMessage({ id: 'event.last_name_err' })} : null}

            Email *
            <input id="email" className={(this.state.error_email) ? 'error' : ''} name="email" type="email" onBlur={this.onBlur} onKeyPress={this.onKeyPress} aria-describedby="email-notes" aria-required="true" required="required" placeholder={intl.formatMessage({ id: 'contact.email_ph' })} />
            {(this.state.error_email) ? {intl.formatMessage({ id: 'contact.email_err' })} : null}

            {intl.formatMessage({ id: 'event.job_title' })}
            <input id="job-title" className={(this.state.error_job_title) ? 'error' : ''} name="job_title" type="text" onBlur={this.onBlur} onKeyPress={this.onKeyPress} placeholder={intl.formatMessage({ id: 'event.job_title_ph' })} />
            {(this.state.error_job_title) ? {intl.formatMessage({ id: 'event.job_title' })} : null}

            {intl.formatMessage({ id: 'event.company' })}
            <input id="company" className={(this.state.error_company) ? 'error' : ''} name="company" type="text" onBlur={this.onBlur} onKeyPress={this.onKeyPress} placeholder={intl.formatMessage({ id: 'event.company_ph' })} />
            {(this.state.error_company) ? {intl.formatMessage({ id: 'event.company_err' })} : null}

            {intl.formatMessage({ id: 'event.address' })} *
            <input id="address" className={(this.state.error_address) ? 'error' : ''} name="address" type="address" onBlur={this.onBlur} onKeyPress={this.onKeyPress} aria-required="true" required="required" placeholder={intl.formatMessage({ id: 'event.address_ph' })} />
            {(this.state.error_address) ? {intl.formatMessage({ id: 'event.address_err' })} : null}

            {intl.formatMessage({ id: 'contact.verification' })} {intl.formatMessage({ id: 'contact.verification_span' })}
            <input id="verify" className={(this.state.error_verify) ? 'error col620 first left clearfix' : 'col620 first left clearfix'} name="verify" type="text" onBlur={this.onBlur} onKeyPress={this.onKeyPress} onChange={this.handleChange} value={this.state.verify} />
            {(this.state.error_verify) ? {intl.formatMessage({ id: 'contact.verification_err' })} : null}

            {(this.state.isSubmitting) ?

...
 :
              <input id="submit" type="submit" name="submit" className="submit col620 first left clearfix" value={intl.formatMessage({ id: 'event.attend' })} />
            }
            <input id="event_name" type="hidden" name="event_name" value={this.state.event_name} />
            <input id="event_startdate" type="hidden" name="event_startdate" value={this.state.event_startdate} />
            <input id="post-id" type="hidden" name="post_id" value={this.state.post_id} />
            <input id="reason" type="hidden" name="reason" value={this.state.reason} />
            <input id="built" type="hidden" name="built" value={this.state.built} />
            <input id="language" type="hidden" name="language" value={this.state.language} />

            * {intl.formatMessage({ id: 'contact.mandatory_fields' })}

        </form>

    );
  }

  render() {
    return (

        {(this.state.deadline_comp >= milli) ?
          this.renderForm() :

{this.props.intl.formatMessage({ id: 'event.deadline_passed' })}

        }

    )
  }

}

export default EventForm;


text:
package com.cognifide.qa.bb.aem.core.modules;

import com.google.inject.AbstractModule;

/**
 * Main module that needs to be installed to use AEM 6.4 functions.
 * <p>
 * It install all sub-modules related to AEM 6.4.
 */
public class Aem64FullModule extends AbstractModule {

  @Override
  protected void configure() {
    install(new AemCoreModule());
    install(new AemLoginModule());
    install(new AemSitesAdminModule());
    install(new SlingPageActionsModule());
    install(new AemComponentModule());
    install(new AemSidePanelModule());
    install(new AemPageModule());
    install(new AemFieldsModule());
    install(new AemConfigModule());
  }

}


text:
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.android_webview;

import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Process;
import android.webkit.WebSettings;

import org.chromium.base.JNINamespace;
import org.chromium.base.ThreadUtils;

/**
 * Stores Android WebView specific settings that does not need to be synced to WebKit.
 * Use {@link org.chromium.content.browser.ContentSettings} for WebKit settings.
 *
 * Methods in this class can be called from any thread, including threads created by
 * the client of WebView.
 */
@JNINamespace("android_webview")
public class AwSettings {
    // Lock to protect all settings.
    private final Object mAwSettingsLock = new Object();

    private final Context mContext;
    private boolean mBlockNetworkLoads;  // Default depends on permission of embedding APK.
    private boolean mAllowContentUrlAccess = true;
    private boolean mAllowFileUrlAccess = true;
    private int mCacheMode = WebSettings.LOAD_DEFAULT;
    private boolean mShouldFocusFirstNode = true;
    private boolean mGeolocationEnabled = true;

    // The native side of this object.
    private int mNativeAwSettings = 0;

    public AwSettings(Context context, int nativeWebContents) {
        mContext = context;
        mBlockNetworkLoads = mContext.checkPermission(
                android.Manifest.permission.INTERNET,
                Process.myPid(),
                Process.myUid()) != PackageManager.PERMISSION_GRANTED;
        mNativeAwSettings = nativeInit(nativeWebContents);
        assert mNativeAwSettings != 0;
    }

    public void destroy() {
        nativeDestroy(mNativeAwSettings);
        mNativeAwSettings = 0;
    }

    /**
     * See {@link android.webkit.WebSettings#setBlockNetworkLoads}.
     */
    public void setBlockNetworkLoads(boolean flag) {
        synchronized (mAwSettingsLock) {
            if (!flag && mContext.checkPermission(
                    android.Manifest.permission.INTERNET,
                    Process.myPid(),
                    Process.myUid()) != PackageManager.PERMISSION_GRANTED) {
                throw new SecurityException("Permission denied - " +
                        "application missing INTERNET permission");
            }
            mBlockNetworkLoads = flag;
        }
    }

    /**
     * See {@link android.webkit.WebSettings#getBlockNetworkLoads}.
     */
    public boolean getBlockNetworkLoads() {
        synchronized (mAwSettingsLock) {
            return mBlockNetworkLoads;
        }
    }

    /**
     * See {@link android.webkit.WebSettings#setAllowFileAccess}.
     */
    public void setAllowFileAccess(boolean allow) {
        synchronized (mAwSettingsLock) {
            if (mAllowFileUrlAccess != allow) {
                mAllowFileUrlAccess = allow;
            }
        }
    }

    /**
     * See {@link android.webkit.WebSettings#getAllowFileAccess}.
     */
    public boolean getAllowFileAccess() {
        synchronized (mAwSettingsLock) {
            return mAllowFileUrlAccess;
        }
    }

    /**
     * See {@link android.webkit.WebSettings#setAllowContentAccess}.
     */
    public void setAllowContentAccess(boolean allow) {
        synchronized (mAwSettingsLock) {
            if (mAllowContentUrlAccess != allow) {
                mAllowContentUrlAccess = allow;
            }
        }
    }

    /**
     * See {@link android.webkit.WebSettings#getAllowContentAccess}.
     */
    public boolean getAllowContentAccess() {
        synchronized (mAwSettingsLock) {
            return mAllowContentUrlAccess;
        }
    }

    /**
     * See {@link android.webkit.WebSettings#setCacheMode}.
     */
    public void setCacheMode(int mode) {
        synchronized (mAwSettingsLock) {
            if (mCacheMode != mode) {
                mCacheMode = mode;
            }
        }
    }

    /**
     * See {@link android.webkit.WebSettings#getCacheMode}.
     */
    public int getCacheMode() {
        synchronized (mAwSettingsLock) {
            return mCacheMode;
        }
    }

    /**
     * See {@link android.webkit.WebSettings#setNeedInitialFocus}.
     */
    public void setShouldFocusFirstNode(boolean flag) {
        synchronized (mAwSettingsLock) {
            mShouldFocusFirstNode = flag;
        }
    }

    /**
     * Sets the text zoom of the page in percent. This kind of zooming is
     * only applicable when Text Autosizing is turned off. Passing -1 will
     * reset the zoom to the default value.
     */
    public void setTextZoom(final int textZoom) {
        // There is no need to lock, because the native code doesn't
        // read anything from the Java side.
        ThreadUtils.runOnUiThreadBlocking(new Runnable() {
            @Override
            public void run() {
                nativeSetTextZoom(mNativeAwSettings, textZoom);
            }
        });
    }

    /**
     * See {@link android.webkit.WebSettings#setNeedInitialFocus}.
     */
    public boolean shouldFocusFirstNode() {
        synchronized(mAwSettingsLock) {
            return mShouldFocusFirstNode;
        }
    }

    /**
     * See {@link android.webkit.WebSettings#setGeolocationEnabled}.
     */
    public void setGeolocationEnabled(boolean flag) {
        synchronized (mAwSettingsLock) {
            if (mGeolocationEnabled != flag) {
                mGeolocationEnabled = flag;
            }
        }
    }

    /**
     * @return Returns if geolocation is currently enabled.
     */
    boolean getGeolocationEnabled() {
        synchronized (mAwSettingsLock) {
            return mGeolocationEnabled;
        }
    }

    public void setWebContents(int nativeWebContents) {
        nativeSetWebContents(mNativeAwSettings, nativeWebContents);
    }

    private native int nativeInit(int webContentsPtr);

    private native void nativeDestroy(int nativeAwSettings);

    private native void nativeSetWebContents(int nativeAwSettings, int nativeWebContents);

    private native void nativeSetTextZoom(int nativeAwSettings, int textZoom);
}


text:
> This file is the entry and logic point of the package.
It contains mostly functions related to file system paths. They are broken up to be
small and reusable.

> The functions openLivingFile and openLivingFoder are the main entries for the actions.
The current way the functions work out could be cleaned up to use more assumtions instead
of always returning undefined is something is not what it should be. Clear up
and problems early so we don't have such a huge chain of undefined/if checks.

> Perhaps pull most of this out into a different file that is required in.

### Current Features

---

> Current features implemented:
* Saving and opening a documentation file in a new split pain.
* Opening a documentation file in markdown-preview in a new split pain.
* Toggling close previously opened living files.
* Saving and opening a folder documentation file in a new split pain.
* Opening a folder documentation file in markdown-preview in a new split pain.
* Toggling close previously opened folder living lifes.

### Unimplemented

---

> Current Unimplemented Features
* Opening source file from living document file.
* Allow some form of naming convention editor for naming living files and folders.
* Reflect source path to tree editor structure changes in the living documents folder.


text:
<!DOCTYPE html>

    <meta http-equiv="refresh" content="0;URL=../../../libc/constant.LC_MONETARY.html">

Redirecting to ../../../libc/constant.LC_MONETARY.html...


text:
<!doctype html>

	<meta charset="utf-8">
	<title>ngProgressLite demo</title>
	<link href='http://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,700,400italic' rel='stylesheet' type='text/css'>
	<link rel="stylesheet" href="../ngprogress-lite.css">

ngPROGRESS lite

Slim progress bars specially for Angular.js applications.

			<button type="button" ng-click="start()">.start()</button>
			<button type="button" ng-click="set()">.set(0.4)</button>
			<button type="button" ng-click="inc()">.inc()</button>
			<button type="button" ng-click="done()">.done()</button>

			Tweet

		Fork on Github

		Your browser does not support iframe.


text:
import mock
from openstack.object_store.v1 import container
from openstack.tests.unit import test_proxy_base

from rackspace.object_store.v1 import _proxy

class TestObjectStoreProxy(test_proxy_base.TestProxyBase):

    def setUp(self):
        super(TestObjectStoreProxy, self).setUp()
        self.session = mock.Mock()

        self.proxy = _proxy.Proxy(self.session)

class Test_bulk_delete(TestObjectStoreProxy):

    @mock.patch("rackspace.object_store.v1.bulk_delete.BulkDelete.delete")
    def test(self, mock_delete):
        self.proxy.objects = mock.Mock()
        container_name = "Clark"
        object_name = "Addison"
        rv = [container.Container.new(name=object_name,
                                      container=container_name)]
        self.proxy.objects.return_value = rv

        self.proxy.bulk_delete("doesn't matter")

        expected = "/{0}/{1}".format(container_name, object_name)
        mock_delete.assert_called_with(self.session, expected)


text:
package org.osgi.framework.connect;

import java.util.Optional;

import org.osgi.annotation.versioning.ConsumerType;
import org.osgi.framework.Bundle;
import org.osgi.framework.FrameworkUtil;

/**
 * A helper for the {@link FrameworkUtil} class.
 *

 * This helper provides alternative implementations for methods on
 * {@link FrameworkUtil}.
 */
@ConsumerType
public interface FrameworkUtilHelper {
	/**
	 * Returns the {@link Bundle} associated with the specified class.
	 *

	 * This helper method is called by {@link FrameworkUtil#getBundle(Class)} if
	 * the standard implementation of {@link FrameworkUtil} is unable to find
	 * the bundle.
	 *
	 * @param classFromBundle A class associated with a bundle.
	 * @return An {@code Optional} containing the {@link Bundle} for the
	 *         specified class, or an empty {@code Optional} if the specified
	 *         class is not from a bundle.
	 */
	default Optional<Bundle> getBundle(Class< ? > classFromBundle) {
		return Optional.empty();
	}
}


text:
using System.Xml.Serialization;

namespace BrightstarDB.Polaris.Configuration
{
    public class PrefixConfiguration
    {
        [XmlAttribute("prefix")]
        public string Prefix { get; set; }

        [XmlAttribute("uri")]
        public string Uri { get; set; }
    }
}


text:
#include <algorithm>
#include <iterator>
#include "driver/ihv/amd/amd_counters.h"
#include "driver/ihv/intel/intel_gl_counters.h"
#include "gl_driver.h"
#include "gl_replay.h"
#include "gl_resources.h"

vector<GPUCounter> GLReplay::EnumerateCounters()
{
  vector<GPUCounter> ret;

  ret.push_back(GPUCounter::EventGPUDuration);

  if(HasExt[ARB_occlusion_query2])
    ret.push_back(GPUCounter::SamplesPassed);

  if(HasExt[ARB_pipeline_statistics_query])
  {
    ret.push_back(GPUCounter::InputVerticesRead);
    ret.push_back(GPUCounter::IAPrimitives);
    ret.push_back(GPUCounter::GSPrimitives);
    ret.push_back(GPUCounter::RasterizerInvocations);
    ret.push_back(GPUCounter::RasterizedPrimitives);
    ret.push_back(GPUCounter::VSInvocations);
    ret.push_back(GPUCounter::TCSInvocations);
    ret.push_back(GPUCounter::TESInvocations);
    ret.push_back(GPUCounter::GSInvocations);
    ret.push_back(GPUCounter::PSInvocations);
    ret.push_back(GPUCounter::CSInvocations);
  }

  if(m_pAMDCounters)
  {
    vector<GPUCounter> amdCounters = m_pAMDCounters->GetPublicCounterIds();
    ret.insert(ret.end(), amdCounters.begin(), amdCounters.end());
  }

  if(m_pIntelCounters)
  {
    vector<GPUCounter> intelCounters = m_pIntelCounters->GetPublicCounterIds();
    ret.insert(ret.end(), intelCounters.begin(), intelCounters.end());
  }

  return ret;
}

CounterDescription GLReplay::DescribeCounter(GPUCounter counterID)
{
  CounterDescription desc = {};

  desc.counter = counterID;

  /////AMD//////
  if(IsAMDCounter(counterID))
  {
    if(m_pAMDCounters)
    {
      desc = m_pAMDCounters->GetCounterDescription(counterID);

      return desc;
    }
  }

  /////Intel/////
  if(IsIntelCounter(counterID))
  {
    if(m_pIntelCounters)
    {
      desc = m_pIntelCounters->GetCounterDescription(counterID);

      return desc;
    }
  }

  // FFBA5548-FBF8-405D-BA18-F0329DA370A0
  desc.uuid.words[0] = 0xFFBA5548;
  desc.uuid.words[1] = 0xFBF8405D;
  desc.uuid.words[2] = 0xBA18F032;
  desc.uuid.words[3] = 0x9DA370A0 ^ (uint32_t)counterID;

  desc.category = "OpenGL Built-in";

  switch(counterID)
  {
    case GPUCounter::EventGPUDuration:
      desc.name = "GPU Duration";
      desc.description =
          "Time taken for this event on the GPU, as measured by delta between two GPU timestamps.";
      desc.resultByteWidth = 8;
      desc.resultType = CompType::Double;
      desc.unit = CounterUnit::Seconds;
      break;
    case GPUCounter::InputVerticesRead:
      desc.name = "Input Vertices Read";
      desc.description = "Number of vertices read by input assembler.";
      desc.resultByteWidth = 8;
      desc.resultType = CompType::UInt;
      desc.unit = CounterUnit::Absolute;
      break;
    case GPUCounter::IAPrimitives:
      desc.name = "Input Primitives";
      desc.description = "Number of primitives read by the input assembler.";
      desc.resultByteWidth = 8;
      desc.resultType = CompType::UInt;
      desc.unit = CounterUnit::Absolute;
      break;
    case GPUCounter::GSPrimitives:
      desc.name = "GS Primitives";
      desc.description = "Number of primitives output by a geometry shader.";
      desc.resultByteWidth = 8;
      desc.resultType = CompType::UInt;
      desc.unit = CounterUnit::Absolute;
      break;
    case GPUCounter::RasterizerInvocations:
      desc.name = "Rasterizer Invocations";
      desc.description = "Number of primitives that were sent to the rasterizer.";
      desc.resultByteWidth = 8;
      desc.resultType = CompType::UInt;
      desc.unit = CounterUnit::Absolute;
      break;
    case GPUCounter::RasterizedPrimitives:
      desc.name = "Rasterized Primitives";
      desc.description = "Number of primitives that were rendered.";
      desc.resultByteWidth = 8;
      desc.resultType = CompType::UInt;
      desc.unit = CounterUnit::Absolute;
      break;
    case GPUCounter::SamplesPassed:
      desc.name = "Samples Passed";
      desc.description = "Number of samples that passed depth/stencil test.";
      desc.resultByteWidth = 8;
      desc.resultType = CompType::UInt;
      desc.unit = CounterUnit::Absolute;
      break;
    case GPUCounter::VSInvocations:
      desc.name = "VS Invocations";
      desc.description = "Number of times a vertex shader was invoked.";
      desc.resultByteWidth = 8;
      desc.resultType = CompType::UInt;
      desc.unit = CounterUnit::Absolute;
      break;
    case GPUCounter::GSInvocations:
      desc.name = "GS Invocations";
      desc.description = "Number of times a geometry shader was invoked.";
      desc.resultByteWidth = 8;
      desc.resultType = CompType::UInt;
      desc.unit = CounterUnit::Absolute;
      break;
    case GPUCounter::TCSInvocations:
      desc.name = "TCS Invocations";
      desc.description = "Number of times a tesselation control shader was invoked.";
      desc.resultByteWidth = 8;
      desc.resultType = CompType::UInt;
      desc.unit = CounterUnit::Absolute;
      break;
    case GPUCounter::TESInvocations:
      desc.name = "TES Invocations";
      desc.description = "Number of times a tesselation evaluation shader was invoked.";
      desc.resultByteWidth = 8;
      desc.resultType = CompType::UInt;
      desc.unit = CounterUnit::Absolute;
      break;
    case GPUCounter::PSInvocations:
      desc.name = "PS Invocations";
      desc.description = "Number of times a pixel shader was invoked.";
      desc.resultByteWidth = 8;
      desc.resultType = CompType::UInt;
      desc.unit = CounterUnit::Absolute;
      break;
    case GPUCounter::CSInvocations:
      desc.name = "CS Invocations";
      desc.description = "Number of times a compute shader was invoked.";
      desc.resultByteWidth = 8;
      desc.resultType = CompType::UInt;
      desc.unit = CounterUnit::Absolute;
      break;
    default:
      desc.name = "Unknown";
      desc.description = "Unknown counter ID";
      desc.resultByteWidth = 0;
      desc.resultType = CompType::Typeless;
      desc.unit = CounterUnit::Absolute;
      break;
  }

  return desc;
}

struct GPUQueries
{
  GLuint obj[ENUM_ARRAY_SIZE(GPUCounter)];
  uint32_t eventId;
};

struct GLCounterContext
{
  uint32_t eventStart;
  vector<GPUQueries> queries;
};

GLenum glCounters[] = {
    eGL_NONE,                                      // Undefined!!
    eGL_TIME_ELAPSED,                              // GPUCounter::EventGPUDuration
    eGL_VERTICES_SUBMITTED_ARB,                    // GPUCounter::InputVerticesRead
    eGL_PRIMITIVES_SUBMITTED_ARB,                  // GPUCounter::IAPrimitives
    eGL_GEOMETRY_SHADER_PRIMITIVES_EMITTED_ARB,    // GPUCounter::GSPrimitives
    eGL_CLIPPING_INPUT_PRIMITIVES_ARB,             // GPUCounter::RasterizerInvocations
    eGL_CLIPPING_OUTPUT_PRIMITIVES_ARB,            // GPUCounter::RasterizedPrimitives
    eGL_SAMPLES_PASSED,                            // GPUCounter::SamplesPassed
    eGL_VERTEX_SHADER_INVOCATIONS_ARB,             // GPUCounter::VSInvocations
    eGL_TESS_CONTROL_SHADER_PATCHES_ARB,           // GPUCounter::TCSInvocations
    eGL_TESS_EVALUATION_SHADER_INVOCATIONS_ARB,    // GPUCounter::TESInvocations
    eGL_GEOMETRY_SHADER_INVOCATIONS,               // GPUCounter::GSInvocations
    eGL_FRAGMENT_SHADER_INVOCATIONS_ARB,           // GPUCounter::PSInvocations
    eGL_COMPUTE_SHADER_INVOCATIONS_ARB             // GPUCounter::CSInvocations
};

void GLReplay::FillTimers(GLCounterContext &ctx, const DrawcallDescription &drawnode,
                          const vector<GPUCounter> &counters)
{
  if(drawnode.children.empty())
    return;

  for(size_t i = 0; i < drawnode.children.size(); i++)
  {
    const DrawcallDescription &d = drawnode.children[i];
    FillTimers(ctx, drawnode.children[i], counters);

    if(d.events.empty())
      continue;

    GPUQueries *queries = NULL;

    {
      ctx.queries.push_back(GPUQueries());

      queries = &ctx.queries.back();
      queries->eventId = d.eventId;
      for(auto q : indices<GPUCounter>())
        queries->obj[q] = 0;

      for(uint32_t c = 0; c < counters.size(); c++)
      {
        m_pDriver->glGenQueries(1, &queries->obj[(uint32_t)counters[c]]);
        if(m_pDriver->glGetError())
          queries->obj[(uint32_t)counters[c]] = 0;
      }
    }

    m_pDriver->ReplayLog(ctx.eventStart, d.eventId, eReplay_WithoutDraw);

    ClearGLErrors();

    // Reverse order so that Timer counter is queried the last.
    for(int32_t q = uint32_t(GPUCounter::Count) - 1; q >= 0; q--)
    {
      if(queries->obj[q])
      {
        m_pDriver->glBeginQuery(glCounters[q], queries->obj[q]);
        if(m_pDriver->glGetError())
        {
          m_pDriver->glDeleteQueries(1, &queries->obj[q]);
          queries->obj[q] = 0;
        }
      }
    }

    m_pDriver->ReplayLog(ctx.eventStart, d.eventId, eReplay_OnlyDraw);

    for(auto q : indices<GPUCounter>())
      if(queries->obj[q])
        m_pDriver->glEndQuery(glCounters[q]);

    ctx.eventStart = d.eventId + 1;
  }
}

void GLReplay::FillTimersAMD(uint32_t *eventStartID, uint32_t *sampleIndex,
                             vector<uint32_t> *eventIDs, const DrawcallDescription &drawnode)
{
  if(drawnode.children.empty())
    return;

  for(size_t i = 0; i < drawnode.children.size(); i++)
  {
    const DrawcallDescription &d = drawnode.children[i];

    FillTimersAMD(eventStartID, sampleIndex, eventIDs, drawnode.children[i]);

    if(d.events.empty())
      continue;

    eventIDs->push_back(d.eventId);

    m_pDriver->ReplayLog(*eventStartID, d.eventId, eReplay_WithoutDraw);

    m_pAMDCounters->BeginSample(*sampleIndex);

    m_pDriver->ReplayLog(*eventStartID, d.eventId, eReplay_OnlyDraw);

    m_pAMDCounters->EndSample();

    *eventStartID = d.eventId + 1;
    ++*sampleIndex;
  }
}

vector<CounterResult> GLReplay::FetchCountersAMD(const vector<GPUCounter> &counters)
{
  if(!m_pAMDCounters->BeginMeasurementMode(AMDCounters::ApiType::Ogl, m_ReplayCtx.ctx))
  {
    return vector<CounterResult>();
  }

  uint32_t sessionID = m_pAMDCounters->CreateSession();
  m_pAMDCounters->DisableAllCounters();

  // enable counters it needs
  for(size_t i = 0; i < counters.size(); i++)
  {
    // This function is only called internally, and violating this assertion means our
    // caller has invoked this method incorrectly
    RDCASSERT(IsAMDCounter(counters[i]));
    m_pAMDCounters->EnableCounter(counters[i]);
  }

  m_pAMDCounters->BeginSession(sessionID);

  uint32_t passCount = m_pAMDCounters->GetPassCount();

  uint32_t sampleIndex = 0;

  vector<uint32_t> eventIDs;

  m_pDriver->ReplayMarkers(false);

  for(uint32_t p = 0; p < passCount; p++)
  {
    m_pAMDCounters->BeginPass();
    m_pAMDCounters->BeginCommandList();
    uint32_t eventStartID = 0;

    sampleIndex = 0;

    eventIDs.clear();

    FillTimersAMD(&eventStartID, &sampleIndex, &eventIDs, m_pDriver->GetRootDraw());
    m_pAMDCounters->EndCommandList();
    m_pAMDCounters->EndPass();
  }

  m_pDriver->ReplayMarkers(true);

  m_pAMDCounters->EndSesssion(sessionID);

  std::vector<CounterResult> ret =
      m_pAMDCounters->GetCounterData(sessionID, sampleIndex, eventIDs, counters);

  m_pAMDCounters->EndMeasurementMode();

  return ret;
}

void GLReplay::FillTimersIntel(uint32_t *eventStartID, uint32_t *sampleIndex,
                               vector<uint32_t> *eventIDs, const DrawcallDescription &drawnode)
{
  if(drawnode.children.empty())
    return;

  for(size_t i = 0; i < drawnode.children.size(); i++)
  {
    const DrawcallDescription &d = drawnode.children[i];

    FillTimersIntel(eventStartID, sampleIndex, eventIDs, drawnode.children[i]);

    if(d.events.empty())
      continue;

    eventIDs->push_back(d.eventId);

    m_pDriver->ReplayLog(*eventStartID, d.eventId, eReplay_WithoutDraw);

    m_pIntelCounters->BeginSample(*sampleIndex);

    m_pDriver->ReplayLog(*eventStartID, d.eventId, eReplay_OnlyDraw);

    m_pIntelCounters->EndSample();

    *eventStartID = d.eventId + 1;
    ++*sampleIndex;
  }
}

vector<CounterResult> GLReplay::FetchCountersIntel(const vector<GPUCounter> &counters)
{
  m_pIntelCounters->DisableAllCounters();

  // enable counters it needs
  for(size_t i = 0; i < counters.size(); i++)
  {
    // This function is only called internally, and violating this assertion means our
    // caller has invoked this method incorrectly
    RDCASSERT(IsIntelCounter(counters[i]));
    m_pIntelCounters->EnableCounter(counters[i]);
  }

  m_pIntelCounters->BeginSession();

  uint32_t passCount = m_pIntelCounters->GetPassCount();

  uint32_t sampleIndex = 0;

  vector<uint32_t> eventIDs;

  m_pDriver->ReplayMarkers(false);

  for(uint32_t p = 0; p < passCount; p++)
  {
    m_pIntelCounters->BeginPass(p);

    uint32_t eventStartID = 0;

    sampleIndex = 0;

    eventIDs.clear();

    FillTimersIntel(&eventStartID, &sampleIndex, &eventIDs, m_pDriver->GetRootDraw());
    m_pIntelCounters->EndPass();
  }

  m_pDriver->ReplayMarkers(true);

  std::vector<CounterResult> ret = m_pIntelCounters->GetCounterData(sampleIndex, eventIDs, counters);

  m_pIntelCounters->EndSession();

  return ret;
}

vector<CounterResult> GLReplay::FetchCounters(const vector<GPUCounter> &allCounters)
{
  vector<CounterResult> ret;

  if(allCounters.empty())
  {
    RDCERR("No counters specified to FetchCounters");
    return ret;
  }

  MakeCurrentReplayContext(&m_ReplayCtx);

  vector<GPUCounter> counters;
  std::copy_if(allCounters.begin(), allCounters.end(), std::back_inserter(counters),
               [](const GPUCounter &c) { return IsGenericCounter(c); });

  if(m_pAMDCounters)
  {
    // Filter out the AMD counters
    vector<GPUCounter> amdCounters;
    std::copy_if(allCounters.begin(), allCounters.end(), std::back_inserter(amdCounters),
                 [](const GPUCounter &c) { return IsAMDCounter(c); });

    if(!amdCounters.empty())
    {
      ret = FetchCountersAMD(amdCounters);
    }
  }

  if(m_pIntelCounters)
  {
    // Filter out the Intel counters
    vector<GPUCounter> intelCounters;
    std::copy_if(allCounters.begin(), allCounters.end(), std::back_inserter(intelCounters),
                 [](const GPUCounter &c) { return IsIntelCounter(c); });

    if(!intelCounters.empty())
    {
      ret = FetchCountersIntel(intelCounters);
    }
  }

  if(counters.empty())
  {
    return ret;
  }

  GLCounterContext ctx;
  ctx.eventStart = 0;

  m_pDriver->ReplayMarkers(false);

  m_pDriver->SetFetchCounters(true);
  FillTimers(ctx, m_pDriver->GetRootDraw(), counters);
  m_pDriver->SetFetchCounters(false);

  m_pDriver->ReplayMarkers(true);

  double nanosToSecs = 1.0 / 1000000000.0;

  GLuint prevbind = 0;
  m_pDriver->glGetIntegerv(eGL_QUERY_BUFFER_BINDING, (GLint *)&prevbind);
  m_pDriver->glBindBuffer(eGL_QUERY_BUFFER, 0);

  for(size_t i = 0; i < ctx.queries.size(); i++)
  {
    for(uint32_t c = 0; c < counters.size(); c++)
    {
      if(ctx.queries[i].obj[(uint32_t)counters[c]])
      {
        GLuint64 data = 0;
        m_pDriver->glGetQueryObjectui64v(ctx.queries[i].obj[(uint32_t)counters[c]],
                                         eGL_QUERY_RESULT, &data);

        double duration = double(data) * nanosToSecs;

        if(m_pDriver->glGetError())
        {
          data = (uint64_t)-1;
          duration = -1;
        }

        if(counters[c] == GPUCounter::EventGPUDuration)
        {
          ret.push_back(CounterResult(ctx.queries[i].eventId, GPUCounter::EventGPUDuration, duration));
        }
        else
          ret.push_back(CounterResult(ctx.queries[i].eventId, counters[c], data));
      }
      else
        ret.push_back(CounterResult(ctx.queries[i].eventId, counters[c], (uint64_t)-1));
    }
  }

  m_pDriver->glBindBuffer(eGL_QUERY_BUFFER, prevbind);

  for(size_t i = 0; i < ctx.queries.size(); i++)
    for(uint32_t c = 0; c < counters.size(); c++)
      if(ctx.queries[i].obj[(uint32_t)counters[c]])
        m_pDriver->glDeleteQueries(1, &ctx.queries[i].obj[(uint32_t)counters[c]]);

  return ret;
}


text:
import sys, os

try:
	from PyQt4 import QtGui, QtCore
except ImportError:
	print "Cant load PyQt4"
	raise # That's fatal

from utils import *
import Traits

try:
	app
except NameError: # only declare if not yet declared
	app = None

def setupAfterAppFinishedLaunching():
	setupMainWindow()
	# app.updateWindows()
	print "setupAfterAppFinishedLaunching ready"

def getWindow(name):
	global windows
	if windows.get(name, None):
		return windows[name].nativeGuiObject
	return None

def quit():
	app.exit(None)

def setup():
	mydir = os.path.dirname(__file__)
	icon = QtGui.QIcon(mydir + '/icon.svg')
	if not icon:
		print "Cant load icon file"
	else:
		app.setWindowIcon(icon)

def buildControlAction(control):
	button = QtGui.QPushButton()
	#actionTarget = ButtonActionHandler().initWithArgs(control.attr, control.parent.subjectObject)
	#control.buttonActionHandler = actionTarget # keep ref here. button.target() is only a weakref
	# button.setTarget_(actionTarget)
	def do_update():
		button.setText(control.attr.name.decode("utf-8"))
	do_update()
	button.adjustSize() # to get height
	#button.setFrameSize_((50, button.frame().size.height))

	def update(ev = None, args = None, kwargs = None):
		# do_in_mainthread(do_update, wait=False)
		do_update()

	control.nativeGuiObject = button
	control.updateContent = update
	return control

def buildControlOneLineText(control):
	label = QtGui.QLineEdit()
	label.setTextMargins(22, 30, 22, 30)
	label.setReadOnly(True)
	control.nativeGuiObject = label
	control.getTextObj = lambda: control.subjectObject

	def update(ev = None, args = None, kwargs = None):
		control.subjectObject = control.attr.__get__(control.parent.subjectObject)
		s = "???"
		try:
			labelContent = control.getTextObj()
			s = convertToUnicode(labelContent)
		except Exception:
			sys.excepthook(*sys.exc_info())
		def do_update():
			label.setText(s)

			if control.attr.autosizeWidth:
				label.adjustSize()

			# if label.onMouseEntered or label.onMouseExited:
			# 	if getattr(label, "trackingRect", None):
			# 		label.removeTrackingRect_(label.trackingRect)
			# 	label.trackingRect = label.addTrackingRect_owner_userData_assumeInside_(label.bounds(), label, None, False)

		# do_in_mainthread(do_update, wait=False)
		do_update()

	control.updateContent = update
	return control

def buildControlClickableLabel(control):
	buildControlOneLineText(control)
	control.getTextObj = lambda: control.subjectObject(handleClick=False)

	label = control.nativeGuiObject

	def onMouseDown(ev):
		try:
			control.subjectObject(handleClick=True)
		except Exception:
			sys.excepthook(*sys.exc_info())
		control.parent.updateContent()

	label.onMouseDown = onMouseDown

	return control

def buildControlSongDisplay(control):
	# TODO ...
	buildControlOneLineText(control)
	return control

def buildControlReal(control):
	# TODO ...
	buildControlOneLineText(control)
	return control

def buildControlList(control):
	# TODO ...
	buildControlOneLineText(control)
	return control

def buildControlObject(control):
	# TODO ...
	buildControlOneLineText(control)
	return control

def buildControl(userAttr, parent):
	print "buildControl %s - %s" % (userAttr, parent)
	control = QtGuiObject()
	control.parent = parent
	control.attr = userAttr
	control.subjectObject = userAttr.__get__(parent.subjectObject)
	typeName = userAttr.getTypeClass().__name__
	assert userAttr.getTypeClass() is getattr(Traits, typeName)
	buildFuncName = "buildControl" + typeName
	buildFunc = globals().get(buildFuncName, None)
	if buildFunc:
		return buildFunc(control)
	else:
		raise NotImplementedError, "%r not handled yet" % userAttr.type

try:
	windows
except NameError:
	windows = {}

class QtGuiObject(object):
	def __init__(self):
		import gui
		self.__class__.__bases__ = (gui.GuiObject, object)

	nativeGuiObject = None
	widget = None
	grid = None

	@property
	def pos(self):
		pos = self.nativeGuiObject.pos()
		return [pos.x(), pos.y()]

	@pos.setter
	def pos(self, value):
		x, y = value
		self.nativeGuiObject.move(x, y)

	@property
	def size(self):
		size = self.nativeGuiObject.frameGeometry()
		return [size.width(), size.height()]

	@size.setter
	def size(self, value):
		self.nativeGuiObject.resize(*value)

	@property
	def innerSize(self):
		size = self.nativeGuiObject.size()
		return (size.width(), size.height())

	@property
	def autoresize(self):
		#flags = self.nativeGuiObject.autoresizingMask()
		#return (flags & NSViewMinXMargin, flags & NSViewMinYMargin, flags & NSViewWidthSizable, flags & NSViewHeightSizable)
		return (False,False,False,False)

	@autoresize.setter
	def autoresize(self, value):
		flags = 0
		#if value[0]: flags |= NSViewMinXMargin
		#if value[1]: flags |= NSViewMinYMargin
		#if value[2]: flags |= NSViewWidthSizable
		#if value[3]: flags |= NSViewHeightSizable
		#self.nativeGuiObject.setAutoresizingMask_(flags)

	def addChild(self, child):
		self.grid.addWidget(child.nativeGuiObject, 0, 0)
		# self.nativeGuiObject.addWidget(child.nativeGuiObject, 0, 0)

def setupWindow(subjectObject, windowName, title, isMainWindow=False):
	# win.show() moves window to the top level
	# if getWindow(windowName):
	# 	getWindow(windowName).makeKeyAndOrderFront_(None)
	# 	return

	win = QtGui.QMainWindow()
	win.setGeometry(200, 500, 400, 600)
	win.setWindowTitle(title)

	window = QtGuiObject()
	window.subjectObject = subjectObject

	window.widget = QtGui.QWidget(win)
	window.grid = QtGui.QGridLayout(window.widget)

	window.nativeGuiObject = win
	window.setupChilds()

	window.widget.setLayout(window.grid)
	win.setCentralWidget(window.widget)

	# win.setMinimumSize(w, h)

	win.setVisible(True) # or show() ?
	# win.makeMainWindow()

	global windows
	windows[windowName] = window

def setupMainWindow():
	print "setupMainWindow"
	from State import state
	import appinfo
	setupWindow(state, windowName="mainWindow", title=appinfo.progname, isMainWindow=True)

def setupSearchWindow():
	from Search import search
	setupWindow(search, windowName="searchWindow", title="Search")

def locateFile(filename):
	# ws = NSWorkspace.sharedWorkspace()
	# ws.selectFile_inFileViewerRootedAtPath_(filename, None)
	pass

try:
	isReload
except NameError:
	isReload = False
else:
	isReload = True

def reloadModuleHandling():
	print "GUI module reload handler ..."

	app.closeAllWindows()

	global windows
	windows.clear()

	# appDelegate = PyAppDelegate.alloc().init()
	# app.setDelegate_(appDelegate)
	# appDelegate.retain()ddd

	try:
	 	setupAfterAppFinishedLaunching()
	except Exception:
	 	sys.excepthook(*sys.exc_info())

def guiMain():
	from State import state
	for ev,args,kwargs in state.updates.read():
		try:
			global windows
			for w in windows.values():
				w.updateContent(ev,args,kwargs)
		except Exception:
			sys.excepthook(*sys.exc_info())

def main():
	global app

	app = QtGui.QApplication(sys.argv)
	setup()

	setupAfterAppFinishedLaunching()

	print "entering QtGui main loop"
	code = app.exec_()

	print "QtGui exit code:", code
	#sys.exit(code)

if isReload:
	do_in_mainthread(reloadModuleHandling)


text:
namespace llvm {
namespace codeview {

/// A locally hashed type represents a straightforward hash code of a serialized
/// record.  The record is simply serialized, and then the bytes are hashed by
/// a standard algorithm.  This is sufficient for the case of de-duplicating
/// records within a single sequence of types, because if two records both have
/// a back-reference to the same type in the same stream, they will both have
/// the same numeric value for the TypeIndex of the back reference.
struct LocallyHashedType {
  hash_code Hash;
  ArrayRef<uint8_t> RecordData;

  /// Given a type, compute its local hash.
  static LocallyHashedType hashType(ArrayRef<uint8_t> RecordData);

  /// Given a sequence of types, compute all of the local hashes.
  template <typename Range>
  static std::vector<LocallyHashedType> hashTypes(Range &&Records) {
    std::vector<LocallyHashedType> Hashes;
    Hashes.reserve(std::distance(std::begin(Records), std::end(Records)));
    for (const auto &R : Records)
      Hashes.push_back(hashType(R));

    return Hashes;
  }

  static std::vector<LocallyHashedType>
  hashTypeCollection(TypeCollection &Types) {
    std::vector<LocallyHashedType> Hashes;
    Types.ForEachRecord([&Hashes](TypeIndex TI, const CVType &Type) {
      Hashes.push_back(hashType(Type.RecordData));
    });
    return Hashes;
  }
};

enum class GlobalTypeHashAlg : uint16_t {
  SHA1 = 0, // standard 20-byte SHA1 hash
  SHA1_8    // last 8-bytes of standard SHA1 hash
};

/// A globally hashed type represents a hash value that is sufficient to
/// uniquely identify a record across multiple type streams or type sequences.
/// This works by, for any given record A which references B, replacing the
/// TypeIndex that refers to B with a previously-computed global hash for B.  As
/// this is a recursive algorithm (e.g. the global hash of B also depends on the
/// global hashes of the types that B refers to), a global hash can uniquely
/// identify identify that A occurs in another stream that has a completely
/// different graph structure.  Although the hash itself is slower to compute,
/// probing is much faster with a globally hashed type, because the hash itself
/// is considered "as good as" the original type.  Since type records can be
/// quite large, this makes the equality comparison of the hash much faster than
/// equality comparison of a full record.
struct GloballyHashedType {
  GloballyHashedType() = default;
  GloballyHashedType(StringRef H)
      : GloballyHashedType(ArrayRef<uint8_t>(H.bytes_begin(), H.bytes_end())) {}
  GloballyHashedType(ArrayRef<uint8_t> H) {
    assert(H.size() == 8);
    ::memcpy(Hash.data(), H.data(), 8);
  }
  std::array<uint8_t, 8> Hash;

  /// Given a sequence of bytes representing a record, compute a global hash for
  /// this record.  Due to the nature of global hashes incorporating the hashes
  /// of referenced records, this function requires a list of types and ids
  /// that RecordData might reference, indexable by TypeIndex.
  static GloballyHashedType hashType(ArrayRef<uint8_t> RecordData,
                                     ArrayRef<GloballyHashedType> PreviousTypes,
                                     ArrayRef<GloballyHashedType> PreviousIds);

  /// Given a sequence of bytes representing a record, compute a global hash for
  /// this record.  Due to the nature of global hashes incorporating the hashes
  /// of referenced records, this function requires a list of types and ids
  /// that RecordData might reference, indexable by TypeIndex.
  static GloballyHashedType hashType(CVType Type,
                                     ArrayRef<GloballyHashedType> PreviousTypes,
                                     ArrayRef<GloballyHashedType> PreviousIds) {
    return hashType(Type.RecordData, PreviousTypes, PreviousIds);
  }

  /// Given a sequence of combined type and ID records, compute global hashes
  /// for each of them, returning the results in a vector of hashed types.
  template <typename Range>
  static std::vector<GloballyHashedType> hashTypes(Range &&Records) {
    std::vector<GloballyHashedType> Hashes;
    for (const auto &R : Records)
      Hashes.push_back(hashType(R, Hashes, Hashes));

    return Hashes;
  }

  /// Given a sequence of combined type and ID records, compute global hashes
  /// for each of them, returning the results in a vector of hashed types.
  template <typename Range>
  static std::vector<GloballyHashedType>
  hashIds(Range &&Records, ArrayRef<GloballyHashedType> TypeHashes) {
    std::vector<GloballyHashedType> IdHashes;
    for (const auto &R : Records)
      IdHashes.push_back(hashType(R, TypeHashes, IdHashes));

    return IdHashes;
  }

  static std::vector<GloballyHashedType>
  hashTypeCollection(TypeCollection &Types) {
    std::vector<GloballyHashedType> Hashes;
    Types.ForEachRecord([&Hashes](TypeIndex TI, const CVType &Type) {
      Hashes.push_back(hashType(Type.RecordData, Hashes, Hashes));
    });
    return Hashes;
  }
};
#if defined(_MSC_VER)
// is_trivially_copyable is not available in older versions of libc++, but it is
// available in all supported versions of MSVC, so at least this gives us some
// coverage.
static_assert(std::is_trivially_copyable<GloballyHashedType>::value,
              "GloballyHashedType must be trivially copyable so that we can "
              "reinterpret_cast arrays of hash data to arrays of "
              "GloballyHashedType");
#endif
} // namespace codeview

template <> struct DenseMapInfo<codeview::LocallyHashedType> {
  static codeview::LocallyHashedType Empty;
  static codeview::LocallyHashedType Tombstone;

  static codeview::LocallyHashedType getEmptyKey() { return Empty; }

  static codeview::LocallyHashedType getTombstoneKey() { return Tombstone; }

  static unsigned getHashValue(codeview::LocallyHashedType Val) {
    return Val.Hash;
  }

  static bool isEqual(codeview::LocallyHashedType LHS,
                      codeview::LocallyHashedType RHS) {
    if (LHS.Hash != RHS.Hash)
      return false;
    return LHS.RecordData == RHS.RecordData;
  }
};

template <> struct DenseMapInfo<codeview::GloballyHashedType> {
  static codeview::GloballyHashedType Empty;
  static codeview::GloballyHashedType Tombstone;

  static codeview::GloballyHashedType getEmptyKey() { return Empty; }

  static codeview::GloballyHashedType getTombstoneKey() { return Tombstone; }

  static unsigned getHashValue(codeview::GloballyHashedType Val) {
    return *reinterpret_cast<const unsigned *>(Val.Hash.data());
  }

  static bool isEqual(codeview::GloballyHashedType LHS,
                      codeview::GloballyHashedType RHS) {
    return LHS.Hash == RHS.Hash;
  }
};

template <> struct format_provider<codeview::LocallyHashedType> {
public:
  static void format(const codeview::LocallyHashedType &V,
                     llvm::raw_ostream &Stream, StringRef Style) {
    write_hex(Stream, V.Hash, HexPrintStyle::Upper, 8);
  }
};

template <> struct format_provider<codeview::GloballyHashedType> {
public:
  static void format(const codeview::GloballyHashedType &V,
                     llvm::raw_ostream &Stream, StringRef Style) {
    for (uint8_t B : V.Hash) {
      write_hex(Stream, B, HexPrintStyle::Upper, 2);
    }
  }
};

} // namespace llvm

#endif


text:
package com.sohu.cache.inspect;

import java.util.List;

/**
 * Created by yijunzhang on 15-1-20.
 */
public interface InspectHandler {

    public void handle();

    public void setInspectorList(List<Inspector> inspectorList);
}