text:
<!DOCTYPE html>

  <meta name="project_path" value="/web/tools/workbox/_project.yaml" />
  <meta name="book_path" value="/web/tools/workbox/_book.yaml" />
  <meta name="gtm_var" data-key="docType" data-value="reference">
  <title>Source: workbox-precaching/_types.mjs</title>
  <link href="jsdoc.css" rel="stylesheet">

Source: workbox-precaching/_types.mjs

import './_version.mjs';

/**
 * @typedef {Object} InstallResult
 * @property {Array&lt;string>} updatedURLs List of URLs that were updated during
 * installation.
 * @property {Array&lt;string>} notUpdatedURLs List of URLs that were already up to
 * date.
 *
 * @memberof workbox.precaching
 */

/**
 * @typedef {Object} CleanupResult
 * @property {Array&lt;string>} deletedCacheRequests List of URLs that were deleted
 * while cleaning up the cache.
 *
 * @memberof workbox.precaching
 */

/**
 * @typedef {Object} PrecacheEntry
 * @property {string} url URL to precache.
 * @property {string} [revision] Revision information for the URL.
 *
 * @memberof workbox.precaching
 */

/**
 * The "urlManipulation" callback can be used to determine if there are any
 * additional permutations of a URL that should be used to check against
 * the available precached files.
 *
 * For example, Workbox supports checking for '/index.html' when the URL
 * '/' is provided. This callback allows additional, custom checks.
 *
 * @callback ~urlManipulation
 * @param {Object} context
 * @param {URL} context.url The request's URL.
 * @return {Array&lt;URL>} To add additional urls to test, return an Array of
 * URLs. Please note that these **should not be strings**, but URL objects.
 *
 * @memberof workbox.precaching
 */


text:
#ifndef MAGE_ECS_TAGGER_H
#define MAGE_ECS_TAGGER_H

#include "ecs/atoms.h"
#include "common.h"

///============================================================================
/// My.Awesome.Game.Engine
///============================================================================
namespace mage { namespace ecs
{

/**
 * Manager tagging enities which provides a way of grouping them.
 */
class Tagger
{
public:

   /**
    *
    */
   void mark(Entity entity, const std::string& tag)
   {
      // Assume single tag for now...
      unmark(entity);

      if (entitiesByTag_.end() == entitiesByTag_.find(tag))
      {
         entitiesByTag_.insert({ tag, std::vector<Entity>() });
      }
      entitiesByTag_.at(tag).push_back(entity);

      tagByEntity_.insert({ entity, tag });
   }

   /**
    *
    */
   void unmark(Entity entity)
   {
      auto entities = entitiesByTag_.find(getTag(entity));
      if (entitiesByTag_.end() != entities)
      {
         auto it = std::find(std::begin(entities->second), std::end(entities->second), entity);
         if (std::end(entities->second) != it)
         {
            std::swap(*it, entities->second.back());
            entities->second.pop_back();
         }
      }

      if (tagByEntity_.end() != tagByEntity_.find(entity))
      {
         tagByEntity_.erase(entity);
      }
   }

   std::string getTag(Entity entity) const
   {
      return (std::end(tagByEntity_) == tagByEntity_.find(entity)) ?
         std::string() : tagByEntity_.at(entity);
   }

   bool isTagged(Entity entity) const
   {
      return !getTag(entity).empty();
   }

   bool isTagged(Entity entity, const std::string& tag) const
   {
      return (getTag(entity) == tag);
   }

   std::vector<Entity> getTaggedEntities(const std::string& tag) const
   {
      auto pos = entitiesByTag_.find(tag);
      return (entitiesByTag_.end() == pos) ? std::vector<Entity>() : entitiesByTag_.at(tag);
   }

   void clear()
   {
      tagByEntity_.clear();
      entitiesByTag_.clear();
   }

private:
   std::unordered_map<Entity, std::string> tagByEntity_;
   std::unordered_map<std::string, std::vector<Entity>> entitiesByTag_;
};

}}
///============================================================================

#endif // MAGE_ECS_TAGGER_H

redpajama_set_name: RedPajamaGithub


text:
import React from 'react'
import PropTypes from 'prop-types'
import StreamContainer from '../../containers/StreamContainer'
import { MainView } from '../views/MainView'
import { ZeroStateCreateRelationship, ZeroStateFirstPost, ZeroStateSayHello } from '../zeros/Zeros'
import { css, media, parent } from '../../styles/jss'
import * as s from '../../styles/jso'
import { isElloAndroid } from '../../lib/jello'

// TODO: Seems like we move this up to Zeros.js?
const zeroStatesStyle = css(
  { maxWidth: 560 },
  s.p10,
  media(s.minBreak2, s.p0, parent('.UserDetails', { maxWidth: 800 })),
  media(s.minBreak4, parent('.UserDetails', { maxWidth: 820 })),
)

const ZeroStates = ({
  isLoggedIn,
  isSelf,
  hasSaidHelloTo,
  hasZeroFollowers,
  hasZeroPosts,
  onSubmitHello,
  userId,
  username,
}) =>
  (<div className={`ZeroStates ${zeroStatesStyle}`}>
    {isSelf && hasZeroPosts && !isElloAndroid() && <ZeroStateFirstPost />}
    {!isSelf && hasZeroFollowers &&
    <ZeroStateCreateRelationship {...{ userId, username }} />
      }
    {isLoggedIn && !isSelf && hasZeroPosts && !isElloAndroid() &&
    <ZeroStateSayHello
      onSubmit={() => onSubmitHello({ username })}
      hasPosted={hasSaidHelloTo}
      username={username}
    />
      }

)
ZeroStates.propTypes = {
  isLoggedIn: PropTypes.bool.isRequired,
  isSelf: PropTypes.bool.isRequired,
  hasSaidHelloTo: PropTypes.bool.isRequired,
  hasZeroFollowers: PropTypes.bool.isRequired,
  hasZeroPosts: PropTypes.bool.isRequired,
  onSubmitHello: PropTypes.func,
  userId: PropTypes.string.isRequired,
  username: PropTypes.string.isRequired,
}
ZeroStates.defaultProps = {
  onSubmitHello: null,
}

export const UserDetail = (props) => {
  // deconstruct props
  const {
    hasSaidHelloTo,
    hasZeroFollowers,
    hasZeroPosts,
    isLoggedIn,
    isPostHeaderHidden,
    isSelf,
    isSystemUser,
    onSubmitHello,
    streamAction,
    userId,
    username,
  } = props

  // construct component props
  const streamProps = { action: streamAction, isPostHeaderHidden }
  const zeroProps = {
    isLoggedIn,
    isSelf,
    hasSaidHelloTo,
    hasZeroFollowers,
    hasZeroPosts,
    onSubmitHello,
    userId,
    username,
  }
  return (
    <MainView className="UserDetail">

        {!isSystemUser && (hasZeroPosts || hasZeroFollowers) && <ZeroStates {...zeroProps} />}
        {streamAction && <StreamContainer {...streamProps} paginatorText="Load More" />}

    </MainView>
  )
}

UserDetail.propTypes = {
  hasSaidHelloTo: PropTypes.bool.isRequired,
  hasZeroFollowers: PropTypes.bool.isRequired,
  hasZeroPosts: PropTypes.bool.isRequired,
  isLoggedIn: PropTypes.bool.isRequired,
  isPostHeaderHidden: PropTypes.bool.isRequired,
  isSelf: PropTypes.bool.isRequired,
  isSystemUser: PropTypes.bool.isRequired,
  onSubmitHello: PropTypes.func,
  onTabClick: PropTypes.func,
  streamAction: PropTypes.object.isRequired,
  userId: PropTypes.string.isRequired,
  username: PropTypes.string.isRequired,
}

export const UserDetailError = ({ children }) =>
  (<MainView className="UserDetail">

      {children}

  </MainView>)

UserDetailError.propTypes = {
  children: PropTypes.node.isRequired,
}


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

<title>HSSFChart.HSSFChartType (POI API Documentation)</title>
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

PREV CLASS

NEXT CLASS

FRAMES

NO FRAMES

All Classes

SUMMARY:

NESTED |

ENUM CONSTANTS |

FIELD |

METHOD

DETAIL:

ENUM CONSTANTS |

FIELD |

METHOD

org.apache.poi.hssf.usermodel

Enum HSSFChart.HSSFChartType

java.lang.Object

java.lang.Enum<HSSFChart.HSSFChartType>

org.apache.poi.hssf.usermodel.HSSFChart.HSSFChartType

All Implemented Interfaces:

java.io.Serializable, java.lang.Comparable<HSSFChart.HSSFChartType>

Enclosing class:

HSSFChart

public static enum HSSFChart.HSSFChartType
extends java.lang.Enum<HSSFChart.HSSFChartType>

Enum Constant Summary

Enum Constants

Enum Constant and Description

Area

Bar

Line

Pie

Scatter

Unknown

Method Summary

Methods

Modifier and Type
Method and Description

abstract short
getSid()

static HSSFChart.HSSFChartType
valueOf(java.lang.String name)

Returns the enum constant of this type with the specified name.

static HSSFChart.HSSFChartType[]
values()

Returns an array containing the constants of this enum type, in
the order they are declared.

Methods inherited from class java.lang.Enum

clone, compareTo, equals, finalize, getDeclaringClass, hashCode, name, ordinal, toString, valueOf

Methods inherited from class java.lang.Object

getClass, notify, notifyAll, wait, wait, wait

Enum Constant Detail

Area

public static final HSSFChart.HSSFChartType Area

Bar

public static final HSSFChart.HSSFChartType Bar

Line

public static final HSSFChart.HSSFChartType Line

Pie

public static final HSSFChart.HSSFChartType Pie

Scatter

public static final HSSFChart.HSSFChartType Scatter

Unknown

public static final HSSFChart.HSSFChartType Unknown

Method Detail

values

public static HSSFChart.HSSFChartType[] values()

Returns an array containing the constants of this enum type, in
the order they are declared.  This method may be used to iterate
over the constants as follows:

for (HSSFChart.HSSFChartType c : HSSFChart.HSSFChartType.values())
    System.out.println(c);

Returns:

an array containing the constants of this enum type, in
the order they are declared

valueOf

public static HSSFChart.HSSFChartType valueOf(java.lang.String name)

Returns the enum constant of this type with the specified name.
The string must match exactly an identifier used to declare an
enum constant in this type.  (Extraneous whitespace characters are
not permitted.)

Parameters:

name - the name of the enum constant to be returned.

Returns:

the enum constant with the specified name

Throws:

java.lang.IllegalArgumentException - if this enum type has no constant
with the specified name

java.lang.NullPointerException - if the argument is null

getSid

public abstract short getSid()

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

