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

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Property</title>
<meta name="date" content="2014-09-16">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

您的浏览器已禁用 JavaScript。

跳过导航链接

概览

程序包

类

使用

树

已过时

索引

帮助

上一个类

下一个类

框架

无框架

所有类

概要:

嵌套 |

字段 |

构造器 |

方法

详细资料:

字段 |

构造器 |

方法

org.kymjs.aframe.database.utils

类 Property

java.lang.Object

org.kymjs.aframe.database.utils.Property

直接已知子类:

Id, ManyToOne, OneToMany

public class Property
extends java.lang.Object

属性 ,【非主键】的【基本数据类型】 都是属性

 创建时间 2014-8-15

版本:

1.0

作者:

michael Young (www.YangFuhai.com)

构造器概要

构造器

构造器和说明

Property()

方法概要

All Methods Instance Methods Concrete Methods

限定符和类型
方法和说明

java.lang.String
getColumn()

java.lang.Class<?>
getDataType()

java.lang.String
getDefaultValue()

java.lang.reflect.Field
getField()

java.lang.String
getFieldName()

java.lang.reflect.Method
getGet()

java.lang.reflect.Method
getSet()

<T> T
getValue(java.lang.Object obj)

获取某个实体执行某个方法的结果

void
setColumn(java.lang.String column)

void
setDataType(java.lang.Class<?> dataType)

void
setDefaultValue(java.lang.String defaultValue)

void
setField(java.lang.reflect.Field field)

void
setFieldName(java.lang.String fieldName)

void
setGet(java.lang.reflect.Method get)

void
setSet(java.lang.reflect.Method set)

void
setValue(java.lang.Object receiver,
        java.lang.Object value)

从类继承的方法 java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

构造器详细资料

Property

public Property()

方法详细资料

setValue

public void setValue(java.lang.Object receiver,
                     java.lang.Object value)

getValue

public <T> T getValue(java.lang.Object obj)

获取某个实体执行某个方法的结果

参数:

obj -

返回:

getFieldName

public java.lang.String getFieldName()

setFieldName

public void setFieldName(java.lang.String fieldName)

getColumn

public java.lang.String getColumn()

setColumn

public void setColumn(java.lang.String column)

getDefaultValue

public java.lang.String getDefaultValue()

setDefaultValue

public void setDefaultValue(java.lang.String defaultValue)

getDataType

public java.lang.Class<?> getDataType()

setDataType

public void setDataType(java.lang.Class<?> dataType)

getGet

public java.lang.reflect.Method getGet()

setGet

public void setGet(java.lang.reflect.Method get)

getSet

public java.lang.reflect.Method getSet()

setSet

public void setSet(java.lang.reflect.Method set)

getField

public java.lang.reflect.Field getField()

setField

public void setField(java.lang.reflect.Field field)

跳过导航链接

概览

程序包

类

使用

树

已过时

索引

帮助

上一个类

下一个类

框架

无框架

所有类

概要:

嵌套 |

字段 |

构造器 |

方法

详细资料:

字段 |

构造器 |

方法


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>h5netcdf.File.create_group — h5netcdf - 1.0.0</title>

  <link href="../_static/css/theme.css" rel="stylesheet">
  <link href="../_static/css/index.ff1ffe594081f20da1ef19478df9384b.css" rel="stylesheet">

  <link rel="stylesheet"
    href="../_static/vendor/fontawesome/5.13.0/css/all.min.css">
  <link rel="preload" as="font" type="font/woff2" crossorigin
    href="../_static/vendor/fontawesome/5.13.0/webfonts/fa-solid-900.woff2">
  <link rel="preload" as="font" type="font/woff2" crossorigin
    href="../_static/vendor/fontawesome/5.13.0/webfonts/fa-brands-400.woff2">

    <link rel="stylesheet" type="text/css" href="../_static/pygments.css" />
    <link rel="stylesheet" type="text/css" href="../_static/sphinx-book-theme.css?digest=84ace793992934648b4de8eed757e5a2" />

  <link rel="preload" as="script" href="../_static/js/index.be7d3bbb2ef33a8344ce.js">

    <link rel="canonical" href="https://h5netcdf.org/generated/h5netcdf.File.create_group.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="next" title="h5netcdf.File.create_variable" href="h5netcdf.File.create_variable.html" />
    <link rel="prev" title="h5netcdf.File" href="h5netcdf.File.html" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="docsearch:language" content="en">

<input type="checkbox" class="sidebar-toggle" name="__navigation" id="__navigation" aria-label="Toggle navigation sidebar">

Toggle navigation sidebar

h5netcdf - 1.0.0

<form class="bd-search d-flex align-items-center" action="../search.html" method="get">

  <input type="search" class="form-control" name="q" id="search-input" placeholder="Search the docs ..." aria-label="Search the docs ..." autocomplete="off" >
</form>

  For users

   Overview

   Feature comparison

   New API Reference

  <input checked="" class="toctree-checkbox" id="toctree-checkbox-1" name="toctree-checkbox-1" type="checkbox"/>

     h5netcdf.File

     h5netcdf.File.create_group

     h5netcdf.File.create_variable

     h5netcdf.File.resize_dimension

     h5netcdf.Group

     h5netcdf.Dimension

     h5netcdf.Variable

   Legacy API Reference

  <input class="toctree-checkbox" id="toctree-checkbox-2" name="toctree-checkbox-2" type="checkbox"/>

     h5netcdf.legacyapi.Dataset

     h5netcdf.legacyapi.Dataset.createGroup

     h5netcdf.legacyapi.Dataset.createDimension

     h5netcdf.legacyapi.Dataset.createVariable

     h5netcdf.legacyapi.Group

     h5netcdf.legacyapi.Dimension

     h5netcdf.legacyapi.Variable

  For developers

   Developers Guide

   Changelog

  Community

   GitHub issues

  Theme by the Executable Book Project

Toggle navigation

    <button id="dropdown-buttons-trigger" class="btn btn-secondary topbarbtn" aria-label="Download this page"></button>

        <button type="button"
                class="btn btn-secondary topbarbtn" title="Download source file" data-toggle="tooltip"
                data-placement="left">.rst</button>

        <button type="button" id="download-print" class="btn btn-secondary topbarbtn" title="Print to PDF"
                onclick="printPdf(this)" data-toggle="tooltip" data-placement="left">.pdf</button>

    <button id="dropdown-buttons-trigger" class="btn btn-secondary topbarbtn"
        aria-label="Connect with source repository"></button>

        <button type="button" class="btn btn-secondary topbarbtn"
                data-toggle="tooltip" data-placement="left" title="Source repository">repository</button>
        <button
                type="button" class="btn btn-secondary topbarbtn" data-toggle="tooltip" data-placement="left"
                title="Open an issue">open issue</button>
        <button
                type="button" class="btn btn-secondary topbarbtn" data-toggle="tooltip" data-placement="left"
                title="Edit this page">suggest edit</button>

<button type="button" class="btn btn-secondary topbarbtn" data-toggle="tooltip"
        data-placement="bottom" onclick="toggleFullScreen()" aria-label="Fullscreen mode"
        title="Fullscreen mode"></button>

h5netcdf.File.create_group

h5netcdf.File.create_group¶

File.create_group(name)¶

Create NetCDF4 group.

Parameters

name (str) – Name of new group.

previous

h5netcdf.File

next

h5netcdf.File.create_variable

        © Copyright 2015-2022, h5netcdf developers.

redpajama_set_name: RedPajamaGithub


text:
Cordova-keyboard is a lightweight package allowing to check the keyboard status (visible or hidden) reactively in a Meteor application.

## Installation

Add the package in your Meteor application with this command:

```
meteor add 255kb:cordova-keyboard
```

## Usage

You can either check the keyboard status by using the Session variable `isKeyboardVisible` or the global template `isKeyboardVisible`:

    Session.get('isKeyboardVisible');

