text:
[![npm version](https://badge.fury.io/js/leaflet.browser.print.svg)](https://www.npmjs.com/package/leaflet.browser.print)

## General information

A [leaflet](http://www.leafletjs.com) plugin which allows users to [print full page map](https://igor-vladyka.github.io/leaflet.browser.print/) directly from the browser
* Pros:
	- Compatible with Leaflet v1+.
	- Any page size from range A0-A10, B0-B10, C0-C10, D0-D10 can se used.
	- North American paper sizes available as well: Letter, HalfLetter, Legal, JuniorLegal, Tabloid, Ledger
	- Available 4 print modes, you can chose any you want and even create your own.
	- Everything in browser, no external apps or dependencies, print your map in one click.
	- You can even override default browser print behavior and export map as image, more details you can find [here](https://github.com/Igor-Vladyka/leaflet.browser.print#download-map-as-image).
	- Any additional page content can be printed together with a map.
	- Leaflet Print Control
	- And many more...just ask!

* Cons:
	- Doesn't change page orientation automatically in IE and FF, due to [The @page rule and forcing Landscape orientation](http://css-discuss.incutio.com/wiki/Print_Stylesheets#The_.40page_rule_and_forcing_Landscape_orientation)

[Changelog](https://github.com/Igor-Vladyka/leaflet.browser.print/blob/master/CHANGELOG.md)

### Other examples:
Check out the:
* [General example](https://igor-vladyka.github.io/leaflet.browser.print/)
* [Localization](https://igor-vladyka.github.io/leaflet.browser.print/examples/localization.html)
* [Print objects manipulations](https://igor-vladyka.github.io/leaflet.browser.print/examples/manipulations.html)
* [Map legend printing](https://igor-vladyka.github.io/leaflet.browser.print/examples/print-with-legend.html)
* [Export map as Image](https://igor-vladyka.github.io/leaflet.browser.print/examples/savePNG.html)

### Be careful when printing map legend
Common problem with printing map with a legend is external CSS plugins that ruins everything, [here is an actual good answer why it is like that with Bootstrap plugin](https://stackoverflow.com/questions/33410724/bootstrap-print-css-removes-background-color). Please read it carefully.

### Downloads
**NPM**
````
	npm install --save leaflet.browser.print
````

**YARN**
````
	yarn add leaflet.browser.print
````

**SCRIPT**
```html
	<script src="dist/leaflet.browser.print.min.js"></script>
```

### Usage
#### Add a Control
Add the following line of code to your map script

```javascript
var browserControl = L.control.browserPrint(options).addTo(map);
```

You can pass a number of options to the control:

| Option        | Type         | Default      | Description   |
| ------------- |--------------|--------------|---------------|
| position      | [Leaflet control position](http://leafletjs.com/reference-1.5.0.html#control-position) | 'topleft' | Position the print button |
| title         | String       | 'Print map'  | Sets the text which appears as the tooltip of the print button |
| printModes    | Array        | ["Portrait", "Landscape", "Auto", "Custom"] | Collection of page print actions |

Also the options for the [backend](#Use it in the Backend) can passed through.

```javascript
L.control.browserPrint({position: 'topleft', title: 'Print ...'}).addTo(map);
```

To use the same BrowserPrint class in the backend and in the control you can pass it while creating the control:
```javascript
var browserPrint = L.browserPrint(map,backendOptions);
L.control.browserPrint(controlOptions,browserPrint).addTo(map);
```

Here's an example of passing through some options:
```javascript
var customActionToPrint = function(context, mode) {
	return function() {
		window.alert("We are printing the MAP. Let's do Custom print here!");
		context._printMode(mode);
	}
};

L.control.browserPrint({
	title: 'Just print me!',
	documentTitle: 'Map printed using leaflet.browser.print plugin',
	printLayer: L.tileLayer('https://stamen-tiles-{s}.a.ssl.fastly.net/watercolor/{z}/{x}/{y}.{ext}', {
					attribution: 'Map tiles by <a href="http://stamen.com">Stamen Design</a>, <a href="http://creativecommons.org/licenses/by/3.0">CC BY 3.0</a> — Map data © <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>',
					subdomains: 'abcd',
					minZoom: 1,
					maxZoom: 16,
					ext: 'png'
				}),
	closePopupsOnPrint: false,
	printModes: [
            L.BrowserPrint.Mode.Landscape("Tabloid",{title: "Tabloid VIEW"}),
            L.browserPrint.mode("Alert",{title:"User specified print action",pageSize: "A6", action: customActionToPrint, invalidateBounds: false}),
            L.BrowserPrint.Mode.Landscape(),
            "Portrait",
            L.BrowserPrint.Mode.Auto("B4",{title: "Auto"}),
            L.BrowserPrint.Mode.Custom("B5",{title:"Select area"})
	],
	manualMode: false
}).addTo(map);
```

To stop printing call `cancel()`:
```javascript
browserControl.cancel();
```

#### Use it in the Backend
Add the following line of code to your map script

```javascript
var browserPrint = L.browserPrint(map, options);
```

And then you can start printing with:
```javascript
browserPrint.print(L.BrowserPrint.Mode.Landscape());
```
To stop printing call `cancel()`:
```javascript
browserPrint.cancel();
```

You can pass a number of options for printing:

| Option        | Type         | Default      | Description   |
| ------------- |--------------|--------------|---------------|
| printModes    | Array        | ["Portrait", "Landscape", "Auto", "Custom"] | Collection of page print actions |
| documentTitle | String       | ''  		  | Sets the text which appears as the print page title |
| printLayer    | [Leaflet tile layer](http://leafletjs.com/reference-1.7.1.html#tilelayer) | null | A tiles layer to show instead of all current active tile layers |
| closePopupsOnPrint | Boolean | true | Indicates if we need to force popup closing for printed map |
| contentSelector | String | "[leaflet-browser-print-content]" | Content selector for printed map, will select and dynamically inject content on printed maps. For full functionality please check "Printing additional content section" |
| pagesSelector | String | "[leaflet-browser-print-pages]" | Pages selector for printed map, will select and dynamically inject additional pages content on printed maps. |
| manualMode | Boolean | false | Adds a button with id='leaflet-browser-print--manualMode-button' for debugging purpose, also can be used to print map with external button. |
| customPrintStyle | [Polyline options](https://leafletjs.com/reference-1.7.1.html#polyline-option) | `{ color: "gray", dashArray: "5, 10", pane: "customPrintPane" }` | Style for rectangle on custom print. 'customPrintPane' - is a custom pane with z-index => 9999 |
| cancelWithEsc    | Boolean        | true | Cancel printing with the ESC key |
| printFunction    | Function | window.print | Function that will be executed for printing. |
| debug    | Boolean        | false | Stops opening the print window. Only for developing use. |

Here's an example of passing through some options:
```javascript
var options = {
    documentTitle: 'Map printed using leaflet.browser.print plugin',
    printLayer: L.tileLayer('https://stamen-tiles-{s}.a.ssl.fastly.net/watercolor/{z}/{x}/{y}.{ext}', {
                    attribution: 'Map tiles by <a href="http://stamen.com">Stamen Design</a>, <a href="http://creativecommons.org/licenses/by/3.0">CC BY 3.0</a> — Map data © <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>',
                    subdomains: 'abcd',
                    minZoom: 1,
                    maxZoom: 16,
                    ext: 'png'
                }),
    closePopupsOnPrint: false,
    manualMode: false
};
var browserPrint = L.browserPrint(map, options);
```

### Print Modes

| Mode          | Description    |
| ------------- | -------------- |
| Portrait      | Print currently visual part of the map with Portrait page dimensions |
| Landscape     | Print currently visual part of the map with Landscape page dimensions |
| Auto          | Track all active map layers (markers, lines, polygons, etc. ) and tries to fit them in print page in Portrait or Landscape page dimensions |
| Custom        | Allows you to select rectangle for printing, and then fit it in Portrait or Landscape page dimensions if it is not explicit set |

General modes:
```javascript
	L.BrowserPrint.Mode.Landscape();
	L.BrowserPrint.Mode.Portrait();
	L.BrowserPrint.Mode.Auto();
	L.BrowserPrint.Mode.Custom();
```

For each general mode the page size and options can be passed. The default page size is `A4`
```javascript
L.BrowserPrint.Mode.Landscape(pageSize,options);
```

| Option        | Type         | Default      | Description   |
| ------------- |--------------|--------------|---------------|
| title         | String       | The mode name. f.e. "Portrait" | Set the control menu text |
| pageSize      | String       | 'A4'          | Size of page that will be printed |
| orientation   | String       | Mode name or calculation (Auto & Custom) | How the page will be displayed landscape or portrait |
| zoom          | Integer      | 0             | Zoom the map to this level |
| enableZoom    | Boolean      | true          | Zoom the map optimal, else the current zoom is taken. `zoom` have to be `0` |
| action        | Function     | default mode action | [Custom print button action](#Custom print button action) |
| rotate        | Integer      | 0             | Rotate the map x-times by 90° |
| margin        | Object       | automatic     | The default margin are `(height + width) / 39.9`. A number can passed for all margins or set it explicit in a object for `left`, `right`, `top`, `bottom` --> `{left: 10, top: 40}`  |
| scale         | Double       | 1             | Scale the map. Shows all bigger or smaller, with `1` the map looks normal |
| header        | Object       |               | Adds a header section to the top of the page. For the available options look in the "Header / Footer Options" table below |
| footer        | Object       |               | Adds a footer section to the bottom of the page. For the available options look in the "Header / Footer Options" table below |

#### Header / Footer Options
| Option        | Type         | Default      | Description   |
| ------------- |--------------|--------------|---------------|
| enabled       | Boolean      | false        | Shows the section |
| text          | String / HTML| ""           | The displayed text |
| size          | String       | "10mm"       | The height of the section |
| overTheMap    | Boolean      | false        | The section is displayed over the map|

You can overwrite the CSS or change the DOM over the ids `#print-header` and `#print-footer`

Creating a own mode: `L.BrowserPrint.Mode(name,options);`
```javascript
L.browserPrint.mode("Alert Mode",{pageSize: 'A3',orientation: 'Portrait'});
```

The mode options can be updated with:
```javascript
mode.setOptions(options);
```

### Map Events

| Map Event           | Event Shortcut                          | Value           		 			     | Description 													   | Purpose |
| ------------------- | --------------------------------------- | -------------------------------------- | --------------------------------------------------------------- | ------- |
| browser-print-init  | L.BrowserPrint.Event.PrintInit  | { mode }                               | Fire right after printing was initialized.                      | To support busy indicator of any type to show user loaing status. |
| browser-pre-print   | L.BrowserPrint.Event.PrePrint   | { pageSize, pageBounds, printObjects } | Fire before print started, allows manipulation with map objects.| For DOM manipulation with real map objects.|
| browser-print-start | L.BrowserPrint.Event.PrintStart | { printLayer, printMap, printObjects } | Fire on print started, before all print calculations is done.   | For DOM manipulation with print map and print objects. |
| browser-print       | L.BrowserPrint.Event.Print      | { printLayer, printMap, printObjects } | Fire right before native print. 								   | For DOM manipulation with print map and print objects. |
| browser-print-end   | L.BrowserPrint.Event.PrintEnd   | { printLayer, printMap, printObjects } | Fire on print end, after we refresh map to show initial view.   | For DOM manipulation with real map objects after print |
| browser-print-cancel| L.BrowserPrint.Event.PrintCancel   | { mode } | Fire when printing cancelded   | For DOM manipulation with real map objects after cancel |

Example can be found here: [DEMO with print objects manipulations](https://igor-vladyka.github.io/leaflet.browser.print/examples/manipulations.html);

### Printing additional content section

To add additional printing content (in addition to a map itself) we need to specify content that should be added: [Demo](https://igor-vladyka.github.io/leaflet.browser.print/);
By default contentSelector: '[leaflet-browser-print-content]' so we need a content with an 'leaflet-browser-print-content' attribute.

Code example:

```html
<style leaflet-browser-print-content>
	.grid-print-container { // grid holder that holds all content (map and any other content)
		grid-template: auto 1fr auto / 1fr;
		background-color: orange;
	}
	.grid-map-print { // map container itself
		grid-row: 2;
	}
	.title { // Dynamic title styling
		grid-row: 1;
		justify-self: center;
		color: white;
	}
	.sub-content { // Dynamic sub content styling
		grid-row: 5;
		padding-left: 10px;
	}
</style>
<h1 class="title" leaflet-browser-print-content>Leaflet Browser print TITLE</h1>
<h3 class="sub-content" leaflet-browser-print-content>Leaflet Browser print SUB TITLE text</h3>
```

On print, plugin will scan DOM by contentSelector, and will add content to print may.

````
We are using CSS-GRID to position all controls on a print page.
Therefor it's not supportable in all browsers, for more information please visit [caniuse.com](https://caniuse.com/#feat=css-grid).
````

### Angular 2+
````
See chapter 4 of https://github.com/Asymmetrik/ngx-leaflet-tutorial-plugins/tree/master/Leaflet.BrowserPrint
````

### New print layers/renderers registration
To add missing print layers you need to explicitly indicate layer, it's identifier and construction function that will return actual layer object.

Example of L.MarkerClusterGroup registration:
```js
L.BrowserPrint.Utils.registerLayer(
	// Actual typeof object to compare with
	L.MarkerClusterGroup,
	// Any string you would like for current function for print events
	'L.MarkerClusterGroup',
	function (layer, utils) {
		// We need to recreate cluster object with available options
		// Here we use function, but we can use object aswell,
		// example: new L.MarkerClusterGroup(layer._group.options);
		var cluster = L.markerClusterGroup(layer._group.options);

		// And we clone all inner layers to our new cluster
		// to properly recalculate/recreate position for print map
		cluster.addLayers(utils.cloneInnerLayers(layer._group));

		return cluster;
	});
```

List of pre-registered layers available for printing:
* L.TileLayer.WMS
* L.TileLayer
* L.ImageOverlay
* L.Marker
* L.Popup
* L.Circle
* L.CircleMarker
* L.Rectangle
* L.Polygon
* L.MultiPolyline
* L.MultiPolygon
* L.Polyline
* L.GeoJSON
* L.FeatureGroup
* L.LayerGroup
* L.Tooltip

Example of renderer registration:
```js
L.BrowserPrint.Utils.registerRenderer(L.SVG, 'L.SVG');
```

List of registered renderers
* L.SVG
* L.Canvas

If you want to override any of those, please register your own builder for them.

#### MarkerClusterGroup OutOfMemory problem:
If you are facing OutOfMemory problem printing huge amount of objects you may consider next workaround:
```js
// markerClusterGroup to print
var printableObjects = L.markerClusterGroup();

// We are not cloning markercluster to preserve original clasterization behavior and prevent OutOfMemory problems
// This way we will need to invalidate MarkerClusterGroup after printing
L.BrowserPrint.Utils.registerLayer(L.MarkerClusterGroup,
										  'L.MarkerClusterGroup',
											function (layer, utils) {
												return layer;
											});

// On print end we invalidate markercluster to update markers;
map.on(L.BrowserPrint.Event.PrintEnd, function(e) {
	map.removeLayer(printableObjects);
	map.addLayer(printableObjects);
});

// Initial rendering ouf objects
map.addLayer(printableObjects);
```

### Download Map as Image
To download map as PNG you have to use external plugin to do the job. Current plugin will do only 1 job - prepare map for printing.
To print actual map we use in-browser print mechanism:
```js
window.print()
```

You can use the options `printFunction` to implement any other behavior that you want.
Example with [domtoimage](https://github.com/tsayen/dom-to-image) plugin to export map as image.png:

```js
var saveAsImage = function () {
	return domtoimage.toPng(document.body)
        .then(function (dataUrl) {
            var link = document.createElement('a');
            link.download = map.printControl.options.documentTitle || "exportedMap" + '.png';
            link.href = dataUrl;
            link.click();
        });
};

L.control.browserPrint({
    documentTitle: "printImage",
    printModes: [
        L.BrowserPrint.Mode.Auto("Download PNG"),
    ],
    printFunction: saveAsImage
}).addTo(map);
```

Full example you can find [here](https://igor-vladyka.github.io/leaflet.browser.print/examples/savePNG.html).

### Custom print button action
Example of how you can use default button or style/specify your own button to call actual print logic. First of all you need to create print plugin with at least one print option to be able to attach it to the map, later you can use any other, even dynamically created print mode with your custom print button.

Example:
```js
    L.control.browserPrint({
        printLayer: L.tileLayer('https://stamen-tiles-{s}.a.ssl.fastly.net/watercolor/{z}/{x}/{y}.{ext}', {
                    	attribution: 'Map tiles by <a href="http://stamen.com">Stamen Design</a>, <a href="http://creativecommons.org/licenses/by/3.0">CC BY 3.0</a> — Map data © <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>',
                    	subdomains: 'abcd',
                    	minZoom: 1,
                    	maxZoom: 16,
                    	ext: 'png'
                    }),
		printModes: [ "Landscape" ],
		manualMode: true // use true if it's debug and/or default button is okay for you, otherwise false.
    }).addTo(map);

	document.querySelector("#custom_print_button").addEventListener("click", function(){
		var modeToUse = L.BrowserPrint.Mode.Auto();
		map.printControl.print(modeToUse);
	});
```

And add next css to hide onmap menu:
```CSS
	.leaflet-control-browser-print {display: none;}
```

### Important notes
````
Unfortunately 'Custom' mode is not working correctly for Leaflet v.0.7.7 in all IE browsers.
````

### Acknowledgements
Thanks to [Rowan Winsemius](https://github.com/rowanwins/leaflet-easyPrint) for general idea with a map print functionality.

Thanks to [Jan Pieter Waagmeester](https://github.com/jieter/leaflet-clonelayer) for an idea that helped with map print functionality.

Also thanks to [IcoMoon](http://icomoon.io/) for the print icon.

Thanks to [Falke-Design](https://github.com/falke-design/) for restructuring the project and adding more functions


text:
package org.asynchttpclient.uri;

import java.net.URI;
import java.net.URISyntaxException;

import org.asynchttpclient.util.MiscUtils;
import org.asynchttpclient.util.StringUtils;

public class Uri {

    public static Uri create(String originalUrl) {
        return create(null, originalUrl);
    }

    public static Uri create(Uri context, final String originalUrl) {
        UriParser parser = new UriParser();
        parser.parse(context, originalUrl);

        return new Uri(parser.scheme,//
                parser.userInfo,//
                parser.host,//
                parser.port,//
                parser.path,//
                parser.query);
    }

    private final String scheme;
    private final String userInfo;
    private final String host;
    private final int port;
    private final String query;
    private final String path;
    private String url;

    public Uri(String scheme,//
            String userInfo,//
            String host,//
            int port,//
            String path,//
            String query) {

        if (scheme == null)
            throw new NullPointerException("scheme");
        if (host == null)
            throw new NullPointerException("host");

        this.scheme = scheme;
        this.userInfo = userInfo;
        this.host = host;
        this.port = port;
        this.path = path;
        this.query = query;
    }

    public String getQuery() {
        return query;
    }

    public String getPath() {
        return path;
    }

    public String getUserInfo() {
        return userInfo;
    }

    public int getPort() {
        return port;
    }

    public String getScheme() {
        return scheme;
    }

    public String getHost() {
        return host;
    }

    public URI toJavaNetURI() throws URISyntaxException {
        return new URI(toUrl());
    }

    public String toUrl() {
        if (url == null) {
            StringBuilder sb = StringUtils.stringBuilder();
            sb.append(scheme).append("://");
            if (userInfo != null)
                sb.append(userInfo).append('@');
            sb.append(host);
            if (port != -1)
                sb.append(':').append(port);
            if (path != null)
                sb.append(path);
            if (query != null)
                sb.append('?').append(query);
            url = sb.toString();
            sb.setLength(0);
        }
        return url;
    }

    public String toRelativeUrl() {
        StringBuilder sb = StringUtils.stringBuilder();
        if (MiscUtils.isNonEmpty(path))
            sb.append(path);
        else
            sb.append('/');
        if (query != null)
            sb.append('?').append(query);

        return sb.toString();
    }

    @Override
    public String toString() {
        // for now, but might change
        return toUrl();
    }

    public Uri withNewScheme(String newScheme) {
        return new Uri(newScheme,//
                userInfo,//
                host,//
                port,//
                path,//
                query);
    }

    public Uri withNewQuery(String newQuery) {
        return new Uri(scheme,//
                userInfo,//
                host,//
                port,//
                path,//
                newQuery);
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((host == null) ? 0 : host.hashCode());
        result = prime * result + ((path == null) ? 0 : path.hashCode());
        result = prime * result + port;
        result = prime * result + ((query == null) ? 0 : query.hashCode());
        result = prime * result + ((scheme == null) ? 0 : scheme.hashCode());
        result = prime * result + ((userInfo == null) ? 0 : userInfo.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Uri other = (Uri) obj;
        if (host == null) {
            if (other.host != null)
                return false;
        } else if (!host.equals(other.host))
            return false;
        if (path == null) {
            if (other.path != null)
                return false;
        } else if (!path.equals(other.path))
            return false;
        if (port != other.port)
            return false;
        if (query == null) {
            if (other.query != null)
                return false;
        } else if (!query.equals(other.query))
            return false;
        if (scheme == null) {
            if (other.scheme != null)
                return false;
        } else if (!scheme.equals(other.scheme))
            return false;
        if (userInfo == null) {
            if (other.userInfo != null)
                return false;
        } else if (!userInfo.equals(other.userInfo))
            return false;
        return true;
    }
}

redpajama_set_name: RedPajamaGithub


text:
import os
import re
import time
import datetime
import hashlib
import string
import random

from google.appengine.ext import webapp
from google.appengine.api import memcache
from google.appengine.ext import db
from google.appengine.ext.webapp import util
from google.appengine.ext.webapp import template

from v2ex.babel import Member
from v2ex.babel import Counter
#from v2ex.babel import Section
from v2ex.babel import Node
from v2ex.babel import Topic
from v2ex.babel import Reply
from v2ex.babel import Note
from v2ex.babel import Site

from v2ex.babel import SYSTEM_VERSION

from v2ex.babel.security import *
from v2ex.babel.ua import *
from v2ex.babel.da import *
from v2ex.babel.l10n import *
from v2ex.babel.ext.cookies import Cookies

template.register_template_library('v2ex.templatetags.filters')

class NotesHomeHandler(webapp.RequestHandler):
    def get(self):
        site = GetSite()
        browser = detect(self.request)
        template_values = {}
        template_values['site'] = site
        template_values['system_version'] = SYSTEM_VERSION
        template_values['page_title'] = site.title + u' › 记事本'
        member = CheckAuth(self)
        l10n = GetMessages(self, member, site)
        template_values['l10n'] = l10n
        if member:
            template_values['member'] = member
            q = db.GqlQuery("SELECT * FROM Note WHERE member = :1 ORDER BY last_modified DESC", member)
            try:
                notes_count = q.count()
            except:
                q = db.GqlQuery("SELECT * FROM Note WHERE member = :1 ORDER BY created DESC", member)
                notes_count = q.count()
            if (notes_count > 0):
                template_values['notes'] = q
            if browser['ios']:
                path = os.path.join(os.path.dirname(__file__), 'tpl', 'mobile', 'notes_home.html')
            else:
                path = os.path.join(os.path.dirname(__file__), 'tpl', 'desktop', 'notes_home.html')
            output = template.render(path, template_values)
            self.response.out.write(output)
        else:
            self.redirect('/signin')

class NotesNewHandler(webapp.RequestHandler):
    def get(self):
        site = GetSite()
        template_values = {}
        template_values['site'] = site
        template_values['system_version'] = SYSTEM_VERSION
        template_values['page_title'] = site.title + u' › 新建记事'
        member = CheckAuth(self)
        l10n = GetMessages(self, member, site)
        template_values['l10n'] = l10n
        if member:
            template_values['member'] = member
            path = os.path.join(os.path.dirname(__file__), 'tpl', 'desktop', 'notes_new.html')
            output = template.render(path, template_values)
            self.response.out.write(output)
        else:
            self.redirect('/signin')

    def post(self):
        site = GetSite()
        template_values = {}
        template_values['site'] = site
        template_values['system_version'] = SYSTEM_VERSION
        template_values['page_title'] = site.title + u' › 新建记事'
        member = CheckAuth(self)
        l10n = GetMessages(self, member, site)
        template_values['l10n'] = l10n
        if member:
            template_values['member'] = member
            # Verification: content
            note_content = self.request.get('content').strip()
            note_content_length = len(note_content)
            if note_content_length > 0:
                note = Note()
                q = db.GqlQuery('SELECT * FROM Counter WHERE name = :1', 'note.max')
                if (q.count() == 1):
                    counter = q[0]
                    counter.value = counter.value + 1
                else:
                    counter = Counter()
                    counter.name = 'note.max'
                    counter.value = 1
                q2 = db.GqlQuery('SELECT * FROM Counter WHERE name = :1', 'note.total')
                if (q2.count() == 1):
                    counter2 = q2[0]
                    counter2.value = counter2.value + 1
                else:
                    counter2 = Counter()
                    counter2.name = 'note.total'
                    counter2.value = 1
                note.num = counter.value
                note.title = note_content.split("\n")[0][0:60].strip()
                note.content = note_content
                note.body = "\n".join(note_content.split("\n")[1:]).strip()
                note.length = len(note_content)
                note.member_num = member.num
                note.member = member
                note.put()
                counter.put()
                counter2.put()
                self.redirect('/notes/' + str(note.num))
            else:
                template_values['note_content'] = note_content
                path = os.path.join(os.path.dirname(__file__), 'tpl', 'desktop', 'notes_new.html')
                output = template.render(path, template_values)
                self.response.out.write(output)
        else:
            self.redirect('/signin')

class NotesItemHandler(webapp.RequestHandler):
    def get(self, num):
        site = GetSite()
        browser = detect(self.request)
        template_values = {}
        template_values['site'] = site
        template_values['system_version'] = SYSTEM_VERSION
        member = CheckAuth(self)
        l10n = GetMessages(self, member, site)
        template_values['l10n'] = l10n
        if member:
            q = db.GqlQuery("SELECT * FROM Note WHERE num = :1", int(num))
            if q.count() > 0:
                note = q[0]
                if note.member.num == member.num:
                    template_values['member'] = member
                    template_values['note'] = note
                    template_values['page_title'] = site.title + u' › 记事本 › ' + note.title
                    if browser['ios']:
                        path = os.path.join(os.path.dirname(__file__), 'tpl', 'mobile', 'notes_item.html')
                    else:
                        path = os.path.join(os.path.dirname(__file__), 'tpl', 'desktop', 'notes_item.html')
                    output = template.render(path, template_values)
                    self.response.out.write(output)
                else:
                    self.redirect('/')
            else:
                self.redirect('/')
        else:
            self.redirect('/signin')

class NotesItemEraseHandler(webapp.RequestHandler):
    def get(self, num):
        site = GetSite()
        template_values = {}
        template_values['site'] = site
        template_values['system_version'] = SYSTEM_VERSION
        template_values['page_title'] = site.title + u' › 记事本'
        member = CheckAuth(self)
        l10n = GetMessages(self, member, site)
        template_values['l10n'] = l10n
        if member:
            q = db.GqlQuery("SELECT * FROM Note WHERE num = :1", int(num))
            if q.count() > 0:
                note = q[0]
                if note.member.num == member.num:
                    note.delete()
                    self.redirect('/notes')
                else:
                    self.redirect('/notes')
            else:
                self.redirect('/notes')
        else:
            self.redirect('/signin')

class NotesItemEditHandler(webapp.RequestHandler):
    def get(self, num):
        site = GetSite()
        template_values = {}
        template_values['site'] = site
        template_values['system_version'] = SYSTEM_VERSION
        template_values['page_title'] = site.title + u' › 记事本 › 编辑'
        member = CheckAuth(self)
        l10n = GetMessages(self, member, site)
        template_values['l10n'] = l10n
        if member:
            q = db.GqlQuery("SELECT * FROM Note WHERE num = :1", int(num))
            if q.count() > 0:
                note = q[0]
                if note.member.num == member.num:
                    template_values['member'] = member
                    template_values['note'] = note
                    path = os.path.join(os.path.dirname(__file__), 'tpl', 'desktop', 'notes_edit.html')
                    output = template.render(path, template_values)
                    self.response.out.write(output)
                else:
                    self.redirect('/notes')
            else:
                self.redirect('/notes')
        else:
            self.redirect('/signin')

    def post(self, num):
        site = GetSite()
        template_values = {}
        template_values['site'] = site
        template_values['system_version'] = SYSTEM_VERSION
        template_values['page_title'] = site.title + u' › 记事本'
        member = CheckAuth(self)
        l10n = GetMessages(self, member, site)
        template_values['l10n'] = l10n
        if member:
            template_values['member'] = member
            # Verification: content
            note_content = self.request.get('content').strip()
            note_content_length = len(note_content)
            if note_content_length > 0:
                q = db.GqlQuery("SELECT * FROM Note WHERE num = :1", int(num))
                if q.count() > 0:
                    note = q[0]
                    template_values['page_title'] = site.title + u' › 记事本 › 编辑'
                    if note.member.num == member.num:
                        note.title = note_content.split("\n")[0][0:60].strip()
                        note.content = note_content
                        note.body = "\n".join(note_content.split("\n")[1:]).strip()
                        note.length = len(note_content)
                        note.edits = note.edits + 1
                        note.put()
                        memcache.set('Note_' + str(note.num), note, 86400)
                        self.redirect('/notes/' + str(note.num))
                    else:
                        self.redirect('/notes')
                else:
                    self.redirect('/notes')
            else:
                template_values['note_content'] = note_content
                path = os.path.join(os.path.dirname(__file__), 'tpl', 'desktop', 'notes_new.html')
                output = template.render(path, template_values)
                self.response.out.write(output)
        else:
            self.redirect('/signin')

def main():
    application = webapp.WSGIApplication([
    ('/notes', NotesHomeHandler),
    ('/notes/new', NotesNewHandler),
    ('/notes/([0-9]+)', NotesItemHandler),
    ('/notes/([0-9]+)/erase', NotesItemEraseHandler),
    ('/notes/([0-9]+)/edit', NotesItemEditHandler)
    ],
                                         debug=True)
    util.run_wsgi_app(application)

if __name__ == '__main__':
    main()


text:
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="hn.join.fieldwork.persistence.TrackInfoMapper">

	<resultMap type="hn.join.fieldwork.domain.TrackInfo" id="trackInfoMap">
		<id column="track_id" property="id" jdbcType="BIGINT" />
		<result column="field_worker_id" property="fieldWorkerId"
			jdbcType="BIGINT" />
		<result column="area_code" property="areaCode" jdbcType="VARCHAR" />
		<result column="latitude" property="latitude" jdbcType="FLOAT" />
		<result column="longitude" property="longitude" jdbcType="FLOAT" />
		<result column="address" property="address" jdbcType="VARCHAR" />
		<result column="create_time" property="createTime" jdbcType="TIMESTAMP" />
		<association property="fieldworker" column="field_worker_id"
			select="hn.join.fieldwork.persistence.FieldWorkerMapper.getById" />
	</resultMap>

	<select id="findInTimeSpan" resultMap="trackInfoMap">

		select track_id,field_worker_id,area_code,latitude,longitude,address,create_time from tbl_track_info
			<trim prefix="WHERE" prefixOverrides="AND |OR ">
				<if test="fieldWorkerId!=null">
					field_worker_id = #{fieldWorkerId}
				</if>
				<if test="fromTime!=null">
					AND create_time >= #{fromTime}
				</if>
				<if test="toTime !=null">
					AND create_time < #{toTime}
				</if>
			</trim>

	</select>

	<insert id="insertTrackInfo" parameterType="hn.join.fieldwork.domain.TrackInfo">
		<selectKey resultType="java.lang.Long" keyProperty="id" order="AFTER">
			select LAST_INSERT_ID()
		</selectKey>
	insert into
	tbl_track_info(field_worker_id,area_code,latitude,longitude,address,create_time)
	values
	(#{fieldWorkerId,jdbcType=BIGINT},#{areaCode,jdbcType=VARCHAR},#{latitude,jdbcType=FLOAT},#{longitude,jdbcType=FLOAT},#{address,jdbcType=VARCHAR},#{createTime,jdbcType=TIMESTAMP})

	</insert>

</mapper>


text:
package com.example.stream.core.ui.recycler;

import android.support.annotation.ColorInt;

import com.choices.divider.DividerItemDecoration;

/**
 * Created by StReaM on 8/25/2017.
 */

public class BaseDecoration extends DividerItemDecoration {

    private BaseDecoration(@ColorInt int color, int size) {
        setDividerLookup(new DividerLookupImpl(color, size));
    }

    public static BaseDecoration create(@ColorInt int color, int size) {
        return new BaseDecoration(color, size);
    }
}


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=ISO-8859-1">
        <TITLE>
            org.apache.commons.cli (Commons CLI 1.2 API)
        </TITLE>

        <META NAME="keywords" CONTENT="org.apache.commons.cli package">

        <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

                            Package
                            Class
                            Use
                            Tree
                            Deprecated
                            Index
                            Help

                     PREV PACKAGE
                     NEXT PACKAGE

                    FRAMES
                     NO FRAMES

                        All Classes

        Package org.apache.commons.cli

    Commons CLI 1.2

        See:

                  Description

                    Interface Summary

            CommandLineParser
            A class that implements the CommandLineParser interface
                can parse a String array according to the Options specified
                and return a CommandLine.

                    Class Summary

            BasicParser
            The class BasicParser provides a very simple implementation of
                the flatten method.

            CommandLine
            Represents list of arguments parsed against a Options descriptor.

            GnuParser
            The class GnuParser provides an implementation of the
                flatten method.

            HelpFormatter
            A formatter of help messages for the current command line options

            Option
            Describes a single command-line option.

            OptionBuilder
            OptionBuilder allows the user to create Options using descriptive methods.

            OptionGroup
            A group of mutually exclusive options.

            Options
            Main entry-point into the library.

            Parser
            Parser creates CommandLines.

            PatternOptionBuilder

                Allows Options to be created from a single String.

            PosixParser
            The class PosixParser provides an implementation of the
                flatten method.

            TypeHandler
            This is a temporary implementation.

                    Exception Summary

            AlreadySelectedException
            Thrown when more than one option in an option group
                has been provided.

            MissingArgumentException
            Thrown when an option requiring an argument
                is not provided with an argument.

            MissingOptionException
            Thrown when a required option has not been provided.

            ParseException
            Base for Exceptions thrown during parsing of a command-line.

            UnrecognizedOptionException
            Exception thrown during parsing signalling an unrecognized
                option was seen.

        Package org.apache.commons.cli Description

        Commons CLI 1.2

                            Package
                            Class
                            Use
                            Tree
                            Deprecated
                            Index
                            Help

                     PREV PACKAGE
                     NEXT PACKAGE

                    FRAMES
                     NO FRAMES

                        All Classes

    Copyright © 2002-2009 The Apache Software Foundation. All Rights Reserved.


text:
package pyspark_cassandra.pickling;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.Iterator;

import net.razorvine.pickle.PickleException;
import net.razorvine.pickle.custom.Pickler;

import org.apache.spark.api.java.function.FlatMapFunction;

import pyspark_cassandra.types.Types;

public class BatchPickle<T> implements FlatMapFunction<Iterator<T>, byte[]> {
	private static final long serialVersionUID = 1L;

	private static final int DEFAULT_BATCH_SIZE = 1000;

	static {
		Types.registerCustomTypes();
	}

	private transient Pickler pickler = new Pickler();
	private int batchSize;

	public BatchPickle() {
		this(DEFAULT_BATCH_SIZE);
	}

	public BatchPickle(int batchSize) {
		this.batchSize = batchSize;
	}

	@Override
	public Iterable<byte[]> call(Iterator<T> partition) throws Exception {
		final BatchingIterator<?> bi = new BatchingIterator<>(partition, this.batchSize);

		return new Iterable<byte[]>() {
			@Override
			public Iterator<byte[]> iterator() {
				return new Iterator<byte[]>() {
					@Override
					public boolean hasNext() {
						return bi.hasNext();
					}

					@Override
					public byte[] next() {
						try {
							return pickler.dumps(bi.next());
						} catch (PickleException | IOException e) {
							throw new RuntimeException(e);
						}
					}

					@Override
					public void remove() {
						throw new UnsupportedOperationException();
					}
				};
			}
		};
	}

	private void readObject(ObjectInputStream s) throws ClassNotFoundException, IOException {
		s.defaultReadObject();
		this.pickler = new Pickler();
	}
}


text:
.mce-ico.mce-i-osc_icon_drop.ebsp_dropdown_icon {
    background: url("../images/icon_dropdown.png") repeat scroll 0 0 rgba(0, 0, 0, 0) !important;
    height: 16px !important;
    position: relative !important;
    top: 0 !important;
    width: 32px !important;
}

.mce-splitbtn.ebsp_dropdown_cs_class {
    height: 22px !important;
    line-height: 22px !important;
}

.mce-splitbtn.ebsp_dropdown_cs_class:hover{
    border: 1px solid #BBBBBB !important;
    background: linear-gradient(to top, #E5E5E5, #FFFFFF) repeat scroll 0 0 #EEEEEE !important;
}
.ebsp_dropdown_items{
    max-height: 22px !important;
}
.mce-i-osc_icon{
    width: 20px !important;
    height: 20px !important;
}


text:
Fxp Jquery Scroller
===================

Fxp Jquery Scroller is a custom scrollbar for desktop browser.

Documentation
-------------

The bulk of the documentation is stored in the `doc/index.md`
file in this library:

[Read the Documentation](doc/index.md)

Installation
------------

All the installation instructions are located in [documentation](doc/index.md).

License
-------

This javascript component is under the MIT license. See the complete license:

[LICENSE](LICENSE)

About
-----

Fxp Jquery Scroller is a [François Pluchino](https://github.com/francoispluchino) initiative.
See also the list of [contributors](https://github.com/fxpio/fxp-jquery-scroller/graphs/contributors).

Reporting an issue or a feature request
---------------------------------------

Issues and feature requests are tracked in the [Github issue tracker](https://github.com/fxpio/fxp-jquery-scroller/issues).


text:
package com.tnovoselec.beautifulweather.api.model;

import com.google.gson.annotations.SerializedName;

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

public class HourlyForecast {

  @SerializedName("list")
  private ArrayList<Forecast> forecasts;

  @SerializedName("city")
  private City city;

  public List<Forecast> getForecasts() {
    return forecasts;
  }

  public City getCity() {
    return city;
  }

  public class Forecast {

    private int cityId;

    @SerializedName("dt")
    private long timestamp;

    @SerializedName("main")
    private Main main;

    @SerializedName("weather")
    private List<Weather> weather;

    @SerializedName("wind")
    private Wind wind;

    @SerializedName("clouds")
    private Clouds clouds;

    public int getCityId() {
      return cityId;
    }

    public void setCityId(int cityId) {
      this.cityId = cityId;
    }

    public long getTimestamp() {
      return timestamp * 1000;
    }

    public void setTimestamp(long timestamp) {
      this.timestamp = timestamp;
    }

    public Main getMain() {
      return main;
    }

    public void setMain(Main main) {
      this.main = main;
    }

    public List<Weather> getWeather() {
      return weather;
    }

    public Weather getFirstWeather() {
      return this.weather != null ? this.weather.get(0) : null;
    }

    public void setWeather(List<Weather> weather) {
      this.weather = weather;
    }

    public Wind getWind() {
      return wind;
    }

    public void setWind(Wind wind) {
      this.wind = wind;
    }

    public Clouds getClouds() {
      return clouds;
    }

    public void setClouds(Clouds clouds) {
      this.clouds = clouds;
    }

    public class Main {

      @SerializedName("temp")
      private float temp;

      @SerializedName("temp_min")
      private float tempMin;

      @SerializedName("temp_max")
      private float tempMax;

      @SerializedName("pressure")
      private float pressure;

      @SerializedName("sea_level")
      private float seaLevel;

      @SerializedName("grnd_level")
      private float groundLevel;

      @SerializedName("humidity")
      private float humidity;

      @SerializedName("temp_kf")
      private float tempKf;

      public float getTemp() {
        return temp;
      }

      public void setTemp(float temp) {
        this.temp = temp;
      }

      public float getTempMin() {
        return tempMin;
      }

      public void setTempMin(float tempMin) {
        this.tempMin = tempMin;
      }

      public float getTempMax() {
        return tempMax;
      }

      public void setTempMax(float tempMax) {
        this.tempMax = tempMax;
      }

      public float getPressure() {
        return pressure;
      }

      public void setPressure(float pressure) {
        this.pressure = pressure;
      }

      public float getSeaLevel() {
        return seaLevel;
      }

      public void setSeaLevel(float seaLevel) {
        this.seaLevel = seaLevel;
      }

      public float getGroundLevel() {
        return groundLevel;
      }

      public void setGroundLevel(float groundLevel) {
        this.groundLevel = groundLevel;
      }

      public float getHumidity() {
        return humidity;
      }

      public void setHumidity(float humidity) {
        this.humidity = humidity;
      }

      public float getTempKf() {
        return tempKf;
      }

      public void setTempKf(float tempKf) {
        this.tempKf = tempKf;
      }

    }

    public class Weather {

      @SerializedName("id")
      private int id;

      @SerializedName("icon")
      private String icon;

      @SerializedName("description")
      private String description;

      @SerializedName("main")
      private String main;

      public int getId() {
        return id;
      }

      public void setId(int id) {
        this.id = id;
      }

      public String getIcon() {
        return icon;
      }

      public void setIcon(String icon) {
        this.icon = icon;
      }

      public String getDescription() {
        return description;
      }

      public void setDescription(String description) {
        this.description = description;
      }

      public String getMain() {
        return main;
      }

      public void setMain(String main) {
        this.main = main;
      }
    }

    public class Clouds {
      @SerializedName("all")
      private float all;

      public float getAll() {
        return all;
      }

      public void setAll(float all) {
        this.all = all;
      }

    }

    public class Wind {

      @SerializedName("speed")
      private float speed;

      @SerializedName("deg")
      private float deg;

      public float getSpeed() {
        return speed;
      }

      public void setSpeed(float speed) {
        this.speed = speed;
      }

      public float getDeg() {
        return deg;
      }

      public void setDeg(float deg) {
        this.deg = deg;
      }

    }
  }

  public class City {

    @SerializedName("id")
    private long id;

    @SerializedName("name")
    private String name;

    @SerializedName("country")
    private String country;

    public long getId() {
      return id;
    }

    public String getName() {
      return name;
    }

    public String getCountry() {
      return country;
    }
  }

}


text:
from django.conf.urls import patterns, include, url
from django.contrib import admin

admin.autodiscover()

urlpatterns = patterns(
    '',
    url(r'^admin/',
        include(admin.site.urls)),
    url(r'^boardgames/',
        include('boardgame.urls')),
)


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

<TITLE>
DBPlugin.ProxyDriver (Play! API)
</TITLE>

<META NAME="date" CONTENT="2010-11-01">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

play.db

Class DBPlugin.ProxyDriver

java.lang.Object
  play.db.DBPlugin.ProxyDriver

All Implemented Interfaces:
java.sql.Driver

Enclosing class:
DBPlugin

public static class DBPlugin.ProxyDriver
extends java.lang.Object
implements java.sql.Driver

Needed because DriverManager will not load a driver ouside of the system classloader

Method Summary

 boolean
acceptsURL(java.lang.String u)

 java.sql.Connection
connect(java.lang.String u,
        java.util.Properties p)

 int
getMajorVersion()

 int
getMinorVersion()

 java.sql.DriverPropertyInfo[]
getPropertyInfo(java.lang.String u,
                java.util.Properties p)

 boolean
jdbcCompliant()

Methods inherited from class java.lang.Object

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

Method Detail

acceptsURL

public boolean acceptsURL(java.lang.String u)
                   throws java.sql.SQLException

Specified by:
acceptsURL in interface java.sql.Driver

Throws:

java.sql.SQLException

connect

public java.sql.Connection connect(java.lang.String u,
                                   java.util.Properties p)
                            throws java.sql.SQLException

Specified by:
connect in interface java.sql.Driver

Throws:

java.sql.SQLException

getMajorVersion

public int getMajorVersion()

Specified by:
getMajorVersion in interface java.sql.Driver

getMinorVersion

public int getMinorVersion()

Specified by:
getMinorVersion in interface java.sql.Driver

getPropertyInfo

public java.sql.DriverPropertyInfo[] getPropertyInfo(java.lang.String u,
                                                     java.util.Properties p)
                                              throws java.sql.SQLException

Specified by:
getPropertyInfo in interface java.sql.Driver

Throws:

java.sql.SQLException

jdbcCompliant

public boolean jdbcCompliant()

Specified by:
jdbcCompliant in interface java.sql.Driver

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

Guillaume Bort & zenexity - Distributed under Apache 2 licence, without any warrantly


text:
module PivoFlow
  class Cli

    def initialize *args
      @file_story_path = File.join(Dir.pwd, "/tmp/.pivotal_story_id")
      @args = args
    end

    def go!
      Signal.trap(2) {
        puts "\nkkthxbye!"
        return 0
      }
      begin
        return parse_argv(@args)
      rescue *PivoFlow::Errors.exceptions => e
        puts "[ERROR] #{e}"
        return 1
      end
    end

    private

    # available commands

    def stories
      pivotal_object.show_stories
    end

    def set story_id=nil
      unless story_id
        puts "Ok, but which story?"
        return 1
      end
      pivotal_object.save_story_id_to_file story_id
      puts "Story ##{story_id} set as current"
    end

    def start story_id=nil
      unless story_id
        puts "Ok, but which story?"
        return 1
      end
      pivotal_object.pick_up_story(story_id)
    end

    def finish story_id=nil
      unless current_story_id
        puts no_story_found_message
        return 1
      end
      pivotal_object.finish_story(current_story_id)
    end

    def deliver
      pivotal_object.deliver
    end

    def clear
      unless current_story_id.nil?
        FileUtils.remove_file(@file_story_path)
        puts "Current pivotal story id cleared."
      else
        puts no_story_found_message
        return 1
      end
    end

    def branch
      unless current_story_id
        puts no_story_found_message
        return 1
      end

      pivotal_object.create_branch(current_story_id)
    end

    def current
      puts current_story_id || no_story_found_message
    end

    def reconfig
      PivoFlow::Base.new.reconfig
    end

    def info
      pivotal_object.show_info
    end

    def version
      puts PivoFlow::VERSION
    end

    # additional methods

    def pivotal_object
      @pivotal_object ||= PivoFlow::Pivotal.new(@options)
    end

    def no_story_found_message
      "No story found in #{@file_story_path}"
    end

    def no_method_error
      puts "You forgot a method name"
    end

    def invalid_method_error
      puts "Ups, no such method..."
    end

    def current_story_id
      return nil unless File.exists?(@file_story_path)
      File.open(@file_story_path).read.strip
    end

    def parse_argv(args)
      @options = {}

      opt_parser = OptionParser.new do |opts|
        opts.banner =   "\nPivoFlow ver. #{PivoFlow::VERSION}\nUsage: pf <COMMAND> [OPTIONS]\n"
        opts.separator  "Commands"
        opts.separator  "     branch            create git branch locally based on current set ticket using 'info' command"
        opts.separator  "     clear             clear STORY_ID from temp file"
        opts.separator  "     current           show STORY_ID from temp file"
        opts.separator  "     deliver           show finished stories and mark selected as delivered in Pivotal Tracker"
        opts.separator  "     help              show this message"
        opts.separator  "     finish [STORY_ID] finish story on Pivotal"
        opts.separator  "     info              show info about current story"
        opts.separator  "     reconfig          clear API_TOKEN and PROJECT_ID from git config and setup new values"
        opts.separator  "     start <STORY_ID>  start a story of given ID (update in Pivotal)"
        opts.separator  "     set <STORY_ID>    set a story of given ID locally (do not update Pivotal)"
        opts.separator  "     stories           list stories for current project"
        opts.separator  "     version           show gem version"
        opts.separator  ""
        opts.separator  "Options"

        opts.on_tail("-h", "--help", "Show this message") do
          puts opts
          return 1
        end

        opts.on_tail("-v", "--version", "Show version") do
          puts PivoFlow::VERSION
          return 1
        end

        opts.on("-t <API_TOKEN>", "--token <API_TOKEN>", "Set Pivotal Tracker API TOKEN") do |api_token|
          @options["api-token"] = api_token
        end

        opts.on("-p <PROJECT_ID>", "--project <PROJECT_ID>", Numeric, "Set Pivotal Tracker PROJECT_ID") do |project_id|
          @options["project-id"] = project_id
        end

      end

      opt_parser.parse!(args)

      case args[0]
      when "start", "finish", "set"
        self.send(args[0].to_sym, args[1])
      when "help"
        puts opt_parser
      when "clear", "current", "deliver", "info", "reconfig", "stories", "branch"
        self.send(args[0].to_sym)
      when nil
        no_method_error
        puts opt_parser
        return 1
      else
        invalid_method_error
        return 1
      end
      return 0

    end

  end

end


text:
using System;
using osu.Game.Graphics;

namespace osu.Game.Rulesets.Mods
{
    public abstract class ModHardRock : Mod
    {
        public override string Name => "Hard Rock";
        public override FontAwesome Icon => FontAwesome.fa_osu_mod_hardrock;
        public override string Description => "Everything just got a bit harder...";
        public override Type[] IncompatibleMods => new[] { typeof(ModEasy) };
    }
}


text:
<?php
session_start();

processCalculation();
function processCalculation(){
    $_SESSION['result'] = getCalculationResult($_POST['calc'],
            $_POST['number1'], $_POST['number2']);
    header('location:calculator.php');
}

function getCalculationResult($operation, $number1, $number2){
    $result = '';
    if( $operation == 'add'){
        $result = add($number1, $number2);
    }elseif($operation == 'subtract'){
        $result = subtract($number1, $number2);
    }elseif($operation == 'multiply'){
        $result = multiply($number1, $number2);
    }elseif($operation == 'divide'){
        $result = divide($number1, $number2);
    }
    return $result;
}

function subtract($number1, $number2){
    $result = null;
   if($number1 > $number2){
       $result = $number1 - $number2;
       return $result;
   } else{
        return "Please provide larger number for number1";
   }

}
function divide($number1, $number2){
    $result = null;
    if($number2 == 0){
       return "Please provide any number which is greater than 0 for number2.";
    }
    $result = $number1 / $number2;
    return $result;
}

function add($number1, $number2){
    $result = null;
    $result = $number1 + $number2;
    return $result;
}

function multiply($number1, $number2){
    $result = null;
    $result = $number1 * $number2;
    return $result;
}


text:
A highly configurable javascript library for creating "twinkling star" effects. You can easily customize
every aspect of it to fit the needs of your website. You can apply the effect to more than one element as well.
Great for banners!

####Requirements: JQuery

#Installation
Download the zip and copy the `starlight.js` file from the `starlight` folder then embed in your html:
```
	<script src="starlight/starlight.js"></script>

	<div class="starlight"></div>
```

#Customization
Customizing the libary is very easy. Just edit the `user_configuration` options in the
`starlight.js` file.

The options available are listed here:

###shape
Could be either `"circle"` or `"square"`
###initial_size
The starting size of the stars when they spawn (eg `"32px"`)
###final_size
The final size of the stars after expansion. Could also be the same as initial size if you don't want the stars to expand (eg `"64px"`)
###expand_speed
How long the stars take to expand/shrink (in CSS time. eg `"1s"`)
###fade_delay
The delay until the stars begin to fade out (in CSS time. eg `"1s"`)
###fade_duration
How long the star will take to fade out (in CSS time. eg `"0.5s"`)
###colors
Possible colors of the stars, each of which will be randomly chosen during spawning.  Can be any CSS complient color (eg. `"rgba(255,255,255,0.5)"`)
###frequency
Delay between star spawns in milliseconds(eg. `250`)
###density
How many stars will spawn per wave (eg `5`)
###keep_lit
`true` or `false`: Whether the stars will fade out
###rotation
`true` or `false` : Whether the stars will rotate
###coverage
How much of the element's area the stars will show up in (0-1 eg `0.75` will cover 75%)
###target_class
Elements that the stars will spawn in. Can be any class, element, or id (eg `".starlight"`)
###custom_svg
Not Supported Yet: If you want to use your own SVG instead of just a circle or a square

There are also more advanced settings that you can configure by modifying the `advanced_configuration` options.
Changing these settings isn't really necessary unless you don't like how some of the transitions play.

#Licence
[MIT](https://raw.githubusercontent.com/sergei1152/Starlight.js/master/LICENCE)


text:
import io
import pyparsing
import pytest

from zs.bibtex import exceptions, structures, parser
from .helpers import parse_entry, parse_bibliography

def test_basic():
    """
    Run some basic tests to see if parsing works at all.
    """
    inp = '@article{somename, author={Max Mustermann}, ' \
            'title={Hello world}}'
    bib = parse_bibliography(inp)
    assert 1 == len(bib)
    assert 'somename' == bib['somename'].name

    entry = bib['somename']
    assert 'Max Mustermann' == entry['author']
    assert 'Hello world' == entry['title']

def test_regression_number_in_name():
    """
    Make sure that numbers can be used in entry-names.
    """
    entry = parse_entry('''@article{mm09,
    author = {Max Mustermann},
    title = {The story of my life},
    year = {2009},
    journal = {Life Journale}
    }''')
    assert 'mm09' == entry.name

def test_regression_optional_last_comma():
    """
    The last statement may or may not be finished with a ,
    """
    parse_entry('''@ARTICLE{article-crossref,
        crossref = {WHOLE-JOURNAL},
        author = {L[eslie] A. Aamport},
        title = {The Gnats and Gnus Document Preparation System},
        pages = "73+",
        note = "This is a cross-referencing ARTICLE entry",
    }''')

def test_regression_numeric_value_without_quotes():
    parse_entry('''@article{mm09,
    author = {Max Mustermann},
    title = {The story of my life},
    year = 2009,
    journal = {Life Journale}
    }''')

def test_uppercase():
    """
    Fieldnames and types should get normalized to their lowercase
    representation.
    """
    entry = parse_entry("@ARTICLE{somename, AUTHOR={Max Mustermann1},"
            " title={Hello world}, journal={My Journal}, year={2009}}")
    assert structures.Article == type(entry)
    entry.validate()

def test_syntaxerror():
    """
    Check if pyparsing.ParseException is raised on syntax errors.
    """
    inp = '@article{name}'
    with pytest.raises(pyparsing.ParseException):
        parse_entry(inp)

def test_comments():
    """
    Make sure that comments don't interfer with the rest of the
    parsing.
    """
    bib = parse_bibliography('''% some comment
@article { name, % whatever
title = {la%la}
}''')
    assert len(bib) == 1
    assert 'la%la' == bib['name']['title']

def test_entry_subtype():
    """
    Check if an UnsupportedEntryType exception is raised if no type could
    be found for a given entry-type.
    """
    inp = '@bibliography{name, title={test}}'
    with pytest.raises(exceptions.UnsupportedEntryType):
        parse_entry(inp)
    inp = '@article2{name, title={test}}'
    with pytest.raises(exceptions.UnsupportedEntryType):
        parse_entry(inp)

def test_basetypes():
    """
    Tests that all basic Entry-subclasses are registered.
    """
    types = ('article', 'book', 'booklet', 'incollection',
                'inproceedings', 'conference', 'inbook', 'manual',
                'mastersthesis', 'misc', 'phdthesis', 'proceedings',
                'techreport', 'unpublished',)
    for type_ in types:
        inp = '@%s {name, title = {test}}' % type_
        parse_entry(inp)

def test_with_validation():
    inp = '''% some comment
    @article { name, author = {Max Mustermann},
        title = {la%la}
    }
    '''
    with pytest.raises(exceptions.InvalidStructure):
        parser.parse_string(inp, validate=True)

    inp = '''% some comment
    @article { name, author = {Max Mustermann},
        year = {2009},
        journal = {Life Journale},
        title = {la%la}
    }
    '''
    parser.parse_string(inp, validate=True)

def test_file_as_path(tmpdir):
    test_file = tmpdir.join('test.bib')
    test_file.write('''
    @article { name, author = {Max Mustermann},
        year = {2009},
        journal = {Life Journale},
        title = {la%la}
    }
    ''')
    parser.parse_file(str(test_file))
    parser.parse_file(str(test_file), validate=True)

    # Invalid structure
    test_file.write('''
    @article { name, author = {Max Mustermann},
        title = {la%la}
    }
    ''')
    parser.parse_file(str(test_file))
    with pytest.raises(exceptions.InvalidStructure):
        parser.parse_file(str(test_file), validate=True)

def test_file_as_object(tmpdir):
    test_file = tmpdir.join('test.bib')
    test_file.write('''
    @article { name, author = {Max Mustermann},
        year = {2009},
        journal = {Life Journale},
        title = {la%la}
    }
    ''')
    with io.open(str(test_file), encoding='utf-8') as fp:
        parser.parse_file(fp)
    with io.open(str(test_file), encoding='utf-8') as fp:
        parser.parse_file(fp, validate=True)

    # Invalid structure
    test_file.write('''
    @article { name, author = {Max Mustermann},
        title = {la%la}
    }
    ''')
    with io.open(str(test_file), encoding='utf-8') as fp:
        parser.parse_file(fp)
    with io.open(str(test_file), encoding='utf-8') as fp:
        with pytest.raises(exceptions.InvalidStructure):
            parser.parse_file(fp, validate=True)


text:
# ng-closure-builder

AST builder to manipulate AngularJS files based in Google closure.

It is designed to manipulate angular modules and ES6 classes written with
Google's closure compiler.

## Installation

```shell
npm install ng-closure-builder
```

## Usage

This library exposes a Transformer class that receives the contents of a
JavaScript file. You can chain multiple calls and when you are done call
toString() to get the transformed file.

# ES6 classes

```js
const Transformer = require('../lib/transformer');

const fileContents = fs.readFileSync('path', 'utf-8');
const transformed = new Transformer(fileContents)
    .injectConstructor('someService', 'foo.bar.SomeService', 'SomeService')
    .toString();

console.log(transformed);
```

## Functions

### addGoogRequire(identifier, namespace)

Adds a goog.require at the top of the file.

```js
const <identifier> goog.require('<namespace>');
```

### injectConstructor(injectableName, namespace, injectableType)

Adds an injectable to a constructor and a goog.require at the top

```js
const transformed = new Transformer(fileContents)
    .injectConstructor('someService', 'foo.bar.SomeService', 'SomeService')
    .toString();
```

Before:

```js
goog.module('foo.bar.SomeComponent');

class SomeComponent {
  /**
   * @ngInject
   */
  constructor() {
  }
}
```

After:

```js
goog.module('foo.bar.SomeComponent');

const SomeService = goog.require('foo.bar.SomeService');

class SomeComponent {
  /**
   * @param {!SomeService} someService
   * @ngInject
   */
  constructor(someService) {
    /** @private {!SomeService} */
    this.someService_ = someService;
  }
}
```

# Angular modules

### addModule(moduleName)

Adds an angular module as a dependency to the current module. Use it with
addGoogRequire() to import the module dependency.

```js
const transformed = new Transformer(fileContents)
    .addGoogRequire('AndresModule', 'foo.bar.AndresModule')
    .addModule('AndresModule')
    .toString();
```

Before:

```js
goog.module('foo.bar.FooBarModule');

const FooBarModule = angular.module('foo.bar.FooBarModule', []);
```

After:

```js
goog.module('foo.bar.FooBarModule');

const AndresModule = goog.require('foo.bar.AndresModule');

const FooBarModule = angular.module('foo.bar.FooBarModule', [AndresModule.name]);
```

### addService(serviceName, className, namespace)

Adds a service to the module along with the goog.require for the service class.

```js
const transformed = new Transformer(initialModule)
    .addService('someService', 'SomeService', 'foo.bar.SomeService')
    .toString();
```

Before:

```js
goog.module('foo.bar.FooBarModule');

const FooBarModule = angular.module('foo.bar.FooBarModule', []);
```

After:

```js
goog.module('foo.bar.FooBarModule');

const SomeService = goog.require('foo.bar.SomeService');

const FooBarModule = angular.module('foo.bar.FooBarModule', []);

FooBarModule.service('someService', SomeService);
```


text:
package org.marketcetera.core;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.atomic.AtomicBoolean;

import javax.annotation.concurrent.ThreadSafe;

import org.marketcetera.util.log.SLF4JLoggerProxy;
import org.marketcetera.util.misc.ClassVersion;
import org.springframework.context.Lifecycle;

/* $License$ */

/**
 * Provides a framework for processing data in a separate thread.
 *
 * @author Colin DuPlantis
 * @version $Id: QueueProcessor.java 83655 2013-12-06 01:42:01Z colin $
 * @since $Release$
 */
@ThreadSafe
@ClassVersion("$Id$")
public abstract class QueueProcessor<Clazz>
        implements Runnable, Lifecycle
{
    /* (non-Javadoc)
     * @see org.springframework.context.Lifecycle#isRunning()
     */
    @Override
    public boolean isRunning()
    {
        return running.get();
    }
    /* (non-Javadoc)
     * @see org.springframework.context.Lifecycle#start()
     */
    @Override
    public synchronized void start()
    {
        if(isRunning()) {
            return;
        }
        try {
            onStart();
        } catch (Exception e) {
            Messages.UNABLE_TO_START.warn(this,
                                          e,
                                          threadDescriptor);
            throw new RuntimeException(e);
        }
        keepAlive.set(true);
        thread = new Thread(this,
                            threadDescriptor);
        thread.start();
        running.set(true);
    }
    /* (non-Javadoc)
     * @see org.springframework.context.Lifecycle#stop()
     */
    @Override
    public synchronized void stop()
    {
        if(!isRunning()) {
            return;
        }
        try {
            onStop();
        } catch (Exception e) {
            Messages.ERROR_DURING_STOP.warn(this,
                                            e,
                                            threadDescriptor);
        }
        keepAlive.set(false);
        if(thread != null) {
            thread.interrupt();
            try {
                thread.join();
            } catch (InterruptedException ignored) {}
        }
    }
    /* (non-Javadoc)
     * @see java.lang.Runnable#run()
     */
    @Override
    public void run()
    {
        try {
            lastException = null;
            interrupted.set(false);
            Messages.STARTED.info(this,
                                  threadDescriptor);
            while(keepAlive.get()) {
                try {
                    Clazz dataObject = queue.take();
                    SLF4JLoggerProxy.trace(this,
                                           "Queue processor {} processing {}",
                                           threadDescriptor,
                                           dataObject);
                    processData(dataObject);
                } catch (InterruptedException e) {
                    throw e;
                } catch (Exception e) {
                    lastException = e;
                    if(shutdownOnException(e)) {
                        throw e;
                    }
                    Messages.IGNORING_EXCEPTION.warn(this,
                                                     e,
                                                     threadDescriptor);
                }
            }
        } catch (InterruptedException e) {
            interrupted.set(true);
            Messages.INTERRUPTED.info(this,
                                      threadDescriptor);
        } catch (Exception e) {
            lastException = e;
            Messages.SHUTTING_DOWN_FROM_ERROR.warn(this,
                                                   e,
                                                   threadDescriptor);
            stop();
        } finally {
            keepAlive.set(false);
            running.set(false);
            Messages.STOPPED.info(this,
                                  threadDescriptor);
        }
    }
    /**
     * Gets the queue to process.
     *
     * @return a BlockingQueue<Clazz> value
     */
    protected BlockingQueue<Clazz> getQueue()
    {
        return queue;
    }
    /**
     * Processes the given data.
     *
     *
This method is invoked when data is available in the processing queue. Data
     * is guaranteed to be processed in the order mandated by the queue. No other data
     * will be processed until this method returns.
     *
     * @param inData a Clazz value
     * @throws Exception an Exception value
     */
    protected abstract void processData(Clazz inData)
            throws Exception;
    /**
     * Called when the processor starts.
     *
     *
Any exception thrown will prevent the processor from starting.
     *
     * @throws Exception if an error occurs
     */
    protected void onStart()
            throws Exception {}
    /**
     * Called when the processor stops.
     *
     *
Any exception thrown will not prevent the processor from stopping.
     *
     * @throws Exception if an error occurs
     */
    protected void onStop()
            throws Exception {}
    /**
     * Gets the last exception thrown by the processor during data processing.
     *
     * @return an Exception value or null
     */
    protected Exception getLastException()
    {
        return lastException;
    }
    /**
     * Indicates if the queue processor was interrupted during data processing.
     *
     * @return a boolean value
     */
    protected boolean wasInterrupted()
    {
        return interrupted.get();
    }
    /**
     * Indicates if the queue processor should shutdown as a result of the given exception.
     *
     * @param inException an Exception value
     * @return a boolean value
     */
    protected boolean shutdownOnException(Exception inException)
    {
        return inException instanceof InterruptedException;
    }
    /**
     * Create a new QueueProcessor instance.
     */
    protected QueueProcessor()
    {
        this("Unknown Queue Processor");
    }
    /**
     * Create a new QueueProcessor instance.
     *
     * @param inThreadDescriptor a String value describing the processor
     */
    protected QueueProcessor(String inThreadDescriptor)
    {
        if(inThreadDescriptor == null) {
            throw new NullPointerException();
        }
        queue = new LinkedBlockingDeque<Clazz>();
        threadDescriptor = inThreadDescriptor;
    }
    /**
     * last exception thrown during data processing or null
     */
    private volatile Exception lastException;
    /**
     * thread value used to process data
     */
    private volatile Thread thread;
    /**
     * indicates if the processor was interrupted during data processing
     */
    private final AtomicBoolean interrupted = new AtomicBoolean(false);
    /**
     * indicates if the processor is running
     */
    private final AtomicBoolean running = new AtomicBoolean(false);
    /**
     * indicates if the processor should continue to process data
     */
    private final AtomicBoolean keepAlive = new AtomicBoolean(true);
    /**
     * queue used to hold data to be processed
     */
    private final BlockingQueue<Clazz> queue;
    /**
     * describes the thread
     */
    private final String threadDescriptor;
}


text:
<!doctype html>

  <title>Constructors | First entity | Intro | Ebean</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <link rel="shortcut icon" href="/images/favicon.ico">
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto|Source+Sans+Pro|Ubuntu&display=swap">
  <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.1.0/css/all.css" integrity="sha384-lKuwvrZot6UHsBSfcMvOkWwlCMgc0TaWr+30HWe3a4ltaBwTZhyTEggF5tJv8tbt" crossorigin="anonymous">
  <link rel="stylesheet" href="/css/reset3.css">
  <link rel="stylesheet" href="/css/site3.css">
  <link rel="stylesheet" href="/css/pygments3.css">

          Documentation / Introduction / First entity / Constructors

    Getting started

    Introduction

    Database & DB

    Configuration

    First entity

    Model

    MappedSuperclass

    Constructors

    Queries

    Logging

    DB Migrations

    Limitations

    Trouble shooting

    Documentation

    Getting help

      API Javadoc

    Videos

    Upgrading

    Releases

<form action="https://www.google.com/search" method="get" class="inline-form">
  <input type="hidden" name="as_sitesearch" value="ebean.io">

      <input class="frm" name="q" id="searchinput" type="text" placeholder="Search... (press 's' to focus)" data-placeholder-focus="Search... (use '↑', '↓' and '⏎' to select results)" data-placeholder-blur="Search... (press 's' to focus)" autocomplete="off">

        <button class="frm" type="submit"></button>

Docs Documentation

And 101 more...

</form>

Constructors

  Ebean does not need a default constructor and this means we can give our entity bean a constructor
  that takes arguments. Typically the arguments are properties that should always be supplied
  when creating a new bean of that type (and by implication are typically non-nullable).

java

kotlin

@Entity
public class Customer {

  @Id
  long id;

  @NotNull @Length(100)
  String name;

  public Customer(String name) {
    this.name = name;
  }

  // getters and setters

}

...
@Entity
class Customer(name : String) {

  @Id
  var id: Long = 0

  @Length(100)
  var name: String = name

}

  Now when we create a new Customer we know we must create it with a name.

  For Kotlin we can now make name a non-nullable type. Ebean will treat Kotlin non-nullable
  types as NOT NULL from a database perspective as well giving us a tighter model.

java

kotlin

Customer customer = new Customer("Hello entity bean")
customer.save()

val customer = Customer("Hello entity bean")
customer.save()

  Kotlin has multiple constructor styles. See here for more information
  on the preferred constructor style for entity beans.

       Edit Page

      Next: Queries


text:
extern xr_token actor_stats_token[];

struct SStatDetailBData: public IPureSerializeObject<IReader,IWriter>
{
	shared_str				key;
	s32						int_count;
	s32						int_points;
	shared_str				str_value;

	virtual void save								(IWriter &stream);
	virtual void load								(IReader &stream);
};

typedef xr_vector<SStatDetailBData>	vStatDetailData;

struct SStatSectionData: public IPureSerializeObject<IReader,IWriter>
{
	shared_str				key;
	vStatDetailData			data;

	SStatDetailBData&		GetData			(const shared_str&);
	s32						GetTotalPoints	() const;
	virtual void			save			(IWriter &stream);
	virtual void			load			(IReader &stream);
};

typedef xr_vector<SStatSectionData> vStatSectionData;
typedef CALifeAbstractRegistry<u16, vStatSectionData> CActorStatisticRegistry;


text:
<!doctype html>

    <title>Code coverage report for backgrid-text-cell.js</title>
    <meta charset="utf-8">

    <link rel="stylesheet" href="../prettify.css">

Code coverage report for backgrid-text-cell.js

        Statements: 87.5% (28 / 32)

        Branches: 78.26% (18 / 23)

        Functions: 85.71% (6 / 7)

        Lines: 90.32% (28 / 31)

All files » ./ » ckgrid-text-cell.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169

1

1

1

1

6

6

6

6

7
2
2

7
7
7
7

7
1

1
1
1

6

2
2

4

4
4

4

1

(function (root, factory) {

  // CommonJS
  Iif (typeof exports == "object") {
    module.exports = factory(require("underscore"),
                             require("backgrid"));
  }
  // Browser
  else factory(root._, root.Backgrid);

}(this, function (_, Backgrid)  {

  /**
     Renders a form with a text area and a save button in a modal dialog.

     @class Backgrid.Extension.TextareaEditor
     @extends Backgrid.CellEditor
  */
  var TextareaEditor = Backgrid.Extension.TextareaEditor = Backgrid.CellEditor.extend({

    /** @property */
    tagName: "div",

    /** @property */
    className: "modal fade",

    /** @property {function(Object, ?Object=): string} template */
    template: _.template('<div class="modal-dialog"><div class="modal-content"><form><div class="modal-header"><button type="button" class="close" data-dismiss="modal">&times;</button><h3><%- column.get("label") %></h3></div><div class="modal-body"><textarea cols="<%= cols %>" rows="<%= rows %>"><%- content %></textarea></div><div class="modal-footer"><input class="btn btn-primary" type="submit" value="Save"/></div></form></div></div>', null, {variable: null}),

    /** @property */
    cols: 80,

    /** @property */
    rows: 10,

    /** @property */
    events: {
      "keydown textarea": "clearError",
      "submit": "saveOrCancel",
      "hide.bs.modal": "saveOrCancel",
      "hidden.bs.modal": "close",
      "shown.bs.modal": "focus"
    },

    /**
       @property {Object} modalOptions The options passed to Bootstrap's modal
       plugin.
    */
    modalOptions: {
      backdrop: false
    },

    /**
       Renders a modal form dialog with a textarea, submit button and a close button.
    */
    render: function () {
      this.$el.html($(this.template({
        column: this.column,
        cols: this.cols,
        rows: this.rows,
        content: this.formatter.fromRaw(this.model.get(this.column.get("name")))
      })));

      this.delegateEvents();

      this.$el.modal(this.modalOptions);

      return this;
    },

    /**
       Event handler. Saves the text in the text area to the model when
       submitting. When cancelling, if the text area is dirty, a confirmation
       dialog will pop up. If the user clicks confirm, the text will be saved to
       the model.

       Triggers a Backbone `backgrid:error` event from the model along with the
       model, column and the existing value as the parameters if the value
       cannot be converted.

       @param {Event} e
    */
    saveOrCancel: function (e) {
      if (e && e.type == "submit") {
        e.preventDefault();
        e.stopPropagation();
      }

      var model = this.model;
      var column = this.column;
      var val = this.$el.find("textarea").val();
      var newValue = this.formatter.toRaw(val);

      if (_.isUndefined(newValue)) {
        model.trigger("backgrid:error", model, column, val);

        Eif (e) {
          e.preventDefault();
          e.stopPropagation();
        }
      }
      else if (!e || e.type == "submit" ||
               (e.type == "hide" &&
                newValue !== (this.model.get(this.column.get("name")) || '').replace(/\r/g, '') &&
                confirm("Would you like to save your changes?"))) {

        model.set(column.get("name"), newValue);
        this.$el.modal("hide");
      }
      else Iif (e.type != "hide") this.$el.modal("hide");
    },

    /**
       Clears the error class on the parent cell.
     */
    clearError: _.debounce(function () {
      if (!_.isUndefined(this.formatter.toRaw(this.$el.find("textarea").val()))) {
        this.$el.parent().removeClass("error");
      }
    }, 150),

    /**
       Triggers a `backgrid:edited` event along with the cell editor as the
       parameter after the modal is hidden.

       @param {Event} e
    */
    close: function (e) {
      var model = this.model;
      model.trigger("backgrid:edited", model, this.column,
                    new Backgrid.Command(e));
    },

    /**
       Focuses the textarea when the modal is shown.
    */
    focus: function () {
      this.$el.find("textarea").focus();
    }

  });

  /**
     TextCell is a string cell type that renders a form with a text area in a
     modal dialog instead of an input box editor. It is best suited for entering
     a large body of text.

     @class Backgrid.Extension.TextCell
     @extends Backgrid.StringCell
  */
  Backgrid.Extension.TextCell = Backgrid.StringCell.extend({

    /** @property */
    className: "text-cell",

    /** @property  */
    editor: TextareaEditor

  });

}));

Generated by istanbul at Tue Jan 21 2014 22:08:48 GMT+0800 (HKT)


text:
package co.com.codesoftware.server.productos;

import java.math.BigDecimal;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.datatype.XMLGregorianCalendar;

/**
 *
Clase Java para productoFacCompraEntity complex type.
 *
 *
El siguiente fragmento de esquema especifica el contenido que se espera que haya en esta clase.
 *
 *

 * <complexType name="productoFacCompraEntity">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="cantidad" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/>
 *         <element name="estado" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *         <element name="fecha" type="{http://www.w3.org/2001/XMLSchema}dateTime" minOccurs="0"/>
 *         <element name="id" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/>
 *         <element name="idFacturaCompra" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/>
 *         <element name="iva" type="{http://www.w3.org/2001/XMLSchema}decimal" minOccurs="0"/>
 *         <element name="porcentajeIva" type="{http://www.w3.org/2001/XMLSchema}decimal" minOccurs="0"/>
 *         <element name="producto" type="{http://productos.server.codesoftware.com.co/}productoEntity" minOccurs="0"/>
 *         <element name="subtotal" type="{http://www.w3.org/2001/XMLSchema}decimal" minOccurs="0"/>
 *         <element name="total" type="{http://www.w3.org/2001/XMLSchema}decimal" minOccurs="0"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "productoFacCompraEntity", propOrder = {
    "cantidad",
    "estado",
    "fecha",
    "id",
    "idFacturaCompra",
    "iva",
    "porcentajeIva",
    "producto",
    "subtotal",
    "total"
})
public class ProductoFacCompraEntity {

    protected Integer cantidad;
    protected String estado;
    @XmlSchemaType(name = "dateTime")
    protected XMLGregorianCalendar fecha;
    protected Integer id;
    protected Integer idFacturaCompra;
    protected BigDecimal iva;
    protected BigDecimal porcentajeIva;
    protected ProductoEntity producto;
    protected BigDecimal subtotal;
    protected BigDecimal total;

    /**
     * Obtiene el valor de la propiedad cantidad.
     *
     * @return
     *     possible object is
     *     {@link Integer }
     *
     */
    public Integer getCantidad() {
        return cantidad;
    }

    /**
     * Define el valor de la propiedad cantidad.
     *
     * @param value
     *     allowed object is
     *     {@link Integer }
     *
     */
    public void setCantidad(Integer value) {
        this.cantidad = value;
    }

    /**
     * Obtiene el valor de la propiedad estado.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getEstado() {
        return estado;
    }

    /**
     * Define el valor de la propiedad estado.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setEstado(String value) {
        this.estado = value;
    }

    /**
     * Obtiene el valor de la propiedad fecha.
     *
     * @return
     *     possible object is
     *     {@link XMLGregorianCalendar }
     *
     */
    public XMLGregorianCalendar getFecha() {
        return fecha;
    }

    /**
     * Define el valor de la propiedad fecha.
     *
     * @param value
     *     allowed object is
     *     {@link XMLGregorianCalendar }
     *
     */
    public void setFecha(XMLGregorianCalendar value) {
        this.fecha = value;
    }

    /**
     * Obtiene el valor de la propiedad id.
     *
     * @return
     *     possible object is
     *     {@link Integer }
     *
     */
    public Integer getId() {
        return id;
    }

    /**
     * Define el valor de la propiedad id.
     *
     * @param value
     *     allowed object is
     *     {@link Integer }
     *
     */
    public void setId(Integer value) {
        this.id = value;
    }

    /**
     * Obtiene el valor de la propiedad idFacturaCompra.
     *
     * @return
     *     possible object is
     *     {@link Integer }
     *
     */
    public Integer getIdFacturaCompra() {
        return idFacturaCompra;
    }

    /**
     * Define el valor de la propiedad idFacturaCompra.
     *
     * @param value
     *     allowed object is
     *     {@link Integer }
     *
     */
    public void setIdFacturaCompra(Integer value) {
        this.idFacturaCompra = value;
    }

    /**
     * Obtiene el valor de la propiedad iva.
     *
     * @return
     *     possible object is
     *     {@link BigDecimal }
     *
     */
    public BigDecimal getIva() {
        return iva;
    }

    /**
     * Define el valor de la propiedad iva.
     *
     * @param value
     *     allowed object is
     *     {@link BigDecimal }
     *
     */
    public void setIva(BigDecimal value) {
        this.iva = value;
    }

    /**
     * Obtiene el valor de la propiedad porcentajeIva.
     *
     * @return
     *     possible object is
     *     {@link BigDecimal }
     *
     */
    public BigDecimal getPorcentajeIva() {
        return porcentajeIva;
    }

    /**
     * Define el valor de la propiedad porcentajeIva.
     *
     * @param value
     *     allowed object is
     *     {@link BigDecimal }
     *
     */
    public void setPorcentajeIva(BigDecimal value) {
        this.porcentajeIva = value;
    }

    /**
     * Obtiene el valor de la propiedad producto.
     *
     * @return
     *     possible object is
     *     {@link ProductoEntity }
     *
     */
    public ProductoEntity getProducto() {
        return producto;
    }

    /**
     * Define el valor de la propiedad producto.
     *
     * @param value
     *     allowed object is
     *     {@link ProductoEntity }
     *
     */
    public void setProducto(ProductoEntity value) {
        this.producto = value;
    }

    /**
     * Obtiene el valor de la propiedad subtotal.
     *
     * @return
     *     possible object is
     *     {@link BigDecimal }
     *
     */
    public BigDecimal getSubtotal() {
        return subtotal;
    }

    /**
     * Define el valor de la propiedad subtotal.
     *
     * @param value
     *     allowed object is
     *     {@link BigDecimal }
     *
     */
    public void setSubtotal(BigDecimal value) {
        this.subtotal = value;
    }

    /**
     * Obtiene el valor de la propiedad total.
     *
     * @return
     *     possible object is
     *     {@link BigDecimal }
     *
     */
    public BigDecimal getTotal() {
        return total;
    }

    /**
     * Define el valor de la propiedad total.
     *
     * @param value
     *     allowed object is
     *     {@link BigDecimal }
     *
     */
    public void setTotal(BigDecimal value) {
        this.total = value;
    }

}


text:
package de.wlanStein.jingularity;
import java.awt.Graphics;
public interface Strategy{
    public void enter();
    public void enter(State prestate);
    public void update(double dt);
    public void draw(Graphics g);
    public void exit();
}