PREV CLASS

NEXT CLASS

FRAMES

NO FRAMES

All Classes

SUMMARY:

NESTED |

ENUM CONSTANTS |

FIELD |

METHOD

DETAIL:

ENUM CONSTANTS |

FIELD |

METHOD

                Copyright 2016 The Apache Software Foundation or
        its licensors, as applicable.


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Zentbl. Bakt. ParasitKde, Abt. II 14: 632 (1905)

#### Original name
Rhizopus oligosporus var. oligosporus Saito, 1905

### Remarks
null


text:
import type { FieldProps } from 'formik';
import { Field, Form, Formik } from 'formik';
import React from 'react';
import { Modal } from 'react-bootstrap';

import { ModalClose, SubmitButton } from '../modal';
import { Markdown, ReactModal } from '../presentation';

export interface ICancelModalProps {
  body?: string;
  buttonText: string;
  cancelButtonText?: string;
  header: string;
  submitMethod: (reason: string, force?: boolean) => PromiseLike<any>;
  closeModal?(result?: any): void; // provided by ReactModal
  dismissModal?(rejection?: any): void; // provided by ReactModal
}

export interface ICancelModalState {
  isSubmitting: boolean;
  error: boolean;
  errorMessage?: string;
}

export interface ICancelModalValues {
  reason?: string;
}

export class CancelModal extends React.Component<ICancelModalProps, ICancelModalState> {
  public static defaultProps: Partial<ICancelModalProps> = {
    cancelButtonText: 'Cancel',
  };

  public state: ICancelModalState = { isSubmitting: false, error: false };

  public static confirm(props: ICancelModalProps): Promise<void> {
    return ReactModal.show(CancelModal, props);
  }

  private close = (args?: any): void => {
    this.props.dismissModal.apply(null, args);
  };

  private showError = (exception: string): void => {
    this.setState({
      error: true,
      errorMessage: exception,
      isSubmitting: false,
    });
  };

  private submitConfirmation = (values: ICancelModalValues): void => {
    this.setState({ isSubmitting: true });
    this.props.submitMethod(values.reason).then(this.close, this.showError);
  };

  public render() {
    const { header, body, buttonText, cancelButtonText } = this.props;
    const { isSubmitting } = this.state;

    const error = this.state.error ? (

An exception occurred:

{this.state.errorMessage || 'No details provided.'}

    ) : null;

    return (
      <Formik
        initialValues={{}}
        onSubmit={this.submitConfirmation}
        render={() => {
          const wrappedBody = body ? <Markdown message={body} trim={true} /> : null;

          return (
            <Form className="form-horizontal">
              <ModalClose dismiss={this.close} />
              <Modal.Header>
                <Modal.Title>{header}</Modal.Title>
              </Modal.Header>
              <Modal.Body>
                {wrappedBody}
                {error}

Reason

                    <Field
                      name="reason"
                      render={({ field }: FieldProps<ICancelModalValues>) => (
                        <textarea
                          className="form-control"
                          {...field}
                          rows={3}
                          placeholder="(Optional) anything that might be helpful to explain the reason for this change; HTML is okay"
                        />
                      )}
                    />

              </Modal.Body>
              <Modal.Footer>
                <button className="btn btn-default" disabled={isSubmitting} onClick={this.close} type="button">
                  {cancelButtonText}
                </button>
                <SubmitButton
                  isDisabled={isSubmitting}
                  submitting={isSubmitting}
                  isFormSubmit={true}
                  label={buttonText}
                />
              </Modal.Footer>
            </Form>
          );
        }}
      />
    );
  }
}