Or

    {{#if isKeyboardVisible}}

    {{/if}}

    {{#unless isKeyboardVisible}}

    {{/unless}}

## Dependencies
- com.ionic.keyboard@1.0.7

## Changelog

### v1.2.0:
- switch to new Cordova plugins repository for dependency

### v1.1.1:
- default value to current keyboard state instead of false

### v1.1.0:
- remove unneeded global helper


text:
@def selectionBorderWidth 2px;
.cellTableWidget {

}

.cellTableFirstColumn {

}

.cellTableLastColumn {

}

.cellTableFooter {
	border-top: 2px solid #6f7277;
	padding: 3px 15px;
	text-align: left;
	color: #4b4a4a;
	text-shadow: #ddf 1px 1px 0;
}

.cellTableHeader {
	border-bottom: 2px solid #6f7277;
	padding: 3px 15px;
	text-align: left;
	color: #4b4a4a;
	text-shadow: #ddf 1px 1px 0;
}

.cellTableCell {
	padding: 0px 0px;
}

.cellTableFirstColumnFooter {

}

.cellTableFirstColumnHeader {

}

.cellTableLastColumnFooter {

}

.cellTableLastColumnHeader {

}

.cellTableEvenRow {
	background: #ffffff;
}

.cellTableEvenRowCell {
	border: selectionBorderWidth solid #ffffff;
}

.cellTableOddRow {
	background: #f3f7fb;
}

.cellTableOddRowCell {
	border: selectionBorderWidth solid #f3f7fb;
}

.cellTableHoveredRow {
	background: #eee;
}

.cellTableHoveredRowCell {
	border: selectionBorderWidth solid #eee;
}

.cellTableKeyboardSelectedRow {
	background: #ffc;
}

.cellTableKeyboardSelectedRowCell {
	border: selectionBorderWidth solid #ffc;
}

.cellTableSelectedRow {
	background: #628cd5;
	color: white;
	height: auto;
	overflow: auto;
}

.cellTableSelectedRowCell {
	border: selectionBorderWidth solid #628cd5;
}

/**
 * The keyboard selected cell is visible over selection.
 */
.cellTableKeyboardSelectedCell {
	border: selectionBorderWidth solid #d7dde8;
}

@sprite .cellTableLoading {
	gwt-image: 'cellTableLoading';
	margin: 30px;
}


text:
/* global require, module */
var EmberApp = require('ember-cli/lib/broccoli/ember-app');
var Funnel = require('broccoli-funnel');

module.exports = function(defaults) {
  var app = new EmberApp(defaults, {
    lessOptions: {
      paths: [
        'bower_components/bootswatch',
        'bower_components/bootstrap/less',
        'bower_components/fontawesome/less',
        'bower_components/bootstrap-select/dist/css'
      ]
    }
  });

  // Import bootstrap js
  app.import('bower_components/bootstrap/dist/js/bootstrap.js');

  // Import bootstrap-select js
  app.import('bower_components/bootstrap-select/dist/js/bootstrap-select.js');

  // Import noty js
  app.import('bower_components/noty/js/noty/packaged/jquery.noty.packaged.js');
  app.import('bower_components/noty/js/noty/themes/bootstrap.js');
  app.import('bower_components/noty/js/noty/themes/relax.js');

  // Import velocity js
  app.import('bower_components/velocity/velocity.js');
  app.import('bower_components/velocity/velocity.ui.js');

  // Import fontawesome fonts
  var fontAwesome = Funnel('bower_components/fontawesome', {
    srcDir: 'fonts',
    destDir: 'fonts'
  });

  return app.toTree([fontAwesome]);
};


text:
'use strict';

( function() {

	var listElementNames = { dt: 1, dd: 1 },
		allListElementNames = { li: 1, dt: 1, dd: 1 };

	CKEDITOR.plugins.add( 'descriptionlist', {
		lang: 'en,de,fr',
		icons: 'descriptionlist,descriptionterm,descriptionvalue', // %REMOVE_LINE_CORE%
		hidpi: true, // %REMOVE_LINE_CORE%
		init: function( editor ) {
			if ( editor.blockless ) {
				return;
			}

			var lang = editor.lang.descriptionlist,
				plugin = CKEDITOR.plugins.descriptionList;

			editor.addCommand( 'descriptionList', {
				allowedContent: 'dl dt dd',
				contextSensitive: true,

				exec: function( editor ) {
					var sel = editor.getSelection(),
						range = sel.getRanges()[ 0 ];

					if ( this.state == CKEDITOR.TRISTATE_OFF ) {
						plugin.createListFromRange( editor, range );
					} else {
						plugin.removeListFromRange( editor, range );
					}

					sel.selectRanges( [ range ] );
				},

				refresh: function( editor, path ) {
					var dl = path.contains( 'dl', 1 );
					this.setState( dl ? CKEDITOR.TRISTATE_ON : CKEDITOR.TRISTATE_OFF );
				}
			} );

			editor.addCommand( 'descriptionTerm', {
				contextSensitive: true,

				exec: function( editor ) {
					var sel = editor.getSelection(),
						range = sel.getRanges()[ 0 ];

					plugin.toggleListElementsTo( editor, range, this.state == CKEDITOR.TRISTATE_OFF ? 'dt' : 'dd' );

					sel.selectRanges( [ range ] );
				},

				refresh: refreshDtDdCallback( 'dt' )
			} );

			editor.addCommand( 'descriptionValue', {
				contextSensitive: true,

				exec: function( editor ) {
					var sel = editor.getSelection(),
						range = sel.getRanges()[ 0 ];

					plugin.toggleListElementsTo( editor, range, this.state == CKEDITOR.TRISTATE_OFF ? 'dd' : 'dt' );

					sel.selectRanges( [ range ] );
				},

				refresh: refreshDtDdCallback( 'dd' )
			} );

			editor.ui.addButton && editor.ui.addButton( 'DescriptionList', {
				label: lang.descriptionList,
				command: 'descriptionList',
				toolbar: 'list,100'
			} );
			editor.ui.addButton && editor.ui.addButton( 'DescriptionTerm', {
				label: lang.descriptionTerm,
				command: 'descriptionTerm',
				toolbar: 'list,110'
			} );
			editor.ui.addButton && editor.ui.addButton( 'descriptionValue', {
				label: lang.descriptionValue,
				command: 'descriptionValue',
				toolbar: 'list,120'
			} );

			handleEnterKey( editor );
		}
	} );

	CKEDITOR.plugins.descriptionList = {
		/**
		 * Note: range must not start in description list.
		 */
		createListFromRange: function( editor, range ) {
			var bm = range.createBookmark(),
				iterator = range.createIterator(),
				blocks = [],
				// Lists (dl,ol,ul) that we may empty when moving blocks
				// to newly created dl. These lists should be removed.
				listsToCheck = [],
				startWithDt = true,
				lastBlockParent, dl, block;

			// Check first node before block in which selection starts.
			// If it's a dl then we'll append new elements to the existing list.
			if ( ( dl = findPrecedingListContainer( range ) ) ) {
				startWithDt = listEndsWithDd( dl );
			}

			// Scan range and remember all blocks.
			while ( ( block = iterator.getNextParagraph() ) ) {
				blocks.push( block );
			}

			// If list container has not been created yet, create it now from the
			// first block.
			if ( !dl ) {
				dl = this.createListContainer( editor, blocks[ 0 ] );
			}

			// We need to remember last block's parent now, cause we'll lost it after
			// moving blocks to created list.
			if ( blocks.length > 1 ) {
				lastBlockParent = blocks[ blocks.length - 1 ].getParent();
			}

			moveBlocksToListContainer( dl, blocks, startWithDt, listsToCheck );

			// Remove list containers that we could empty when moving
			// block (in this case list items) to definition list container.
			cleanUpEmptiedLists( listsToCheck );

			if ( lastBlockParent && lastBlockParent.is( 'li' ) && isBlockEmpty( lastBlockParent ) ) {
				lastBlockParent.remove();
			}

			// If newly create list is followed by another list, merge them.
			mergeToFollowingListContainer( dl );

			range.moveToBookmark( bm );
		},

		/**
		 * Note: range must start in description list.
		 */
		removeListFromRange: function( editor, range ) {
			var bm = range.createBookmark(),
				iterator = range.createIterator(),
				block,
				firstBlock,
				blocks = [];

			// Expand range so it contains all real blocks from list
			// items that are at least partially selected.
			// We need to do that because:
			// * list item is handled as whole - even partially selected will be entirely removed,
			// * at the end we remove list items, so blocks must be extracted from them beforehand.
			expandRangeToEntireItems( range );

			while ( ( block = iterator.getNextParagraph() ) ) {
				if ( block.getAscendant( listElementNames, true ) ) {
					blocks.push( block );
				}
			}

			var block = blocks.shift(),
				currentList = block.getAscendant( 'dl' ),
				splitRange = editor.createRange(),
				listsToCheck = [ currentList ],
				itemsToRemove = [],
				list, item;

			splitRange.moveToPosition( block.getAscendant( listElementNames, true ), CKEDITOR.POSITION_BEFORE_START );
			currentList = splitRange.splitElement( currentList );
			listsToCheck.push( currentList );
			moveBlock();

			while ( ( block = blocks.shift() ) ) {
				list = block.getAscendant( 'dl' );
				if ( list.equals( currentList ) ) {
					moveBlock();
				} else {
					listsToCheck.push( list );
					splitRange.moveToPosition( block.getAscendant( listElementNames, true ), CKEDITOR.POSITION_BEFORE_START );
					currentList = splitRange.splitElement( list );
					listsToCheck.push( currentList );
					moveBlock();
				}
			}

			while ( ( item = itemsToRemove.pop() ) ) {
				item.remove();
			}

			while ( ( list = listsToCheck.pop() ) ) {
				if ( list.getParent && isBlockEmpty( list ) ) {
					list.remove();
				}
			}

			range.moveToBookmark( bm );

			function moveBlock() {
				if ( block.is( listElementNames ) ) {
					block.renameNode( 'p' );
				} else {
					itemsToRemove.push( block.getAscendant( listElementNames ) );
				}
				block.insertBefore( currentList );
			}
		},

		createListContainer: function( editor, block ) {
			var dl = editor.document.createElement( 'dl' ),
				blockParent = block.getParent(),
				list = getWrappingList( block ),
				secondList, splitRange;

			if ( list ) {
				splitRange = editor.createRange();
				splitRange.moveToPosition( block, CKEDITOR.POSITION_BEFORE_START );
				secondList = splitRange.splitElement( list );
			}

			dl.insertBefore( list ? secondList : block );

			// We need to remove block now, so if it was the list item in
			//

 we'll have an empty list which we'll be able to remove.
			block.remove();

			if ( list ) {
				// Split might result in leaving:

...
				if ( isBlockEmpty( list ) ) {
					list.remove();

				// It could also result in:

...
				// if the passed block was a block inside list item (e.g.

).
				} else if ( !block.is( 'li' ) && isBlockEmpty( blockParent ) ) {
					blockParent.remove();
				}
			}

			// Do the same as above, but for the list after created
.
			// Note - this works only in case of a collapsed range.
			if ( secondList ) {
				if ( isBlockEmpty( secondList ) ) {
					secondList.remove();
				} else if ( !block.is( 'li' ) ) {
					// But this time we have to find the list item.
					var listItem = secondList.getFirst( isElement( 'li' ) );
					if ( listItem && isBlockEmpty( listItem ) ) {
						listItem.remove();
					}
				}
			}

			return dl;
		},

		toggleListElementsTo: function( editor, range, toggleTo ) {
			var bm = range.createBookmark(),
				walkerRange = editor.createRange(),
				walker,
				isElementToToggle = isElement( toggleTo == 'dt' ? 'dd' : 'dt' ),
				elementsToToggle = [],
				node;

			walkerRange.setStartAt( range.startPath().contains( listElementNames ), CKEDITOR.POSITION_BEFORE_START );
			walkerRange.setEndAt( range.endPath().contains( listElementNames ), CKEDITOR.POSITION_AFTER_START );
			walker = new CKEDITOR.dom.walker( walkerRange );

			while ( ( node = walker.next() ) ) {
				if ( isElementToToggle( node ) ) {
					elementsToToggle.push( node );
				}
			}

			while ( ( node = elementsToToggle.pop() ) ) {
				node.renameNode( toggleTo );
			}

			range.moveToBookmark( bm );
		}
	};

	// Checks passed list containers (ul, ol, dl) and removes empty ones.
	// @param {CKEDITOR.dom.element[]} listsToCheck
	function cleanUpEmptiedLists( listsToCheck ) {
		var list;

		while ( ( list = listsToCheck.shift() ) ) {
			// It could be already removed.
			if ( list.getParent() && isBlockEmpty( list ) ) {
				list.remove();
			}
		}
	}

	// @returns {Boolean} Whether next list element should be a dt.
	function createListElement( dl, block, createDt ) {
		// It may happen that we are processing a block which already is a dt or dd
		// (e.g. we're extending a dl). Just move the block to new dl container.
		if ( block.is( listElementNames ) ) {
			block.appendTo( dl );

			return block.is( 'dd' );
		} else {
			var newBlock = block.getDocument().createElement( createDt ? 'dt' : 'dd' );
			block.moveChildren( newBlock );
			newBlock.appendTo( dl );
			block.remove();

			return !createDt;
		}
	}

	// Expand range so it contains entire list items that may initially be contained
	// only partially. For example:
	//
...

foo

[bar

ba]z
bom

...

	// after expanding:
	//
...
[
foo

bar

baz
bom
]
...

	function expandRangeToEntireItems( range ) {
		var item = range.startContainer.getAscendant( listElementNames, true );
		if ( item ) {
			range.setStartAt( item, CKEDITOR.POSITION_AFTER_START );
		}
		item = range.endContainer.getAscendant( listElementNames, true );
		if ( item ) {
			range.setEndAt( item, CKEDITOR.POSITION_BEFORE_END );
		}
	}

	// Finds list container that precedes block in which range starts.
	// @returns CKEDITOR.dom.element List container or null.
	function findPrecedingListContainer( range ) {
		var previousNode = range.startPath().block.getPrevious( isNotIgnored );

		return ( previousNode && isDl( previousNode ) ) ? previousNode : null;
	}

	// Returns dl, ol or ul element being direct parent or
	// parent's parent of passed block.
	function getWrappingList( block ) {
		var blockParent = block.getParent();

		if ( block.is( allListElementNames ) ) {
			return blockParent;
		//
 cannot be the editable, so we don't have to check whether
		// we're not leaking from it.
		} else if ( blockParent && blockParent.is( allListElementNames ) ) {
			return blockParent.getParent();
		}
	}

	// Handle enter:
	// * At the end of list item - toggle from dt to dl and vice versa.
	// * In an empty list item - exit the list.
	function handleEnterKey( editor ) {
		var cmd = editor.getCommand( 'enter' );
		if ( !cmd ) {
			return;
		}

		cmd.on( 'exec', function( evt ) {
			if ( !isSelectionInListItem( editor ) ) {
				return;
			}

			var range = editor.getSelection().getRanges()[ 0 ];

			// Collapsed selection in an empty list item - exit the list.
			if ( range.collapsed && range.checkEndOfBlock() && range.checkStartOfBlock() ) {
				editor.execCommand( 'descriptionList' );
				evt.cancel();
			}
		} );

		editor.on( 'beforeCommandExec', function( evt ) {
			if ( evt.data.name != 'enter' || !isSelectionInListItem( editor ) ) {
				return;
			}

			var range = editor.getSelection().getRanges()[ 0 ];

			// Collapsed selection at the end of list item - toggle newly created item.
			if ( range.collapsed && range.checkEndOfBlock() && !range.checkStartOfBlock() ) {
				evt.data.toggleDescriptionListBlock = true;
			}
		} );

		editor.on( 'afterCommandExec', function( evt ) {
			if ( evt.data.name == 'enter' && evt.data.toggleDescriptionListBlock  ) {
				editor.execCommand( 'descriptionTerm' );
			}
		} );
	}

	function isBlockEmpty( list ) {
		var isNotIgnored = CKEDITOR.dom.walker.ignored( true ),
			range = new CKEDITOR.dom.range( list.getDocument() ),
			walker;

		range.selectNodeContents( list );

		walker = new CKEDITOR.dom.walker( range );
		walker.evaluator = function( node ) {
			if ( node.type == CKEDITOR.NODE_ELEMENT ) {
				return node.is( CKEDITOR.dtd.$empty );
			} else {
				return isNotIgnored( node );
			}
		};

		return !walker.next();
	}

	function isElement( elementName ) {
		return function( node ) {
			return node.type == CKEDITOR.NODE_ELEMENT && node.is( elementName );
		};
	}

	function isDtOrDd( node ) {
		return node.type == CKEDITOR.NODE_ELEMENT && node.is( listElementNames );
	}

	var isNotIgnored = CKEDITOR.dom.walker.ignored( true ),
		isDl = isElement( 'dl' );

	// Checks whether selection is in list item (but not deeper - e.g. in

^

).
	function isSelectionInListItem( editor ) {
		var path = editor.elementPath();
		return path.block && path.block.is( listElementNames );
	}

	// Checks if list ends with a dd element.
	// @returns {Boolean}
	function listEndsWithDd( dl ) {
		var lastElement = dl.getLast( isDtOrDd );
		return lastElement ? lastElement.is( 'dd' ) : false;
	}

	// Looks for list container that follows the passed one
	// and if found moves children of the passed one to the following one.
	function mergeToFollowingListContainer( dl ) {
		var nextNode = dl.getNext( isNotIgnored );

		if ( nextNode && isDl( nextNode ) ) {
			dl.moveChildren( nextNode, true );
			dl.remove();
		}
	}

	// @param {CKEDITOR.dom.element} dl List container to which blocks will be appended.
	// @param {CKEDITOR.dom.element[]} blocks Blocks that will be transformed to dt/dd and appended
	// to list container.
	// @param {Boolean} startWithDt Whether first block should be transformed to dt or dd.
	// @param {CKEDITOR.dom.element[]} Array to which lists containers (ul, ol, dl) that might
	// be emptied when moving blocks will be pushed.
	function moveBlocksToListContainer( dl, blocks, startWithDt, listsToCheck ) {
		var i = 0,
			createDt = startWithDt,
			list, block;

		for ( ; i < blocks.length; ++i ) {
			block = blocks[ i ];

			list = getWrappingList( block );
			if ( list ) {
				listsToCheck.push( list );
			}

			createDt = createListElement( dl, block, createDt );
		}
	}

	function refreshDtDdCallback( dlOrDt ) {
		var names = { dl: 1 };
		names[ dlOrDt ] = 1;

		return function( editor, path ) {
			var listElement = path.contains( names, 1 );

			if ( !listElement ) {
				this.setState( CKEDITOR.TRISTATE_DISABLED );
			} else {
				this.setState( listElement.is( dlOrDt ) ? CKEDITOR.TRISTATE_ON : CKEDITOR.TRISTATE_OFF );
			}
		};
	}

} )();


text:
package report

import (
	"fmt"
	"io"
	"math"
	"path/filepath"
	"regexp"
	"sort"
	"strconv"
	"strings"
	"text/tabwriter"
	"time"

	"github.com/google/pprof/internal/graph"
	"github.com/google/pprof/internal/measurement"
	"github.com/google/pprof/internal/plugin"
	"github.com/google/pprof/profile"
)

// Output formats.
const (
	Callgrind = iota
	Comments
	Dis
	Dot
	List
	Proto
	Raw
	Tags
	Text
	TopProto
	Traces
	Tree
	WebList
)

// Options are the formatting and filtering options used to generate a
// profile.
type Options struct {
	OutputFormat int

	CumSort             bool
	CallTree            bool
	DropNegative        bool
	PositivePercentages bool
	CompactLabels       bool
	Ratio               float64
	Title               string
	ProfileLabels       []string
	ActiveFilters       []string
	NumLabelUnits       map[string]string

	NodeCount    int
	NodeFraction float64
	EdgeFraction float64

	SampleValue       func(s []int64) int64
	SampleMeanDivisor func(s []int64) int64
	SampleType        string
	SampleUnit        string // Unit for the sample data from the profile.

	OutputUnit string // Units for data formatting in report.

	Symbol     *regexp.Regexp // Symbols to include on disassembly report.
	SourcePath string         // Search path for source files.
}

// Generate generates a report as directed by the Report.
func Generate(w io.Writer, rpt *Report, obj plugin.ObjTool) error {
	o := rpt.options

	switch o.OutputFormat {
	case Comments:
		return printComments(w, rpt)
	case Dot:
		return printDOT(w, rpt)
	case Tree:
		return printTree(w, rpt)
	case Text:
		return printText(w, rpt)
	case Traces:
		return printTraces(w, rpt)
	case Raw:
		fmt.Fprint(w, rpt.prof.String())
		return nil
	case Tags:
		return printTags(w, rpt)
	case Proto:
		return rpt.prof.Write(w)
	case TopProto:
		return printTopProto(w, rpt)
	case Dis:
		return printAssembly(w, rpt, obj)
	case List:
		return printSource(w, rpt)
	case WebList:
		return printWebSource(w, rpt, obj)
	case Callgrind:
		return printCallgrind(w, rpt)
	}
	return fmt.Errorf("unexpected output format")
}

// newTrimmedGraph creates a graph for this report, trimmed according
// to the report options.
func (rpt *Report) newTrimmedGraph() (g *graph.Graph, origCount, droppedNodes, droppedEdges int) {
	o := rpt.options

	// Build a graph and refine it. On each refinement step we must rebuild the graph from the samples,
	// as the graph itself doesn't contain enough information to preserve full precision.
	visualMode := o.OutputFormat == Dot
	cumSort := o.CumSort

	// The call_tree option is only honored when generating visual representations of the callgraph.
	callTree := o.CallTree && (o.OutputFormat == Dot || o.OutputFormat == Callgrind)

	// First step: Build complete graph to identify low frequency nodes, based on their cum weight.
	g = rpt.newGraph(nil)
	totalValue, _ := g.Nodes.Sum()
	nodeCutoff := abs64(int64(float64(totalValue) * o.NodeFraction))
	edgeCutoff := abs64(int64(float64(totalValue) * o.EdgeFraction))

	// Filter out nodes with cum value below nodeCutoff.
	if nodeCutoff > 0 {
		if callTree {
			if nodesKept := g.DiscardLowFrequencyNodePtrs(nodeCutoff); len(g.Nodes) != len(nodesKept) {
				droppedNodes = len(g.Nodes) - len(nodesKept)
				g.TrimTree(nodesKept)
			}
		} else {
			if nodesKept := g.DiscardLowFrequencyNodes(nodeCutoff); len(g.Nodes) != len(nodesKept) {
				droppedNodes = len(g.Nodes) - len(nodesKept)
				g = rpt.newGraph(nodesKept)
			}
		}
	}
	origCount = len(g.Nodes)

	// Second step: Limit the total number of nodes. Apply specialized heuristics to improve
	// visualization when generating dot output.
	g.SortNodes(cumSort, visualMode)
	if nodeCount := o.NodeCount; nodeCount > 0 {
		// Remove low frequency tags and edges as they affect selection.
		g.TrimLowFrequencyTags(nodeCutoff)
		g.TrimLowFrequencyEdges(edgeCutoff)
		if callTree {
			if nodesKept := g.SelectTopNodePtrs(nodeCount, visualMode); len(g.Nodes) != len(nodesKept) {
				g.TrimTree(nodesKept)
				g.SortNodes(cumSort, visualMode)
			}
		} else {
			if nodesKept := g.SelectTopNodes(nodeCount, visualMode); len(g.Nodes) != len(nodesKept) {
				g = rpt.newGraph(nodesKept)
				g.SortNodes(cumSort, visualMode)
			}
		}
	}

	// Final step: Filter out low frequency tags and edges, and remove redundant edges that clutter
	// the graph.
	g.TrimLowFrequencyTags(nodeCutoff)
	droppedEdges = g.TrimLowFrequencyEdges(edgeCutoff)
	if visualMode {
		g.RemoveRedundantEdges()
	}
	return
}

func (rpt *Report) selectOutputUnit(g *graph.Graph) {
	o := rpt.options

	// Select best unit for profile output.
	// Find the appropriate units for the smallest non-zero sample
	if o.OutputUnit != "minimum" || len(g.Nodes) == 0 {
		return
	}
	var minValue int64

	for _, n := range g.Nodes {
		nodeMin := abs64(n.FlatValue())
		if nodeMin == 0 {
			nodeMin = abs64(n.CumValue())
		}
		if nodeMin > 0 && (minValue == 0 || nodeMin < minValue) {
			minValue = nodeMin
		}
	}
	maxValue := rpt.total
	if minValue == 0 {
		minValue = maxValue
	}

	if r := o.Ratio; r > 0 && r != 1 {
		minValue = int64(float64(minValue) * r)
		maxValue = int64(float64(maxValue) * r)
	}

	_, minUnit := measurement.Scale(minValue, o.SampleUnit, "minimum")
	_, maxUnit := measurement.Scale(maxValue, o.SampleUnit, "minimum")

	unit := minUnit
	if minUnit != maxUnit && minValue*100 < maxValue && o.OutputFormat != Callgrind {
		// Minimum and maximum values have different units. Scale
		// minimum by 100 to use larger units, allowing minimum value to
		// be scaled down to 0.01, except for callgrind reports since
		// they can only represent integer values.
		_, unit = measurement.Scale(100*minValue, o.SampleUnit, "minimum")
	}

	if unit != "" {
		o.OutputUnit = unit
	} else {
		o.OutputUnit = o.SampleUnit
	}
}

// newGraph creates a new graph for this report. If nodes is non-nil,
// only nodes whose info matches are included. Otherwise, all nodes
// are included, without trimming.
func (rpt *Report) newGraph(nodes graph.NodeSet) *graph.Graph {
	o := rpt.options

	// Clean up file paths using heuristics.
	prof := rpt.prof
	for _, f := range prof.Function {
		f.Filename = trimPath(f.Filename)
	}
	// Removes all numeric tags except for the bytes tag prior
	// to making graph.
	// TODO: modify to select first numeric tag if no bytes tag
	for _, s := range prof.Sample {
		numLabels := make(map[string][]int64, len(s.NumLabel))
		numUnits := make(map[string][]string, len(s.NumLabel))
		for k, vs := range s.NumLabel {
			if k == "bytes" {
				unit := o.NumLabelUnits[k]
				numValues := make([]int64, len(vs))
				numUnit := make([]string, len(vs))
				for i, v := range vs {
					numValues[i] = v
					numUnit[i] = unit
				}
				numLabels[k] = append(numLabels[k], numValues...)
				numUnits[k] = append(numUnits[k], numUnit...)
			}
		}
		s.NumLabel = numLabels
		s.NumUnit = numUnits
	}

	formatTag := func(v int64, key string) string {
		return measurement.ScaledLabel(v, key, o.OutputUnit)
	}

	gopt := &graph.Options{
		SampleValue:       o.SampleValue,
		SampleMeanDivisor: o.SampleMeanDivisor,
		FormatTag:         formatTag,
		CallTree:          o.CallTree && (o.OutputFormat == Dot || o.OutputFormat == Callgrind),
		DropNegative:      o.DropNegative,
		KeptNodes:         nodes,
	}

	// Only keep binary names for disassembly-based reports, otherwise
	// remove it to allow merging of functions across binaries.
	switch o.OutputFormat {
	case Raw, List, WebList, Dis, Callgrind:
		gopt.ObjNames = true
	}

	return graph.New(rpt.prof, gopt)
}

func printTopProto(w io.Writer, rpt *Report) error {
	p := rpt.prof
	o := rpt.options
	g, _, _, _ := rpt.newTrimmedGraph()
	rpt.selectOutputUnit(g)

	out := profile.Profile{
		SampleType: []*profile.ValueType{
			{Type: "cum", Unit: o.OutputUnit},
			{Type: "flat", Unit: o.OutputUnit},
		},
		TimeNanos:     p.TimeNanos,
		DurationNanos: p.DurationNanos,
		PeriodType:    p.PeriodType,
		Period:        p.Period,
	}
	functionMap := make(functionMap)
	for i, n := range g.Nodes {
		f := functionMap.FindOrAdd(n.Info)
		flat, cum := n.FlatValue(), n.CumValue()
		l := &profile.Location{
			ID:      uint64(i + 1),
			Address: n.Info.Address,
			Line: []profile.Line{
				{
					Line:     int64(n.Info.Lineno),
					Function: f,
				},
			},
		}

		fv, _ := measurement.Scale(flat, o.SampleUnit, o.OutputUnit)
		cv, _ := measurement.Scale(cum, o.SampleUnit, o.OutputUnit)
		s := &profile.Sample{
			Location: []*profile.Location{l},
			Value:    []int64{int64(cv), int64(fv)},
		}
		out.Function = append(out.Function, f)
		out.Location = append(out.Location, l)
		out.Sample = append(out.Sample, s)
	}

	return out.Write(w)
}

type functionMap map[string]*profile.Function

func (fm functionMap) FindOrAdd(ni graph.NodeInfo) *profile.Function {
	fName := fmt.Sprintf("%q%q%q%d", ni.Name, ni.OrigName, ni.File, ni.StartLine)

	if f := fm[fName]; f != nil {
		return f
	}

	f := &profile.Function{
		ID:         uint64(len(fm) + 1),
		Name:       ni.Name,
		SystemName: ni.OrigName,
		Filename:   ni.File,
		StartLine:  int64(ni.StartLine),
	}
	fm[fName] = f
	return f
}

// printAssembly prints an annotated assembly listing.
func printAssembly(w io.Writer, rpt *Report, obj plugin.ObjTool) error {
	return PrintAssembly(w, rpt, obj, -1)
}

// PrintAssembly prints annotated disasssembly of rpt to w.
func PrintAssembly(w io.Writer, rpt *Report, obj plugin.ObjTool, maxFuncs int) error {
	o := rpt.options
	prof := rpt.prof

	g := rpt.newGraph(nil)

	// If the regexp source can be parsed as an address, also match
	// functions that land on that address.
	var address *uint64
	if hex, err := strconv.ParseUint(o.Symbol.String(), 0, 64); err == nil {
		address = &hex
	}

	fmt.Fprintln(w, "Total:", rpt.formatValue(rpt.total))
	symbols := symbolsFromBinaries(prof, g, o.Symbol, address, obj)
	symNodes := nodesPerSymbol(g.Nodes, symbols)

	// Sort for printing.
	var syms []*objSymbol
	for s := range symNodes {
		syms = append(syms, s)
	}
	byName := func(a, b *objSymbol) bool {
		if na, nb := a.sym.Name[0], b.sym.Name[0]; na != nb {
			return na < nb
		}
		return a.sym.Start < b.sym.Start
	}
	if maxFuncs < 0 {
		sort.Sort(orderSyms{syms, byName})
	} else {
		byFlatSum := func(a, b *objSymbol) bool {
			suma, _ := symNodes[a].Sum()
			sumb, _ := symNodes[b].Sum()
			if suma != sumb {
				return suma > sumb
			}
			return byName(a, b)
		}
		sort.Sort(orderSyms{syms, byFlatSum})
		if len(syms) > maxFuncs {
			syms = syms[:maxFuncs]
		}
	}

	// Correlate the symbols from the binary with the profile samples.
	for _, s := range syms {
		sns := symNodes[s]

		// Gather samples for this symbol.
		flatSum, cumSum := sns.Sum()

		// Get the function assembly.
		insts, err := obj.Disasm(s.sym.File, s.sym.Start, s.sym.End)
		if err != nil {
			return err
		}

		ns := annotateAssembly(insts, sns, s.base)

		fmt.Fprintf(w, "ROUTINE ======================== %s\n", s.sym.Name[0])
		for _, name := range s.sym.Name[1:] {
			fmt.Fprintf(w, "    AKA ======================== %s\n", name)
		}
		fmt.Fprintf(w, "%10s %10s (flat, cum) %s of Total\n",
			rpt.formatValue(flatSum), rpt.formatValue(cumSum),
			percentage(cumSum, rpt.total))

		function, file, line := "", "", 0
		for _, n := range ns {
			locStr := ""
			// Skip loc information if it hasn't changed from previous instruction.
			if n.function != function || n.file != file || n.line != line {
				function, file, line = n.function, n.file, n.line
				if n.function != "" {
					locStr = n.function + " "
				}
				if n.file != "" {
					locStr += n.file
					if n.line != 0 {
						locStr += fmt.Sprintf(":%d", n.line)
					}
				}
			}
			switch {
			case locStr == "":
				// No location info, just print the instruction.
				fmt.Fprintf(w, "%10s %10s %10x: %s\n",
					valueOrDot(n.flatValue(), rpt),
					valueOrDot(n.cumValue(), rpt),
					n.address, n.instruction,
				)
			case len(n.instruction) < 40:
				// Short instruction, print loc on the same line.
				fmt.Fprintf(w, "%10s %10s %10x: %-40s;%s\n",
					valueOrDot(n.flatValue(), rpt),
					valueOrDot(n.cumValue(), rpt),
					n.address, n.instruction,
					locStr,
				)
			default:
				// Long instruction, print loc on a separate line.
				fmt.Fprintf(w, "%74s;%s\n", "", locStr)
				fmt.Fprintf(w, "%10s %10s %10x: %s\n",
					valueOrDot(n.flatValue(), rpt),
					valueOrDot(n.cumValue(), rpt),
					n.address, n.instruction,
				)
			}
		}
	}
	return nil
}

// symbolsFromBinaries examines the binaries listed on the profile
// that have associated samples, and identifies symbols matching rx.
func symbolsFromBinaries(prof *profile.Profile, g *graph.Graph, rx *regexp.Regexp, address *uint64, obj plugin.ObjTool) []*objSymbol {
	hasSamples := make(map[string]bool)
	// Only examine mappings that have samples that match the
	// regexp. This is an optimization to speed up pprof.
	for _, n := range g.Nodes {
		if name := n.Info.PrintableName(); rx.MatchString(name) && n.Info.Objfile != "" {
			hasSamples[n.Info.Objfile] = true
		}
	}

	// Walk all mappings looking for matching functions with samples.
	var objSyms []*objSymbol
	for _, m := range prof.Mapping {
		if !hasSamples[m.File] {
			if address == nil || !(m.Start <= *address && *address <= m.Limit) {
				continue
			}
		}

		f, err := obj.Open(m.File, m.Start, m.Limit, m.Offset)
		if err != nil {
			fmt.Printf("%v\n", err)
			continue
		}

		// Find symbols in this binary matching the user regexp.
		var addr uint64
		if address != nil {
			addr = *address
		}
		msyms, err := f.Symbols(rx, addr)
		base := f.Base()
		f.Close()
		if err != nil {
			continue
		}
		for _, ms := range msyms {
			objSyms = append(objSyms,
				&objSymbol{
					sym:  ms,
					base: base,
					file: f,
				},
			)
		}
	}

	return objSyms
}

// objSym represents a symbol identified from a binary. It includes
// the SymbolInfo from the disasm package and the base that must be
// added to correspond to sample addresses
type objSymbol struct {
	sym  *plugin.Sym
	base uint64
	file plugin.ObjFile
}

// orderSyms is a wrapper type to sort []*objSymbol by a supplied comparator.
type orderSyms struct {
	v    []*objSymbol
	less func(a, b *objSymbol) bool
}

func (o orderSyms) Len() int           { return len(o.v) }
func (o orderSyms) Less(i, j int) bool { return o.less(o.v[i], o.v[j]) }
func (o orderSyms) Swap(i, j int)      { o.v[i], o.v[j] = o.v[j], o.v[i] }

// nodesPerSymbol classifies nodes into a group of symbols.
func nodesPerSymbol(ns graph.Nodes, symbols []*objSymbol) map[*objSymbol]graph.Nodes {
	symNodes := make(map[*objSymbol]graph.Nodes)
	for _, s := range symbols {
		// Gather samples for this symbol.
		for _, n := range ns {
			address := n.Info.Address - s.base
			if address >= s.sym.Start && address < s.sym.End {
				symNodes[s] = append(symNodes[s], n)
			}
		}
	}
	return symNodes
}

type assemblyInstruction struct {
	address         uint64
	instruction     string
	function        string
	file            string
	line            int
	flat, cum       int64
	flatDiv, cumDiv int64
	startsBlock     bool
	inlineCalls     []callID
}

type callID struct {
	file string
	line int
}

func (a *assemblyInstruction) flatValue() int64 {
	if a.flatDiv != 0 {
		return a.flat / a.flatDiv
	}
	return a.flat
}

func (a *assemblyInstruction) cumValue() int64 {
	if a.cumDiv != 0 {
		return a.cum / a.cumDiv
	}
	return a.cum
}

// annotateAssembly annotates a set of assembly instructions with a
// set of samples. It returns a set of nodes to display. base is an
// offset to adjust the sample addresses.
func annotateAssembly(insts []plugin.Inst, samples graph.Nodes, base uint64) []assemblyInstruction {
	// Add end marker to simplify printing loop.
	insts = append(insts, plugin.Inst{
		Addr: ^uint64(0),
	})

	// Ensure samples are sorted by address.
	samples.Sort(graph.AddressOrder)

	s := 0
	asm := make([]assemblyInstruction, 0, len(insts))
	for ix, in := range insts[:len(insts)-1] {
		n := assemblyInstruction{
			address:     in.Addr,
			instruction: in.Text,
			function:    in.Function,
			line:        in.Line,
		}
		if in.File != "" {
			n.file = filepath.Base(in.File)
		}

		// Sum all the samples until the next instruction (to account
		// for samples attributed to the middle of an instruction).
		for next := insts[ix+1].Addr; s < len(samples) && samples[s].Info.Address-base < next; s++ {
			sample := samples[s]
			n.flatDiv += sample.FlatDiv
			n.flat += sample.Flat
			n.cumDiv += sample.CumDiv
			n.cum += sample.Cum
			if f := sample.Info.File; f != "" && n.file == "" {
				n.file = filepath.Base(f)
			}
			if ln := sample.Info.Lineno; ln != 0 && n.line == 0 {
				n.line = ln
			}
			if f := sample.Info.Name; f != "" && n.function == "" {
				n.function = f
			}
		}
		asm = append(asm, n)
	}

	return asm
}

// valueOrDot formats a value according to a report, intercepting zero
// values.
func valueOrDot(value int64, rpt *Report) string {
	if value == 0 {
		return "."
	}
	return rpt.formatValue(value)
}

// printTags collects all tags referenced in the profile and prints
// them in a sorted table.
func printTags(w io.Writer, rpt *Report) error {
	p := rpt.prof

	o := rpt.options
	formatTag := func(v int64, key string) string {
		return measurement.ScaledLabel(v, key, o.OutputUnit)
	}

	// Hashtable to keep accumulate tags as key,value,count.
	tagMap := make(map[string]map[string]int64)
	for _, s := range p.Sample {
		for key, vals := range s.Label {
			for _, val := range vals {
				valueMap, ok := tagMap[key]
				if !ok {
					valueMap = make(map[string]int64)
					tagMap[key] = valueMap
				}
				valueMap[val] += o.SampleValue(s.Value)
			}
		}
		for key, vals := range s.NumLabel {
			unit := o.NumLabelUnits[key]
			for _, nval := range vals {
				val := formatTag(nval, unit)
				valueMap, ok := tagMap[key]
				if !ok {
					valueMap = make(map[string]int64)
					tagMap[key] = valueMap
				}
				valueMap[val] += o.SampleValue(s.Value)
			}
		}
	}

	tagKeys := make([]*graph.Tag, 0, len(tagMap))
	for key := range tagMap {
		tagKeys = append(tagKeys, &graph.Tag{Name: key})
	}
	tabw := tabwriter.NewWriter(w, 0, 0, 1, ' ', tabwriter.AlignRight)
	for _, tagKey := range graph.SortTags(tagKeys, true) {
		var total int64
		key := tagKey.Name
		tags := make([]*graph.Tag, 0, len(tagMap[key]))
		for t, c := range tagMap[key] {
			total += c
			tags = append(tags, &graph.Tag{Name: t, Flat: c})
		}

		f, u := measurement.Scale(total, o.SampleUnit, o.OutputUnit)
		fmt.Fprintf(tabw, "%s:\t Total %.1f%s\n", key, f, u)
		for _, t := range graph.SortTags(tags, true) {
			f, u := measurement.Scale(t.FlatValue(), o.SampleUnit, o.OutputUnit)
			if total > 0 {
				fmt.Fprintf(tabw, " \t%.1f%s (%s):\t %s\n", f, u, percentage(t.FlatValue(), total), t.Name)
			} else {
				fmt.Fprintf(tabw, " \t%.1f%s:\t %s\n", f, u, t.Name)
			}
		}
		fmt.Fprintln(tabw)
	}
	return tabw.Flush()
}

// printComments prints all freeform comments in the profile.
func printComments(w io.Writer, rpt *Report) error {
	p := rpt.prof

	for _, c := range p.Comments {
		fmt.Fprintln(w, c)
	}
	return nil
}

// TextItem holds a single text report entry.
type TextItem struct {
	Name                  string
	InlineLabel           string // Not empty if inlined
	Flat, Cum             int64  // Raw values
	FlatFormat, CumFormat string // Formatted values
}

// TextItems returns a list of text items from the report and a list
// of labels that describe the report.
func TextItems(rpt *Report) ([]TextItem, []string) {
	g, origCount, droppedNodes, _ := rpt.newTrimmedGraph()
	rpt.selectOutputUnit(g)
	labels := reportLabels(rpt, g, origCount, droppedNodes, 0, false)

	var items []TextItem
	var flatSum int64
	for _, n := range g.Nodes {
		name, flat, cum := n.Info.PrintableName(), n.FlatValue(), n.CumValue()

		var inline, noinline bool
		for _, e := range n.In {
			if e.Inline {
				inline = true
			} else {
				noinline = true
			}
		}

		var inl string
		if inline {
			if noinline {
				inl = "(partial-inline)"
			} else {
				inl = "(inline)"
			}
		}

		flatSum += flat
		items = append(items, TextItem{
			Name:        name,
			InlineLabel: inl,
			Flat:        flat,
			Cum:         cum,
			FlatFormat:  rpt.formatValue(flat),
			CumFormat:   rpt.formatValue(cum),
		})
	}
	return items, labels
}

// printText prints a flat text report for a profile.
func printText(w io.Writer, rpt *Report) error {
	items, labels := TextItems(rpt)
	fmt.Fprintln(w, strings.Join(labels, "\n"))
	fmt.Fprintf(w, "%10s %5s%% %5s%% %10s %5s%%\n",
		"flat", "flat", "sum", "cum", "cum")
	var flatSum int64
	for _, item := range items {
		inl := item.InlineLabel
		if inl != "" {
			inl = " " + inl
		}
		flatSum += item.Flat
		fmt.Fprintf(w, "%10s %s %s %10s %s  %s%s\n",
			item.FlatFormat, percentage(item.Flat, rpt.total),
			percentage(flatSum, rpt.total),
			item.CumFormat, percentage(item.Cum, rpt.total),
			item.Name, inl)
	}
	return nil
}

// printTraces prints all traces from a profile.
func printTraces(w io.Writer, rpt *Report) error {
	fmt.Fprintln(w, strings.Join(ProfileLabels(rpt), "\n"))

	prof := rpt.prof
	o := rpt.options

	const separator = "-----------+-------------------------------------------------------"

	_, locations := graph.CreateNodes(prof, &graph.Options{})
	for _, sample := range prof.Sample {
		var stack graph.Nodes
		for _, loc := range sample.Location {
			id := loc.ID
			stack = append(stack, locations[id]...)
		}

		if len(stack) == 0 {
			continue
		}

		fmt.Fprintln(w, separator)
		// Print any text labels for the sample.
		var labels []string
		for s, vs := range sample.Label {
			labels = append(labels, fmt.Sprintf("%10s:  %s\n", s, strings.Join(vs, " ")))
		}
		sort.Strings(labels)
		fmt.Fprint(w, strings.Join(labels, ""))

		// Print any numeric labels for the sample
		var numLabels []string
		for key, vals := range sample.NumLabel {
			unit := o.NumLabelUnits[key]
			numValues := make([]string, len(vals))
			for i, vv := range vals {
				numValues[i] = measurement.Label(vv, unit)
			}
			numLabels = append(numLabels, fmt.Sprintf("%10s:  %s\n", key, strings.Join(numValues, " ")))
		}
		sort.Strings(numLabels)
		fmt.Fprint(w, strings.Join(numLabels, ""))

		var d, v int64
		v = o.SampleValue(sample.Value)
		if o.SampleMeanDivisor != nil {
			d = o.SampleMeanDivisor(sample.Value)
		}
		// Print call stack.
		if d != 0 {
			v = v / d
		}
		fmt.Fprintf(w, "%10s   %s\n",
			rpt.formatValue(v), stack[0].Info.PrintableName())
		for _, s := range stack[1:] {
			fmt.Fprintf(w, "%10s   %s\n", "", s.Info.PrintableName())
		}
	}
	fmt.Fprintln(w, separator)
	return nil
}

// printCallgrind prints a graph for a profile on callgrind format.
func printCallgrind(w io.Writer, rpt *Report) error {
	o := rpt.options
	rpt.options.NodeFraction = 0
	rpt.options.EdgeFraction = 0
	rpt.options.NodeCount = 0

	g, _, _, _ := rpt.newTrimmedGraph()
	rpt.selectOutputUnit(g)

	nodeNames := getDisambiguatedNames(g)

	fmt.Fprintln(w, "positions: instr line")
	fmt.Fprintln(w, "events:", o.SampleType+"("+o.OutputUnit+")")

	objfiles := make(map[string]int)
	files := make(map[string]int)
	names := make(map[string]int)

	// prevInfo points to the previous NodeInfo.
	// It is used to group cost lines together as much as possible.
	var prevInfo *graph.NodeInfo
	for _, n := range g.Nodes {
		if prevInfo == nil || n.Info.Objfile != prevInfo.Objfile || n.Info.File != prevInfo.File || n.Info.Name != prevInfo.Name {
			fmt.Fprintln(w)
			fmt.Fprintln(w, "ob="+callgrindName(objfiles, n.Info.Objfile))
			fmt.Fprintln(w, "fl="+callgrindName(files, n.Info.File))
			fmt.Fprintln(w, "fn="+callgrindName(names, n.Info.Name))
		}

		addr := callgrindAddress(prevInfo, n.Info.Address)
		sv, _ := measurement.Scale(n.FlatValue(), o.SampleUnit, o.OutputUnit)
		fmt.Fprintf(w, "%s %d %d\n", addr, n.Info.Lineno, int64(sv))

		// Print outgoing edges.
		for _, out := range n.Out.Sort() {
			c, _ := measurement.Scale(out.Weight, o.SampleUnit, o.OutputUnit)
			callee := out.Dest
			fmt.Fprintln(w, "cfl="+callgrindName(files, callee.Info.File))
			fmt.Fprintln(w, "cfn="+callgrindName(names, nodeNames[callee]))
			// pprof doesn't have a flat weight for a call, leave as 0.
			fmt.Fprintf(w, "calls=0 %s %d\n", callgrindAddress(prevInfo, callee.Info.Address), callee.Info.Lineno)
			// TODO: This address may be in the middle of a call
			// instruction. It would be best to find the beginning
			// of the instruction, but the tools seem to handle
			// this OK.
			fmt.Fprintf(w, "* * %d\n", int64(c))
		}

		prevInfo = &n.Info
	}

	return nil
}

// getDisambiguatedNames returns a map from each node in the graph to
// the name to use in the callgrind output. Callgrind merges all
// functions with the same [file name, function name]. Add a [%d/n]
// suffix to disambiguate nodes with different values of
// node.Function, which we want to keep separate. In particular, this
// affects graphs created with --call_tree, where nodes from different
// contexts are associated to different Functions.
func getDisambiguatedNames(g *graph.Graph) map[*graph.Node]string {
	nodeName := make(map[*graph.Node]string, len(g.Nodes))

	type names struct {
		file, function string
	}

	// nameFunctionIndex maps the callgrind names (filename, function)
	// to the node.Function values found for that name, and each
	// node.Function value to a sequential index to be used on the
	// disambiguated name.
	nameFunctionIndex := make(map[names]map[*graph.Node]int)
	for _, n := range g.Nodes {
		nm := names{n.Info.File, n.Info.Name}
		p, ok := nameFunctionIndex[nm]
		if !ok {
			p = make(map[*graph.Node]int)
			nameFunctionIndex[nm] = p
		}
		if _, ok := p[n.Function]; !ok {
			p[n.Function] = len(p)
		}
	}

	for _, n := range g.Nodes {
		nm := names{n.Info.File, n.Info.Name}
		nodeName[n] = n.Info.Name
		if p := nameFunctionIndex[nm]; len(p) > 1 {
			// If there is more than one function, add suffix to disambiguate.
			nodeName[n] += fmt.Sprintf(" [%d/%d]", p[n.Function]+1, len(p))
		}
	}
	return nodeName
}

// callgrindName implements the callgrind naming compression scheme.
// For names not previously seen returns "(N) name", where N is a
// unique index. For names previously seen returns "(N)" where N is
// the index returned the first time.
func callgrindName(names map[string]int, name string) string {
	if name == "" {
		return ""
	}
	if id, ok := names[name]; ok {
		return fmt.Sprintf("(%d)", id)
	}
	id := len(names) + 1
	names[name] = id
	return fmt.Sprintf("(%d) %s", id, name)
}

// callgrindAddress implements the callgrind subposition compression scheme if
// possible. If prevInfo != nil, it contains the previous address. The current
// address can be given relative to the previous address, with an explicit +/-
// to indicate it is relative, or * for the same address.
func callgrindAddress(prevInfo *graph.NodeInfo, curr uint64) string {
	abs := fmt.Sprintf("%#x", curr)
	if prevInfo == nil {
		return abs
	}

	prev := prevInfo.Address
	if prev == curr {
		return "*"
	}

	diff := int64(curr - prev)
	relative := fmt.Sprintf("%+d", diff)

	// Only bother to use the relative address if it is actually shorter.
	if len(relative) < len(abs) {
		return relative
	}

	return abs
}

// printTree prints a tree-based report in text form.
func printTree(w io.Writer, rpt *Report) error {
	const separator = "----------------------------------------------------------+-------------"
	const legend = "      flat  flat%   sum%        cum   cum%   calls calls% + context 	 	 "

	g, origCount, droppedNodes, _ := rpt.newTrimmedGraph()
	rpt.selectOutputUnit(g)

	fmt.Fprintln(w, strings.Join(reportLabels(rpt, g, origCount, droppedNodes, 0, false), "\n"))

	fmt.Fprintln(w, separator)
	fmt.Fprintln(w, legend)
	var flatSum int64

	rx := rpt.options.Symbol
	for _, n := range g.Nodes {
		name, flat, cum := n.Info.PrintableName(), n.FlatValue(), n.CumValue()

		// Skip any entries that do not match the regexp (for the "peek" command).
		if rx != nil && !rx.MatchString(name) {
			continue
		}

		fmt.Fprintln(w, separator)
		// Print incoming edges.
		inEdges := n.In.Sort()
		for _, in := range inEdges {
			var inline string
			if in.Inline {
				inline = " (inline)"
			}
			fmt.Fprintf(w, "%50s %s |   %s%s\n", rpt.formatValue(in.Weight),
				percentage(in.Weight, cum), in.Src.Info.PrintableName(), inline)
		}

		// Print current node.
		flatSum += flat
		fmt.Fprintf(w, "%10s %s %s %10s %s                | %s\n",
			rpt.formatValue(flat),
			percentage(flat, rpt.total),
			percentage(flatSum, rpt.total),
			rpt.formatValue(cum),
			percentage(cum, rpt.total),
			name)

		// Print outgoing edges.
		outEdges := n.Out.Sort()
		for _, out := range outEdges {
			var inline string
			if out.Inline {
				inline = " (inline)"
			}
			fmt.Fprintf(w, "%50s %s |   %s%s\n", rpt.formatValue(out.Weight),
				percentage(out.Weight, cum), out.Dest.Info.PrintableName(), inline)
		}
	}
	if len(g.Nodes) > 0 {
		fmt.Fprintln(w, separator)
	}
	return nil
}

// GetDOT returns a graph suitable for dot processing along with some
// configuration information.
func GetDOT(rpt *Report) (*graph.Graph, *graph.DotConfig) {
	g, origCount, droppedNodes, droppedEdges := rpt.newTrimmedGraph()
	rpt.selectOutputUnit(g)
	labels := reportLabels(rpt, g, origCount, droppedNodes, droppedEdges, true)

	c := &graph.DotConfig{
		Title:       rpt.options.Title,
		Labels:      labels,
		FormatValue: rpt.formatValue,
		Total:       rpt.total,
	}
	return g, c
}

// printDOT prints an annotated callgraph in DOT format.
func printDOT(w io.Writer, rpt *Report) error {
	g, c := GetDOT(rpt)
	graph.ComposeDot(w, g, &graph.DotAttributes{}, c)
	return nil
}

// percentage computes the percentage of total of a value, and encodes
// it as a string. At least two digits of precision are printed.
func percentage(value, total int64) string {
	var ratio float64
	if total != 0 {
		ratio = math.Abs(float64(value)/float64(total)) * 100
	}
	switch {
	case math.Abs(ratio) >= 99.95 && math.Abs(ratio) <= 100.05:
		return "  100%"
	case math.Abs(ratio) >= 1.0:
		return fmt.Sprintf("%5.2f%%", ratio)
	default:
		return fmt.Sprintf("%5.2g%%", ratio)
	}
}

// ProfileLabels returns printable labels for a profile.
func ProfileLabels(rpt *Report) []string {
	label := []string{}
	prof := rpt.prof
	o := rpt.options
	if len(prof.Mapping) > 0 {
		if prof.Mapping[0].File != "" {
			label = append(label, "File: "+filepath.Base(prof.Mapping[0].File))
		}
		if prof.Mapping[0].BuildID != "" {
			label = append(label, "Build ID: "+prof.Mapping[0].BuildID)
		}
	}
	// Only include comments that do not start with '#'.
	for _, c := range prof.Comments {
		if !strings.HasPrefix(c, "#") {
			label = append(label, c)
		}
	}
	if o.SampleType != "" {
		label = append(label, "Type: "+o.SampleType)
	}
	if prof.TimeNanos != 0 {
		const layout = "Jan 2, 2006 at 3:04pm (MST)"
		label = append(label, "Time: "+time.Unix(0, prof.TimeNanos).Format(layout))
	}
	if prof.DurationNanos != 0 {
		duration := measurement.Label(prof.DurationNanos, "nanoseconds")
		totalNanos, totalUnit := measurement.Scale(rpt.total, o.SampleUnit, "nanoseconds")
		var ratio string
		if totalUnit == "ns" && totalNanos != 0 {
			ratio = "(" + percentage(int64(totalNanos), prof.DurationNanos) + ")"
		}
		label = append(label, fmt.Sprintf("Duration: %s, Total samples = %s %s", duration, rpt.formatValue(rpt.total), ratio))
	}
	return label
}

// reportLabels returns printable labels for a report. Includes
// profileLabels.
func reportLabels(rpt *Report, g *graph.Graph, origCount, droppedNodes, droppedEdges int, fullHeaders bool) []string {
	nodeFraction := rpt.options.NodeFraction
	edgeFraction := rpt.options.EdgeFraction
	nodeCount := len(g.Nodes)

	var label []string
	if len(rpt.options.ProfileLabels) > 0 {
		label = append(label, rpt.options.ProfileLabels...)
	} else if fullHeaders || !rpt.options.CompactLabels {
		label = ProfileLabels(rpt)
	}

	var flatSum int64
	for _, n := range g.Nodes {
		flatSum = flatSum + n.FlatValue()
	}

	if len(rpt.options.ActiveFilters) > 0 {
		activeFilters := legendActiveFilters(rpt.options.ActiveFilters)
		label = append(label, activeFilters...)
	}

	label = append(label, fmt.Sprintf("Showing nodes accounting for %s, %s of %s total", rpt.formatValue(flatSum), strings.TrimSpace(percentage(flatSum, rpt.total)), rpt.formatValue(rpt.total)))

	if rpt.total != 0 {
		if droppedNodes > 0 {
			label = append(label, genLabel(droppedNodes, "node", "cum",
				rpt.formatValue(abs64(int64(float64(rpt.total)*nodeFraction)))))
		}
		if droppedEdges > 0 {
			label = append(label, genLabel(droppedEdges, "edge", "freq",
				rpt.formatValue(abs64(int64(float64(rpt.total)*edgeFraction)))))
		}
		if nodeCount > 0 && nodeCount < origCount {
			label = append(label, fmt.Sprintf("Showing top %d nodes out of %d",
				nodeCount, origCount))
		}
	}
	return label
}

func legendActiveFilters(activeFilters []string) []string {
	legendActiveFilters := make([]string, len(activeFilters)+1)
	legendActiveFilters[0] = "Active filters:"
	for i, s := range activeFilters {
		if len(s) > 80 {
			s = s[:80] + "…"
		}
		legendActiveFilters[i+1] = "   " + s
	}
	return legendActiveFilters
}

func genLabel(d int, n, l, f string) string {
	if d > 1 {
		n = n + "s"
	}
	return fmt.Sprintf("Dropped %d %s (%s <= %s)", d, n, l, f)
}

// New builds a new report indexing the sample values interpreting the
// samples with the provided function.
func New(prof *profile.Profile, o *Options) *Report {
	format := func(v int64) string {
		if r := o.Ratio; r > 0 && r != 1 {
			fv := float64(v) * r
			v = int64(fv)
		}
		return measurement.ScaledLabel(v, o.SampleUnit, o.OutputUnit)
	}
	return &Report{prof, computeTotal(prof, o.SampleValue, o.SampleMeanDivisor, !o.PositivePercentages),
		o, format}
}

// NewDefault builds a new report indexing the last sample value
// available.
func NewDefault(prof *profile.Profile, options Options) *Report {
	index := len(prof.SampleType) - 1
	o := &options
	if o.Title == "" && len(prof.Mapping) > 0 && prof.Mapping[0].File != "" {
		o.Title = filepath.Base(prof.Mapping[0].File)
	}
	o.SampleType = prof.SampleType[index].Type
	o.SampleUnit = strings.ToLower(prof.SampleType[index].Unit)
	o.SampleValue = func(v []int64) int64 {
		return v[index]
	}
	return New(prof, o)
}

// computeTotal computes the sum of all sample values. This will be
// used to compute percentages. If includeNegative is set, use use
// absolute values to provide a meaningful percentage for both
// negative and positive values. Otherwise only use positive values,
// which is useful when comparing profiles from different jobs.
func computeTotal(prof *profile.Profile, value, meanDiv func(v []int64) int64, includeNegative bool) int64 {
	var div, ret int64
	for _, sample := range prof.Sample {
		var d, v int64
		v = value(sample.Value)
		if meanDiv != nil {
			d = meanDiv(sample.Value)
		}
		if v >= 0 {
			ret += v
			div += d
		} else if includeNegative {
			ret -= v
			div += d
		}
	}
	if div != 0 {
		return ret / div
	}
	return ret
}

// Report contains the data and associated routines to extract a
// report from a profile.
type Report struct {
	prof        *profile.Profile
	total       int64
	options     *Options
	formatValue func(int64) string
}

// Total returns the total number of samples in a report.
func (rpt *Report) Total() int64 { return rpt.total }

func abs64(i int64) int64 {
	if i < 0 {
		return -i
	}
	return i
}


text:
package com.planet_ink.coffee_mud.Races;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;
import java.util.Vector;

@SuppressWarnings("unchecked")
public class GiantWolf extends Wolf
{
	public String ID(){	return "GiantWolf"; }
	public String name(){ return "Giant Wolf"; }
	public int shortestMale(){return 26;}
	public int shortestFemale(){return 26;}
	public int heightVariance(){return 12;}
	public int lightestWeight(){return 80;}
	public int weightVariance(){return 60;}
	public long forbiddenWornBits(){return Integer.MAX_VALUE-Wearable.WORN_HEAD-Wearable.WORN_FEET-Wearable.WORN_NECK-Wearable.WORN_EARS-Wearable.WORN_EYES;}
	public String racialCategory(){return "Canine";}

	//                                an ey ea he ne ar ha to le fo no gi mo wa ta wi
	private static final int[] parts={0 ,2 ,2 ,1 ,1 ,0 ,0 ,1 ,4 ,4 ,1 ,0 ,1 ,1 ,1 ,0 };
	public int[] bodyMask(){return parts;}

	protected static Vector resources=new Vector();
	public void affectEnvStats(Environmental affected, EnvStats affectableStats)
	{
		super.affectEnvStats(affected,affectableStats);
		affectableStats.setSensesMask(affectableStats.sensesMask()|EnvStats.CAN_SEE_INFRARED);
	}
	public void affectCharState(MOB affectedMob, CharState affectableMaxState)
	{
		affectableMaxState.setMovement(affectableMaxState.getMovement()+200);
	}
	public void affectCharStats(MOB affectedMOB, CharStats affectableStats)
	{
		super.affectCharStats(affectedMOB, affectableStats);
		affectableStats.setRacialStat(CharStats.STAT_STRENGTH,13);
		affectableStats.setRacialStat(CharStats.STAT_DEXTERITY,13);
	}
	public Vector myResources()
	{
		synchronized(resources)
		{
			if(resources.size()==0)
			{
				resources.addElement(makeResource
				("some "+name().toLowerCase()+" claws",RawMaterial.RESOURCE_BONE));
				for(int i=0;i<4;i++)
					resources.addElement(makeResource
					("a strip of "+name().toLowerCase()+" hair",RawMaterial.RESOURCE_HIDE));
				for(int i=0;i<2;i++)
					resources.addElement(makeResource
					("a pound of "+name().toLowerCase()+" meat",RawMaterial.RESOURCE_MEAT));
				resources.addElement(makeResource
				("some "+name().toLowerCase()+" blood",RawMaterial.RESOURCE_BLOOD));
				resources.addElement(makeResource
				("a pile of "+name().toLowerCase()+" bones",RawMaterial.RESOURCE_BONE));
			}
		}
		return resources;
	}
}


text:
var _ = require('lodash');
var util = require('util');

var debug = require('debug')('bot');

var EventEmitter = require('events').EventEmitter;

module.exports = function (connection) {

	var Users = function () {
		var users = [];

		// incoming event handlers
		this.on('add', add);

		function add(user) {
			debug('user added to collection: %s (%d)', user.name, user.session);
			users.push(new User(user));
		};

		function remove(id) {
			var user = _.where(users, {session: id});
			if (user) {
				users.splice(users.indexOf(user), 1);
			}
		};

		// helper methods
		this.get = function (id) {
			if (id) { return _.find(users, {session: id}); }
			return users;
		}

		this.exists = function (id) {
			return (!!_.find(users, {session: id}));
		};
	};

	util.inherits(Users, EventEmitter);

	var User = function (user) {
		_.assign(this, user);

		this.move = function (channelId) {
			connection.sendMessage('UserState', {
				session: this.session,
				actor: connection.sessionId,
				channelId: channelId
			});
		};

		this.message = function (message) {
			connection.sendMessage('TextMessage', {
				actor: connection.sessionId,
				session: [this.session],
				message: message
			});
		};

	};

	util.inherits(User, EventEmitter);

	return {
		Users: Users,
		User: User
	}
};


text:
require 'open-uri'
require 'open_uri_redirections'
require 'nokogiri'

class IndexAccountJob
  include Resque::Plugins::UniqueJob

  @queue = :account_queue

  def self.perform(seller)
    seller = Seller.find(seller)
    if seller.region.name == 'Garena'
      url = 'http://web.poe.garena.com/account/view-profile/'+seller.account_name
    else
      url = 'http://www.pathofexile.com/account/view-profile/'+seller.account_name
    end
    profile = Nokogiri::HTML(open(URI.encode(url), allow_redirections: :safe).read, nil, 'utf-8')
    ign = profile.css('div.characters div.profile-character div.character-info span.characterName')
    unless ign.first.nil?
      ign = ign.first.text
    else
      ign = '(!) Private'
    end
    seller.ign = ign
    challenge = profile.css('div.challenge-level img.achievement')
    seller.challenge_icon = challenge.first["src"] unless challenge.first.nil?
    account_id = profile.xpath('/html/body/script[5]').first.content.scan(/accountID: \d+/).first
    seller.account_id = account_id.sub('accountID: ', '') if account_id
    seller.updated_at = Time.now
    seller.save

    seller = nil
    profile = nil
    challenge = nil
    ign = nil
  end
end


text:
import re
import requests
import csv
import pymysql
import lxml

DOWNLOAD_URL = 'http://movie.douban.com/top250/'
db = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='syb123', db='douban',
                     charset='utf8')
cur = db.cursor()

def download_page(url):
    return requests.get(url, headers={
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:56.0) Gecko/20100101 Firefox/56.0'
    }).text

def execute_db(movies_info):
    sql = "INSERT INTO test(rank, NAME, score, country, year, " \
          "category, votes, douban_url) values(%s,%s,%s,%s,%s,%s,%s,%s)"
    try:
        cur.executemany(sql, movies_info)
        db.commit()
    except Exception as e:
        print("Error:", e)
        db.rollback()

def parse_html(html, writer, movies_info):
    tree = lxml.html.fromstring(html)

    movies = tree.xpath("//ol[@class='grid_view']/li")
    for movie in movies:

        name_num = len(movie.xpath("descendant::span[@class='title']"))
        name = ''
        for num in range(0, name_num):
            name += movie.xpath("descendant::span[@class='title']")[num].text.strip()
        name = ' '.join(name.replace('/', '').split())  # 清洗数据
        # 排名,豆瓣页面
        num = movie.xpath("descendant::em/text()")[0]
        # < class 'lxml.etree._ElementUnicodeResult'>
        url = movie.xpath("descendant::div[@class='pic']/a/@href")[0]
        # 年份,国家,类型
        data = movie.xpath("descendant::div[@class='bd']/p")[0].xpath('string(.)')
        info = re.findall(r'\d.*', data)[0].split('/')
        year, country, category = info[0].strip(), info[1].strip(), info[2].strip()
        # 得分,投票数
        score = movie.xpath("descendant::div[@class='star']/span")[1].text
        voting_num = movie.xpath("descendant::div[@class='star']/span")[3].text

        movie_info = (int(num), name, float(score), country, int(year), category, int(voting_num[0:-3]), url)
        movies_info.append(movie_info)
        #print(movie_info)
        writer.writerow(movie_info)
    try:
        next_page = tree.xpath("//span[@class='next']/a/@href")[0]
        return DOWNLOAD_URL + next_page
    except:
        return None