text:
[![npm](https://img.shields.io/npm/v/botyo.svg)](https://www.npmjs.com/package/botyo)
[![npm](https://img.shields.io/npm/dt/botyo.svg)](https://www.npmjs.com/package/botyo)
![license](https://img.shields.io/npm/l/botyo.svg)

**Botyo** is a modular bot designed for group chat rooms on Facebook. It is designed with flexibility and modularity
in mind.

## Requirements
* Node.js >= 8.3.0

## Install
`npm install --save botyo`

## Documentation

Documentation for Botyo is available here:
* [Botyo Documentation](https://ivkos.github.io/botyo)
* [Botyo API Documentation](https://ivkos.github.io/botyo-api)

## Quick Start
Please explore the [Botyo Example Project](https://github.com/ivkos/botyo-example) to jump start your project.

## Modules
> **Want to see your module for Botyo here?**
Please refer to the [Botyo API](https://github.com/ivkos/botyo-api)
for documentation on how to develop modules for Botyo.
Then submit a PR with a link to your module to have it included in this list.

### Bundles
> Bundles are collections of multiple modules.

* [Instagram Bundle](https://github.com/ivkos/botyo-bundle-instagram) -
modules providing some useful Instagram integrations

* [Persistence Bundle](https://github.com/ivkos/botyo-bundle-persistence) -
components related to the persistence of messages in a MongoDB database

### Commands
> Commands are modules that handle commands that users can send to the bot.
Commands must begin with a prefix that can be configured globally,
or on a per-chat-thread or per-user basis.

* [Ping Command](https://github.com/ivkos/botyo-command-ping) -
sends a ping in a private message to a specific person,
or makes the bot respond to the ping sent by the participants of a chat thread

* [Quote Command](https://github.com/ivkos/botyo-command-quote) -
uses Markov chains to generate quotes based on messages sent by the participants of a chat thread

* [Reverse Image Search Command](https://github.com/ivkos/botyo-command-reverse-image-search) -
runs a reverse image search on the last uploaded picture and posts links to the results
from Google Images, Bing Images, and TinEye

* [ShowMe Command](https://github.com/ivkos/botyo-command-showme) -
returns the first few images found in Google Images matching a query

* [Spotify Command](https://github.com/ivkos/botyo-command-spotify) -
posts a Spotify song to the chat

* [YouTube Command](https://github.com/ivkos/botyo-command-youtube) -
posts a YouTube video to the chat

### Filters
> Filters are modules that manipulate or filter out messages as they arrive.

### Scheduled Tasks
> A scheduled task is module that defines a task that is
executed periodically or upon the start of the bot.


text:
This control selects **[nucleic acids](lexicon-nucleic)** present in the molecular model. Every nucleic chains or individual nucleotides are selected with this command.

After selecting, it's possible to act (represent, color,...) upon these selected atoms without affecting the rest of the molecular model.

![Select nucleic](static/img/selectnuc.png)
The pre-visualization of the selection is transiently displayed when the mouse hovers and makes it possible to check the quality of the selection made.


text:
<?php

namespace Satooshi\Component\Enum;

/**
 * Enum object.
 *
 * Require EnumValueObject inteface implementation.
 *
 * @author Kitamura Satoshi <with.no.parachute@gmail.com>
 */
trait Enum
{
    use ConventionalEnum;
    use EnumObject;
    use EnumValueObjectTrait;
    use SerializableEnum;
}


text:
package com.dangdang.ddframe.job.lite.lifecycle.domain;

import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.Setter;

import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 服务器维度简明信息对象.
 *
 * @author caohao
 */
@RequiredArgsConstructor
@Getter
@Setter
public final class ServerBriefInfo implements Serializable, Comparable<ServerBriefInfo> {

    private static final long serialVersionUID = 1133149706443681483L;

    private final String serverIp;

    private final Set<String> instances = new HashSet<>();

    private final Set<String> jobNames = new HashSet<>();

    private int instancesNum;

    private int jobsNum;

    private AtomicInteger disabledJobsNum = new AtomicInteger();

    @Override
    public int compareTo(final ServerBriefInfo o) {
        return (getServerIp()).compareTo(o.getServerIp());
    }
}


text:
package org.apache.jmeter.visualizers;

import java.lang.reflect.Method;

import junit.framework.TestCase;

import org.junit.Test;

public class TestRenderAsJson extends TestCase {

    private Method prettyJSON;
    private final String TAB = ":   ";

    private String prettyJSON(String prettify) throws Exception {
        return (String) prettyJSON.invoke(null, prettify);
    }

    @Override
    protected void setUp() throws Exception {
        super.setUp();
        prettyJSON = RenderAsJSON.class.getDeclaredMethod("prettyJSON",
                String.class);
        prettyJSON.setAccessible(true);
    }

    @Test
    public void testRenderResultWithLongStringBug54826() throws Exception {
        StringBuilder json = new StringBuilder();
        json.append("\"customData\":\"");
        for (int i = 0; i < 100; i++) {
            json.append("somenotsorandomtext");
        }
        json.append("\"");

        assertEquals("{\n" + TAB + json.toString() + "\n}",
                prettyJSON("{" + json.toString() + "}"));
    }

    @Test
    public void testRenderResultSimpleObject() throws Exception {
        assertEquals("{\n}", prettyJSON("{}"));
    }

    @Test
    public void testRenderResultSimpleArray() throws Exception {
        assertEquals("[\n]", prettyJSON("[]"));
    }

    @Test
    public void testRenderResultSimpleNumber() throws Exception {
        assertEquals("42", prettyJSON("42"));
    }

    @Test
    public void testRenderResultSimpleString() throws Exception {
        assertEquals("Hello World", prettyJSON("Hello World"));
    }

    @Test
    public void testRenderResultSimpleStructure() throws Exception {
        assertEquals(
                "{\n" + TAB + "\"Hello\": \"World\", \n" + TAB + "\"more\": \n"
                        + TAB + "[\n" + TAB + TAB + "\"Something\", \n" + TAB
                        + TAB + "\"else\", \n" + TAB + "]\n}",
                prettyJSON("{\"Hello\": \"World\", \"more\": [\"Something\", \"else\", ]}"));
    }

}


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

<title>org.raspberrypi.cecil.model</title>
<meta name="date" content="2013-12-09">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

org.raspberrypi.cecil.model

Interfaces

ModelInterface

Classes

Compiler

Model

Runner

Simulator

WelcomeMusic


text:
@implementation UIDevice (AVCaptureVideoOrientation)
- (AVCaptureVideoOrientation)videoOrientation{
    return [self videoOrientationFromDeviceOrientation:[self orientation]];
}

- (AVCaptureVideoOrientation)videoOrientationFromDeviceOrientation:(UIDeviceOrientation)orientation
{
    switch (orientation)
    {
        case UIDeviceOrientationPortrait:
            return AVCaptureVideoOrientationPortrait;
        case UIDeviceOrientationPortraitUpsideDown:
            return AVCaptureVideoOrientationPortraitUpsideDown;
        case UIDeviceOrientationLandscapeRight:
            return AVCaptureVideoOrientationLandscapeLeft;
        case UIDeviceOrientationLandscapeLeft:
            return AVCaptureVideoOrientationLandscapeRight;
        default:
            return AVCaptureVideoOrientationPortrait;
    }
}

@end


text:
package com.fska.swarm.pathing;

import com.badlogic.gdx.maps.tiled.TiledMap;
import com.badlogic.gdx.maps.tiled.TiledMapTile;
import com.fska.swarm.map.MapData;

public class GreedyPathFinder extends PathFinder {

	public GreedyPathFinder(){
		super();
	}
	@Override
	public void findPath(TiledMap map, TiledMapTile start, TiledMapTile dest) {

	}

}


text:
namespace System.Runtime.InteropServices
{
    [Bridge.NonScriptable]
    [AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
    public sealed class OutAttribute : Attribute
    {
        public OutAttribute()
        {
        }
    }
}


text:
class CreateAppSettings < ActiveRecord::Migration
  def change
    create_table :app_settings do |t|
      t.string :key, limit: 50
      t.string :value

      t.timestamps
    end
    add_index :app_settings, :key
  end
end


text:
package org.g4studio.system.admin.web.tag.vo;

import org.g4studio.core.metatype.BaseVo;

/**
 * 部门值对象
 * @author XiongChun
 * @since 2010-05-22
 */
public class DeptVo extends BaseVo{
	private String deptid;
	private String deptname;
	private String parentid;
	private String icon;
	private String isroot;
	public String getDeptid() {
		return deptid;
	}
	public void setDeptid(String deptid) {
		this.deptid = deptid;
	}
	public String getDeptname() {
		return deptname;
	}
	public void setDeptname(String deptname) {
		this.deptname = deptname;
	}
	public String getParentid() {
		return parentid;
	}
	public void setParentid(String parentid) {
		this.parentid = parentid;
	}
	public String getIcon() {
		return icon;
	}
	public void setIcon(String icon) {
		this.icon = icon;
	}
	public String getIsroot() {
		return isroot;
	}
	public void setIsroot(String isroot) {
		this.isroot = isroot;
	}

}


text:
<?php

/**
 * Created by PhpStorm.
 * User: g
 * Date: 26.02.2015
 * Time: 22:35
 */
class Bb_CmsBlock_Adminhtml_Cms_Page_UpdateController extends Mage_Adminhtml_Controller_Action
{

    /**
     *
     */
    public function massUpdateSaveAction()
    {
        $params = Mage::app()->getRequest()->getParams();

        if (empty($params['page_ids'])) {
            $this->_redirect('*/cms_page/index');
            return;
        }
        $tempData = $this->getRequest()->getPost();
        $data     = array();
        foreach ($tempData as $key => $value) {
            if (!in_array($key, Mage::getModel('bb_cms/page')->fieldsUsedInMultiUpdate())) {
                continue;
            }

            if (empty($tempData[$key . '-checkbox']) || $tempData[$key . '-checkbox'] != '1') {
                continue;
            }
            $data[$key] = $value;
        }

        $pageIds = explode(',', $params['page_ids']);
        if (empty($pageIds)) {
            $this->_redirect('*/cms_page/index');
            return;

        }

        foreach ($pageIds as $id) {
            // init model and set data
            $model = Mage::getModel('cms/page')->load($id);
            if (!$model->getId() && $id) {
                Mage::getSingleton('adminhtml/session')->addError(Mage::helper('cms')->__('This page "%s" no longer exists.', $id));
            }

            foreach ($data as $key => $value) {
                $model->setData($key, $value);
            }

            // try to save it
            try {
                // save the data
                $model->save();

            } catch (Exception $e) {
                // display error message
                Mage::getSingleton('adminhtml/session')->addError(Mage::helper('cms')->__('Page %s error: %s', $id, $e->getMessage()));
            }
        }

        // display success message
        Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('cms')->__('The save process has been finished'));

        $this->_redirect('*/cms_page/index');
    }

    public function massUpdateAction()
    {
        if (!$this->_validatePages()) {
            return;
        }

        $model = Mage::getModel('cms/page');
        Mage::register('cms_page',$model);
        $this->loadLayout();
        $this->renderLayout();
    }

    /**
     * Validate selection of pages for massupdate
     *
     * @return boolean
     */
    protected function _validatePages()
    {
        return true;
    }

    /**
     * remove multiple checked entries
     */
    public function massDeleteAction()
    {

        $entityIds = $this->getRequest()->getParam('page');
        if (!is_array($entityIds)) {
            $this->_getSession()->addError($this->__('Please select page(s).'));
        } else {
            if (!empty($entityIds)) {
                try {
                    foreach ($entityIds as $entryId) {
                        $entryObj = Mage::getModel('cms/page')->load($entryId);
                        Mage::dispatchEvent('bb_cms_controller_cms_page_delete', array('page' => $entryObj));
                        $entryObj->delete();
                    }
                    $this->_getSession()->addSuccess(
                        $this->__('Total of %d record(s) have been deleted.', count($entityIds))
                    );
                } catch (Exception $e) {
                    $this->_getSession()->addError($e->getMessage());
                }
            }
        }
        $this->_redirect('*/cms_page/index');
    }

    /**
     *
     */
    public function massStatusAction()
    {
        $entityIds = (array)$this->getRequest()->getParam('page');
        $status    = (int)$this->getRequest()->getParam('status');

        $i = 0;
        foreach ($entityIds as $entryId) {
            $cmsSingleton = Mage::getModel('cms/page');
            try {
                $this->_validateMassStatus($entityIds, $status);

                $entryObj = $cmsSingleton->load($entryId);
                $entryObj->setData('is_active', $status);
                $entryObj->save();

                $i++;
            } catch (Mage_Core_Model_Exception $e) {
                $this->_getSession()->addError($e->getMessage());
            } catch (Mage_Core_Exception $e) {
                $this->_getSession()->addError($e->getMessage());
            } catch (Exception $e) {
                $this->_getSession()
                    ->addException($e, $this->__('An error occurred while updating the page(s) status.'));
            }
            unset($cmsSingleton);
        }

        if ($i > 0) {
            $this->_getSession()->addSuccess(
                $this->__('Total of %d record(s) have been updated.', $i)
            );
        }

        $this->_redirect('*/cms_page/index', array());

    }

    /**
     * Validate batch of entities before theirs status will be set
     *
     * @throws Mage_Core_Exception
     *
     * @param  array $entityIds
     * @param  int   $status
     *
     * @return void
     */
    public function _validateMassStatus(array $entityIds, $status)
    {

    }

}


text:
'use strict';

angular.module('app', ['ui.router', 'oc.lazyLoad',
    'ngSanitize', 'ngStorage', 'smart-table',
    'uuid4', 'ngCsv', 'angular-loading-bar',
    'infinite-scroll', 'chart.js', 'toaster', 'ngAnimate'
]);


text:
<?php
/**
 * Created by PhpStorm.
 * User: root
 * Date: 4/4/15
 * Time: 11:04 PM
 */
/**
 * @package     Semite LLC avista
 * @version     dashboard.php 4/4/15 root
 * @copyright   Copyright (c) 2014 Semite LLC .
 * @license     http://www.semitepayment.com/license/
 */
/**
 * Description of dashboard.php
 *
 * @author root
 */

// Heading
$_['heading_title']   = 'Dashboard';

// TEXT


text:
[Nelibur](http://nelibur.org/) - Message based web service framework on the pure WCF
=======

[![Nuget downloads](http://img.shields.io/nuget/dt/nelibur.svg)](https://www.nuget.org/packages/Nelibur/)
[![Source Browser](https://img.shields.io/badge/Browse-Source-green.svg)](http://sourcebrowser.io/Browse/Nelibur/Nelibur/)
[![GitHub license](https://img.shields.io/github/license/mashape/apistatus.svg)](https://github.com/Nelibur/Nelibur/blob/master/LICENSE)

Nelibur is message based web service framework on the pure [**WCF**](http://msdn.microsoft.com/en-us/library/ms731082.aspx). Nelibur simplifies creating high-performance and message based web services and you certainly have **all the power of the WCF**

Use the [Google Group](https://groups.google.com/forum/#!forum/nelibur) for feature requests and
follow [@Nelibur](http://twitter.com/Nelibur) for project updates.

![Nelibur on Nuget](https://raw.github.com/Nelibur/Nelibur/master/.nuget/NeliburNuget.png)

What to read
============

 * [Advantages of message based web services](https://github.com/ServiceStack/ServiceStack/wiki/Advantages-of-message-based-web-services)
 * [Getting Started with RESTful WCF Powered by Nelibur](http://www.codeproject.com/Articles/780654/Getting-Started-with-RESTful-WCF-Powered-by-Nelibu)
 * [Building RESTful Message Based Web Services with WCF](http://www.codeproject.com/Articles/712689/Building-RESTful-Message-Based-Web-Services-with-W)
 * [Building SOAP Message Based Web Services with WCF](http://www.codeproject.com/Articles/598157/Message-based-web-service-in-WCF)
 * [How to create REST message based Servcie on the pure WCF](https://github.com/Nelibur/Nelibur/wiki/How-to-create-REST-message-based-Servcie-on-pure-WCF)
 * [How to use REST message based Client](https://github.com/Nelibur/Nelibur/wiki/How-to-use-REST-message-based-Client)
 * [How to create SOAP message based Servcie on the pure WCF](https://github.com/Nelibur/Nelibur/wiki/How-to-create-message-based-web-servcie-in-WCF)
 * [How to use SOAP message based Client](https://github.com/Nelibur/Nelibur/wiki/Wcf-client-for-message-based-web-service)

Simple RESTful Message based Client
==================================

```csharp
var client = new JsonServiceClient("http://localhost:8080/webhost");

var createRequest = new CreateClientRequest
    {
        Email = "email@email.com"
    };
ClientResponse response = client.Post<ClientResponse>(createRequest);

var updateRequest = new UpdateClientRequest
    {
        Email = "new@email.com",
        Id = response.Id
    };
response = client.Put<ClientResponse>(updateRequest);

var getClientRequest = new GetClientRequest
    {
        Id = response.Id
    };
response = client.Get<ClientResponse>(getClientRequest);

var deleteRequest = new DeleteClientRequest
    {
        Id = response.Id
    };
client.Delete(deleteRequest);
```

Simple RESTful Message based service on the pure WCF
===================

```csharp
var service = new WebServiceHost(typeof(JsonServicePerCall));
service.Open();
```

`JsonServicePerCall` - is predefined service which implements following interface **IJsonService**

The **IJsonService** is flexible, stable and maintainable, we can transfer **any** data, because the service contract depends only from WCF's Message class. "The [Message](http://msdn.microsoft.com/en-us/library/system.servicemodel.channels.message.aspx) class is fundamental to Windows Communication Foundation (WCF). All communication between clients and services ultimately results in Message instances being sent and received." ([MSDN](http://msdn.microsoft.com/en-us/library/ms734675.aspx))

```csharp
[ServiceContract]
public interface IJsonService
{
    [OperationContract]
    [WebInvoke(Method = OperationType.Delete,
        UriTemplate = RestServiceMetadata.Path.Delete,
        RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
    Message Delete(Message message);

    [OperationContract]
    [WebInvoke(Method = OperationType.Delete,
        UriTemplate = RestServiceMetadata.Path.DeleteOneWay,
        RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
    void DeleteOneWay(Message message);

    [OperationContract]
    [WebGet(UriTemplate = RestServiceMetadata.Path.Get,
        RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
    Message Get(Message message);

    [OperationContract]
    [WebGet(UriTemplate = RestServiceMetadata.Path.GetOneWay,
        RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
    void GetOneWay(Message message);

    [OperationContract]
    [WebInvoke(Method = OperationType.Post,
        UriTemplate = RestServiceMetadata.Path.Post,
        RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
    Message Post(Message message);

    [OperationContract]
    [WebInvoke(Method = OperationType.Post,
        UriTemplate = RestServiceMetadata.Path.PostOneWay,
        RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
    void PostOneWay(Message message);

    [OperationContract]
    [WebInvoke(Method = OperationType.Put,
        UriTemplate = RestServiceMetadata.Path.Put,
        RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
    Message Put(Message message);

    [OperationContract]
    [WebInvoke(Method = OperationType.Put,
        UriTemplate = RestServiceMetadata.Path.PutOneWay,
        RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
    void PutOneWay(Message message);
}
```
### Performance of CRUD operations - `JsonServiceClient`

		Method
		Duration
		Remarks

		Get
		3767 ms
		10 000 messages. Default WebServiceHost settings.
		JsonServiceClient sends messages in one thread.
		Win x64. Intel Core i7-2600 3.4 GHz.

		Post with void return
		4546 ms

		Post
		5323 ms

		Put with void return
		4521 ms

		Put
		5334 ms

		Delete with void return
		3243 ms

		Delete
		3807 ms

WCF's RESTful service

Nelibur already contains `JsonServicePerCall` service, but you can create your own custom Service, for instance

```csharp
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
public sealed class SampleWebService : IJsonService
{
    public void DeleteOneWay(Message message)
    {
        NeliburRestService.ProcessOneWay(message);
    }

    public Message Delete(Message message)
    {
        return NeliburRestService.Process(message);
    }

    public void GetOneWay(Message message)
    {
        NeliburRestService.ProcessOneWay(message);
    }

    public Message Get(Message message)
    {
        return NeliburRestService.Process(message);
    }

    public void PostOneWay(Message message)
    {
        NeliburRestService.ProcessOneWay(message);
    }

    public Message Post(Message message)
    {
        return NeliburRestService.Process(message);
    }

    public void PutOneWay(Message message)
    {
        NeliburRestService.ProcessOneWay(message);
    }

    public Message Put(Message message)
    {
        return NeliburRestService.Process(message);
    }
}
```

Request binding on appropriate Processor

```csharp
NeliburRestService.Configure(x =>
{
    x.Bind<CreateClientRequest, ClientProcessor>();
    x.Bind<UpdateClientRequest, ClientProcessor>();
    x.Bind<DeleteClientRequest, ClientProcessor>();
    x.Bind<GetClientRequest, ClientProcessor>();
});
```

ClientProcessor example

```csharp
public sealed class ClientProcessor : IPost<CreateClientRequest>,
									 IGet<GetClientRequest>,
									 IDeleteOneWay<DeleteClientRequest>,
									 IPut<UpdateClientRequest>
{
    private static List<Client> _clients = new List<Client>();

    public void DeleteOneWay(DeleteClientRequest request)
    {
        _clients = _clients.Where(x => x.Id != request.Id).ToList();
    }

    public object Get(GetClientRequest request)
    {
        Client client = _clients.Single(x => x.Id == request.Id);
        return new ClientResponse { Id = client.Id, Email = client.Email };
    }

    public object Post(CreateClientRequest request)
    {
        var client = new Client
        {
            Id = Guid.NewGuid(),
            Email = request.Email
        };
        _clients.Add(client);
        return new ClientResponse { Id = client.Id, Email = client.Email };
    }

    public object Put(UpdateClientRequest request)
    {
        Client client = _clients.Single(x => x.Id == request.Id);
        client.Email = request.Email;
        return new ClientResponse { Id = client.Id, Email = client.Email };
    }
}
```

Simple SOAP Message based Client
==================================

```csharp
var client = new SoapServiceClient("NeliburSoapService");

var createRequest = new CreateClientRequest
    {
        Email = "email@email.com"
    };
ClientResponse response = client.Post<ClientResponse>(createRequest);

var updateRequest = new UpdateClientRequest
    {
        Email = "new@email.com",
        Id = response.Id
    };
response = client.Put<ClientResponse>(updateRequest);

var getClientRequest = new GetClientRequest
    {
        Id = response.Id
    };
response = client.Get<ClientResponse>(getClientRequest);

var deleteRequest = new DeleteClientRequest
    {
        Id = response.Id
    };
client.Delete(deleteRequest);
```

Simple SOAP Message based service on the pure WCF
===================
WCF's ServiceContract

```csharp
[ServiceContract]
public interface ISoapService
{

    [OperationContract(Action = SoapServiceMetadata.Action.Process,
        ReplyAction = SoapServiceMetadata.Action.ProcessResponse)]
    Message Process(Message message);

    [OperationContract(Action = SoapServiceMetadata.Action.ProcessOneWay)]
    void ProcessOneWay(Message message);
}
```

WCF's SOAP service

```csharp
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
public sealed class SampleSoapService : ISoapService
{
    public Message Process(Message message)
    {
        return NeliburSoapService.Process(message);
    }

    public void ProcessOneWay(Message message)
    {
        NeliburSoapService.ProcessOneWay(message);
    }
}
```

Request binding on appropriate Processor

```csharp
NeliburSoapService.Configure(x =>
{
    x.Bind<CreateClientRequest, ClientProcessor>();
    x.Bind<UpdateClientRequest, ClientProcessor>();
    x.Bind<DeleteClientRequest, ClientProcessor>();
    x.Bind<GetClientRequest, ClientProcessor>();
});
```

ClientProcessor is the same as for RESTful

```csharp
public sealed class ClientProcessor : IPost<CreateClientRequest>,
									 IGet<GetClientRequest>,
									 IDeleteOneWay<DeleteClientRequest>,
									 IPut<UpdateClientRequest>
{
    private static List<Client> _clients = new List<Client>();

    public void DeleteOneWay(DeleteClientRequest request)
    {
        _clients = _clients.Where(x => x.Id != request.Id).ToList();
    }

    public object Get(GetClientRequest request)
    {
        Client client = _clients.Single(x => x.Id == request.Id);
        return new ClientResponse { Id = client.Id, Email = client.Email };
    }

    public object Post(CreateClientRequest request)
    {
        var client = new Client
        {
            Id = Guid.NewGuid(),
            Email = request.Email
        };
        _clients.Add(client);
        return new ClientResponse { Id = client.Id, Email = client.Email };
    }

    public object Put(UpdateClientRequest request)
    {
        Client client = _clients.Single(x => x.Id == request.Id);
        client.Email = request.Email;
        return new ClientResponse { Id = client.Id, Email = client.Email };
    }
}
```

Contributing
===================

### Before you do anything else

 * Before reporting an issue or creating a pull request, please discuss it in the [Google Group](https://groups.google.com/group/nelibur)

### To contribute please follow these guidelines:

* Fork the project
* Spaces, not Tabs and no regions
* Make a branch for each thing you want to do
* Send a pull request


text:
module Profiler
  class Profile
    # Create a profile based off modified files in the current directory
    # If append is true, it will append to the matching profile
    # If append is false, it will delete the current profile if one exists
    def self.create_profile(p_name, append=true)
      Profiler::Talker.say "Creating profile #{p_name} from changed files" unless append
      Profiler::Talker.say "Appending changed files to profile #{p_name}" if append

      # Remove the current profile is append is false
      Profiler::Data.remove_profile_directory(p_name) unless append
      # Create the profile directory (won't do anything if it already exists)
      Profiler::Data.create_profile_directory(p_name)

      Profiler::Scm.changed_files.each do |relative_path|
        Profiler::Talker.whisper "Adding file #{relative_path} to profile #{p_name}"
        Profiler::Data.copy_to_profile(p_name, relative_path)
      end
    end

    def self.retract_profile(p_name)
      Profiler::Talker.say "Retracting profile #{p_name}"
      Profiler::Data.backed_up_files(p_name).each do |relative_path|
        Profiler::Talker.whisper "Restoring file #{relative_path} from profile #{p_name}"
        Profiler::Data.remove_from_project(p_name, relative_path)
      end
    end

    def self.retract_profiles(p_names = nil)
      if p_names
        Profiler::Talker.whisper "Profiles #{p_names.join(',')} will be retracted"
        # Sort the profiles based off of time of application
        applied_profiles = Profiler::Data.current_profiles
        p_names.sort!{ |a,b| applied_profiles.index(a) <=> applied_profiles.index(b) }
      else
        Profiler::Talker.whisper "All applied profiles will be retracted"
        p_names = Profiler::Data.current_profiles
      end
      p_names.each do |p_name|
        Profiler::Profile.retract_profile(p_name)
      end
    end

    def self.apply_profile(p_name, append=true)
      Profiler::Profile.retract_all_profiles unless append

      # Don't re-apply a profile if it is already applied
      if Profiler::Data.current_profiles.include?(p_name)
        Talker.say "Profile #{p_name} is already applied, skipping"
        return
      end

      Profiler::Talker.say "Applying profile #{p_name}"
      Profiler::Data.profile_files(p_name).each do |relative_path|
        Profiler::Talker.whisper "Applying file #{relative_path} from profile #{p_name}"
        Profiler::Data.copy_to_project(p_name, relative_path)
      end
    end

    def self.delete_profile(p_name)
      Talker.say "Deleting profile #{p_name} from your stored profiles"
      Profiler::Data.remove_profile_directory(p_name)
    end
  end
end


text:
/**
 * THIS FILE IS AUTOGENERATED BY Makefile, do not edit directly
 *
 */

// Copyright (c) 2014 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.

'use strict';

(function() {
  if (window.web_smoothness && window.web_smoothness.FrameTimingDataCollector)
    return;
  if (!window.web_smoothness)
    window.web_smoothness = {};

  var QUIESENCE_TIMEOUT_MS = 500;

  var HISTORY_LENGTH_MS = 15000;

  /*
   * We need setImmediate in order to schedule a task right after the
   * commit yields. setTimeout(,0) has a 1-2ms gap, and mutation observers
   * actually push out rendering.
   */
  function createSetImmediateFunction(window) {
    var queue = [];
    window.addEventListener('message', function(m) {
      if (!m.data.drainPlease)
        return;

      var toProcess = queue.slice();
      queue = [];
      toProcess.forEach(function(tuple) {
        tuple[0].call(tuple[1], tuple[2], tuple[3]);
      });
    })

    function setImmediate(callback, binding, arg0, arg1) {
      queue.push([callback, binding, arg0, arg1]);
      if (queue.length == 1)
        window.postMessage({drainPlease: true}, '*');
    }
    return setImmediate;
  }

  /**
   * @constructor
   */
  function PerformanceRenderEntry() {
    this.name = 'requestAnimationFrame';
    this.entryType = 'render';
    this.startTime = 0;
    this.duration = 0;
    this.sourceFrame = 0;
  }

  var nextRAFNumber = 0;

  /**
   * Simple rAF-based perf monitoring used when window.performance doesn't
   * support draw and commit timings.
   *
   * @constructor
   */
  function RAFBasedDataCollector(window, opt_bufferSize) {
    this.maxBufferSize_ = opt_bufferSize || 60;

    this.listeners_ = {'full' : [],
                       'called': []};

    this.enabled_ = false;
    this.events_ = [];
    this.raf_ = this.raf_.bind(this);
    this.window_ = window;
    this.setImmediate_ = createSetImmediateFunction(this.window_);
  }

  RAFBasedDataCollector.prototype = {
    get enabled() {
      return this.enabled_;
    },

    set enabled(enabled) {
      enabled = !!enabled;
      if (this.enabled_ == enabled)
        return;
      this.enabled_ = enabled;
      if (this.enabled_)
        this.window_.requestAnimationFrame(this.raf_);
    },

    raf_: function(frameBeginTime) {
      if (!this.enabled_)
        return;

      this.dispatchEvent('called');

      var sourceFrame = nextRAFNumber++;

      // The mostly-correct time to measure the commit in Chrome is right
      // after the main thread regains control after committing to the
      // compositor thread.
      //
      // TODO(nduca): See how it behaves on other browsers.
      //
      // Note: setTimeout doesn't work --- there's a ~1ms gap between the post
      // and the task firing.

      //setTimeout(this.measure_.bind(this, sourceFrame, frameBeginTime), 0);
      this.setImmediate_(this.measure_, this, sourceFrame, frameBeginTime);

      if (this.enabled_)
        this.window_.requestAnimationFrame(this.raf_);
    },

    measure_: function(sourceFrame, frameBeginTime) {
      var now = this.window_.performance.now();
      if (this.events_.length < this.maxBufferSize_) {
        var e = new PerformanceRenderEntry();
        e.sourceFrame = sourceFrame;
        e.startTime = frameBeginTime;
        e.duration = now - frameBeginTime;
        this.events_.push(e);
      }

      if (this.events_.length >= this.maxBufferSize_)
        this.dispatchEvent('full');
    },

    clearEvents: function() {
      this.events_ = [];
    },

    getEvents: function() {
      return this.events_;
    },

    addEventListener: function(name, cb) {
      if (!this.listeners_[name])
        throw new Error('Unsupported: ' + name);
      this.listeners_[name].push(cb);
    },

    removeEventListener: function(name, cb) {
      if (!this.listeners_[name])
        throw new Error('Unsupported: ' + name);
      var i = this.listeners_[name].indexOf(cb);
      if (i == -1)
        throw new Error('Not found');
      this.listeners_[name].splice(i, 1);
    },

    dispatchEvent: function(name) {
      this.listeners_[name].forEach(function(listener) {
        listener.call(this.window_);
      }, this);
    }
  };

  function FrameTimingInfoForRange(
      opt_rafEvents,
      opt_commitEvents, opt_compositeEvents) {
    /* Baic information: we report frame intervals instead of frame rate because
     * of how human minds perceive log scales.
     *
     * Think miles-per-gallon vs gallons-per-mile.
     *
     * When we see 14ms vs 16.66ms frame times, we think hmm
     * thats a little bit bigger. But when you see 60fps to 71fps, people
     * almost always get confused and think the change is bigger.
     */
    this.measuredTimeRange = undefined;
    this.startTime = undefined;
    this.endTime = undefined;

    // frameIntervalMs is commit rate without the frame timing api, but is
    // draw rate with it present.
    this.frameIntervalMs = undefined;

    // Details on main thread commit rate. Always available but noisy
    // without frame timing api.
    this.rafIntervalMs = undefined;

    // Details on actual true screen fps. Undefined when frame timing api is not
    // available.
    this.commitIntervalMs = undefined;
    this.drawIntervalMs = undefined;
    this.drawsPerCommit = undefined;

    // The high-precision stream for applications which require it.
    this.frameIntervalsForRange = [];

    //Private

    // The raw event stream
    this.rafEvents_ = opt_rafEvents || [];
    this.commitEvents_ = opt_commitEvents || [];
    this.compositeEvents_ = opt_compositeEvents || [];

    this.calculate_();
  }
  FrameTimingInfoForRange.prototype = {
    addMoreInfo: function(info, opt_historyLengthMs, opt_now) {
      if (!(info instanceof FrameTimingInfoForRange))
        throw new Error('Must be info');

      Array.prototype.push.apply(this.rafEvents_, info.rafEvents_);
      Array.prototype.push.apply(this.commitEvents_, info.commitEvents_);
      Array.prototype.push.apply(this.compositeEvents_, info.compositeEvents_);

      if (opt_historyLengthMs !== undefined)
        this.purgeOldEvents_(opt_historyLengthMs, opt_now);

      this.calculate_();
    },

    purgeOldEvents_: function(historyLengthMs, opt_now) {
      var now = opt_now || window.performance.now();
      var retirementTimestamp = now - historyLengthMs;
      function isStillCurrent(e) {
        return e.startTime + e.duration >= retirementTimestamp;
      }
      this.rafEvents_ = this.rafEvents_.filter(isStillCurrent);
      this.commitEvents_ = this.commitEvents_.filter(isStillCurrent);
      this.compositeEvents_ = this.compositeEvents_.filter(isStillCurrent);
    },

    getBounds_: function() {
      var min = Number.MAX_VALUE;
      var max = -Number.MAX_VALUE;
      for (var i = 0; i < this.rafEvents_.length; i++) {
        var e = this.rafEvents_[i];
        if (e.startTime < min) min = e.startTime;
        if (e.startTime + e.duration > max) max = e.startTime + e.duration;
      }
       for (var i = 0; i < this.compositeEvents_.length; i++) {
        var e = this.compositeEvents_[i];
        if (e.startTime < min) min = e.startTime;
        if (e.startTime + e.duration > max) max = e.startTime + e.duration;
      }
      if(min === Number.MAX_VALUE || max === -Number.MAX_VALUE)
        return {
          min: undefined,
          max: undefined,
          range: undefined
        };
      return {
        min: min,
        max: max,
        range: max - min
      };
    },

    computeCurrentFramesFromCurrentData_: function() {
      function Frame(commitEvent) {
        this.commitEvent = commitEvent;
        this.drawEvents = [];
      }
      var framesBySourceFrame = {};
      this.commitEvents_.forEach(function(e) {
        if (framesBySourceFrame[e.sourceFrame]){
          return;
        }
        framesBySourceFrame[e.sourceFrame] = new Frame(e);
      });

      this.compositeEvents_.forEach(function(e) {
        // The compositor may be drawing a frame whose commit event we long-ago
        // threw away.
        if (!framesBySourceFrame[e.sourceFrame])
          return;
        framesBySourceFrame[e.sourceFrame].drawEvents.push(e);
      });

      var frames = [];
      for (var sourceFrame in framesBySourceFrame)
        frames.push(framesBySourceFrame[sourceFrame]);
      return frames;
    },

    calculate_: function() {
      var bounds = this.getBounds_();
      this.measuredTimeRange = bounds.range;
      this.startTime = bounds.min;
      this.endTime = bounds.max;

      if (bounds.range === undefined) {
        return;
      }
      return this.rafEvents_.length ? this.calculateRaf_() :
          this.calculateFrameTiming_();
    },

    findIntervals_: function(v, i, a) {
      if(this.last === undefined) {
        this.last = v.startTime;
        return;
      }
      var et = v.startTime - this.last;
      this.last = v.startTime;
      return {time: v.startTime, intervalMs: et};
    },

    calculateRaf_: function() {
      // rafIntervalMs.
      if (this.rafEvents_.length) {
        this.rafIntervalMs = this.measuredTimeRange / this.rafEvents_.length;
      }
      this.frameIntervalsForRange = this.rafEvents_.map(
          this.findIntervals_, {last: undefined});
      this.frameIntervalsForRange.splice(0,1);
      this.frameIntervalMs = this.rafIntervalMs;
    },

    calculateFrameTiming_: function() {
      // commitIntervalMs.
      if (this.commitEvents_.length) {
        this.commitIntervalMs = this.measuredTimeRange /
            this.commitEvents_.length;
      } else {
        this.commitIntervalMs = 0;
      }

      // drawIntervalMs.
      if (this.compositeEvents_.length) {
        this.drawIntervalMs = this.measuredTimeRange /
            this.compositeEvents_.length;
      } else {
        this.drawIntervalMs = 0;
      }
      this.frameIntervalsForRange = this.compositeEvents_.map(
          this.findIntervals_, {last: undefined});
      this.frameIntervalsForRange.splice(0,1);

      // drawsPerCommit.
      var numDraws = 0;
      var frames = this.computeCurrentFramesFromCurrentData_();
      if (frames.length) {
        frames.forEach(function(f) {
          numDraws += f.drawEvents.length;
        });
        this.drawsPerCommit = numDraws / frames.length;
      }

      this.frameIntervalMs = this.drawIntervalMs;
    }

  };

  var instance_ = [];

  /**
   * Infrastructure for monitoring frame timing related statistics, both
   * overall and for specific interactions.
   *
   * @constructor
   */
  function FrameTimingDataCollector (opt_window, opt_document) {
    this.window_ = opt_window || window;
    this.document_ = opt_document || document;

    if (instance_[this.window_])
      throw new Error('Get FrameTimingDataCollector via FrameTimingDataCollector.getInstance()');

    this.pageVisibilityChanged_ = this.onPageVisibilityChanged_.bind(this);
    this.onQuiesenceTimeout_ = this.onQuiesenceTimeout_.bind(this);
    this.onRafBufferFull_ = this.onRafBufferFull_.bind(this);
    this.onFrameTimingBufferFull_ = this.onFrameTimingBufferFull_.bind(this);
    this.handleEventTrigger_ = this.handleEventTrigger_.bind(this);

    this.hasFrameTimingApi_ = this.window_.PerformanceRenderTiming !== undefined;

    if (!this.hasFrameTimingApi_) {
      this.rafCommitMonitor_ = new RAFBasedDataCollector(this.window_);
      this.rafCommitMonitor_.addEventListener('full', this.onRafBufferFull_);
    } else {
      this.rafCommitMonitor_ = undefined;
    }

    // Listeners, etc.
    this.listeners_ = {'got-data' : [],
                       'did-quiesce' : [],
                       'cancel-promises' : [] };

    // Raw data.
    this.enabled_ = 0;
    this.historyLengthMs_ = 15000;
    this.currentQuiesenceTimeout_ = undefined;
    this.rafCommitEvents_ = [];
    this.compositorCommitEvents_ = [];
    this.compositorDrawEvents_ = [];
  }

  FrameTimingDataCollector.getInstance = function(opt_window) {
    var win = opt_window || window;
    if (!instance_[win])
      instance_[win] = new FrameTimingDataCollector(win);
    return instance_[win];
  };

  FrameTimingDataCollector.destroyInstance = function(opt_window) {
    var win = opt_window || window;
    if (instance_[win])
      instance_[win].destroy(win);
  };

  FrameTimingDataCollector.prototype = {
    destroy: function(win) {
      while (this.enabled)
        this.decEnabledCount();
      instance_[win] = undefined;
    },

    get enabled() {
      return this.enabled_ > 0;
    },

    incEnabledCount: function() {
      ++this.enabled_;
      if (this.enabled_ != 1)
        return;

      this.rafCommitEvents_ = [];
      this.compositorCommitEvents_ = [];
      this.compositorDrawEvents_ = [];

      if (!this.hasFrameTimingApi_) {
        this.rafCommitMonitor_.enabled = true;
      } else {
        this.window_.performance.addEventListener(
            'webkitframetimingbufferfull', this.onFrameTimingBufferFull_);
        this.window_.performance.webkitSetFrameTimingBufferSize(1);
      }
      this.document_.addEventListener('visibilitychange',
                                      this.pageVisibilityChanged_);
    },

    decEnabledCount: function() {
      if (this.enabled_ == 0)
        throw new Error('Error disabling monitor: not enabled');

      --this.enabled_;
      if (this.enabled_ != 0)
        return;

      this.document_.removeEventListener('visibilitychange',
                                         this.pageVisibilityChanged_);

      if (!this.hasFrameTimingApi_) {
        this.rafCommitMonitor_.enabled = false;
      } else {
        this.window_.performance.removeEventListener(
            'webkitframetimingbufferfull', this.onFrameTimingBufferFull_);
      }

      if (this.currentQuiesenceTimeout_) {
        this.window_.clearTimeout(this.currentQuiesenceTimeout_);
        this.currentQuiesenceTimeout_ = undefined;
      }
    },

    get supportsFrameTimingEvents() {
      return this.hasFrameTimingApi_;
    },

    addEventListener: function(name, cb) {
      if (!this.listeners_[name])
        throw new Error('Unsupported: ' + name);
      this.listeners_[name].push(cb);
    },

    removeEventListener: function(name, cb) {
      if (!this.listeners_[name])
        throw new Error('Unsupported: ' + name);
      var i = this.listeners_[name].indexOf(cb);
      if (i == -1)
        throw new Error('Not found');
      this.listeners_[name].splice(i, 1);
    },

    dispatchEvent: function(name) {
      this.listeners_[name].forEach(function(listener) {
        listener.call(this.window_);
      }, this);
    },

    forceCollectEvents: function() {
      this.handleEventTrigger_();
    },

    onRafBufferFull_: function() {
      this.handleEventTrigger_();
    },

    onFrameTimingBufferFull_: function() {
      var didGetEvents = this.handleEventTrigger_();
      if (didGetEvents) {
        this.window_.performance.webkitSetFrameTimingBufferSize(150);
      }
    },

    handleEventTrigger_: function() {
      var didGetEvents = this.collectEvents_();
      if (didGetEvents) {
        this.dispatchEvent('got-data');
        this.renewQuiescenceTimeout_();
      }
      return didGetEvents;
    },

    collectEvents_: function() {
      var didGetEvents = false;

      if (this.rafCommitMonitor_ && this.rafCommitMonitor_.enabled) {
        var events = this.rafCommitMonitor_.getEvents();
        this.rafCommitEvents_.push.apply(this.rafCommitEvents_, events);

        this.rafCommitMonitor_.clearEvents();

        didGetEvents = events.length > 0;
      }

      if(this.hasFrameTimingApi_) {
        var commitEvents = this.window_.performance.getEntriesByType("render");
        var drawEvents = this.window_.performance.getEntriesByType("composite");

        this.compositorCommitEvents_.push.apply(
            this.compositorCommitEvents_, commitEvents);
        this.compositorDrawEvents_.push.apply(
            this.compositorDrawEvents_, drawEvents);

        this.window_.performance.webkitClearFrameTimings();

        didGetEvents = didGetEvents || commitEvents.length > 0
            || drawEvents.length > 0;
      }

      this.purgeOldEvents_();
      return didGetEvents;
    },

    renewQuiescenceTimeout_: function() {
      // Quiesence based on timeouts isn't supported in raf mode. The issue is
      // we can't tell apart rAFs that do nothing from rAFs that do real work.
      if (!this.hasFrameTimingApi_)
        return;

      if (this.currentQuiesenceTimeout_) {
        this.window_.clearTimeout(this.currentQuiesenceTimeout_);
      }
      this.currentQuiesenceTimeout_ = this.window_.setTimeout(
          this.onQuiesenceTimeout_, QUIESENCE_TIMEOUT_MS);
    },

    onQuiesenceTimeout_: function() {
      this.currentQuiesenceTimeout_ = undefined;
      this.onQuiesence_();
    },

    onPageVisibilityChanged_: function() {
      if (document.visibilityState === 'hidden' ||
          document.visibilityState === 'unloaded') {
        this.dispatchEvent('cancel-promises');
        if (this.currentQuiesenceTimeout_) {
          this.window_.clearTimeout(this.currentQuiesenceTimeout_);
          this.currentQuiesenceTimeout_ = undefined;
        }
        this.onQuiesence_();
      }
    },

    onQuiesence_: function() {
      var didGetEvents = this.handleEventTrigger_();
      if (didGetEvents)
        return;
      this.dispatchEvent('did-quiesce');
      if (this.hasFrameTimingApi_) {
        // Wait for the next event
        this.window_.performance.webkitSetFrameTimingBufferSize(1);
        this.window_.performance.webkitClearFrameTimings();
      }
      /* TODO(nduca): It seems right that we clear the saved events, but
       * its not 100% clear to me that this is the case. */
      this.compositorCommitEvents_ = [];
      this.compositorDrawEvents_ = [];
    },

    purgeOldEvents_: function(opt_now) {
      var now = opt_now !== undefined ? opt_now : this.window_.performance.now();
      var retirementTimestamp = now - this.historyLengthMs_;

      function f(e) {
        return e.startTime + e.duration >= retirementTimestamp;
      }
      this.rafCommitEvents_ = this.rafCommitEvents_.filter(f);
      this.compositorCommitEvents_ = this.compositorCommitEvents_.filter(f);
      this.compositorDrawEvents_ = this.compositorDrawEvents_.filter(f);
    },

    /**
     * Gets a FrameTimingInfoForRange for the currently recorded amount of time
     */
    get overallFrameTimingInfo() {
      return new FrameTimingInfoForRange(this.rafCommitEvents_,
                                        this.compositorCommitEvents_,
                                        this.compositorDrawEvents_);
    },

    getOverallFrameTimingInfoSinceTime: function(startTime) {
      function f(e) {
        return e.startTime + e.duration > startTime;
      }
      return new FrameTimingInfoForRange(this.rafCommitEvents_.filter(f),
                                        this.compositorCommitEvents_.filter(f),
                                        this.compositorDrawEvents_.filter(f));
    },

    /* Returns promise that, when resolved, will tell time of the draw of the
     * first frame, as measured by requestAnimationFrame or frame timing if
     * present.
     * E.g.:
     *   element.addEventListener('click', function() {
     *     montior.requestFirstFramePromise().then(function(elapsedTime) {
     *       console.log("TTFS: ", elapsedTime);
     *     })
     *   });
     *
     * Note: this promise really can fail. When the page goes invisible,
     * for instance.
     */
    requestFirstFramePromise: function() {
      return this.hasFrameTimingApi_ ?
          this.requestFirstFramePromiseUsingFrameTiming_() :
          this.requestFirstFramePromiseUsingRAF_();
    },

    requestFirstFramePromiseUsingRAF_: function () {
      return new Promise(function(resolve, reject) {
        var startTime = this.window_.performance.now();

        var cancelRafPromise = function() {
          this.removeEventListener('cancel-promises', cancelRafPromise);
          reject(new Error("Page visibility changed"));
        }.bind(this);
        this.addEventListener('cancel-promises', cancelRafPromise);

        this.window_.requestAnimationFrame(function() {
          this.window_.requestAnimationFrame(function() {
            this.removeEventListener('cancel-promises', cancelRafPromise);
            resolve(this.window_.performance.now() - startTime);
          }.bind(this));
        }.bind(this));
      }.bind(this));
    },

    requestFirstFramePromiseUsingFrameTiming_: function () {
      return new Promise(function(resolve, reject) {
        var targetCommitEvent;
        var startTime = this.window_.performance.now();
        var frameTimingCallback;
        this.incEnabledCount();

        var cancelFrameTimingPromise = function() {
          this.removeEventListener('cancel-promises', cancelFrameTimingPromise);
          this.removeEventListener('got-data', frameTimingCallback);
          this.decEnabledCount();
          reject(new Error("Page visibility changed"));
        }.bind(this);
        this.addEventListener('cancel-promises', cancelFrameTimingPromise);

        frameTimingCallback = function() {
          if (!targetCommitEvent) {
            for(var i = 0; i < this.compositorCommitEvents_.length; ++i) {
              if (this.compositorCommitEvents_[i].startTime > startTime) {
                targetCommitEvent = this.compositorCommitEvents_[i];
                break;
              }
            }
          }
          if (!targetCommitEvent) {
            return;
          }
          var targetFrame = targetCommitEvent.sourceFrame;
          for (var j = 0; j < this.compositorDrawEvents_.length; ++j) {
            if (this.compositorDrawEvents_[j].sourceFrame >= targetFrame) {
              this.removeEventListener('cancel-promises',
                                       cancelFrameTimingPromise);
              this.removeEventListener('got-data', frameTimingCallback);
              this.decEnabledCount();
              resolve(this.compositorDrawEvents_[j].startTime - startTime);
            }
          }
        }.bind(this);

        this.addEventListener('got-data', frameTimingCallback);
        this.renewQuiescenceTimeout_();
      }.bind(this));
    }
  };

  window.web_smoothness.RAFBasedDataCollector = RAFBasedDataCollector;
  window.web_smoothness.FrameTimingDataCollector = FrameTimingDataCollector;
  window.web_smoothness.FrameTimingInfoForRange = FrameTimingInfoForRange;
})();
// Copyright (c) 2014 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.

'use strict';

(function() {
  if (window.web_smoothness && window.web_smoothness.Monitor)
    return;
  if (!window.web_smoothness)
    window.web_smoothness = {};

   var HISTORY_LENGTH_MS = 15000;

  /*
   * Does this environment support PerformanceFrameTiming events?
   * If not, fall back to using requestAnimationFrame to approximate.
   */
  function supportsFrameTimingEvents() {
    return web_smoothness.FrameTimingDataCollector.getInstance().
        supportsFrameTimingEvents;
  }

  /* Invoke 'cb' when a FrameTiming event appears on the performance timeline,
   * or requestAnimationFrame monitoring fills the buffer.
   */
  function requestGotDataNotification(cb, opt_win) {
    var cb_ = function() {
      web_smoothness.FrameTimingDataCollector.getInstance(opt_win).
          removeEventListener('got-data', cb_);
      web_smoothness.FrameTimingDataCollector.getInstance(opt_win).
          decEnabledCount();
      cb();
    };
    web_smoothness.FrameTimingDataCollector.getInstance(opt_win).
        addEventListener('got-data', cb_);
    web_smoothness.FrameTimingDataCollector.getInstance(opt_win).
        incEnabledCount();
  }

  /* Returns promise that, when resolved, will tell time of the draw of the
   * first frame, as measured by requestAnimationFrame or frameTiming if
   * present.
   * E.g.:
   *   element.addEventListener('click', function() {
   *     web_smoothness.requestFirstFramePromise().then(function(elapsedTime) {
   *       console.log("TTFF: ", elapsedTime);
   *     })
   *   });
   *
   * Note: this promise really can fail. When the page goes invisible,
   * for instance.
   */
  function requestFirstFramePromise(opt_win) {
    return web_smoothness.FrameTimingDataCollector.getInstance(opt_win).
        requestFirstFramePromise();
  }

  /* Starts monitoring FPS for a specific range. Create one of these
   * when you start an animation, then call end() when you're done.
   * This lets you have per-animation monitoring of your application, useful
   * when one team member is working on a drawer system, while another team
   * member is working on the scrolling system.
   */
  function Monitor(opt_collector, opt_dataCallback, opt_historyLengthMs) {
    /* register with monitor for events */
    this.collector_ = opt_collector ||
        web_smoothness.FrameTimingDataCollector.getInstance();
    this.dataCallback_ = opt_dataCallback;
    this.historyLengthMs_ = opt_historyLengthMs || HISTORY_LENGTH_MS;

    this.dataHandler_ = this.dataHandler_.bind(this);
    this.quiesceHandler_ = this.quiesceHandler_.bind(this);
    this.endAndGetData_ = this.endAndGetData_.bind(this);

    this.currentFrameTimingInfo_ = new web_smoothness.FrameTimingInfoForRange();
    this.collector_.addEventListener('got-data', this.dataHandler_);
    this.collector_.addEventListener('did-quiesce', this.quiesceHandler_);
    this.collector_.incEnabledCount();
  }

  Monitor.prototype = {

    /*
     * Set the data callback to be used when Monitor.end() is
     * called.
     */
    set dataCallback(dataCallback) {
      this.dataCallback_ = dataCallback;
    },

    /*
     * Returns the current frameTiming information up to this point
     */
    get frameTimingInfo() {
      if (this.collector_) {
        this.collector_.forceCollectEvents();
      }
      return this.currentFrameTimingInfo_;
    },

    /*
     * Stop monitoring and if Monitor was created with an
     * opt_dataCallback, or one was set via a call to set dataCallback,
     * invoke that callback with the collected data.
     */
    end: function() {
      this.endAndGetData_(this.dataCallback_);
    },

    /*
     * Stop monitoring. Do not call any callback with data.
     */
    abort: function() {
      this.endAndGetData_(function() {});
    },

    /*
     * Stop monitoring and invoke gotDataCallback with the collected data.
     */
    endAndGetData_: function(gotDataCallback) {
      if (!this.collector_){
        return;
      }
      /* wait until we see the current frame number make it up onscreen,
       * handling case where maybe when we call end() another frame isn't
       * necessarily coming.
       *
       * Then unregister with collector, and create FrameTimingInfoForRange for
       * the intervening time period, and pass to gotDataCallback.
       */
      if (gotDataCallback)
        gotDataCallback(this.frameTimingInfo);

      this.collector_.decEnabledCount();
      this.collector_.removeEventListener('got-data', this.dataHandler_);
      this.collector_.removeEventListener('did-quiesce', this.quiesceHandler_);
      this.collector_ = undefined;
    },

    dataHandler_: function() {
      var stats = this.currentFrameTimingInfo_.endTime ?
           this.collector_.getOverallFrameTimingInfoSinceTime(
               this.currentFrameTimingInfo_.endTime) :
           this.collector_.overallFrameTimingInfo;
      if (stats)
        this.currentFrameTimingInfo_.addMoreInfo(stats, this.historyLengthMs_);
    },

    quiesceHandler_: function() {
      this.end();
    }
  };

  window.web_smoothness.Monitor = Monitor;
  window.web_smoothness.__defineGetter__('supportsFrameTimingEvents',
                                         supportsFrameTimingEvents);
  window.web_smoothness.requestGotDataNotification = requestGotDataNotification;
  window.web_smoothness.requestFirstFramePromise = requestFirstFramePromise;
})();
// Copyright (c) 2014 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.

'use strict';

(function() {
  if (window.web_smoothness && window.web_smoothness.FPSMeter)
    return;
  if (!window.web_smoothness)
    window.web_smoothness = {};

  function FPSMeter(opt_window) {
    var iframe = document.createElement('iframe');
    iframe.classList.add('fps-meter');
    iframe.__proto__ = FPSMeter.prototype;
    iframe.constuctor = FPSMeter;
    iframe.decorate();
    requestAnimationFrame(function(){
      iframe.onAttach(opt_window);
    });
    return iframe;
  }

  FPSMeter.initWhenReady = function(opt_window) {
    var search = window.location.search.substring(1);
    if (search.indexOf('fps') == -1)
      return;
    document.addEventListener('DOMContentLoaded', function() {
      if (document.body.querySelector('fps-meter'))
        return;
      document.body.appendChild(new FPSMeter(opt_window));
    });
  }

  FPSMeter.prototype = {
    __proto__: HTMLDivElement.prototype,

    decorate: function() {
      this.classList.add('fps-meter');
    },

    onAttach: function(win) {
      var linkEl = this.contentDocument.createElement('link');
      linkEl.setAttribute('rel', 'stylesheet');
      linkEl.setAttribute('href', '../css/fps_meter_element.css');
      this.contentDocument.head.appendChild(linkEl);

      this.contentDocument.body.style.margin = '0px';
      this.contentDocument.body.appendChild(new FPSMeterElement(win));
    }
  }

  /**
   * @constructor
   */
  function FPSMeterElement(win) {
    var div = document.createElement('div');
    div.window_ = win;
    div.classList.add('fps-meter-element');
    div.__proto__ = FPSMeterElement.prototype;
    div.constuctor = FPSMeterElement;
    div.decorate();
    return div;
  }

  FPSMeterElement.prototype = {
    __proto__: HTMLDivElement.prototype,

    decorate: function() {
      this.classList.add('fps-meter-element');
      this.updateContents_ = this.updateContents_.bind(this);
      this.restartMonitor_ = this.restartMonitor_.bind(this);

      this.textBox_ = document.createElement('div');
      this.textBox_.className = 'text-box';
      this.textBox_.fpsLabel_ = document.createElement('span');
      this.textBox_.fpsLabel_.title='Frames per second';
      this.textBox_.fpsLabel_.style.color='blue';
      this.textBox_.appendChild(this.textBox_.fpsLabel_);
      this.textBox_.appendChild(document.createElement('br'));
      this.textBox_.cpsfLabel_ = document.createElement('span');
      this.textBox_.cpsfLabel_.title='Composites per source frame';
      this.textBox_.cpsfLabel_.style.color='red';
      this.textBox_.appendChild(this.textBox_.cpsfLabel_);
      this.textBox_.appendChild(document.createElement('br'));
      this.appendChild(this.textBox_);

      this.chartBox_ = document.createElement('div');
      this.chartBox_.className = 'chart-box';
      this.appendChild(this.chartBox_);

      this.chartData_ = [];
      this.restartMonitor_();
      web_smoothness.requestGotDataNotification(this.updateContents_, this.window_);
      this.setupGoogleChart_(this, this.chartOpts);
    },

    restartMonitor_: function() {
      var collector = web_smoothness.FrameTimingDataCollector.getInstance(this.window_);
      this.monitor_ = new web_smoothness.Monitor(collector, this.restartMonitor_);
    },

    updateChartOptions_: function() {
      var rect = this.chartBox_.getBoundingClientRect();
      this.chartOptions_.width = rect.width - 1;
      this.chartOptions_.height = rect.height;
    },

    setupGoogleChart_: function() {
      this.chartOptions_ = {
        title:null,
        legend: {position:"none"},
        backgroundColor:"white",
        vAxes: {0: {title: null, ticks: [0,60,120]},
                1: {title: null, ticks: [0,100]}},
        hAxis: {title: null, ticks: []}
      };
      if (web_smoothness.supportsFrameTimingEvents) {
        this.chartOptions_.series = {
          0: {targetAxisIndex: 0, color:'blue'},
          1: {targetAxisIndex: 1, color:'orange'}
        }
      } else {
        this.chartOptions_.series = {
          0: {targetAxisIndex: 0, color:'blue'}
        }
      }
      this.updateChartOptions_();

      var gscript = document.createElement('script');
      gscript.setAttribute("type", "application/javascript");
      gscript.setAttribute("id", "XX-GMPlusGoogle-XX");
      document.head.appendChild(gscript);

      // event listener setup
      gscript.addEventListener("load",
          function changeCB(params) {
              gscript.removeEventListener("load", changeCB);
              google.load("visualization", "1", {packages:["corechart"],
                  "callback": function drawChart() {
                    this.chart_ = new google.visualization.LineChart(
                        this.chartBox_);
                  }.bind(this)
              });
          }.bind(this)
      );
      gscript.src = "http://www.google.com/jsapi";
    },

    updateContents_: function() {
      web_smoothness.requestGotDataNotification(this.updateContents_,
                                                this.window_);
      var stats = this.monitor_.frameTimingInfo;
      if (!stats)
        return;

      var fps;
      if (stats.frameIntervalMs !== 0)
        fps = 1000 / stats.frameIntervalMs;
      else
        fps = 0;

      this.chartData_ = [];

      this.textBox_.fpsLabel_.innerText = "FPS: " + fps.toFixed(2);

      if (stats.drawsPerCommit) {
        this.textBox_.cpsfLabel_.innerText = "CPSF: " +
            stats.drawsPerCommit.toFixed(2);
        this.textBox_.cpsfLabel_.style.visibility = 'visible';
      } else {
        this.textBox_.cpsfLabel_.style.visibility = 'hidden';
      }

      // TODO(nduca): Compute this from the actual stored frame data, instead of
      // once a second.
      var now = window.performance.now();
      if (web_smoothness.supportsFrameTimingEvents) {
        if (this.chartData_.length == 0)
          this.chartData_.push(['Date', 'FPS', 'CPSF']);
        stats.frameIntervalsForRange.forEach(function(e) {
          this.chartData_.push([e.time, (e.intervalMs? 1000/e.intervalMs : 0),
                                stats.drawsPerCommit]);
        }.bind(this));
      } else {
        if (this.chartData_.length == 0)
          this.chartData_.push(['Date', 'FPS']);
        stats.frameIntervalsForRange.forEach(function(e) {
          this.chartData_.push([e.time, (e.intervalMs? 1000/e.intervalMs : 0)]);
        }.bind(this));
      }

      if (this.chartData_.length <= 1)
        return;

      this.chartData_.sort(function(a,b) { return a[0] - b[0]; });

      // Limit moving graph window to 15 seconds
      while ((this.chartData_[1] && this.chartData_[1][0] + 15000) < now)
        this.chartData_.splice(1,1);
      if(this.chartData_.length <= 1)
        return;

      if (this.chart_) {
        this.updateChartOptions_();
        var data = google.visualization.arrayToDataTable(this.chartData_);
        this.chart_.draw(data, this.chartOptions_);
      }
    }
  };

  window.web_smoothness.FPSMeter = FPSMeter;
})();


text:
package registry

import (
	"errors"

	"github.com/control-center/serviced/commons"
	"github.com/control-center/serviced/datastore"
	"github.com/control-center/serviced/dfs/docker"
	"github.com/control-center/serviced/domain/registry"
)

var ErrImageNotFound = errors.New("registry index: image not found")

// RegistryIndex is the index for the docker registry on the server
type RegistryIndex interface {
	FindImage(image string) (*registry.Image, error)
	PushImage(image, uuid string, hash string) error
	RemoveImage(image string) error
	SearchLibraryByTag(library string, tag string) ([]registry.Image, error)
}

var _ = RegistryIndex(&RegistryIndexClient{})

// facade has the index for this docker registry
type facade interface {
	GetRegistryImage(ctx datastore.Context, image string) (*registry.Image, error)
	SetRegistryImage(ctx datastore.Context, rImage *registry.Image) error
	DeleteRegistryImage(ctx datastore.Context, image string) error
	GetRegistryImages(ctx datastore.Context) ([]registry.Image, error)
	SearchRegistryLibraryByTag(ctx datastore.Context, library, tag string) ([]registry.Image, error)
}

// RegistryIndexClient is the facade client that runs the docker registry server
type RegistryIndexClient struct {
	ctx    datastore.Context
	facade facade
}

// NewRegistryIndexClient creates a new client for the registry index.
func NewRegistryIndexClient(f facade) *RegistryIndexClient {
	return &RegistryIndexClient{
		ctx:    datastore.Get(),
		facade: f,
	}
}

// parseImage trims the registry host:port
func (client *RegistryIndexClient) parseImage(image string) (string, error) {
	imageID, err := commons.ParseImageID(image)
	if err != nil {
		return "", err
	}
	if imageID.IsLatest() {
		imageID.Tag = docker.Latest
	}
	image = commons.ImageID{
		User: imageID.User,
		Repo: imageID.Repo,
		Tag:  imageID.Tag,
	}.String()
	return image, nil
}

// FindImage implements RegistryIndex
func (client *RegistryIndexClient) FindImage(image string) (*registry.Image, error) {
	image, err := client.parseImage(image)
	if err != nil {
		return nil, err
	}
	rImage, err := client.facade.GetRegistryImage(client.ctx, image)
	if datastore.IsErrNoSuchEntity(err) {
		return nil, ErrImageNotFound
	}
	return rImage, err
}

// PushImage implements RegistryIndex
func (client *RegistryIndexClient) PushImage(image, uuid string, hash string) error {
	imageID, err := commons.ParseImageID(image)
	if err != nil {
		return err
	}
	if imageID.IsLatest() {
		imageID.Tag = docker.Latest
	}

	rImage := &registry.Image{
		Library: imageID.User,
		Repo:    imageID.Repo,
		Tag:     imageID.Tag,
		UUID:    uuid,
		Hash:    hash,
	}
	return client.facade.SetRegistryImage(client.ctx, rImage)
}

// RemoveImage implements RegistryIndex
func (client *RegistryIndexClient) RemoveImage(image string) error {
	var err error
	if image, err = client.parseImage(image); err != nil {
		return err
	}
	return client.facade.DeleteRegistryImage(client.ctx, image)
}

// SearchLibraryByTag implements RegistryIndex
func (client *RegistryIndexClient) SearchLibraryByTag(library, tag string) ([]registry.Image, error) {
	return client.facade.SearchRegistryLibraryByTag(client.ctx, library, tag)
}


text:
using System;

namespace FastRT
{
    public interface IMemberInfo
    {
        string MemberName { get; }
        Type MemberType { get; }
        Type ObjectType { get; }
    }
}


text:
module Cheers
  class Background < Component

    attr_reader :color

    def initialize(canvas, randomizer)
      super

      @color = Avatar::BACKGROUND_COLORS.sample(random: randomizer)
    end

    def apply
      # Work around instance_eval wonkiness by declaring local variables:
      color = self.color

      colored_image(color)
    end
  end
end


text:
<?php

	namespace HairPointener\Data
	{
		require_once(dirname(__FILE__).'/IGoal.php');

		interface IGoalObserver
		{
			public function notifyTagChange(IGoal $goal);
			public function notifyDescriptionChange(IGoal $goal);
			public function notifyWeightChange(IGoal $goal);
		}
	}

?>


text:
var __memTestDone = false;

var counter = 0;

var total = 20;

var arr = [];

function add() {
    if (counter < total) {
        for (var i = 0; i < 100; i++) {
            var div = document.createElement('div');
            arr.push(div);
            document.getElementById('fizz').appendChild(div);
        }
        setTimeout(remove,0);
        counter++;
    } else {
        __memTestDone = true;
    }

}

function remove() {
    if (counter < total) {
        document.getElementById('fizz').innerHTML = "";
        setTimeout(add,0);
        counter++;
    } else {
        __memTestDone = true;
    }

}

setTimeout(add, 0);


text:
import {NgModule,Component,Input,Output,OnInit,AfterViewInit,OnDestroy,EventEmitter,Renderer,ElementRef} from '@angular/core';
import {CommonModule} from '@angular/common';
import {DomHandler} from '../dom/domhandler';

@Component({
    selector: 'p-overlayPanel',
    template: `

                <ng-content></ng-content>

    `,
    providers: [DomHandler]
})
export class OverlayPanel implements OnInit,AfterViewInit,OnDestroy {

    @Input() dismissable: boolean = true;

    @Input() showCloseIcon: boolean;

    @Input() style: any;

    @Input() styleClass: string;

    @Input() appendTo: any;

    @Output() onBeforeShow: EventEmitter<any> = new EventEmitter();

    @Output() onAfterShow: EventEmitter<any> = new EventEmitter();

    @Output() onBeforeHide: EventEmitter<any> = new EventEmitter();

    @Output() onAfterHide: EventEmitter<any> = new EventEmitter();

    container: any;

    visible: boolean = false;

    hoverCloseIcon: boolean;

    documentClickListener: any;

    selfClick: boolean;

    targetEvent: boolean;

    target: any;

    constructor(public el: ElementRef, public domHandler: DomHandler, public renderer: Renderer) {}

    ngOnInit() {
        if(this.dismissable) {
            this.documentClickListener = this.renderer.listenGlobal('body', 'click', () => {
                if(!this.selfClick&&!this.targetEvent) {
                    this.hide();
                }
                this.selfClick = false;
                this.targetEvent = false;
            });
        }
    }

    ngAfterViewInit() {
        this.container = this.el.nativeElement.children[0];
        if(this.appendTo) {
            if(this.appendTo === 'body')
                document.body.appendChild(this.container);
            else
                this.appendTo.appendChild(this.container);
        }
    }

    toggle(event,target?) {
        let currentTarget = (target||event.currentTarget||event.target);

        if(!this.target||this.target == currentTarget) {
            if(this.visible)
                this.hide();
            else
                this.show(event, target);
        }
        else {
            this.show(event, target);
        }

        if(this.dismissable) {
            this.targetEvent = true;
        }

        this.target = currentTarget;
    }

    show(event,target?) {
        if(this.dismissable) {
            this.targetEvent = true;
        }

        this.onBeforeShow.emit(null);
        let elementTarget = target||event.currentTarget||event.target;
        this.container.style.zIndex = ++DomHandler.zindex;

        if(this.visible) {
            this.domHandler.absolutePosition(this.container, elementTarget);
        }
        else {
            this.visible = true;
            this.domHandler.absolutePosition(this.container, elementTarget);
            this.domHandler.fadeIn(this.container, 250);
        }
        this.onAfterShow.emit(null);
    }

    hide() {
        if(this.visible) {
            this.onBeforeHide.emit(null);
            this.visible = false;
            this.onAfterHide.emit(null);
        }
    }

    onPanelClick() {
        if(this.dismissable) {
            this.selfClick = true;
        }
    }

    onCloseClick(event) {
        this.hide();

        if(this.dismissable) {
            this.selfClick = true;
        }

        event.preventDefault();
    }

    ngOnDestroy() {
        if(this.documentClickListener) {
            this.documentClickListener();
        }

        if(this.appendTo) {
            this.el.nativeElement.appendChild(this.container);
        }

        this.target = null;
    }
}

@NgModule({
    imports: [CommonModule],
    exports: [OverlayPanel],
    declarations: [OverlayPanel]
})
export class OverlayPanelModule { }