def main():
    url = DOWNLOAD_URL
    # 将数据导入到csv文件中
    writer = csv.writer(open('movies.csv', 'w', newline='', encoding='utf-8'))
    fields = ('rank',  'name', 'score', 'country', 'year', 'category', 'votes', 'douban_url')
    writer.writerow(fields)
    movies_info = []
    while url:
        html = download_page(url)
        url = parse_html(html, writer, movies_info)
    execute_db(movies_info)

if __name__ == '__main__':
    main()


text: {% include icon-github.svg %}{{ include.username }}


text:
/**
 * String utility
 *
 * A small module containing utilities to work with Strings
 */

/**
 * Return string with first letter capitalised
 *
 * @param  {String} str
 * @return {String}
 */
function upperFirst(str) {
  return str ? str.substr(0, 1).toUpperCase() + str.substr(1) : ''
}

/**
 * Return pluralised String
 *
 * @param  {String} str
 * @return {String}
 */
function pluralise(str) {
  let lastCharMatch = str.match(/([a-zA-Z]{1})[^a-zA-Z]*$/)

  if (!lastCharMatch) { return str }

  let val = lastCharMatch[0]
  let index = lastCharMatch.index + 1

  if (val === 'y') {
    return `${ str.substr(0, index - 1) }ies${ str.substr(index) }`
  }

  return `${ str.substr(0, index) }s${ str.substr(index) }`
}

/**
 * Return a String representing the given number padded with leading zeroes to
 * given length
 *
 * @param  {Number} n
 * @param  {Number} length
 * @return {String}
 */
function zeropad(n, width) {
  n = `${ n }`
  return n.length >= width ? n : new Array(width - n.length + 1).join('0') + n
}

/**
 * Return `a` or `an` depending on whether given string starts with a vowel
 *
 * @param  {String} string
 * @return {String}
 */
function getArticle(string) {
  return /^([aeiou])/i.test(string.substr(0, 1)) ? 'an' : 'a'
}

/**
 * Return an Array of map keys which values have been found in given String
 *
 * @param  {Object} map
 * @param  {String} string
 * @return {[String]}
 */
function tagsFromKeywordsSearch(string, map) {
  let out = []

  string = string.toLowerCase()

  for (let key in map) {
    for (let keyword of map[key]) {
      let negative = false

      keyword = keyword.toLowerCase()

      if (keyword.substr(0, 1) === '!') {
        keyword = keyword.substr(1)
        negative = true
      }

      if (string.indexOf(keyword) !== -1) {
        if (negative) {
          if (out.indexOf(keyword) !== -1) { out.splice(out.indexOf(keyword)) }
          continue
        }

        out.push(key)
        break
      }
    }
  }

  return out
}

/**
 * Ensure returned String ends with a rtailing slash
 *
 * @param  {String} str
 * @return {String}
 */
function ensureTrailingSlash(str) {
  return str.substr(-1) === '/' ? str : `${ str || '' }/`
}

/**
 * Remove trailing slash from String if found
 *
 * @param  {String} str
 * @return {String}
 */
function removeTrailingSlash(str) {
  return str.substr(-1) === '/' ? str.substr(0, str.length - 1) : str
}

/**
 * Remove trailing slash from String if found
 *
 * @param  {String} str
 * @return {String}
 */
function removeInitialSlash(str) {
  return str.substr(0, 1) === '/' ? str.substr(1) : str
}

module.exports = {
  upperFirst,
  pluralise,
  zeropad,
  getArticle,
  tagsFromKeywordsSearch,
  ensureTrailingSlash,
  removeTrailingSlash,
  removeInitialSlash
}


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Loading..."
        android:id="@+id/loading"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true" />

    <ListView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/timetable"
        tools:listitem="@android:layout/simple_list_item_1"
        android:layout_below="@+id/loading"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:layout_marginTop="55dp" />

    <Button
        style="?android:attr/buttonStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text=">"
        android:id="@+id/button_forward"
        android:layout_alignParentTop="true"
        android:layout_alignRight="@+id/timetable"
        android:layout_alignEnd="@+id/timetable"
        android:onClick="moveForward"
        />

    <Button
        style="?android:attr/buttonStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="<"
        android:id="@+id/button_backward"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:onClick="moveBackward"
        />
</RelativeLayout>


text:
<?php
namespace SmsOrange\Cruise;

use SmsOrange\Main;

class CostaCruisesWebservice extends Main
{
    public function getComponents()
    {

    }

    public function getAvailableCategories()
    {

    }

    public function getCabins()
    {

    }

}


text:
{% extends "vmenu.html" %}

{% block title %}ttDashboard - Home{% endblock %}
{% block meta_keywords %}api, turntable dashboard, ttdashboard, turntable.fm, turntable, turntablefm, live stats, dashboard, statistiques, statistics, Alain Gilbert{% endblock %}

{% block extrahead %}
<link rel="stylesheet" media="screen" type="text/css" href="/css/vmenu.css" />
<link rel="stylesheet" media="screen" type="text/css" href="/css/playlists_add_song.css" />
{% endblock %}

{% block content_right %}

Add song to your playlists

<form method="post" action="">{% csrf_token %}

   {% for playlist in playlists %}

      <input type="checkbox" name="playlist_{{forloop.counter}}" value="{{playlist.id}}" id="playlist_{{forloop.counter}}" {% if playlist.song_id %}checked="checked"{% endif %}/>
      {{playlist.name}}

   {% endfor %}

   <input type="submit" value="Add to these playlists" />
</form>

{% endblock %}


text:
// Copyright 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.

package org.chromium.base;

import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.util.Log;

import org.chromium.base.annotations.CalledByNative;
import org.chromium.base.annotations.JNINamespace;

import java.io.IOException;

/**
 * A utility class to retrieve references to uncompressed assets insides the apk. A reference is
 * defined as tuple (file descriptor, offset, size) enabling direct mapping without deflation.
 * This can be used even within the renderer process, since it just dup's the apk's fd.
 */
@JNINamespace("base::android")
public class ApkAssets {
    private static final String LOGTAG = "ApkAssets";

    @CalledByNative
    public static long[] open(Context context, String fileName) {
        AssetFileDescriptor afd = null;
        try {
            AssetManager manager = context.getAssets();
            afd = manager.openNonAssetFd(fileName);
            return new long[] { afd.getParcelFileDescriptor().detachFd(),
                                afd.getStartOffset(),
                                afd.getLength() };
        } catch (IOException e) {
            Log.e(LOGTAG, "Error while loading asset " + fileName + ": " + e);
            return new long[] {-1, -1, -1};
        } finally {
            try {
                if (afd != null) {
                    afd.close();
                }
            } catch (IOException e2) {
                Log.e(LOGTAG, "Unable to close AssetFileDescriptor", e2);
            }
        }
    }
}


text:
<?php

namespace PHP_CodeSniffer\Standards\Squiz\Sniffs\Scope;

use PHP_CodeSniffer\Sniffs\AbstractVariableSniff;
use PHP_CodeSniffer\Files\File;
use PHP_CodeSniffer\Util\Tokens;

class MemberVarScopeSniff extends AbstractVariableSniff
{

    /**
     * Processes the function tokens within the class.
     *
     * @param \PHP_CodeSniffer\Files\File $phpcsFile The file where this token was found.
     * @param int                         $stackPtr  The position where the token was found.
     *
     * @return void
     */
    protected function processMemberVar(File $phpcsFile, $stackPtr)
    {
        $tokens = $phpcsFile->getTokens();

        $modifier = null;
        for ($i = ($stackPtr - 1); $i > 0; $i--) {
            if ($tokens[$i]['line'] < $tokens[$stackPtr]['line']) {
                break;
            } else if (isset(Tokens::$scopeModifiers[$tokens[$i]['code']]) === true) {
                $modifier = $i;
                break;
            }
        }

        if ($modifier === null) {
            $error = 'Scope modifier not specified for member variable "%s"';
            $data  = [$tokens[$stackPtr]['content']];
            $phpcsFile->addError($error, $stackPtr, 'Missing', $data);
        }

    }//end processMemberVar()

    /**
     * Processes normal variables.
     *
     * @param \PHP_CodeSniffer\Files\File $phpcsFile The file where this token was found.
     * @param int                         $stackPtr  The position where the token was found.
     *
     * @return void
     */
    protected function processVariable(File $phpcsFile, $stackPtr)
    {
        /*
            We don't care about normal variables.
        */

    }//end processVariable()

    /**
     * Processes variables in double quoted strings.
     *
     * @param \PHP_CodeSniffer\Files\File $phpcsFile The file where this token was found.
     * @param int                         $stackPtr  The position where the token was found.
     *
     * @return void
     */
    protected function processVariableInString(File $phpcsFile, $stackPtr)
    {
        /*
            We don't care about normal variables.
        */

    }//end processVariableInString()

}//end class


text:
import Vault

import Crypto.Random
import Test.QuickCheck
import Test.QuickCheck.Test
import System.IO
import Control.Applicative ((<$>))
import qualified Data.ByteString as B

fakeKey  = makeKey $ B.replicate 32 0xf
fakeSalt = makeSalt $ B.replicate 16 0x0

newtype FakeRNG = FakeRNG Int

instance CryptoRandomGen FakeRNG where
	newGen        = undefined
	genSeedLength = undefined
	reseed        = undefined
	genBytes i (FakeRNG z) = Right (B.replicate i (fromIntegral z), FakeRNG $ z+1)

genByteString :: Int -> Gen B.ByteString
genByteString i = B.pack <$> vector i

instance Arbitrary Secret where
	arbitrary = makeSecret <$> listOf arbitrary
instance Arbitrary Key where
	arbitrary = makeKey <$> genByteString 32
instance Arbitrary Salt where
	arbitrary = makeSalt <$> genByteString 16

instance Show Secret where
	show s = "Secret " ++ (show $ getSecret s)
instance Show Key where
	show = const "Key[..]"
instance Show Salt where
	show = const "Salt[..]"

prop_identity secret = unstoreSecret fakeKey encrypted == secret
	where
		(encrypted, _) = storeSecret fakeKey fakeSalt secret (FakeRNG 12)

prop_identityAll (key, salt, secret) = unstoreSecret key encrypted == secret
	where
		(encrypted, _) = storeSecret key salt secret (FakeRNG 12)

myQuickCheckArgs = stdArgs

run_test n t = putStr ("  " ++ n ++ " ... ") >> hFlush stdout >> quickCheckWith myQuickCheckArgs t

main = do
	run_test "identity" prop_identity
	run_test "identity-all" prop_identityAll


text:
namespace graphic
{
	class cRenderer;

	class cIndexBuffer
	{
	public:
		cIndexBuffer();
		virtual ~cIndexBuffer();

		bool Create(cRenderer &renderer, int faceCount);
		bool Create2(cRenderer &renderer, const int primitiveCount, const int primitiveSize);
		void* Lock();
		void Unlock();
		void Bind(cRenderer &renderer) const;
		int GetFaceCount() const;
		void Clear();

		void Set(cRenderer &renderer, cIndexBuffer &rhs);
		//cIndexBuffer& operator=(cIndexBuffer &rhs);

	private:
		LPDIRECT3DINDEXBUFFER9 m_pIdxBuff; // À妽º ¹öÆÛ
		int m_faceCount;
	};

	inline int cIndexBuffer::GetFaceCount() const { return m_faceCount; }
}


text:
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;

namespace DotJEM.Json.Storage.Test
{
    public static class TestContext
    {
        public static string ConnectionString
            => Environment.GetEnvironmentVariable("appveyor_sqlconnection")
            ?? "Data Source=.\\DEV;Initial Catalog=json;Integrated Security=True";

        public static void DropArea(string area)
        {
            using (SqlConnection connection = new SqlConnection(TestContext.ConnectionString))
            {
                connection.Open();
                List<string> tables = LookupAreaTables(area, connection).ToList();
                foreach (string table in tables)
                {
                    using (SqlCommand command = new SqlCommand { Connection = connection })
                    {
                        command.CommandText = $"DROP TABLE [dbo].[{table}]";
                        command.ExecuteScalar();
                    }
                }

            }
        }

        public static IEnumerable<string> LookupAreaTables(string area, SqlConnection connection)
        {
            using (SqlCommand command = new SqlCommand { Connection = connection })
            {
                command.CommandText = $"SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbo' AND ( TABLE_NAME = '{area}' OR TABLE_NAME LIKE '{area}.%' )";
                using (SqlDataReader reader = command.ExecuteReader())
                {
                    int col = reader.GetOrdinal("TABLE_NAME");
                    while (reader.Read())
                        yield return reader.GetString(col);
                }
            }
        }
    }
}


text:
package com.MayaProject.Ragusa.Federico.data;

import org.json.JSONObject;

public interface JSONPopulator {
    void populate(JSONObject data);

    JSONObject toJSON();
}


text:
require 'spec_helper'
require 'ostruct'

module RecordSpec

  def self.type
    if ActiveRecord::VERSION::MAJOR >= 5
      @type ||= ActiveModel::Type::Value.new
    end
  end

  class Record < ActiveType::Record

    attribute :virtual_string, :string
    attribute :virtual_integer, :integer
    attribute :virtual_time, :datetime
    attribute :virtual_date, :date
    attribute :virtual_boolean, :boolean
    attribute :virtual_attribute
    attribute :virtual_type_attribute, RecordSpec.type

  end

  class RecordWithValidations < Record

    validates :persisted_string, :presence => true
    validates :virtual_string, :presence => true

  end

  class RecordWithOverrides < Record

    attribute :overridable_test, :string

    def overridable_test
      super + super
    end

  end

  class RecordCopy < ActiveType::Record
    self.table_name = 'records'

    attribute :virtual_string, :string

  end

  class OtherRecord < ActiveType::Record
  end

  class Child < ActiveRecord::Base
  end

  class RecordWithBelongsTo < Record

    attribute :child_id, :integer

    belongs_to :child

  end
end

describe ActiveType::Record do

  subject { RecordSpec::Record.new }
  t = Time.new(2016, 2, 1, 12)

  it 'is a ActiveRecord::Base' do
    expect(subject).to be_a(ActiveRecord::Base)
  end

  it 'is an abstract class' do
    expect(ActiveType::Record).to be_abstract_class
  end

  describe 'constructors' do
    subject { RecordSpec::Record }

    it_should_behave_like 'ActiveRecord-like constructors', { :persisted_string => "string", :persisted_integer => 100, :persisted_time => t, :persisted_date => Date.today, :persisted_boolean => true }

    it_should_behave_like 'ActiveRecord-like constructors', { :virtual_string => "string", :virtual_integer => 100, :virtual_time => t, :virtual_date => Date.today, :virtual_boolean => true }

  end

  describe 'mass assignment' do
    it_should_behave_like 'ActiveRecord-like mass assignment', { :persisted_string => "string", :persisted_integer => 100, :persisted_time => t, :persisted_date => Date.today, :persisted_boolean => true }

    it_should_behave_like 'ActiveRecord-like mass assignment', { :virtual_string => "string", :virtual_integer => 100, :virtual_time => t, :virtual_date => Date.today, :virtual_boolean => true }
  end

  describe 'accessors' do
    it_should_behave_like 'ActiveRecord-like accessors', { :persisted_string => "string", :persisted_integer => 100, :persisted_time => t, :persisted_date => Date.today, :persisted_boolean => true }

    it_should_behave_like 'ActiveRecord-like accessors', { :virtual_string => "string", :virtual_integer => 100, :virtual_time => t, :virtual_date => Date.today, :virtual_boolean => true }
  end

  describe 'overridable attributes' do

    subject { RecordSpec::RecordWithOverrides.new }

    it 'is possible to override attributes with super' do
      subject.overridable_test = "test"

      expect(subject.overridable_test).to eq("testtest")
    end
  end

  describe 'attribute name validation' do
    it 'crashes when trying to define an invalid attribute name' do
      klass = Class.new(ActiveType::Record)
      expect {
        klass.class_eval do
          attribute :"<attr>", :string
        end
      }.to raise_error(ActiveType::InvalidAttributeNameError)
    end
  end

  describe '.reset_column_information' do
    it 'does not affect virtual attributes' do
      RecordSpec::RecordCopy.new.persisted_string = "string"
      RecordSpec::RecordCopy.reset_column_information

      expect do
        RecordSpec::RecordCopy.new.virtual_string = "string"
      end.to_not raise_error
    end
  end

  context 'coercible' do
    describe 'string columns' do
      it_should_behave_like 'a coercible string column', :persisted_string
      it_should_behave_like 'a coercible string column', :virtual_string
    end

    describe 'integer columns' do
      it_should_behave_like 'a coercible integer column', :persisted_integer
      it_should_behave_like 'a coercible integer column', :virtual_integer
    end

    describe 'date columns' do
      it_should_behave_like 'a coercible date column', :persisted_date
      it_should_behave_like 'a coercible date column', :virtual_date
    end

    describe 'time columns' do
      it_should_behave_like 'a coercible time column', :persisted_time
      it_should_behave_like 'a coercible time column', :virtual_time
    end

    describe 'boolean columns' do
      it_should_behave_like 'a coercible boolean column', :persisted_boolean
      it_should_behave_like 'a coercible boolean column', :virtual_boolean
    end

    describe 'untyped columns' do
      it_should_behave_like 'an untyped column', :virtual_attribute
    end

    describe 'type columns' do
      it_should_behave_like 'a coercible type column', :virtual_type_attribute, RecordSpec.type
    end
  end

  describe '#inspect' do

    it 'returns the contents of the object as a nicely formatted string' do
      t = Time.now
      subject.persisted_string = "persisted string"
      subject.virtual_string = "string"
      subject.persisted_integer = 20
      subject.virtual_integer = 17
      subject.virtual_time = t
      subject.virtual_date = Date.today
      subject.virtual_boolean = true
      subject.virtual_attribute = OpenStruct.new({:test => "openstruct"})

      expect(subject.inspect).to eq("#<RecordSpec::Record id: nil, persisted_boolean: nil, persisted_date: nil, persisted_integer: 20, persisted_string: \"persisted string\", persisted_time: nil, virtual_attribute: #<OpenStruct test=\"openstruct\">, virtual_boolean: true, virtual_date: \"#{Date.today}\", virtual_integer: 17, virtual_string: \"string\", virtual_time: \"#{t.to_formatted_s(:db)}\", virtual_type_attribute: nil>")
    end

  end

  describe '#attributes' do

    it 'returns a hash of virtual and persisted attributes' do
      subject.persisted_string = "string"
      subject.virtual_string = "string"
      subject.virtual_integer = "17"

      expect(subject.attributes).to eq({
        "virtual_string" => "string",
        "virtual_integer" => 17,
        "virtual_time" => nil,
        "virtual_date" => nil,
        "virtual_boolean" => nil,
        "virtual_attribute" => nil,
        "virtual_type_attribute" => nil,
        "id" => nil,
        "persisted_string" => "string",
        "persisted_integer" => nil,
        "persisted_time" => nil,
        "persisted_date" => nil,
        "persisted_boolean" => nil,
      })
    end

  end

  describe 'validations' do
    subject { RecordSpec::RecordWithValidations.new }

    it 'has 1 error_on' do
      expect(subject.error_on(:persisted_string).size).to eq(1)
    end
    it 'has 1 error_on' do
      expect(subject.error_on(:virtual_string).size).to eq(1)
    end
  end

  describe 'undefined columns' do
    it 'raises an error when trying to access an undefined virtual attribute' do
      expect do
        subject.read_virtual_attribute('foo')
      end.to raise_error(ActiveType::MissingAttributeError)
    end
  end

  describe 'defaults' do
    it_should_behave_like "a class accepting attribute defaults", RecordSpec::Record
  end

  describe 'duping' do
    it_should_behave_like "a class supporting dup for attributes", RecordSpec::Record
  end

  describe 'dirty tracking' do
    it_should_behave_like 'a class supporting dirty tracking for virtual attributes', RecordSpec::Record
  end

  describe 'persistence' do

    it 'persists to the database' do
      subject.persisted_string = "persisted string"
      expect(subject.save).to eq(true)

      expect(subject.class.find(subject.id).persisted_string).to eq("persisted string")
    end
  end

  describe 'isolation' do
    it 'does not let column information bleed into different models' do
      record = RecordSpec::Record.new
      other_record = RecordSpec::OtherRecord.new

      expect(record).not_to respond_to(:other_string)
      expect(other_record).not_to respond_to(:persisted_string)
    end
  end

  describe '#belongs_to' do
    subject { RecordSpec::RecordWithBelongsTo.new }

    it_should_behave_like 'a belongs_to association', :child, RecordSpec::Child
  end

  it 'can access virtual attributes after .find' do
    subject.save!
    expect(subject.class.find(subject.id).virtual_string).to eq(nil)
    expect(subject.class.find(subject.id).virtual_string).to eq(nil)
  end

  if ActiveRecord::VERSION::MAJOR >= 5
    describe '#ar_attribute' do
      it 'delegates to ActiveRecord\'s original .attribute method' do
        klass = Class.new(RecordSpec::Record) do
          ar_attribute :ar_type, RecordSpec.type
        end
        subject = klass.new

        expect(RecordSpec.type).to receive(:cast).with('input').and_return('output')
        subject.ar_type = 'input'

        expect(subject.ar_type).to eq('output')
      end
    end
  end

  describe "#serializable_hash" do
    it "returns a hash of virtual and real attributes for serialization" do
      subject.persisted_string = "string"
      subject.virtual_string = "string"
      subject.virtual_integer = "17"

      expect(subject.serializable_hash).to eq({
        "id" => nil,
        "persisted_boolean" => nil,
        "persisted_date" => nil,
        "persisted_integer" => nil,
        "persisted_string" => "string",
        "persisted_time" => nil,
        "virtual_string" => "string",
        "virtual_integer" => 17,
        "virtual_time" => nil,
        "virtual_date" => nil,
        "virtual_boolean" => nil,
        "virtual_attribute" => nil,
        "virtual_type_attribute" => nil,
      })
    end
  end

end


text:
module ActionMailer
  module AdvAttrAccessor #:nodoc:
    def adv_attr_accessor(name, deprecation=nil)
      ivar = "@#{name}"
      deprecation ||= "Please pass :#{name} as hash key to mail() instead"

      class_eval <<-ACCESSORS, __FILE__, __LINE__ + 1
        def #{name}=(value)
          ActiveSupport::Deprecation.warn "#{name}= is deprecated. #{deprecation}"
          #{ivar} = value
        end

        def #{name}(*args)
          raise ArgumentError, "expected 0 or 1 parameters" unless args.length <= 1
          if args.empty?
            ActiveSupport::Deprecation.warn "#{name}() is deprecated and will be removed in future versions."
            #{ivar} if instance_variable_names.include?(#{ivar.inspect})
          else
            ActiveSupport::Deprecation.warn "#{name}(value) is deprecated. #{deprecation}"
            #{ivar} = args.first
          end
        end
      ACCESSORS

      self.protected_instance_variables << ivar if self.respond_to?(:protected_instance_variables)
    end
  end
end


text:
package ucar.nc2.dt;

import ucar.nc2.dataset.NetcdfDataset;
import ucar.nc2.constants.FeatureType;
import java.io.IOException;

/**
 * Interface for factories that wrap a NetcdfDataset with a subclass of TypedDataset
 *
 * @deprecated use ucar.nc2.ft.*
 * @author caron
 */
public interface TypedDatasetFactoryIF {

  /**
   * Determine if this dataset belongs to you
   *
   * @param ncd examine this NetcdfDataset to see if it belongs to this class.
   * @return true if this class knows how to create a TypedDataset out of this NetcdfDataset.
   */
  public boolean isMine(NetcdfDataset ncd);

  /**
   * Open a NetcdfDataset as a TypedDataset.
   *
   * @param ncd already opened NetcdfDataset.
   * @param task use may cancel
   * @param errlog place errors here
   * @return a subclass of TypedDataset
   * @throws java.io.IOException on error
   */
  public TypedDataset open(NetcdfDataset ncd, ucar.nc2.util.CancelTask task, StringBuilder errlog) throws IOException;

  /**
   * What kind of cientific data type will this return?
   *
   * @return scientific data type
   */
  public FeatureType getScientificDataType();

}


text:
package io.wcm.devops.conga.resource;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;

class ClasspathResourceImpl extends AbstractClasspathResourceImpl implements Resource {

  private static final long CLASS_LOADING_TIME = new Date().getTime();

  private final URL url;

  ClasspathResourceImpl(String path, ResourceLoader resourceLoader) {
    super(path, resourceLoader.getClassLoader());
    this.url = this.classLoader.getResource(convertPath(path));
  }

  ClasspathResourceImpl(URL url, ResourceLoader resourceLoader) {
    super(url.getPath(), resourceLoader.getClassLoader());
    this.url = url;
  }

  @Override
  public boolean exists() {
    return (url != null);
  }

  @Override
  public final long getLastModified() {
    return CLASS_LOADING_TIME;
  }

  @Override
  public InputStream getInputStream() {
    try {
      return url.openStream();
    }
    catch (IOException ex) {
      throw new ResourceException("Unable to open classpath stream for: " + path, ex);
    }
  }

}


text:
/**
 * Controller module for the header
 * @module controllers/header
 */

angular.module('controllers.header', [
	'config',
	'services.auth',
	'services.article'
])
.controller('HeaderController', function($scope, $rootScope, $location, AuthService, ArticlesService) {
	$scope.message = 'Who we are';
	$rootScope.user = AuthService.get();
	$rootScope.alert = {
		class: 'alert-success',
		message: 'Done'
	};
	$rootScope.articleNumber = 0;
	if($rootScope.user) ArticlesService.get(function(arg){
		$scope.articles = arg;
		//load first by default if exist
		if($scope.articles.length) $scope.load($scope.articleNumber);
	});
	// OPS
	$scope.load = function(index) {
		var content = $scope.articles[index];
		$rootScope.articleNumber = index;
		console.log('loading content...', content);
		$('#originalText').val(content.content);
		$('div[ng-model="html"]').html(content.wysiwyg);
		// insert into editor mode
		$rootScope.article = content;
		console.log($location);
		switch($location.path()) {
			case '/worknotes':
				console.log('wee');
				break;
			default:
				console.log('mark', content.markdown);
				window.editor.setValue(content.markdown);
		}
	}

	$scope.save = function(){
		var auxObj = {
			title: $scope.title,
			content: $('#originalText').val(),
			markdown: window.html,
			wysiwyg: $('input[type="hidden"]').val()
		};
		var article = new ArticlesService(auxObj);
		article.$save(function(arg) {
			$rootScope.alert = {
				class: 'alert-success',
				message: 'Saved properly'
			};
			$('.alert').show();
			auxObj.id = arg.id;
			$scope.articles = ArticlesService.get();
		});
	}
	$scope.update = function(articleID) {
		// console.log(articleID);
		var a = articleID;
		var auxObj = {
			content: $('#originalText').val(),
			markdown: window.html
		};
		ArticlesService.update({id: a}, auxObj, function(arg) {
			$rootScope.alert = {
				class: 'alert-info',
				message: 'Updated properly'
			};
			$('#myModal .close-modal').click();
			$('.alert').show();
			$scope.articles = ArticlesService.get();
		});
	}

	$scope.delete = function(articleID) {
		// console.log(articleID);
		var a = articleID;
		ArticlesService.delete({id:a}, function(arg) {
			$rootScope.alert = {
				class: 'alert-danger',
				message: 'Deleted properly'
			};
			$('#myModal .close-modal').click();
			$('.alert').show();
			$scope.articles = ArticlesService.get();
		});
	}

	$rootScope.toggleNav = function() {
		$('#navbar').toggle();
		$('#toggleDown').toggle();
	}
})


text:
hapi-plugin-djStatic
================

Static files plugin for hapi integration testing