code
stringlengths 2
1.05M
| repo_name
stringlengths 5
114
| path
stringlengths 4
991
| language
stringclasses 1
value | license
stringclasses 15
values | size
int32 2
1.05M
|
---|---|---|---|---|---|
(function ($) {
function FewbricksDevHelper() {
var $this = this;
/**
*
*/
this.init = function() {
$this.cssClassFull = 'fewbricks-info-pane--full';
if(!$this.initMainElm()) {
return;
}
$this.initToggler();
$this.$mainElm.show();
}
/**
*
*/
this.initMainElm = function() {
$this.$mainElm = $('#fewbricks-info-pane');
if($this.$mainElm.length === 0) {
return false;
}
if(typeof fewbricksInfoPane !== 'undefined' && typeof fewbricksInfoPane.startHeight !== 'undefined') {
$this.toggleMainElm(fewbricksInfoPane.startHeight);
}
return true;
}
/**
*
*/
this.initToggler = function() {
$('[data-fewbricks-info-pane-toggler]')
.unbind('click')
.on('click', function() {
let height = $(this).attr('data-fewbricks-info-pane-height');
$this.toggleMainElm(height);
document.cookie = 'fewbricks_info_pane_height=' + height;
});
}
/**
*
*/
this.toggleMainElm = function(height) {
if(height === 'minimized') {
$this.$mainElm.attr('style', function(i, style)
{
return style && style.replace(/height[^;]+;?/g, '');
});
} else {
$this.$mainElm.height(height + 'vh');
}
}
/**
*
* @returns {*|boolean}
*/
this.mainElmIsFull = function() {
return $this.$mainElm.hasClass($this.cssClassFull);
}
}
$(document).ready(function () {
(new FewbricksDevHelper()).init();
});
})(jQuery);
| folbert/fewbricks | assets/scripts/info-pane.js | JavaScript | gpl-3.0 | 1,977 |
/**
* ...
* @author paul
*/
function initCBX(object, id, options) {
var design = "assets";
if(object == null){
jQuery.noConflict();
var cboxClass;
cboxClass = jQuery(id).attr("class");
if(jQuery.browser.msie && parseInt(jQuery.browser.version)<8 ){
jQuery(id).colorbox();
}
else{
if(cboxClass.indexOf("cboxElement") == -1){
if(options.classes.image.id){
jQuery('.'+options.classes.image.id).colorbox({transition:options.classes.image.transition, slideshow:options.classes.image.slideshow, slideshowSpeed:options.classes.image.slideshowSpeed});
}
if(options.classes.video){
if(options.classes.video.id){
jQuery('.'+options.classes.video.id).colorbox({iframe:true, innerWidth:options.classes.video.innerWidth, innerHeight:options.classes.video.innerHeight, transition:options.classes.image.transition, slideshow:options.classes.image.slideshow, slideshowSpeed:options.classes.image.slideshowSpeed});
}
}
if(options.classes.swf){
if(options.classes.swf.id){
var cbxSWFSrc = jQuery('.'+options.classes.swf.id).attr("href");
var objEmbd = '<OBJECT classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0" WIDTH="'+options.classes.video.innerWidth+'" HEIGHT="'+options.classes.video.innerHeight+'" id="cbxSWF" ALIGN="">'+
'<PARAM NAME=movie VALUE="'+cbxSWFSrc+'">' +
'<PARAM NAME=quality VALUE=high>' +
'<PARAM NAME=wmode VALUE=transparent>'+
'<PARAM NAME=bgcolor VALUE=#333399>'+
'<EMBED src="'+cbxSWFSrc+'" quality=high wmode=transparent WIDTH="'+options.classes.video.innerWidth+'" HEIGHT="'+options.classes.video.innerHeight+'" NAME="Yourfilename" ALIGN="" TYPE="application/x-shockwave-flash" PLUGINSPAGE="http://www.macromedia.com/go/getflashplayer"></EMBED>'+
'</OBJECT>';
jQuery('.'+options.classes.swf.id).colorbox({html:objEmbd, transition:options.classes.image.transition, slideshow:options.classes.image.slideshow, slideshowSpeed:options.classes.image.slideshowSpeed});
}
}
}
}
jQuery(id).trigger('click');
return;
}
loadjQuery = function(filename) {
loadjQuery.getScript(object.path+"/"+filename);
loadjQuery.retry(0);
}
loadColorbox = function(filename) {
loadColorbox.getScript(object.path+"/"+filename);
loadColorbox.retry(0);
}
loadjQuery.getScript = function(filename) {
if(typeof jQuery == "undefined"){
var script = document.createElement('script');
script.setAttribute("type","text/javascript");
script.setAttribute("src", filename);
document.getElementsByTagName("head")[0].appendChild(script);
}
}
loadColorbox.getScript = function(filename) {
if(typeof jQuery.colorbox == "undefined"){
var link = document.createElement('link');
link.setAttribute('media', 'screen');
link.setAttribute('href', object.path+'/'+design+'/colorbox.css');
link.setAttribute('rel', 'stylesheet');
document.getElementsByTagName("head")[0].appendChild(link);
var script = document.createElement('script');
script.setAttribute("type","text/javascript");
script.setAttribute("src", filename);
document.getElementsByTagName("head")[0].appendChild(script);
}
}
loadjQuery.retry = function(time_elapsed) {
if (typeof jQuery == "undefined") {
if (time_elapsed <= 5000) {
setTimeout("loadjQuery.retry(" + (time_elapsed + 200) + ")", 200);
}
}
else {
if(typeof jQuery.colorbox == "undefined"){
loadColorbox("jquery.colorbox-min.js");
}
}
}
loadColorbox.retry = function(time_elapsed) {
if (typeof jQuery.colorbox == "undefined") {
if (time_elapsed <= 5000) {
setTimeout("loadColorbox.retry(" + (time_elapsed + 200) + ")", 200);
}
}
}
if(typeof jQuery == "undefined"){
loadjQuery("jquery-1.7.2.min.js");
}
else if(typeof jQuery.colorbox == "undefined"){
loadColorbox("jquery.colorbox-min.js");
}
}
| PhoenixInteractiveNL/emuControlCenter | ecc-core/tools/3dGallery_scripts/circulargallery/colorbox/swf.js.communication.js | JavaScript | gpl-3.0 | 3,990 |
/*
Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'newpage', 'eo', {
toolbar: 'Nova Paĝo'
} );
| vanpouckesven/cosnics | src/Chamilo/Libraries/Resources/Javascript/HtmlEditor/Ckeditor/src/plugins/newpage/lang/eo.js | JavaScript | gpl-3.0 | 226 |
var searchData=
[
['transfer_20commands',['Transfer Commands',['../group___d_a_p__transfer__gr.html',1,'']]]
];
| Stanford-BDML/super-scamp | vendor/CMSIS/CMSIS/Documentation/DAP/html/search/groups_74.js | JavaScript | gpl-3.0 | 114 |
// @flow
import React, { Component } from 'react'
import { withStyles } from 'material-ui/styles'
import Profile from 'models/Profile'
import IconButton from 'material-ui/IconButton'
import Typography from 'material-ui/Typography'
import FontAwesome from 'react-fontawesome'
import Avatar from 'components/common/Avatar'
import Pubkey from 'components/common/Pubkey'
import InsetText from 'components/common/InsetText'
class ShowProfile extends Component {
props: {
profile: Profile,
onEditClick: () => any
}
render() {
const { classes, profile } = this.props
return (
<div>
<div className={classes.header}>
<div className={classes.lateral} />
<Typography className={classes.identity}>{profile.identity}</Typography>
<IconButton className={classes.lateral} onClick={this.props.onEditClick}><FontAwesome name="pencil" /></IconButton>
</div>
{ profile.avatarUrl
? <Avatar person={profile} className={classes.avatar} />
: <div className={classes.noAvatar}><Typography>No avatar</Typography></div>
}
<InsetText text={profile.bio} placeholder='No biography' />
<Typography align="center" variant="body2">
Share your Arbore ID
</Typography>
<Pubkey pubkey={profile.pubkey} />
</div>
)
}
}
const style = theme => ({
header: {
display: 'flex',
flexDirection: 'row',
alignItems: 'center',
margin: '10px 0 20px',
},
avatar: {
width: '200px !important',
height: '200px !important',
margin: 'auto',
userSelect: 'none',
pointerEvents: 'none',
},
noAvatar: {
width: 200,
height: 200,
borderRadius: '50%',
backgroundColor: theme.palette.background.dark,
margin: 'auto',
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
},
identity: {
margin: '0 10px 0 !important',
fontSize: '2em !important',
textAlign: 'center',
flexGrow: 1,
},
lateral: {
width: '20px !important',
},
})
export default withStyles(style)(ShowProfile)
| MichaelMure/TotallyNotArbore | app/components/profile/ShowProfile.js | JavaScript | gpl-3.0 | 2,101 |
{
"": {
"domain": "ckan",
"lang": "cs_CZ",
"plural-forms": "nplurals=3; plural=(n==1) ? 0 : (n>=2 && n<=4) ? 1 : 2;"
},
"An Error Occurred": [
null,
"Nastala chyba"
],
"Are you sure you want to perform this action?": [
null,
"Jste si jistí, že chcete provést tuto akci?"
],
"Cancel": [
null,
"Zrušit"
],
"Confirm": [
null,
"Potvrdit"
],
"Edit": [
null,
"Upravit"
],
"Failed to load data API information": [
null,
"Pokus o získání informací pomocí API selhal"
],
"Follow": [
null,
"Sledovat"
],
"Hide": [
null,
"Skrýt"
],
"Image": [
null,
"Obrázek"
],
"Input is too short, must be at least one character": [
null,
"Zadaný vstup je příliš krátký, musíte zadat alespoň jeden znak"
],
"Link": [
null,
"Odkaz"
],
"Link to a URL on the internet (you can also link to an API)": [
null,
"Odkaz na internetovou URL adresu (můžete také zadat odkaz na API)"
],
"Loading...": [
null,
"Nahrávám ..."
],
"No matches found": [
null,
"Nenalezena žádná shoda"
],
"Please Confirm Action": [
null,
"Prosím potvrďte akci"
],
"Remove": [
null,
"Odstranit"
],
"Reorder resources": [
null,
"Změnit pořadí zdrojů"
],
"Reset this": [
null,
"Resetovat"
],
"Resource uploaded": [
null,
"Zdroj nahrán"
],
"Save order": [
null,
"Uložit pořadí"
],
"Saving...": [
null,
"Ukládám..."
],
"Show more": [
null,
"Ukázat více"
],
"Start typing…": [
null,
"Začněte psát..."
],
"There are unsaved modifications to this form": [
null,
"Tento formulář obsahuje neuložené změny"
],
"There is no API data to load for this resource": [
null,
"Tento zdroj neobsahuje žádná data, která lze poskytnou přes API"
],
"URL": [
null,
"URL"
],
"Unable to authenticate upload": [
null,
"Nastala chyba autentizace při nahrávání dat"
],
"Unable to get data for uploaded file": [
null,
"Nelze získat data z nahraného souboru"
],
"Unable to upload file": [
null,
"Nelze nahrát soubor"
],
"Unfollow": [
null,
"Přestat sledovat"
],
"Upload": [
null,
"Nahrát"
],
"Upload a file": [
null,
"Nahrát soubor"
],
"Upload a file on your computer": [
null,
"Nahrát soubor na Váš počítač"
],
"You are uploading a file. Are you sure you want to navigate away and stop this upload?": [
null,
"Právě nahráváte soubor. Jste si opravdu jistí, že chcete tuto stránku opustit a ukončit tak nahrávání?"
],
"show less": [
null,
"ukázat méně"
],
"show more": [
null,
"ukázat více"
]
} | nucleo-digital/ckan-theme-cmbd | public/base/i18n/cs_CZ.js | JavaScript | gpl-3.0 | 2,840 |
cordova.define('cordova/plugin_list', function(require, exports, module) {
module.exports = [
{
"file": "plugins/cordova-plugin-device/www/device.js",
"id": "cordova-plugin-device.device",
"pluginId": "cordova-plugin-device",
"clobbers": [
"device"
]
},
{
"file": "plugins/cordova-plugin-device/src/browser/DeviceProxy.js",
"id": "cordova-plugin-device.DeviceProxy",
"pluginId": "cordova-plugin-device",
"runs": true
},
{
"file": "plugins/cordova-plugin-device-orientation/www/CompassError.js",
"id": "cordova-plugin-device-orientation.CompassError",
"pluginId": "cordova-plugin-device-orientation",
"clobbers": [
"CompassError"
]
},
{
"file": "plugins/cordova-plugin-device-orientation/www/CompassHeading.js",
"id": "cordova-plugin-device-orientation.CompassHeading",
"pluginId": "cordova-plugin-device-orientation",
"clobbers": [
"CompassHeading"
]
},
{
"file": "plugins/cordova-plugin-device-orientation/www/compass.js",
"id": "cordova-plugin-device-orientation.compass",
"pluginId": "cordova-plugin-device-orientation",
"clobbers": [
"navigator.compass"
]
},
{
"file": "plugins/cordova-plugin-device-orientation/src/browser/CompassProxy.js",
"id": "cordova-plugin-device-orientation.CompassProxy",
"pluginId": "cordova-plugin-device-orientation",
"runs": true
},
{
"file": "plugins/cordova-plugin-dialogs/www/notification.js",
"id": "cordova-plugin-dialogs.notification",
"pluginId": "cordova-plugin-dialogs",
"merges": [
"navigator.notification"
]
},
{
"file": "plugins/cordova-plugin-dialogs/www/browser/notification.js",
"id": "cordova-plugin-dialogs.notification_browser",
"pluginId": "cordova-plugin-dialogs",
"merges": [
"navigator.notification"
]
},
{
"file": "plugins/cordova-plugin-network-information/www/network.js",
"id": "cordova-plugin-network-information.network",
"pluginId": "cordova-plugin-network-information",
"clobbers": [
"navigator.connection",
"navigator.network.connection"
]
},
{
"file": "plugins/cordova-plugin-network-information/www/Connection.js",
"id": "cordova-plugin-network-information.Connection",
"pluginId": "cordova-plugin-network-information",
"clobbers": [
"Connection"
]
},
{
"file": "plugins/cordova-plugin-network-information/src/browser/network.js",
"id": "cordova-plugin-network-information.NetworkInfoProxy",
"pluginId": "cordova-plugin-network-information",
"runs": true
},
{
"file": "plugins/cordova-plugin-splashscreen/www/splashscreen.js",
"id": "cordova-plugin-splashscreen.SplashScreen",
"pluginId": "cordova-plugin-splashscreen",
"clobbers": [
"navigator.splashscreen"
]
},
{
"file": "plugins/cordova-plugin-splashscreen/src/browser/SplashScreenProxy.js",
"id": "cordova-plugin-splashscreen.SplashScreenProxy",
"pluginId": "cordova-plugin-splashscreen",
"runs": true
},
{
"file": "plugins/cordova-plugin-statusbar/www/statusbar.js",
"id": "cordova-plugin-statusbar.statusbar",
"pluginId": "cordova-plugin-statusbar",
"clobbers": [
"window.StatusBar"
]
},
{
"file": "plugins/cordova-plugin-statusbar/src/browser/statusbar.js",
"id": "cordova-plugin-statusbar.statusbar.Browser",
"pluginId": "cordova-plugin-statusbar",
"merges": [
"window.StatusBar"
]
},
{
"file": "plugins/phonegap-plugin-mobile-accessibility/www/mobile-accessibility.js",
"id": "phonegap-plugin-mobile-accessibility.mobile-accessibility",
"pluginId": "phonegap-plugin-mobile-accessibility",
"clobbers": [
"window.MobileAccessibility"
]
},
{
"file": "plugins/phonegap-plugin-mobile-accessibility/www/MobileAccessibilityNotifications.js",
"id": "phonegap-plugin-mobile-accessibility.MobileAccessibilityNotifications",
"pluginId": "phonegap-plugin-mobile-accessibility",
"clobbers": [
"MobileAccessibilityNotifications"
]
},
{
"file": "plugins/cordova-plugin-device-motion/www/Acceleration.js",
"id": "cordova-plugin-device-motion.Acceleration",
"pluginId": "cordova-plugin-device-motion",
"clobbers": [
"Acceleration"
]
},
{
"file": "plugins/cordova-plugin-device-motion/www/accelerometer.js",
"id": "cordova-plugin-device-motion.accelerometer",
"pluginId": "cordova-plugin-device-motion",
"clobbers": [
"navigator.accelerometer"
]
},
{
"file": "plugins/cordova-plugin-device-motion/src/browser/AccelerometerProxy.js",
"id": "cordova-plugin-device-motion.AccelerometerProxy",
"pluginId": "cordova-plugin-device-motion",
"runs": true
},
{
"file": "plugins/cordova-plugin-globalization/www/GlobalizationError.js",
"id": "cordova-plugin-globalization.GlobalizationError",
"pluginId": "cordova-plugin-globalization",
"clobbers": [
"window.GlobalizationError"
]
},
{
"file": "plugins/cordova-plugin-globalization/www/globalization.js",
"id": "cordova-plugin-globalization.globalization",
"pluginId": "cordova-plugin-globalization",
"clobbers": [
"navigator.globalization"
]
},
{
"file": "plugins/cordova-plugin-globalization/www/browser/moment.js",
"id": "cordova-plugin-globalization.moment",
"pluginId": "cordova-plugin-globalization",
"runs": true
},
{
"file": "plugins/cordova-plugin-globalization/src/browser/GlobalizationProxy.js",
"id": "cordova-plugin-globalization.GlobalizationProxy",
"pluginId": "cordova-plugin-globalization",
"runs": true
},
{
"file": "plugins/cordova-plugin-inappbrowser/www/inappbrowser.js",
"id": "cordova-plugin-inappbrowser.inappbrowser",
"pluginId": "cordova-plugin-inappbrowser",
"clobbers": [
"cordova.InAppBrowser.open",
"window.open"
]
},
{
"file": "plugins/cordova-plugin-inappbrowser/src/browser/InAppBrowserProxy.js",
"id": "cordova-plugin-inappbrowser.InAppBrowserProxy",
"pluginId": "cordova-plugin-inappbrowser",
"merges": [
""
]
},
{
"file": "plugins/cordova-plugin-file/www/DirectoryEntry.js",
"id": "cordova-plugin-file.DirectoryEntry",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.DirectoryEntry"
]
},
{
"file": "plugins/cordova-plugin-file/www/DirectoryReader.js",
"id": "cordova-plugin-file.DirectoryReader",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.DirectoryReader"
]
},
{
"file": "plugins/cordova-plugin-file/www/Entry.js",
"id": "cordova-plugin-file.Entry",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.Entry"
]
},
{
"file": "plugins/cordova-plugin-file/www/File.js",
"id": "cordova-plugin-file.File",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.File"
]
},
{
"file": "plugins/cordova-plugin-file/www/FileEntry.js",
"id": "cordova-plugin-file.FileEntry",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.FileEntry"
]
},
{
"file": "plugins/cordova-plugin-file/www/FileError.js",
"id": "cordova-plugin-file.FileError",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.FileError"
]
},
{
"file": "plugins/cordova-plugin-file/www/FileReader.js",
"id": "cordova-plugin-file.FileReader",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.FileReader"
]
},
{
"file": "plugins/cordova-plugin-file/www/FileSystem.js",
"id": "cordova-plugin-file.FileSystem",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.FileSystem"
]
},
{
"file": "plugins/cordova-plugin-file/www/FileUploadOptions.js",
"id": "cordova-plugin-file.FileUploadOptions",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.FileUploadOptions"
]
},
{
"file": "plugins/cordova-plugin-file/www/FileUploadResult.js",
"id": "cordova-plugin-file.FileUploadResult",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.FileUploadResult"
]
},
{
"file": "plugins/cordova-plugin-file/www/FileWriter.js",
"id": "cordova-plugin-file.FileWriter",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.FileWriter"
]
},
{
"file": "plugins/cordova-plugin-file/www/Flags.js",
"id": "cordova-plugin-file.Flags",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.Flags"
]
},
{
"file": "plugins/cordova-plugin-file/www/LocalFileSystem.js",
"id": "cordova-plugin-file.LocalFileSystem",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.LocalFileSystem"
],
"merges": [
"window"
]
},
{
"file": "plugins/cordova-plugin-file/www/Metadata.js",
"id": "cordova-plugin-file.Metadata",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.Metadata"
]
},
{
"file": "plugins/cordova-plugin-file/www/ProgressEvent.js",
"id": "cordova-plugin-file.ProgressEvent",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.ProgressEvent"
]
},
{
"file": "plugins/cordova-plugin-file/www/fileSystems.js",
"id": "cordova-plugin-file.fileSystems",
"pluginId": "cordova-plugin-file"
},
{
"file": "plugins/cordova-plugin-file/www/requestFileSystem.js",
"id": "cordova-plugin-file.requestFileSystem",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.requestFileSystem"
]
},
{
"file": "plugins/cordova-plugin-file/www/resolveLocalFileSystemURI.js",
"id": "cordova-plugin-file.resolveLocalFileSystemURI",
"pluginId": "cordova-plugin-file",
"merges": [
"window"
]
},
{
"file": "plugins/cordova-plugin-file/www/browser/isChrome.js",
"id": "cordova-plugin-file.isChrome",
"pluginId": "cordova-plugin-file",
"runs": true
},
{
"file": "plugins/cordova-plugin-file/www/browser/Preparing.js",
"id": "cordova-plugin-file.Preparing",
"pluginId": "cordova-plugin-file",
"runs": true
},
{
"file": "plugins/cordova-plugin-file/src/browser/FileProxy.js",
"id": "cordova-plugin-file.browserFileProxy",
"pluginId": "cordova-plugin-file",
"runs": true
},
{
"file": "plugins/cordova-plugin-file/www/fileSystemPaths.js",
"id": "cordova-plugin-file.fileSystemPaths",
"pluginId": "cordova-plugin-file",
"merges": [
"cordova"
],
"runs": true
},
{
"file": "plugins/cordova-plugin-file/www/browser/FileSystem.js",
"id": "cordova-plugin-file.firefoxFileSystem",
"pluginId": "cordova-plugin-file",
"merges": [
"window.FileSystem"
]
},
{
"file": "plugins/cordova-plugin-media/www/MediaError.js",
"id": "cordova-plugin-media.MediaError",
"pluginId": "cordova-plugin-media",
"clobbers": [
"window.MediaError"
]
},
{
"file": "plugins/cordova-plugin-media/www/Media.js",
"id": "cordova-plugin-media.Media",
"pluginId": "cordova-plugin-media",
"clobbers": [
"window.Media"
]
},
{
"file": "plugins/cordova-plugin-media/www/browser/Media.js",
"id": "cordova-plugin-media.BrowserMedia",
"pluginId": "cordova-plugin-media",
"clobbers": [
"window.Media"
]
}
];
module.exports.metadata =
// TOP OF METADATA
{
"cordova-plugin-console": "1.0.5",
"cordova-plugin-device": "1.1.4",
"cordova-plugin-device-orientation": "1.0.5",
"cordova-plugin-dialogs": "1.2.1",
"cordova-plugin-network-information": "1.2.1",
"cordova-plugin-splashscreen": "3.2.2",
"cordova-plugin-statusbar": "2.1.3",
"cordova-plugin-whitelist": "1.2.2",
"phonegap-plugin-mobile-accessibility": "1.0.5-dev",
"cordova-plugin-device-motion": "1.2.4",
"cordova-plugin-globalization": "1.0.6",
"cordova-plugin-inappbrowser": "1.3.0",
"cordova-plugin-compat": "1.1.0",
"cordova-plugin-file": "4.3.2",
"cordova-plugin-media": "2.2.0"
}
// BOTTOM OF METADATA
}); | Nullpo/Kallat-Tablero | platforms/browser/www/cordova_plugins.js | JavaScript | gpl-3.0 | 13,698 |
module.exports = { domain:"messages",
locale_data:{ messages:{ "":{ domain:"messages",
plural_forms:"nplurals=2; plural=(n != 1);",
lang:"el" },
"%(addonName)s %(startSpan)sby %(authorList)s%(endSpan)s":[ "%(addonName)s %(startSpan)s από %(authorList)s%(endSpan)s" ],
"Extension Metadata":[ "Μεταδεδομένα επέκτασης" ],
Screenshots:[ "Στιγμιότυπα" ],
"About this extension":[ "Σχετικά με την επέκταση" ],
"Rate your experience":[ "Αξιολογήστε την εμπειρία σας" ],
Category:[ "Κατηγορία" ],
"Used by":[ "Χρήση από" ],
Sentiment:[ "Αίσθηση" ],
Back:[ "Πίσω" ],
Submit:[ "Υποβολή" ],
"Please enter some text":[ "Παρακαλώ εισάγετε κείμενο" ],
"Write a review":[ "Γράψτε μια κριτική" ],
"Tell the world why you think this extension is fantastic!":[ "Πείτε στον κόσμο γιατί θεωρείτε ότι αυτή η επέκταση είναι φανταστική!" ],
"Privacy policy":[ "Πολιτική απορρήτου" ],
"Legal notices":[ "Νομικές σημειώσεις" ],
"View desktop site":[ "Προβολή ιστοσελίδας για υπολογιστές" ],
"Browse in your language":[ "Περιήγηση στη γλώσσα σας" ],
"Firefox Add-ons":[ "Πρόσθετα Firefox" ],
"How are you enjoying your experience with %(addonName)s?":[ "Απολαμβάνετε την εμπειρία σας με το %(addonName)s;" ],
"screenshot %(imageNumber)s of %(totalImages)s":[ "Στιγμιότυπο %(imageNumber)s από %(totalImages)s" ],
"Average rating: %(rating)s out of 5":[ "Μέση βαθμολογία: %(rating)s από 5" ],
"No ratings":[ "Καμία κριτική" ],
"%(users)s user":[ "%(users)s χρήστης",
"%(users)s χρήστες" ],
"Log out":[ "Αποσύνδεση" ],
"Log in/Sign up":[ "Σύνδεση/Εγγραφή" ],
"Add-ons for Firefox":[ "Πρόσθετα για το Firefox" ],
"What do you want Firefox to do?":[ "Τι θέλετε να κάνει το Firefox;" ],
"Block ads":[ "Αποκλεισμός διαφημίσεων" ],
Screenshot:[ "Στιγμιότυπο οθόνης" ],
"Save stuff":[ "Αποθήκευση στοιχείων" ],
"Shop online":[ "Διαδικτυακές αγορές" ],
"Be social":[ "Κοινωνικοποίηση" ],
"Share stuff":[ "Κοινή χρήση στοιχείων" ],
"Browse all extensions":[ "Περιήγηση σε όλες τις επεκτάσεις" ],
"How do you want Firefox to look?":[ "Τι εμφάνιση θέλετε να έχει το Firefox;" ],
Wild:[ "Άγρια" ],
Abstract:[ "Αφηρημένη" ],
Fashionable:[ "Μοδάτη" ],
Scenic:[ "Σκηνική" ],
Sporty:[ "Αθλητική" ],
Mystical:[ "Μυστική" ],
"Browse all themes":[ "Περιήγηση σε όλα τα θέματα" ],
"Downloading %(name)s.":[ "Γίνεται λήψη του %(name)s." ],
"Installing %(name)s.":[ "Γίνεται εγκατάσταση του %(name)s." ],
"%(name)s is installed and enabled. Click to uninstall.":[ "Το %(name)s έχει εγκατασταθεί και ενεργοποιηθεί. Κάντε κλικ για απεγκατάσταση." ],
"%(name)s is disabled. Click to enable.":[ "Το %(name)s έχει απενεργοποιηθεί. Κάντε κλικ για ενεργοποίηση." ],
"Uninstalling %(name)s.":[ "Γίνεται απεγκατάσταση του %(name)s." ],
"%(name)s is uninstalled. Click to install.":[ "Το %(name)s έχει απεγκατασταθεί. Κάντε κλικ για εγκατάσταση." ],
"Install state for %(name)s is unknown.":[ "Η κατάσταση εγκατάστασης για το %(name)s είναι άγνωστη." ],
Previous:[ "Προηγούμενη" ],
Next:[ "Επόμενη" ],
"Page %(currentPage)s of %(totalPages)s":[ "Σελίδα %(currentPage)s από %(totalPages)s" ],
"Your search for \"%(query)s\" returned %(count)s result.":[ "Η αναζήτησή σας για το \"%(query)s\" είχε %(count)s αποτέλεσμα.",
"Η αναζήτησή σας για το \"%(query)s\" είχε %(count)s αποτελέσματα." ],
"Searching...":[ "Αναζήτηση..." ],
"No results were found for \"%(query)s\".":[ "Δεν βρέθηκε κανένα αποτέλεσμα για το \"%(query)s\"." ],
"Please supply a valid search":[ "Παρακαλώ κάντε μια έγκυρη αναζήτηση" ] } },
_momentDefineLocale:function anonymous() {
//! moment.js locale configuration
//! locale : Greek [el]
//! author : Aggelos Karalias : https://github.com/mehiel
;(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined'
&& typeof require === 'function' ? factory(require('../moment')) :
typeof define === 'function' && define.amd ? define(['../moment'], factory) :
factory(global.moment)
}(this, (function (moment) { 'use strict';
function isFunction(input) {
return input instanceof Function || Object.prototype.toString.call(input) === '[object Function]';
}
var el = moment.defineLocale('el', {
monthsNominativeEl : 'Ιανουάριος_Φεβρουάριος_Μάρτιος_Απρίλιος_Μάιος_Ιούνιος_Ιούλιος_Αύγουστος_Σεπτέμβριος_Οκτώβριος_Νοέμβριος_Δεκέμβριος'.split('_'),
monthsGenitiveEl : 'Ιανουαρίου_Φεβρουαρίου_Μαρτίου_Απριλίου_Μαΐου_Ιουνίου_Ιουλίου_Αυγούστου_Σεπτεμβρίου_Οκτωβρίου_Νοεμβρίου_Δεκεμβρίου'.split('_'),
months : function (momentToFormat, format) {
if (/D/.test(format.substring(0, format.indexOf('MMMM')))) { // if there is a day number before 'MMMM'
return this._monthsGenitiveEl[momentToFormat.month()];
} else {
return this._monthsNominativeEl[momentToFormat.month()];
}
},
monthsShort : 'Ιαν_Φεβ_Μαρ_Απρ_Μαϊ_Ιουν_Ιουλ_Αυγ_Σεπ_Οκτ_Νοε_Δεκ'.split('_'),
weekdays : 'Κυριακή_Δευτέρα_Τρίτη_Τετάρτη_Πέμπτη_Παρασκευή_Σάββατο'.split('_'),
weekdaysShort : 'Κυρ_Δευ_Τρι_Τετ_Πεμ_Παρ_Σαβ'.split('_'),
weekdaysMin : 'Κυ_Δε_Τρ_Τε_Πε_Πα_Σα'.split('_'),
meridiem : function (hours, minutes, isLower) {
if (hours > 11) {
return isLower ? 'μμ' : 'ΜΜ';
} else {
return isLower ? 'πμ' : 'ΠΜ';
}
},
isPM : function (input) {
return ((input + '').toLowerCase()[0] === 'μ');
},
meridiemParse : /[ΠΜ]\.?Μ?\.?/i,
longDateFormat : {
LT : 'h:mm A',
LTS : 'h:mm:ss A',
L : 'DD/MM/YYYY',
LL : 'D MMMM YYYY',
LLL : 'D MMMM YYYY h:mm A',
LLLL : 'dddd, D MMMM YYYY h:mm A'
},
calendarEl : {
sameDay : '[Σήμερα {}] LT',
nextDay : '[Αύριο {}] LT',
nextWeek : 'dddd [{}] LT',
lastDay : '[Χθες {}] LT',
lastWeek : function () {
switch (this.day()) {
case 6:
return '[το προηγούμενο] dddd [{}] LT';
default:
return '[την προηγούμενη] dddd [{}] LT';
}
},
sameElse : 'L'
},
calendar : function (key, mom) {
var output = this._calendarEl[key],
hours = mom && mom.hours();
if (isFunction(output)) {
output = output.apply(mom);
}
return output.replace('{}', (hours % 12 === 1 ? 'στη' : 'στις'));
},
relativeTime : {
future : 'σε %s',
past : '%s πριν',
s : 'λίγα δευτερόλεπτα',
m : 'ένα λεπτό',
mm : '%d λεπτά',
h : 'μία ώρα',
hh : '%d ώρες',
d : 'μία μέρα',
dd : '%d μέρες',
M : 'ένας μήνας',
MM : '%d μήνες',
y : 'ένας χρόνος',
yy : '%d χρόνια'
},
ordinalParse: /\d{1,2}η/,
ordinal: '%dη',
week : {
dow : 1, // Monday is the first day of the week.
doy : 4 // The week that contains Jan 4st is the first week of the year.
}
});
return el;
})));
} } | jasonthomas/addons-frontend | src/locale/el/amo.js | JavaScript | mpl-2.0 | 8,820 |
/**
* Nooku Platform - http://www.nooku.org/platform
*
* @copyright Copyright (C) 2011 - 2014 Johan Janssens and Timble CVBA. (http://www.timble.net)
* @license GNU GPLv3 <http://www.gnu.org/licenses/gpl.html>
* @link https://github.com/nooku/nooku-platform for the canonical source repository
*/
if(!Attachments) var Attachments = {};
Attachments.List = new Class({
element : null,
initialize: function(options) {
this.element = document.id(options.container);
this.url = options.action;
this.token = options.token;
this.coordinates = '';
this.trueSize = '';
if(!this.element) {
return;
}
this.addCrop();
var that = this;
this.element.getElements('a[data-action]').each(function(a) {
if(a.get('data-action'))
{
a.addEvent('click', function(e) {
e.stop();
that.execute(this.get('data-action'), this.get('data-id'), this.get('data-row'));
});
}
});
},
addCrop: function()
{
var target = jQuery('#target');
var img = new Image(), self = this;
img.onload = function() {
self.trueSize = [this.width, this.height];
if (target.length) {
target.Jcrop({
boxWidth: 600,
boxHeight: 600,
trueSize: self.trueSize,
aspectRatio: 4 / 3,
minSize: [200, 150],
setSelect: [0, 0, 200, 150],
onSelect: self.setCoordinates.bind(self),
onChange: self.setCoordinates.bind(self)
});
}
};
var source = target.attr("src");
if (source) {
img.src = source;
}
},
setCoordinates: function(c)
{
this.coordinates = c;
},
execute: function(action, id, row)
{
var method = '_action' + action.capitalize();
if($type(this[method]) == 'function')
{
this.action = action;
var uri = new URI(this.url);
uri.setData('id', id);
this[method].call(this, uri);
}
},
_actionDelete: function(uri)
{
var form = new Kodekit.Form({
method: 'post',
url: uri.toString(),
params: {
_action: 'delete',
csrf_token: this.token
}
});
form.submit();
},
_actionCrop: function(uri)
{
jQuery.ajax({
url: uri.toString(),
dataType: 'json',
method: 'post',
data: {
_action: 'edit',
csrf_token: this.token,
x1: this.coordinates.x,
y1: this.coordinates.y,
x2: this.coordinates.x2,
y2: this.coordinates.y2
}
}).then(function(data, textStatus, xhr) {
if (xhr.status === 204) {
jQuery.ajax({
url: uri.toString(),
dataType: 'json',
method: 'get'
}).then(function(data, textStatus, xhr) {
if (xhr.status === 200 && typeof data.item === 'object') {
var thumbnail = data.item.thumbnail,
element = window.parent.jQuery('.thumbnail[data-id="'+data.item.id+'"] img'),
source = element.attr('src');
thumbnail = source.substring(0, source.lastIndexOf('/'))+'/'+thumbnail;
element.attr('src', thumbnail);
if (window.parent.SqueezeBox) {
window.parent.SqueezeBox.close();
}
}
});
} else {
alert('Unable to crop thumbnail');
}
});
}
}); | nooku/nooku-platform | component/attachments/resources/assets/js/attachments.list.js | JavaScript | mpl-2.0 | 4,062 |
/*! JointJS v3.4.1 (2021-08-18) - JavaScript diagramming library
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
this.joint = this.joint || {};
this.joint.shapes = this.joint.shapes || {};
(function (exports, basic_mjs, Element_mjs, Link_mjs) {
'use strict';
var State = basic_mjs.Circle.define('fsa.State', {
attrs: {
circle: { 'stroke-width': 3 },
text: { 'font-weight': '800' }
}
});
var StartState = Element_mjs.Element.define('fsa.StartState', {
size: { width: 20, height: 20 },
attrs: {
circle: {
transform: 'translate(10, 10)',
r: 10,
fill: '#000000'
}
}
}, {
markup: '<g class="rotatable"><g class="scalable"><circle/></g></g>',
});
var EndState = Element_mjs.Element.define('fsa.EndState', {
size: { width: 20, height: 20 },
attrs: {
'.outer': {
transform: 'translate(10, 10)',
r: 10,
fill: '#ffffff',
stroke: '#000000'
},
'.inner': {
transform: 'translate(10, 10)',
r: 6,
fill: '#000000'
}
}
}, {
markup: '<g class="rotatable"><g class="scalable"><circle class="outer"/><circle class="inner"/></g></g>',
});
var Arrow = Link_mjs.Link.define('fsa.Arrow', {
attrs: { '.marker-target': { d: 'M 10 0 L 0 5 L 10 10 z' }},
smooth: true
});
exports.Arrow = Arrow;
exports.EndState = EndState;
exports.StartState = StartState;
exports.State = State;
}(this.joint.shapes.fsa = this.joint.shapes.fsa || {}, joint.shapes.basic, joint.dia, joint.dia));
| DavidDurman/joint | dist/joint.shapes.fsa.js | JavaScript | mpl-2.0 | 1,920 |
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import { createStore, applyMiddleware } from 'redux';
import threadDispatcher from '../../common/thread-middleware';
import handleMessages from '../../common/message-handler';
import messages from './messages-worker';
import reducers from './reducers';
import thunk from 'redux-thunk';
const store = createStore(
// Reducers:
reducers,
// Initial State:
{},
// Enhancers:
applyMiddleware(
...[
thunk,
threadDispatcher(self, 'toContent'),
].filter(fn => fn)
)
);
handleMessages(self, store, messages);
| squarewave/bhr.html | src/workers/summary/index.js | JavaScript | mpl-2.0 | 743 |
/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//-----------------------------------------------------------------------------
var BUGNUMBER = 474935;
var summary = 'Do not assert: !ti->typeMap.matches(ti_other->typeMap)';
var actual = '';
var expect = '';
//-----------------------------------------------------------------------------
test();
//-----------------------------------------------------------------------------
function test()
{
enterFunc ('test');
printBugNumber(BUGNUMBER);
printStatus (summary);
var a = ["", 0, 0, 0, 0, 0, "", "", 0, "", 0, ""];
var i = 0;
var g = 0;
for each (let e in a) {
"" + [e];
if (i == 3 || i == 7) {
for each (g in [1]) {
}
}
++i;
}
reportCompare(expect, actual, summary);
exitFunc ('test');
}
| cstipkovic/spidermonkey-research | js/src/tests/js1_8/regress/regress-474935.js | JavaScript | mpl-2.0 | 1,026 |
import React from 'react';
import ImmutablePropTypes from 'react-immutable-proptypes';
import PropTypes from 'prop-types';
import IconButton from './icon_button';
import DropdownMenu from './dropdown_menu';
import { defineMessages, injectIntl } from 'react-intl';
import ImmutablePureComponent from 'react-immutable-pure-component';
const messages = defineMessages({
delete: { id: 'status.delete', defaultMessage: 'Delete' },
mention: { id: 'status.mention', defaultMessage: 'Mention @{name}' },
mute: { id: 'account.mute', defaultMessage: 'Mute @{name}' },
block: { id: 'account.block', defaultMessage: 'Block @{name}' },
reply: { id: 'status.reply', defaultMessage: 'Reply' },
replyAll: { id: 'status.replyAll', defaultMessage: 'Reply to thread' },
reblog: { id: 'status.reblog', defaultMessage: 'Boost' },
cannot_reblog: { id: 'status.cannot_reblog', defaultMessage: 'This post cannot be boosted' },
favourite: { id: 'status.favourite', defaultMessage: 'Favourite' },
open: { id: 'status.open', defaultMessage: 'Expand this status' },
report: { id: 'status.report', defaultMessage: 'Report @{name}' },
muteConversation: { id: 'status.mute_conversation', defaultMessage: 'Mute conversation' },
unmuteConversation: { id: 'status.unmute_conversation', defaultMessage: 'Unmute conversation' },
});
@injectIntl
export default class StatusActionBar extends ImmutablePureComponent {
static contextTypes = {
router: PropTypes.object,
};
static propTypes = {
status: ImmutablePropTypes.map.isRequired,
onReply: PropTypes.func,
onFavourite: PropTypes.func,
onReblog: PropTypes.func,
onDelete: PropTypes.func,
onMention: PropTypes.func,
onMute: PropTypes.func,
onBlock: PropTypes.func,
onReport: PropTypes.func,
onMuteConversation: PropTypes.func,
me: PropTypes.number.isRequired,
withDismiss: PropTypes.bool,
intl: PropTypes.object.isRequired,
};
// Avoid checking props that are functions (and whose equality will always
// evaluate to false. See react-immutable-pure-component for usage.
updateOnProps = [
'status',
'me',
'withDismiss',
]
handleReplyClick = () => {
this.props.onReply(this.props.status, this.context.router.history);
}
handleFavouriteClick = () => {
this.props.onFavourite(this.props.status);
}
handleReblogClick = (e) => {
this.props.onReblog(this.props.status, e);
}
handleDeleteClick = () => {
this.props.onDelete(this.props.status);
}
handleMentionClick = () => {
this.props.onMention(this.props.status.get('account'), this.context.router.history);
}
handleMuteClick = () => {
this.props.onMute(this.props.status.get('account'));
}
handleBlockClick = () => {
this.props.onBlock(this.props.status.get('account'));
}
handleOpen = () => {
this.context.router.history.push(`/statuses/${this.props.status.get('id')}`);
}
handleReport = () => {
this.props.onReport(this.props.status);
}
handleConversationMuteClick = () => {
this.props.onMuteConversation(this.props.status);
}
render () {
const { status, me, intl, withDismiss } = this.props;
const reblogDisabled = status.get('visibility') === 'private' || status.get('visibility') === 'direct';
const mutingConversation = status.get('muted');
let menu = [];
let reblogIcon = 'retweet';
let replyIcon;
let replyTitle;
menu.push({ text: intl.formatMessage(messages.open), action: this.handleOpen });
menu.push(null);
if (withDismiss) {
menu.push({ text: intl.formatMessage(mutingConversation ? messages.unmuteConversation : messages.muteConversation), action: this.handleConversationMuteClick });
menu.push(null);
}
if (status.getIn(['account', 'id']) === me) {
menu.push({ text: intl.formatMessage(messages.delete), action: this.handleDeleteClick });
} else {
menu.push({ text: intl.formatMessage(messages.mention, { name: status.getIn(['account', 'username']) }), action: this.handleMentionClick });
menu.push(null);
menu.push({ text: intl.formatMessage(messages.mute, { name: status.getIn(['account', 'username']) }), action: this.handleMuteClick });
menu.push({ text: intl.formatMessage(messages.block, { name: status.getIn(['account', 'username']) }), action: this.handleBlockClick });
menu.push({ text: intl.formatMessage(messages.report, { name: status.getIn(['account', 'username']) }), action: this.handleReport });
}
if (status.get('visibility') === 'direct') {
reblogIcon = 'envelope';
} else if (status.get('visibility') === 'private') {
reblogIcon = 'lock';
}
if (status.get('in_reply_to_id', null) === null) {
replyIcon = 'reply';
replyTitle = intl.formatMessage(messages.reply);
} else {
replyIcon = 'reply-all';
replyTitle = intl.formatMessage(messages.replyAll);
}
return (
<div className='status__action-bar'>
<IconButton className='status__action-bar-button' title={replyTitle} icon={replyIcon} onClick={this.handleReplyClick} />
<IconButton className='status__action-bar-button' disabled={reblogDisabled} active={status.get('reblogged')} title={reblogDisabled ? intl.formatMessage(messages.cannot_reblog) : intl.formatMessage(messages.reblog)} icon={reblogIcon} onClick={this.handleReblogClick} />
<IconButton className='status__action-bar-button star-icon' animate active={status.get('favourited')} title={intl.formatMessage(messages.favourite)} icon='star' onClick={this.handleFavouriteClick} />
<div className='status__action-bar-dropdown'>
<DropdownMenu items={menu} icon='ellipsis-h' size={18} direction='right' ariaLabel='More' />
</div>
</div>
);
}
}
| Toootim/mastodon | app/javascript/mastodon/components/status_action_bar.js | JavaScript | agpl-3.0 | 5,791 |
import ITEM_QUALITIES from '../ITEM_QUALITIES';
export default {
// Shared legendaries
SOUL_OF_THE_SHADOWBLADE: {
id: 150936,
name: 'Soul of the Shadowblade',
icon: 'inv_jewelry_ring_56',
quality: ITEM_QUALITIES.LEGENDARY,
},
MANTLE_OF_THE_MASTER_ASSASSIN: {
id: 144236,
name: 'Mantle of the Master Assassin',
icon: 'inv_shoulder_leather_raidrogue_k_01',
quality: ITEM_QUALITIES.LEGENDARY,
},
INSIGNIA_OF_RAVENHOLDT: {
id: 137049,
name: 'Insignia of Ravenholdt',
icon: 'inv_misc_epicring_a2',
quality: ITEM_QUALITIES.LEGENDARY,
},
WILL_OF_VALEERA: {
id: 137069,
name: 'Will of Valeera',
icon: 'inv_pants_cloth_02',
quality: ITEM_QUALITIES.LEGENDARY,
},
THE_DREADLORDS_DECEIT: {
id: 137021,
name: 'The Dreadlord\'s Deceit',
icon: 'inv_cape_pandaria_d_03',
quality: ITEM_QUALITIES.LEGENDARY,
},
// Assassination legendaries
DUSKWALKERS_FOOTPADS: {
id: 137030,
name: 'Duskwalker\'s Footpads',
icon: 'inv_boots_leather_8',
quality: ITEM_QUALITIES.LEGENDARY,
},
ZOLDYCK_FAMILY_TRAINING_SHACKLES: {
id: 137098,
name: 'Zoldyck Family Training Shackles',
icon: 'inv_bracer_leather_raiddruid_i_01',
quality: ITEM_QUALITIES.LEGENDARY,
},
THE_EMPTY_CROWN: {
id: 151815,
name: 'The Empty Crown',
icon: 'inv_crown_02',
quality: ITEM_QUALITIES.LEGENDARY,
},
// Outlaw legendaries
THRAXIS_TRICKSY_TREADS: {
id: 137031,
name: 'Thraxi\'s Tricksy Treads',
icon: 'inv_boots_leather_03a',
quality: ITEM_QUALITIES.LEGENDARY,
},
GREENSKINS_WATERLOGGED_WRISTCUFFS: {
id: 137099,
name: 'Greenskin\'s Waterlogged Wristcuffs',
icon: 'inv_bracer_leather_raidrogue_k_01',
quality: ITEM_QUALITIES.LEGENDARY,
},
SHIVARRAN_SYMMETRY: {
id: 141321,
name: 'Shivarran Symmetry',
icon: 'inv_gauntlets_83',
quality: ITEM_QUALITIES.LEGENDARY,
},
THE_CURSE_OF_RESTLESSNESS: {
id: 151817,
name: 'The Curse of Restlessness',
icon: 'inv_qiraj_draperegal',
quality: ITEM_QUALITIES.LEGENDARY,
},
// Subtlety legendaries
SHADOW_SATYRS_WALK: {
id: 137032,
name: 'Shadow Satyr\'s Walk',
icon: 'inv_boots_mail_dungeonmail_c_04',
quality: ITEM_QUALITIES.LEGENDARY,
},
DENIAL_OF_THE_HALF_GIANTS: {
id: 137100,
name: 'Denial of the Half-Giants',
icon: 'inv_bracer_leather_panda_b_02_crimson',
quality: ITEM_QUALITIES.LEGENDARY,
},
THE_FIRST_OF_THE_DEAD: {
id: 151818,
name: 'The First of the Dead',
icon: 'inv_glove_cloth_raidwarlockmythic_q_01',
quality: ITEM_QUALITIES.LEGENDARY,
},
};
| enragednuke/WoWAnalyzer | src/common/ITEMS/ROGUE.js | JavaScript | agpl-3.0 | 2,649 |
const LdapStrategy = require('./LdapStrategy');
const MoodleStrategy = require('./MoodleStrategy');
const IservStrategy = require('./IservStrategy');
const TSPStrategy = require('./TSPStrategy');
const ApiKeyStrategy = require('./ApiKeyStrategy');
module.exports = {
LdapStrategy,
MoodleStrategy,
IservStrategy,
TSPStrategy,
ApiKeyStrategy,
};
| schul-cloud/schulcloud-server | src/services/authentication/strategies/index.js | JavaScript | agpl-3.0 | 350 |
// Generated by CoffeeScript 1.10.0
var api, baseOVHKonnector, connector, name, slug;
baseOVHKonnector = require('../lib/base_ovh_konnector');
name = 'Kimsufi EU';
slug = 'kimsufi_eu';
api = {
endpoint: 'kimsufi-eu',
appKey: '',
appSecret: ''
};
connector = module.exports = baseOVHKonnector.createNew(api, name, slug);
| frankrousseau/konnectors | build/server/konnectors/kimsufi_eu.js | JavaScript | agpl-3.0 | 331 |
/* Taken from a very informative blogpost by Eldar Djafarov:
* http://eldar.djafarov.com/2013/11/reactjs-mixing-with-backbone/
*/
(function() {
'use strict';
module.exports = {
/* Forces an update when the underlying Backbone model instance has
* changed. Users will have to implement getBackboneModels().
* Also requires that React is loaded with addons.
*/
__syncedModels: [],
componentDidMount: function() {
// Whenever there may be a change in the Backbone data, trigger a reconcile.
this.getBackboneModels().forEach(this.injectModel, this);
},
componentWillUnmount: function() {
// Ensure that we clean up any dangling references when the component is
// destroyed.
this.__syncedModels.forEach(function(model) {
model.off(null, model.__updater, this);
}, this);
},
injectModel: function(model){
if(!~this.__syncedModels.indexOf(model)){
var updater = function() {
try {
this.forceUpdate();
} catch(e) {
// This means the component is already being updated somewhere
// else, so we just silently go on with our business.
// This is most likely due to some AJAX callback that already
// updated the model at the same time or slightly earlier.
}
}.bind(this, null);
model.__updater = updater;
model.on('add change remove', updater, this);
}
},
bindTo: function(model, key){
/* Allows for two-way databinding for Backbone models.
* Use by passing it as a 'valueLink' property, e.g.:
* valueLink={this.bindTo(model, attribute)} */
return {
value: model.get(key),
requestChange: function(value){
model.set(key, value);
}.bind(this)
};
}
};
})();
| jbaiter/spreads | spreadsplug/web/client/lib/backbonemixin.js | JavaScript | agpl-3.0 | 1,858 |
/*@author Jvlaple
*Crystal of Roots
*/
var status = 0;
var PQItems = Array(4001087, 4001088, 4001089, 4001090, 4001091, 4001092, 4001093);
importPackage(net.sf.odinms.client);
function start() {
status = -1;
action(1, 0, 0);
}
function action(mode, type, selection) {
if (mode == -1) {
cm.dispose();
} else {
if (status >= 0 && mode == 0) {
cm.sendOk("Ok, keep preservering!");
cm.dispose();
return;
}
if (mode == 1)
status++;
else
status--;
if (status == 0 ) {
cm.sendYesNo("Hello I'm the Dungeon Exit NPC. Do you wish to go out from here?");
} else if (status == 1) {
var eim = cm.getPlayer().getEventInstance();
cm.warp(100000000, 0);
if (eim != null) {
eim.unregisterPlayer(cm.getPlayer());
}cm.dispose();
}
}
} | ZenityMS/forgottenstorysource | scripts/npc/2111005.js | JavaScript | agpl-3.0 | 1,027 |
// Generated by CoffeeScript 1.10.0
var Bill, baseKonnector, filterExisting, linkBankOperation, ovhFetcher, saveDataAndFile;
ovhFetcher = require('../lib/ovh_fetcher');
filterExisting = require('../lib/filter_existing');
saveDataAndFile = require('../lib/save_data_and_file');
linkBankOperation = require('../lib/link_bank_operation');
baseKonnector = require('../lib/base_konnector');
Bill = require('../models/bill');
module.exports = {
createNew: function(ovhApi, name, slug) {
var connector, fetchBills, fileOptions, logger, ovhFetcherInstance;
fileOptions = {
vendor: slug,
dateFormat: 'YYYYMMDD'
};
logger = require('printit')({
prefix: name,
date: true
});
ovhFetcherInstance = ovhFetcher["new"](ovhApi, slug, logger);
fetchBills = function(requiredFields, entries, body, next) {
return ovhFetcherInstance.fetchBills(requiredFields, entries, body, next);
};
return connector = baseKonnector.createNew({
name: name,
fields: {
loginUrl: "link",
token: "hidden",
folderPath: "folder"
},
models: [Bill],
fetchOperations: [
fetchBills, filterExisting(logger, Bill), saveDataAndFile(logger, Bill, fileOptions, ['bill']), linkBankOperation({
log: logger,
model: Bill,
identifier: slug,
dateDelta: 4,
amountDelta: 0.1
})
]
});
}
};
| frankrousseau/konnectors | build/server/lib/base_ovh_konnector.js | JavaScript | agpl-3.0 | 1,438 |
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import store from './store'
import VueBootstrap from 'bootstrap-vue'
import 'bootstrap/dist/css/bootstrap.css'
import 'bootstrap-vue/dist/bootstrap-vue.css'
Vue.use(VueBootstrap)
// HTTP Client we use.
import Axios from 'axios'
// TODO: Set these during build time.
Axios.defaults.baseURL = 'http://localhost:8080'
Axios.defaults.headers['Content-Type'] = 'application/json; charset=UTF-8'
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
store,
template: '<App/>',
components: { App }
})
| praelatus/backend | client/src/main.js | JavaScript | agpl-3.0 | 761 |
namespace("JSTools.Event");
/// <class>
/// Provides an interface for attaching and detaching Observer objects. Any number of
/// Observer objects may observe a subject.
/// </class>
JSTools.Event.Subject = function()
{
//------------------------------------------------------------------------
// Declarations
//------------------------------------------------------------------------
this.InitType(arguments, "JSTools.Event.Subject");
var _this = this;
var _observers = null;
//------------------------------------------------------------------------
// Constructor
//------------------------------------------------------------------------
/// <constructor>
/// Creates a new JSTools.Event.Subject instance.
/// </constructor>
function Init()
{
_this.Clear();
}
//------------------------------------------------------------------------
// Methods
//------------------------------------------------------------------------
/// <method>
/// Removes all registered observer object.
/// </method>
function Clear()
{
_observers = [ ];
}
this.Clear = Clear;
/// <method>
/// Attaches the given observer function to this subject.
/// </method>
/// <param name="objIObserver" type="JSTools.Event.IObserver">Observer to attach.</param>
/// <returns type="Integer">Returns the index, at which the observer object has been added.
/// Returns -1 if the given observer object is invalid and not added.</returns>
function Attach(objIObserver)
{
if (objIObserver
&& typeof(objIObserver) == 'object'
&& objIObserver.IsTypeOf(JSTools.Event.IObserver))
{
_observers.Add(objIObserver);
return _observers.length - 1;
}
return -1;
}
this.Attach = Attach;
/// <method>
/// Detaches the given observer object from this subject.
/// </method>
/// <param name="objIObserverToDetach" type="JSTools.Event.IObserver">Observer to detach.</param>
function Detach(objIObserverToDetach)
{
_observers.Remove(objIObserverToDetach);
}
this.Detach = Detach;
/// <method>
/// Detaches an observer at the given index from this subject.
/// </method>
/// <param name="intIndex" type="Integer">Index to detach.</param>
function DetachByIndex(intIndex)
{
_observers.RemoveAt(intIndex);
}
this.DetachByIndex = DetachByIndex;
/// <method>
/// Notifies the observer about an update.
/// </method>
/// <param name="objEvent" type="Object">An object instance, which represents the event argument.</param>
function Notify(objEvent)
{
for (var i = 0; i < _observers.length; ++i)
{
_observers[i].Update(objEvent);
}
}
this.Notify = Notify;
Init();
}
| sgeh/JSTools.net | Branches/JSTools 0.41/JSTools.JavaScript/JSTools/Event/Subject.js | JavaScript | lgpl-2.1 | 2,624 |
asynctest(
'browser.tinymce.core.keyboard.BoundaryLocationTest',
[
'ephox.agar.api.Assertions',
'ephox.agar.api.GeneralSteps',
'ephox.agar.api.Logger',
'ephox.agar.api.Pipeline',
'ephox.agar.api.Step',
'ephox.katamari.api.Fun',
'ephox.sugar.api.dom.Hierarchy',
'ephox.sugar.api.node.Element',
'ephox.sugar.api.search.Selectors',
'tinymce.core.caret.CaretPosition',
'tinymce.core.keyboard.BoundaryLocation',
'tinymce.core.test.ViewBlock',
'tinymce.core.text.Zwsp'
],
function (Assertions, GeneralSteps, Logger, Pipeline, Step, Fun, Hierarchy, Element, Selectors, CaretPosition, BoundaryLocation, ViewBlock, Zwsp) {
var success = arguments[arguments.length - 2];
var failure = arguments[arguments.length - 1];
var ZWSP = Zwsp.ZWSP;
var viewBlock = ViewBlock();
var createViewElement = function (html) {
viewBlock.update(html);
return Element.fromDom(viewBlock.get());
};
var createLocation = function (elm, elementPath, offset) {
var container = Hierarchy.follow(elm, elementPath);
var pos = new CaretPosition(container.getOrDie().dom(), offset);
var location = BoundaryLocation.readLocation(elm.dom(), pos);
return location;
};
var createPosition = function (elm, elementPath, offset) {
var container = Hierarchy.follow(elm, elementPath);
return new CaretPosition(container.getOrDie().dom(), offset);
};
var locationName = function (location) {
return location.fold(
Fun.constant('before'),
Fun.constant('start'),
Fun.constant('end'),
Fun.constant('after')
);
};
var locationElement = function (location) {
return Element.fromDom(location.fold(
Fun.identity,
Fun.identity,
Fun.identity,
Fun.identity
));
};
var sTestValidLocation = function (html, elementPath, offset, expectedLocationName, expectedInline) {
return Step.sync(function () {
var elm = createViewElement(html);
var location = createLocation(elm, elementPath, offset);
Assertions.assertEq('Should be a valid location: ' + html, true, location.isSome());
Assertions.assertEq('Should be expected location', expectedLocationName, locationName(location.getOrDie()));
Assertions.assertDomEq('Should be expected element', Selectors.one(expectedInline, elm).getOrDie(), locationElement(location.getOrDie()));
});
};
var sTestInvalidLocation = function (html, elementPath, offset) {
return Step.sync(function () {
var elm = createViewElement(html);
var location = createLocation(elm, elementPath, offset);
Assertions.assertEq('Should not be a valid location: ' + html, true, location.isNone());
});
};
var sTestFindLocation = function (forward, html, elementPath, offset, expectedLocationName, expectedInline) {
return Step.sync(function () {
var elm = createViewElement(html);
var position = createPosition(elm, elementPath, offset);
var location = forward ? BoundaryLocation.nextLocation(elm.dom(), position) : BoundaryLocation.prevLocation(elm.dom(), position);
Assertions.assertDomEq('Should be expected element', Selectors.one(expectedInline, elm).getOrDie(), locationElement(location.getOrDie()));
Assertions.assertEq('Should be a valid location: ' + html, true, location.isSome());
Assertions.assertEq('Should be expected location', expectedLocationName, locationName(location.getOrDie()));
});
};
var sTestFindLocationInvalid = function (forward, html, elementPath, offset) {
return Step.sync(function () {
var elm = createViewElement(html);
var position = createPosition(elm, elementPath, offset);
var location = forward ? BoundaryLocation.nextLocation(elm.dom(), position) : BoundaryLocation.prevLocation(elm.dom(), position);
Assertions.assertEq('Should not be a valid location: ' + html, true, location.isNone());
});
};
var sTestPrevLocation = Fun.curry(sTestFindLocation, false);
var sTestNextLocation = Fun.curry(sTestFindLocation, true);
var sTestPrevLocationInvalid = Fun.curry(sTestFindLocationInvalid, false);
var sTestNextLocationInvalid = Fun.curry(sTestFindLocationInvalid, true);
var sTestValidLocations = Logger.t('sTestValidLocations', GeneralSteps.sequence([
sTestValidLocation('<p><a href="a">a</a></p>', [0], 0, 'before', 'a'),
sTestValidLocation('<p><a href="a">a</a></p>', [0, 0, 0], 0, 'start', 'a'),
sTestValidLocation('<p><a href="a">a</a></p>', [0, 0, 0], 1, 'end', 'a'),
sTestValidLocation('<p><a href="a">a</a></p>', [0], 1, 'after', 'a'),
sTestValidLocation('<p>a<a href="a">a</a></p>', [0, 0], 1, 'before', 'a'),
sTestValidLocation('<p><a href="a">a</a>a</p>', [0, 1], 0, 'after', 'a'),
sTestValidLocation('<p><a href="a">ab</a></p>', [0, 0, 0], 0, 'start', 'a'),
sTestValidLocation('<p><a href="a">ab</a></p>', [0, 0, 0], 2, 'end', 'a'),
sTestValidLocation('<p><img src="a"><a href="a">a</a></p>', [0], 1, 'before', 'a'),
sTestValidLocation('<p><a href="a"><img src="a"></a></p>', [0, 0], 0, 'start', 'a'),
sTestValidLocation('<p><a href="a"><img src="a"></a></p>', [0, 0], 1, 'end', 'a'),
sTestValidLocation('<p><a href="a">a</a><img src="a"></p>', [0], 1, 'after', 'a'),
sTestValidLocation('<p><a href="a">a</a></p><p><a href="b">b</a></p>', [0], 1, 'after', 'a'),
sTestValidLocation('<p><a href="a">a</a></p><p><a href="b">b</a></p>', [1], 0, 'before', 'p:nth-child(2) a')
]));
var sTestValidZwspLocations = Logger.t('sTestValidZwspLocations', GeneralSteps.sequence([
sTestValidLocation('<p>' + ZWSP + '<a href="a">a</a></p>', [0, 0], 0, 'before', 'a'),
sTestValidLocation('<p><a href="a">' + ZWSP + 'a</a></p>', [0, 0, 0], 1, 'start', 'a'),
sTestValidLocation('<p><a href="a">a' + ZWSP + '</a></p>', [0, 0, 0], 1, 'end', 'a'),
sTestValidLocation('<p><a href="a">a</a>' + ZWSP + '</p>', [0, 1], 1, 'after', 'a')
]));
var sTestInvalidLocations = Logger.t('sTestInvalidLocations', GeneralSteps.sequence([
sTestInvalidLocation('<p>a</p>', [0, 0], 0),
sTestInvalidLocation('<p><b>a</b></p>', [0], 0),
sTestInvalidLocation('<p><b>a</b></p>', [0], 1),
sTestInvalidLocation('<p>a<a href="a">a</a>b</p>', [0, 0], 0),
sTestInvalidLocation('<p>a<a href="a">a</a>b</p>', [0, 2], 1),
sTestInvalidLocation('<p><img src="a"><a href="a">a</a></p>', [0], 0),
sTestInvalidLocation('<p><a href="a">a</a><img src="a"></p>', [0], 2),
sTestInvalidLocation('<p><a href="a"><img src="a"><img src="a"></a><img src="a"></p>', [0, 0], 1),
sTestInvalidLocation('<p dir="rtl"><a href="a">a</a></p>', [0, 0, 0], 0),
sTestInvalidLocation('<p><a href="a">\u05D4</a></p>', [0, 0, 0], 0)
]));
var sTestPrevLocations = Logger.t('sTestPrevLocations', GeneralSteps.sequence([
sTestPrevLocation('<p><a href="a">a</a>b</p>', [0, 1], 1, 'after', 'a'),
sTestPrevLocation('<p><a href="a">a</a></p>', [0], 1, 'end', 'a'),
sTestPrevLocation('<p><a href="a">a</a></p>', [0, 0, 0], 1, 'start', 'a'),
sTestPrevLocation('<p><a href="a">a</a></p>', [0, 0, 0], 0, 'before', 'a'),
sTestPrevLocation('<p><a href="a"><img src="about:blank"></a></p>', [0], 1, 'end', 'a'),
sTestPrevLocation('<p><a href="a"><img src="about:blank"></a></p>', [0, 0], 1, 'start', 'a'),
sTestPrevLocation('<p><a href="a"><img src="about:blank"></a></p>', [0, 0], 0, 'before', 'a')
]));
var sTestPrevLocationsBetweenInlines = Logger.t('sTestPrevLocationsBetweenInlines', GeneralSteps.sequence([
sTestPrevLocation('<p><a href="a">a</a><a href="b">b</a></p>', [0, 1, 0], 0, 'before', 'a:nth-child(2)')
]));
var sTestPrevLocationsBetweenBlocks = Logger.t('sTestPrevLocationsBetweenBlocks', GeneralSteps.sequence([
sTestPrevLocation('<p><a href="a">a</a></p><p><a href="b">b</a></p>', [1], 0, 'end', 'p:nth-child(1) a'),
sTestPrevLocation('<p><a href="a">a</a></p><p><a href="b">b</a></p>', [1, 0, 0], 0, 'before', 'p:nth-child(2) a'),
sTestPrevLocation('<p><a href="a">a</a>b</p><p><a href="c">c</a></p>', [1, 0, 0], 0, 'before', 'p:nth-child(2) a'),
sTestPrevLocation('<p><a href="a">a</a><br /></p><p><a href="c">c</a></p>', [1], 0, 'after', 'p:nth-child(1) a'),
sTestPrevLocationInvalid('<p><a href="a">a</a></p><p>b<a href="c">c</a></p>', [1, 0], 1),
sTestPrevLocationInvalid('<p><a href="a">a</a>b</p><p><a href="c">c</a></p>', [1], 0)
]));
var sTestPrevZwspLocations = Logger.t('sTestPrevLocations', GeneralSteps.sequence([
sTestPrevLocation('<p><a href="a">a</a>' + ZWSP + 'b</p>', [0, 1], 2, 'after', 'a'),
sTestPrevLocation('<p><a href="a">a</a>' + ZWSP + '</p>', [0, 1], 1, 'end', 'a'),
sTestPrevLocation('<p><a href="a">a' + ZWSP + '</a></p>', [0, 0, 0], 1, 'start', 'a'),
sTestPrevLocation('<p><a href="a">' + ZWSP + 'a</a></p>', [0, 0, 0], 1, 'before', 'a')
]));
var sTestNextLocations = Logger.t('sTestNextLocations', GeneralSteps.sequence([
sTestNextLocation('<p>a<a href="a">b</a></p>', [0, 0], 0, 'before', 'a'),
sTestNextLocation('<p><a href="a">a</a></p>', [0], 0, 'start', 'a'),
sTestNextLocation('<p><a href="a">a</a></p>', [0, 0, 0], 0, 'end', 'a'),
sTestNextLocation('<p><a href="a">a</a></p>', [0, 0, 0], 1, 'after', 'a'),
sTestNextLocation('<p><a href="a"><img src="about:blank"></a></p>', [0], 0, 'start', 'a'),
sTestNextLocation('<p><a href="a"><img src="about:blank"></a></p>', [0, 0], 0, 'end', 'a'),
sTestNextLocation('<p><a href="a"><img src="about:blank"></a></p>', [0, 0], 1, 'after', 'a')
]));
var sTestNextLocationsBetweenInlines = Logger.t('sTestNextLocationsBetweenInlines', GeneralSteps.sequence([
sTestNextLocation('<p><a href="a">a</a><a href="a">b</a></p>', [0, 0, 0], 1, 'after', 'a:nth-child(1)')
]));
var sTestNextLocationsBetweenBlocks = Logger.t('sTestNextLocationsBetweenBlocks', GeneralSteps.sequence([
sTestNextLocation('<p><a href="a">a</a></p><p><a href="b">b</a></p>', [0], 1, 'start', 'p:nth-child(2) a'),
sTestNextLocation('<p><a href="a">a</a></p><p><a href="b">b</a></p>', [0, 0, 0], 1, 'after', 'p:nth-child(1) a'),
sTestNextLocationInvalid('<p><a href="a">a</a>b</p><p><a href="c">c</a></p>', [0, 1], 0),
sTestNextLocationInvalid('<p><a href="a">a</a></p><p>b<a href="c">c</a></p>', [0], 1)
]));
var sTestNextZwspLocations = Logger.t('sTestNextZwspLocations', GeneralSteps.sequence([
sTestNextLocation('<p>a' + ZWSP + '<a href="a">b</a></p>', [0, 0], 0, 'before', 'a'),
sTestNextLocation('<p>' + ZWSP + '<a href="a">a</a></p>', [0], 0, 'start', 'a'),
sTestNextLocation('<p><a href="a">' + ZWSP + 'a</a></p>', [0, 0, 0], 1, 'end', 'a'),
sTestNextLocation('<p><a href="a">a' + ZWSP + '</a></p>', [0, 0, 0], 1, 'after', 'a')
]));
viewBlock.attach();
Pipeline.async({}, [
sTestValidLocations,
sTestValidZwspLocations,
sTestInvalidLocations,
sTestPrevLocations,
sTestPrevLocationsBetweenInlines,
sTestPrevLocationsBetweenBlocks,
sTestPrevZwspLocations,
sTestNextLocations,
sTestNextLocationsBetweenInlines,
sTestNextLocationsBetweenBlocks,
sTestNextZwspLocations
], function () {
viewBlock.detach();
success();
}, failure);
}
); | MediehusetTek/tinymce | src/core/src/test/js/browser/keyboard/BoundaryLocationTest.js | JavaScript | lgpl-2.1 | 11,571 |
var searchData=
[
['own_5faddress',['own_address',['../classRiots__BabyRadio.html#a0e4c8a64bf259ce380431879871bf872',1,'Riots_BabyRadio::own_address()'],['../classRiots__MamaRadio.html#ae1e3a65b5c9768df2a514fb984fe6a8c',1,'Riots_MamaRadio::own_address()']]],
['own_5fconfig_5fmessage',['own_config_message',['../classRiots__MamaRadio.html#a513d856339fc044e1ba21da1227be711',1,'Riots_MamaRadio']]],
['own_5fring_5fevent_5fongoing',['own_ring_event_ongoing',['../classRiots__BabyRadio.html#a20d65ad231afd698d7fd9440cf89d84b',1,'Riots_BabyRadio']]]
];
| myriots/riots-libraries | doc/search/variables_b.js | JavaScript | lgpl-2.1 | 555 |
br.test.GwtTestRunner.initialize();
describe("Dashboard App", function() {
fixtures("brjs.dashboard.app.testing.DashboardFixtureFactory");
it("displays the screens that are visible", function() {
given("dash.loaded = true");
and("dash.model.appsScreen.visible = true");
and("dash.model.appDetailScreen.visible = true");
and("dash.model.releaseNoteScreen.visible = true");
then("dash.view.(#appsScreen).isVisible = true");
and("dash.view.(#appDetailScreen).isVisible = true");
and("dash.view.(#releaseNoteScreen).isVisible = true");
});
it("hides the screens that are not visible", function() {
given("dash.loaded = true");
and("dash.model.appsScreen.visible = false");
and("dash.model.appDetailScreen.visible = false");
and("dash.model.releaseNoteScreen.visible = false");
then("dash.view.(#appsScreen).isVisible = false");
and("dash.view.(#appDetailScreen).isVisible = false");
and("dash.view.(#releaseNoteScreen).isVisible = false");
});
});
| andreoid/testing | brjs-sdk/workspace/sdk/system-applications/dashboard/dashboard-bladeset/blades/app/tests/test-acceptance/js-test-driver/tests/bindings-app.js | JavaScript | lgpl-3.0 | 992 |
var searchData=
[
['keep_5fhistory_2ecpp',['keep_history.cpp',['../keep__history_8cpp.html',1,'']]],
['keep_5fhistory_5fpass_2ecpp',['keep_history_pass.cpp',['../keep__history__pass_8cpp.html',1,'']]],
['keep_5fhistory_5fpass_2eh',['keep_history_pass.h',['../keep__history__pass_8h.html',1,'']]]
];
| bduvenhage/flitr | Doxygen/html/search/files_6b.js | JavaScript | lgpl-3.0 | 311 |
/**
* 基于jquery.select2扩展的select插件,基本使用请参考select2相关文档
* 默认是多选模式,并提供了input模式下的初始化方法,对应的数据格式是{ id: 1, text: "Hello" }
* 这里的参数只对扩展的部分作介绍
* filter、includes、excludes、query四个参数是互斥的,理论只能有其一个参数
* @method ibosSelect
* @param option.filter
* @param {Function} option.filter 用于过滤源数据的函数
* @param {Array} option.includes 用于过滤源数据的数据,有效数据的id组
* @param {Array} option.excludes 用于过滤源数据的数据,无效数据的id组
* @param {Boolean} option.pinyin 启用拼音搜索,需要pinyinEngine组件
* @return {jQuery}
*/
$.fn.ibosSelect = (function(){
var _process = function(datum, collection, filter){
var group, attr;
datum = datum[0];
if (datum.children) {
group = {};
for (attr in datum) {
if (datum.hasOwnProperty(attr)) group[attr] = datum[attr];
}
group.children = [];
$(datum.children).each2(function(i, childDatum) {
_process(childDatum, group.children, filter);
});
if (group.children.length) {
collection.push(group);
}
} else {
if(filter && !filter(datum)) {
return false;
}
collection.push(datum);
}
}
// 使用带有filter过滤源数据的query函数,其实质就是在query函数执行之前,用filter函数先过滤一次数据
var _queryWithFilter = function(query, filter){
var t = query.term, filtered = { results: [] }, data = [];
$(this.data).each2(function(i, datum) {
_process(datum, data, filter);
});
if (t === "") {
query.callback({ results: data });
return;
}
$(data).each2(function(i, datum) {
_process(datum, filtered.results, function(d){
return query.matcher(t, d.text + "");
})
});
query.callback(filtered);
}
// 根据ID从data数组中获取对应的文本, 主要用于val设置
var _getTextById = function(id, data){
// debugger;
var ret;
for(var i = 0; i < data.length; i++){
if(data[i].children){
ret = _getTextById(id, data[i].children);
if(typeof ret !== "undefined"){
break;
}
} else {
if(data[i].id + "" === id) {
ret = data[i].text;
break;
}
}
}
return ret;
}
var defaults = {
multiple: true,
pinyin: true,
formatResultCssClass: function(data){
return data.cls;
},
formatNoMatches: function(){ return U.lang("S2.NO_MATCHES"); },
formatSelectionTooBig: function (limit) { return U.lang("S2.SELECTION_TO_BIG", { count: limit}); },
formatSearching: function () { return U.lang("S2.SEARCHING"); },
formatInputTooShort: function (input, min) { return U.lang("S2.INPUT_TO_SHORT", { count: min - input.length}); },
formatLoadMore: function (pageNumber) { return U.lang("S2.LOADING_MORE"); },
initSelection: function(elem, callback){
var ins = elem.data("select2"),
data = ins.opts.data,
results;
if(ins.opts.multiple) {
results = [];
$.each(elem.val().split(','), function(index, val){
results.push({id: val, text: _getTextById(val, data)});
})
} else {
results = {
id: elem.val(),
text: _getTextById(elem.val(), data)
}
}
callback(results);
}
}
var select2 = function(option){
if(typeof option !== "string") {
option = $.extend({}, defaults, option);
// 注意: filter | query | includes | excludes 四个属性是互斥的
// filter基于query, 而includes、excludes基于filter
// 优先度 includes > excludes > filter > query
// includes是一个数组,指定源数据中有效数据的ID值,将过滤ID不在此数组中的数据
if(option.includes && $.isArray(option.includes)){
option.filter = function(datum){
return $.inArray(datum.id, option.includes) !== -1;
}
// includes是一个数组,指定源数据中无效数据的ID值,将过滤ID在此数组中的数据
} else if(option.excludes && $.isArray(option.excludes)) {
option.filter = function(datum){
return $.inArray(datum.id, option.excludes) === -1;
}
}
// 当有filter属性时,将使用自定义的query方法替代原来的query方法,filter用于从源数据层面上过滤不需要出现的数据
if(option.filter){
option.query = function(query) {
_queryWithFilter(query, option.filter);
}
}
// 使用pinyin搜索引擎
if(option.pinyin) {
var _customMatcher = option.matcher;
option.matcher = function(term){
if(term === ""){
return true;
}
return Ibos.matchSpell.apply(this, arguments) &&
(_customMatcher ? _customMatcher.apply(this, arguments) : true);
}
}
// 使用 select 元素时,要去掉一部分默认项
if($(this).is("select")) {
delete option.multiple;
delete option.initSelection;
}
return $.fn.select2.call(this, option)
}
return $.fn.select2.apply(this, arguments)
}
return select2;
})(); | SeekArt/IBOS | static/js/src/base/ibos.select2.js | JavaScript | lgpl-3.0 | 5,038 |
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
function Square(props) {
return (
<button className="square" onClick={props.onClick}>
{props.value}
</button>
);
}
class Board extends React.Component {
renderSquare(i) {
return (
<Square
value={this.props.squares[i]}
onClick={() => this.props.onClick(i)}
/>
);
}
render() {
return (
<div>
<div className="board-row">
{this.renderSquare(0)}
{this.renderSquare(1)}
{this.renderSquare(2)}
</div>
<div className="board-row">
{this.renderSquare(3)}
{this.renderSquare(4)}
{this.renderSquare(5)}
</div>
<div className="board-row">
{this.renderSquare(6)}
{this.renderSquare(7)}
{this.renderSquare(8)}
</div>
</div>
);
}
}
class Game extends React.Component {
constructor(props) {
super(props);
this.state = {
history: [{
squares: Array(9).fill(null)
}],
xIsNext: true
};
}
handleClick(i) {
const history = this.state.history;
const current = history[history.length - 1];
const squares = current.squares.slice();
if (calculateWinner(squares) || squares[i]) {
return;
}
squares[i] = this.state.xIsNext ? 'X' : 'O';
this.setState({
history: history.concat([{
squares: squares
}]),
xIsNext: !this.state.xIsNext,
});
}
render() {
const history = this.state.history;
const current = history[history.length - 1];
const winner = calculateWinner(current.squares);
let status;
if (winner) {
status = 'Winner: ' + winner;
} else {
status = 'Next player: ' + (this.state.xIsNext ? 'X' : 'O');
}
return (
<div className="game">
<div className="game-board">
<Board
squares={current.squares}
onClick={(i) => this.handleClick(i)}
/>
</div>
<div className="game-info">
<div>{status}</div>
<ol>{/* TODO */}</ol>
</div>
</div>
);
}
}
// ========================================
ReactDOM.render(
<Game />,
document.getElementById('root')
);
function calculateWinner(squares) {
const lines = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
[0, 4, 8],
[2, 4, 6],
];
for (let i = 0; i < lines.length; i++) {
const [a, b, c] = lines[i];
if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {
return squares[a];
}
}
return null;
}
| xiaoxiaoyao/MyApp | HTML/前端/my-react-app-spring-boot-yao/src/index.js | JavaScript | unlicense | 2,690 |
require('babel-core/register')({plugins: ['babel-plugin-rewire']})
import packageJson from '../package.json'
import conformToMask from '../src/conformToMask'
import {placeholderChar} from '../src/constants'
const createTextMaskInputElement = (isVerify()) ?
require(`../${packageJson.main}`).createTextMaskInputElement :
require('../src/createTextMaskInputElement.js').default
describe('createTextMaskInputElement', () => {
let inputElement
beforeEach(() => {
inputElement = document.createElement('input')
})
it('takes an inputElement and other Text Mask parameters and returns an object which ' +
'allows updating and controlling the masking of the input element', () => {
const maskedInputElementControl = createTextMaskInputElement({
inputElement,
mask: ['(', /\d/, /\d/, /\d/, ')', ' ', /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/]
})
expect(maskedInputElementControl.update).to.be.a('function')
})
it('works with mask functions', () => {
const mask = () => [/\d/, /\d/, /\d/, /\d/]
expect(() => createTextMaskInputElement({inputElement, mask})).to.not.throw()
})
it('displays mask when showMask is true', () => {
const textMaskControl = createTextMaskInputElement({
showMask: true,
inputElement,
mask: ['(', /\d/, /\d/, /\d/, ')', ' ', /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/]
})
textMaskControl.update()
expect(inputElement.value).to.equal('(___) ___-____')
})
it('does not display mask when showMask is false', () => {
const textMaskControl = createTextMaskInputElement({
showMask: false,
inputElement,
mask: ['(', /\d/, /\d/, /\d/, ')', ' ', /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/]
})
textMaskControl.update()
expect(inputElement.value).to.equal('')
})
describe('`update` method', () => {
it('conforms whatever value is in the input element to a mask', () => {
const mask = ['(', /\d/, /\d/, /\d/, ')', ' ', /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/]
const textMaskControl = createTextMaskInputElement({inputElement, mask})
inputElement.value = '2'
textMaskControl.update()
expect(inputElement.value).to.equal('(2__) ___-____')
})
it('works after multiple calls', () => {
const mask = ['+', '1', ' ', '(', /\d/, /\d/, /\d/, ')', ' ', /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/]
const textMaskControl = createTextMaskInputElement({inputElement, mask})
inputElement.value = '2'
textMaskControl.update()
expect(inputElement.value).to.equal('+1 (2__) ___-____')
inputElement.value = '+1 (23__) ___-____'
inputElement.selectionStart = 6
textMaskControl.update()
expect(inputElement.value).to.equal('+1 (23_) ___-____')
inputElement.value = '+1 (2_) ___-____'
inputElement.selectionStart = 5
textMaskControl.update()
expect(inputElement.value).to.equal('+1 (2__) ___-____')
inputElement.value = '+1 (__) ___-____'
inputElement.selectionStart = 4
textMaskControl.update()
expect(inputElement.value).to.equal('')
})
it('accepts a string to conform and overrides whatever value is in the input element', () => {
const mask = ['(', /\d/, /\d/, /\d/, ')', ' ', /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/]
const textMaskControl = createTextMaskInputElement({inputElement, mask})
inputElement.value = '2'
textMaskControl.update('123')
expect(inputElement.value).to.equal('(123) ___-____')
})
it('accepts an empty string and overrides whatever value is in the input element', () => {
const mask = ['(', /\d/, /\d/, /\d/, ')', ' ', /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/]
const textMaskControl = createTextMaskInputElement({inputElement, mask})
textMaskControl.update(123)
expect(inputElement.value).to.equal('(123) ___-____')
textMaskControl.update('')
expect(inputElement.value).to.equal('')
})
it('accepts an empty string after reinitializing text mask', () => {
const mask = ['(', /\d/, /\d/, /\d/, ')', ' ', /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/]
let textMaskControl = createTextMaskInputElement({inputElement, mask})
textMaskControl.update(123)
expect(inputElement.value).to.equal('(123) ___-____')
//reset text mask
textMaskControl = createTextMaskInputElement({inputElement, mask})
// now clear the value
textMaskControl.update('')
expect(inputElement.value).to.equal('')
})
if (!isVerify()) {
it('does not conform given parameter if it is the same as the previousConformedValue', () => {
const conformToMaskSpy = sinon.spy(conformToMask)
const mask = ['(', /\d/, /\d/, /\d/, ')', ' ', /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/]
const textMaskControl = createTextMaskInputElement({inputElement, mask})
createTextMaskInputElement.__Rewire__('conformToMask', conformToMaskSpy)
inputElement.value = '2'
textMaskControl.update()
expect(inputElement.value).to.equal('(2__) ___-____')
expect(conformToMaskSpy.callCount).to.equal(1)
textMaskControl.update('(2__) ___-____')
expect(conformToMaskSpy.callCount).to.equal(1)
createTextMaskInputElement.__ResetDependency__('conformToMask')
})
}
it('works with a string', () => {
const mask = ['(', /\d/, /\d/, /\d/, ')', ' ', /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/]
const textMaskControl = createTextMaskInputElement({inputElement, mask})
textMaskControl.update('2')
expect(inputElement.value).to.equal('(2__) ___-____')
})
it('works with a number by coercing it into a string', () => {
const mask = ['(', /\d/, /\d/, /\d/, ')', ' ', /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/]
const textMaskControl = createTextMaskInputElement({inputElement, mask})
textMaskControl.update(2)
expect(inputElement.value).to.equal('(2__) ___-____')
})
it('works with `undefined` and `null` by treating them as empty strings', () => {
const mask = ['(', /\d/, /\d/, /\d/, ')', ' ', /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/]
const textMaskControl = createTextMaskInputElement({inputElement, mask})
textMaskControl.update(undefined)
expect(inputElement.value).to.equal('')
textMaskControl.update(null)
expect(inputElement.value).to.equal('')
})
it('throws if given a value that it cannot work with', () => {
const mask = ['(', /\d/, /\d/, /\d/, ')', ' ', /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/]
const textMaskControl = createTextMaskInputElement({inputElement, mask})
expect(() => textMaskControl.update({})).to.throw()
expect(() => textMaskControl.update(() => 'howdy')).to.throw()
expect(() => textMaskControl.update([])).to.throw()
})
it('adjusts the caret position', () => {
const mask = ['(', /\d/, /\d/, /\d/, ')', ' ', /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/]
const textMaskControl = createTextMaskInputElement({inputElement, mask, placeholderChar})
inputElement.focus()
inputElement.value = '2'
inputElement.selectionStart = 1
textMaskControl.update()
expect(inputElement.selectionStart).to.equal(2)
})
it('does not adjust the caret position if the input element is not focused', () => {
const mask = ['(', /\d/, /\d/, /\d/, ')', ' ', /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/]
const textMaskControl = createTextMaskInputElement({inputElement, mask})
inputElement.value = '2'
inputElement.selectionStart = 1
textMaskControl.update()
expect(inputElement.selectionStart).to.equal(0)
})
it('calls the mask function before every update', () => {
const maskSpy = sinon.spy(() => [/\d/, /\d/, /\d/, /\d/])
const textMaskControl = createTextMaskInputElement({inputElement, mask: maskSpy})
inputElement.value = '2'
textMaskControl.update()
expect(inputElement.value).to.equal('2___')
inputElement.value = '24'
textMaskControl.update()
expect(inputElement.value).to.equal('24__')
expect(maskSpy.callCount).to.equal(2)
})
it('can be disabled with `false` mask', () => {
const mask = false
const textMaskControl = createTextMaskInputElement({inputElement, mask})
inputElement.value = 'a'
textMaskControl.update()
expect(inputElement.value).to.equal('a')
})
it('can be disabled by returning `false` from mask function', () => {
const mask = () => false
const textMaskControl = createTextMaskInputElement({inputElement, mask})
inputElement.value = 'a'
textMaskControl.update()
expect(inputElement.value).to.equal('a')
})
it('can pass in a config object to the update method', () => {
const mask = ['(', /\d/, /\d/, /\d/, ')', ' ', /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/]
const textMaskControl = createTextMaskInputElement()
let inputElement = {value: '2'}
textMaskControl.update(inputElement.value, {inputElement, mask})
expect(inputElement.value).to.equal('(2__) ___-____')
})
it('can change the mask passed to the update method', () => {
const textMaskControl = createTextMaskInputElement()
let inputElement = {value: '2'}
textMaskControl.update(inputElement.value, {
inputElement,
mask: ['(', /\d/, /\d/, /\d/, ')', ' ', /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/]
})
expect(inputElement.value).to.equal('(2__) ___-____')
textMaskControl.update('2', {
inputElement,
mask: ['+', '1', ' ', '(', /\d/, /\d/, /\d/, ')', ' ', /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/]
})
expect(inputElement.value).to.equal('+1 (2__) ___-____')
})
it('can change the guide passed to the update method', () => {
const mask = ['(', /\d/, /\d/, /\d/, ')', ' ', /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/]
const textMaskControl = createTextMaskInputElement()
let inputElement = {value: '2'}
textMaskControl.update(inputElement.value, {inputElement, mask, guide: true})
expect(inputElement.value).to.equal('(2__) ___-____')
textMaskControl.update('2', {inputElement, mask, guide: false})
expect(inputElement.value).to.equal('(2')
})
it('can change the placeholderChar passed to the update method', () => {
const mask = ['(', /\d/, /\d/, /\d/, ')', ' ', /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/]
const textMaskControl = createTextMaskInputElement()
let inputElement = {value: '2'}
textMaskControl.update(inputElement.value, {inputElement, mask, placeholderChar: '_'})
expect(inputElement.value).to.equal('(2__) ___-____')
textMaskControl.update('2', {inputElement, mask, placeholderChar: '*'})
expect(inputElement.value).to.equal('(2**) ***-****')
})
it('can change the inputElement passed to the update method', () => {
const mask = ['(', /\d/, /\d/, /\d/, ')', ' ', /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/]
const textMaskControl = createTextMaskInputElement()
let firstInputElement = {value: '1'}
let secondInputElement = {value: '2'}
textMaskControl.update('1', {inputElement: firstInputElement, mask})
expect(firstInputElement.value).to.equal('(1__) ___-____')
textMaskControl.update('2', {inputElement: secondInputElement, mask})
expect(secondInputElement.value).to.equal('(2__) ___-____')
})
it('can change the config passed to createTextMaskInputElement', () => {
const config = {
inputElement,
mask: ['(', /\d/, /\d/, /\d/, ')', ' ', /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/],
guide: true,
placeholderChar: '_'
}
const textMaskControl = createTextMaskInputElement(config)
inputElement.value = '2'
textMaskControl.update()
expect(inputElement.value).to.equal('(2__) ___-____')
// change the mask
config.mask = ['+', '1', ' ', '(', /\d/, /\d/, /\d/, ')', ' ', /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/]
inputElement.value = '23' // <- you have to change the value
textMaskControl.update()
expect(inputElement.value).to.equal('+1 (23_) ___-____')
// change the placeholderChar
config.placeholderChar = '*'
inputElement.value = '4' // <- you have to change the value
textMaskControl.update()
expect(inputElement.value).to.equal('+1 (4**) ***-****')
// change the guide
config.guide = false
inputElement.value = '45' // <- you have to change the value
textMaskControl.update()
expect(inputElement.value).to.equal('+1 (45')
})
it('can override the config passed to createTextMaskInputElement', () => {
const textMaskControl = createTextMaskInputElement({
inputElement,
mask: ['(', /\d/, /\d/, /\d/, ')', ' ', /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/],
guide: true
})
inputElement.value = '2'
textMaskControl.update()
expect(inputElement.value).to.equal('(2__) ___-____')
// pass in a config to the update method
textMaskControl.update('23', {
inputElement,
mask: ['+', '1', ' ', '(', /\d/, /\d/, /\d/, ')', ' ', /\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/],
guide: false
})
expect(inputElement.value).to.equal('+1 (23')
// use original config again
inputElement.value = '234' // <- you have to change the value
textMaskControl.update()
expect(inputElement.value).to.equal('(234) ___-____')
})
})
})
| CrisDan1905/text-mask | core/test/createTextMaskInputElement.spec.js | JavaScript | unlicense | 13,794 |
GoogleElectionMap.shapeReady({name:"28_05",type:"state",state:"28_05",bounds:[],centroid:[],shapes:[
{points:[
{x:32.8810559124534,y: 24.5253494052583}
,
{x:32.8804366855404,y: 24.5250018993236}
,
{x:32.8804349320052,y: 24.5250021192127}
,
{x:32.8800699675051,y: 24.52504787811}
,
{x:32.880107603168,y: 24.5253602242076}
,
{x:32.8802839839792,y: 24.52603126374}
,
{x:32.8806752087983,y: 24.5268181464166}
,
{x:32.8813572439035,y: 24.5276168223645}
,
{x:32.8819505502392,y: 24.5286583392856}
,
{x:32.8825307177406,y: 24.5302435034032}
,
{x:32.882934635026,y: 24.5310072542635}
,
{x:32.8834485851789,y: 24.5330479929378}
,
{x:32.8837280117142,y: 24.5339626803751}
,
{x:32.884343892289,y: 24.534985099402}
,
{x:32.8849707220765,y: 24.5357073551443}
,
{x:32.8857139839758,y: 24.5365877815531}
,
{x:32.8867322124162,y: 24.5378013619691}
,
{x:32.8876882846372,y: 24.5390216560881}
,
{x:32.8891919119942,y: 24.540785084219}
,
{x:32.8898616158364,y: 24.5413523715326}
,
{x:32.890834703648,y: 24.5420471161423}
,
{x:32.892022806308,y: 24.5427073069361}
,
{x:32.8929960248504,y: 24.543274797266}
,
{x:32.8936151079581,y: 24.5439230021262}
,
{x:32.8939563239076,y: 24.5441777223781}
,
{x:32.8941969226219,y: 24.5443351788832}
,
{x:32.8942217362609,y: 24.5443514180803}
,
{x:32.8943103917561,y: 24.5441895397177}
,
{x:32.8939318918876,y: 24.5431597894563}
,
{x:32.8935156289255,y: 24.5419333682628}
,
{x:32.8928971968486,y: 24.5405332931207}
,
{x:32.8917605486434,y: 24.5388783635996}
,
{x:32.8902124631775,y: 24.5361164927854}
,
{x:32.888306467008,y: 24.5329536141396}
,
{x:32.8876782300639,y: 24.5314852017043}
,
{x:32.8871284082075,y: 24.5298608543163}
,
{x:32.8865281254967,y: 24.5282916909969}
,
{x:32.8855427814326,y: 24.5272845980552}
,
{x:32.8843422710402,y: 24.5265318135685}
,
{x:32.8843325732352,y: 24.5265286685573}
,
{x:32.8830908791957,y: 24.5261259978265}
,
{x:32.881890005934,y: 24.525789614878}
,
{x:32.8818650371091,y: 24.5257764371665}
,
{x:32.8810559124534,y: 24.5253494052583}
]}
,
{points:[
{x:32.9019960722517,y: 24.546197781935}
,
{x:32.9010302932533,y: 24.5450044439886}
,
{x:32.9010174381379,y: 24.545007502719}
,
{x:32.9007640795607,y: 24.5450677818085}
,
{x:32.9005131225026,y: 24.5451274885421}
,
{x:32.9003777640669,y: 24.5457237535524}
,
{x:32.9002865578843,y: 24.5473482461574}
,
{x:32.9004882152,y: 24.5482120654834}
,
{x:32.9003525941626,y: 24.5491373531242}
,
{x:32.900832773743,y: 24.55037862879}
,
{x:32.9018562389718,y: 24.5516524640258}
,
{x:32.9023628597906,y: 24.552782200296}
,
{x:32.9021249492644,y: 24.5534958706051}
,
{x:32.9022027836992,y: 24.5546847079245}
,
{x:32.9023690012363,y: 24.5560566043976}
,
{x:32.9028188794294,y: 24.5584934715349}
,
{x:32.9029844838607,y: 24.5607298870529}
,
{x:32.9032690872615,y: 24.5622439360486}
,
{x:32.9035020034828,y: 24.5643563747934}
,
{x:32.9037861391809,y: 24.5666009905706}
,
{x:32.9050066369447,y: 24.5719657076965}
,
{x:32.9052751701374,y: 24.5736726816184}
,
{x:32.9057684355406,y: 24.5755648725823}
,
{x:32.9061501491834,y: 24.5763054129537}
,
{x:32.9068912719161,y: 24.5775602749211}
,
{x:32.9071826506696,y: 24.5788354173812}
,
{x:32.9074633948669,y: 24.5793008493204}
,
{x:32.9078171918728,y: 24.5798100253351}
,
{x:32.9084907789616,y: 24.5812139252027}
,
{x:32.9090556117857,y: 24.5819898205123}
,
{x:32.9090636373088,y: 24.5820008439576}
,
{x:32.9092325012938,y: 24.5820241121723}
,
{x:32.9094009189669,y: 24.5820473185113}
,
{x:32.9096709844482,y: 24.5817544472809}
,
{x:32.909941684888,y: 24.5805824705258}
,
{x:32.9102296567228,y: 24.5788398566416}
,
{x:32.9103986387366,y: 24.5783849828288}
,
{x:32.9104974920394,y: 24.5767592356871}
,
{x:32.9105124195482,y: 24.5765137378363}
,
{x:32.9108056159214,y: 24.5753006450003}
,
{x:32.9102678229386,y: 24.5726887078502}
,
{x:32.9104706554834,y: 24.5720513487502}
,
{x:32.9103591291708,y: 24.5707968848439}
,
{x:32.9091798931689,y: 24.5670953383371}
,
{x:32.9087759661133,y: 24.5655306319631}
,
{x:32.9086508606572,y: 24.5642050621524}
,
{x:32.9078914454148,y: 24.5627695300111}
,
{x:32.9076658286507,y: 24.5618722099146}
,
{x:32.9077735243321,y: 24.5588879375975}
,
{x:32.907774932616,y: 24.5588497040426}
,
{x:32.9073701959783,y: 24.5556912390294}
,
{x:32.9072276733165,y: 24.5544241590121}
,
{x:32.906409261338,y: 24.5532986913824}
,
{x:32.9056973049112,y: 24.5517939294792}
,
{x:32.9049817259066,y: 24.5509504330437}
,
{x:32.9049658377677,y: 24.5509316956826}
,
{x:32.90381474316,y: 24.5492835424285}
,
{x:32.9037636822701,y: 24.5492027419115}
,
{x:32.9030737275812,y: 24.5481109239315}
,
{x:32.9019960722517,y: 24.546197781935}
]}
,
{points:[
{x:32.9068658186117,y: 24.5915723876647}
,
{x:32.9066878311066,y: 24.5915748676675}
,
{x:32.9067076277387,y: 24.5919749787228}
,
{x:32.9070246099623,y: 24.592443930182}
,
{x:32.9076231833487,y: 24.5928835333985}
,
{x:32.9088028737963,y: 24.5933109251489}
,
{x:32.9090074056725,y: 24.5934322206895}
,
{x:32.9090270978349,y: 24.5934438824877}
,
{x:32.9092976821383,y: 24.5934462932366}
,
{x:32.909286973302,y: 24.5931893578706}
,
{x:32.9091097934543,y: 24.5929591806176}
,
{x:32.9086061068361,y: 24.5926094511158}
,
{x:32.9074405092677,y: 24.5920562524253}
,
{x:32.9068790119857,y: 24.5915721962758}
,
{x:32.9068658186117,y: 24.5915723876647}
]}
,
{points:[
{x:32.9306380028288,y: 24.6439357499388}
,
{x:32.9304193835619,y: 24.6415543043021}
,
{x:32.9308201553539,y: 24.6410593727391}
,
{x:32.9305410201023,y: 24.6400288328263}
,
{x:32.9302961762274,y: 24.6395098034689}
,
{x:32.9300974490365,y: 24.6387671899185}
,
{x:32.9300874336471,y: 24.6384384253086}
,
{x:32.9298430339207,y: 24.6372989142743}
,
{x:32.9296187700537,y: 24.6366815740391}
,
{x:32.929292660736,y: 24.6357273153721}
,
{x:32.9289463936502,y: 24.6345297135787}
,
{x:32.9283143679605,y: 24.6333846414923}
,
{x:32.9276090835126,y: 24.6321245908133}
,
{x:32.9259368471765,y: 24.6299243777634}
,
{x:32.9249381092441,y: 24.628550513942}
,
{x:32.9243679699102,y: 24.6275159314012}
,
{x:32.9239819137914,y: 24.6264069339599}
,
{x:32.9237194492429,y: 24.6248475503466}
,
{x:32.9232304161745,y: 24.6244313972004}
,
{x:32.9226807488606,y: 24.6237706813579}
,
{x:32.9219094664714,y: 24.6220371266924}
,
{x:32.9209583026776,y: 24.6194354801501}
,
{x:32.9202098225335,y: 24.6176989185076}
,
{x:32.9196484077822,y: 24.6155277855946}
,
{x:32.9186196956626,y: 24.613296574409}
,
{x:32.9177874586635,y: 24.6120536075743}
,
{x:32.9169938204959,y: 24.6094799128237}
,
{x:32.9161977168247,y: 24.6075728003033}
,
{x:32.9158716227109,y: 24.6060585022178}
,
{x:32.9155042947087,y: 24.605048882695}
,
{x:32.9152185857547,y: 24.6042823155805}
,
{x:32.9149134545365,y: 24.602057702674}
,
{x:32.9145055301289,y: 24.6006555094605}
,
{x:32.9138931797687,y: 24.5992345016333}
,
{x:32.912469444399,y: 24.5990566945658}
,
{x:32.9121294329819,y: 24.5972399297232}
,
{x:32.9118492363033,y: 24.5956865239906}
,
{x:32.9114585710327,y: 24.5953194691625}
,
{x:32.9105310622483,y: 24.5941426406149}
,
{x:32.9094407460489,y: 24.5939341256383}
,
{x:32.9079374522802,y: 24.5932473626289}
,
{x:32.9066457405462,y: 24.5928325034861}
,
{x:32.9060107956899,y: 24.5916107817261}
,
{x:32.9048985872142,y: 24.5910952990972}
,
{x:32.9046749020783,y: 24.589543656946}
,
{x:32.9047226388473,y: 24.5894667537846}
,
{x:32.9046136175776,y: 24.5894867602747}
,
{x:32.9045531817626,y: 24.5883230970128}
,
{x:32.904354674077,y: 24.5872715018379}
,
{x:32.9039262262108,y: 24.5861776988867}
,
{x:32.9034211182531,y: 24.5850978637064}
,
{x:32.9028247295084,y: 24.583120715002}
,
{x:32.9025193327864,y: 24.5815503220875}
,
{x:32.9021368365261,y: 24.5805546797424}
,
{x:32.9018160783231,y: 24.579040352879}
,
{x:32.9016023333368,y: 24.5779186450114}
,
{x:32.9014042324767,y: 24.576404397734}
,
{x:32.901160779702,y: 24.574091002157}
,
{x:32.9003959129671,y: 24.5716522686668}
,
{x:32.9000808960838,y: 24.5709728465639}
,
{x:32.8997346638503,y: 24.5690107188021}
,
{x:32.8996510630001,y: 24.5674002554552}
,
{x:32.8995356436118,y: 24.56571795718}
,
{x:32.8992341125435,y: 24.5625019090756}
,
{x:32.8991040170725,y: 24.5599708549208}
,
{x:32.8989477034196,y: 24.5590748844666}
,
{x:32.8980879321001,y: 24.5575373917488}
,
{x:32.8979337637813,y: 24.5561042766295}
,
{x:32.8975376570664,y: 24.554970632733}
,
{x:32.896736102018,y: 24.5525857967486}
,
{x:32.8958712057812,y: 24.5510907338809}
,
{x:32.894948379246,y: 24.5496231562703}
,
{x:32.8943796417896,y: 24.547913414668}
,
{x:32.8941659601485,y: 24.5468477713103}
,
{x:32.8939212363672,y: 24.5462447535708}
,
{x:32.8933393728601,y: 24.5455854179938}
,
{x:32.8920374332369,y: 24.544603111427}
,
{x:32.8898776653757,y: 24.5431154603853}
,
{x:32.887671719285,y: 24.5419081362463}
,
{x:32.8852323439757,y: 24.5389890291771}
,
{x:32.8834157379391,y: 24.5365649375411}
,
{x:32.8827275622485,y: 24.5354673965301}
,
{x:32.882159612944,y: 24.5344169078237}
,
{x:32.8813308567563,y: 24.5323449731674}
,
{x:32.8809043076298,y: 24.5314279071763}
,
{x:32.8805244747611,y: 24.5297327853161}
,
{x:32.8800349412484,y: 24.5288102153174}
,
{x:32.8789196989165,y: 24.5269400357722}
,
{x:32.8784032313241,y: 24.525718351981}
,
{x:32.8779144990341,y: 24.523998211083}
,
{x:32.8772079782751,y: 24.5221283481906}
,
{x:32.8761208595581,y: 24.5194606056338}
,
{x:32.8755236038326,y: 24.5173415838965}
,
{x:32.8753881295868,y: 24.5165937557813}
,
{x:32.874844274727,y: 24.51559635064}
,
{x:32.8748371177966,y: 24.5155034947354}
,
{x:32.8743083111815,y: 24.5140476528538}
,
{x:32.8742450595108,y: 24.5137386722838}
,
{x:32.8731774306802,y: 24.5138787634109}
,
{x:32.8645361363841,y: 24.5159432258465}
,
{x:32.8652039569641,y: 24.5189366440886}
,
{x:32.8652520261104,y: 24.5190904950891}
,
{x:32.86244624526,y: 24.5168613373775}
,
{x:32.8550215473134,y: 24.5082612011912}
,
{x:32.8473672482674,y: 24.4977405036822}
,
{x:32.839149268727,y: 24.4926116118191}
,
{x:32.8195473431857,y: 24.51359608293}
,
{x:32.819206702427,y: 24.5139593793166}
,
{x:32.7247874545531,y: 24.4984739899919}
,
{x:32.7247343429083,y: 24.4967570827833}
,
{x:32.3053274242314,y: 24.5150151524095}
,
{x:32.3505190734948,y: 24.6001500683935}
,
{x:32.3751072001533,y: 24.6461496615975}
,
{x:32.7461789449408,y: 24.6231108842054}
,
{x:32.7467358579721,y: 24.6194649771254}
,
{x:32.7477559210231,y: 24.6199341877182}
,
{x:32.803738660182,y: 24.6230308346119}
,
{x:32.8701734869393,y: 24.627487662961}
,
{x:32.8967684734596,y: 24.636735017169}
,
{x:32.9086564138478,y: 24.6444041966976}
,
{x:32.9085952015556,y: 24.6446983519101}
,
{x:32.9088839652403,y: 24.6443743822834}
,
{x:32.9137395360047,y: 24.649022571411}
,
{x:32.9145728631378,y: 24.6528254798246}
,
{x:32.9171523484769,y: 24.6557762121668}
,
{x:32.9203176535248,y: 24.6567084526774}
,
{x:32.9225677645859,y: 24.6573297898235}
,
{x:32.9261012000676,y: 24.6570952672514}
,
{x:32.9281613976806,y: 24.6563682843939}
,
{x:32.9283076390063,y: 24.6563166930561}
,
{x:32.9300460768901,y: 24.6557632153275}
,
{x:32.930078176546,y: 24.6543167402235}
,
{x:32.9301291123022,y: 24.6515128973271}
,
{x:32.9302158149965,y: 24.6495805473188}
,
{x:32.9303714586333,y: 24.6486101642897}
,
{x:32.9306624148647,y: 24.647151462599}
,
{x:32.9305883773967,y: 24.6456266408222}
,
{x:32.9306380028288,y: 24.6439357499388}
]}
,
{points:[
{x:32.9301278080931,y: 24.6938136329239}
,
{x:32.9300377541867,y: 24.692156899672}
,
{x:32.9298164212757,y: 24.6882072762278}
,
{x:32.9297121107921,y: 24.6879556459738}
,
{x:32.9294180587474,y: 24.6874089693958}
,
{x:32.9293234043731,y: 24.6868710594824}
,
{x:32.9291527308794,y: 24.6864372171446}
,
{x:32.9291336578181,y: 24.6864421087535}
,
{x:32.9288488400492,y: 24.6865151526406}
,
{x:32.9282123364019,y: 24.6870874210293}
,
{x:32.9278797114991,y: 24.6875991050041}
,
{x:32.9277883747344,y: 24.6905152719209}
,
{x:32.9278152013799,y: 24.6920194262524}
,
{x:32.927028589153,y: 24.6952566372695}
,
{x:32.9266666440096,y: 24.6968847884626}
,
{x:32.9265143277109,y: 24.6975527094942}
,
{x:32.926504784016,y: 24.6978942538227}
,
{x:32.9265046315795,y: 24.697899715071}
,
{x:32.926704004053,y: 24.6979605380045}
,
{x:32.9271507021965,y: 24.6972580566782}
,
{x:32.9278343315725,y: 24.694109085076}
,
{x:32.9284985018112,y: 24.6926815228648}
,
{x:32.9287653309034,y: 24.6924156915316}
,
{x:32.9287763780245,y: 24.6924047858588}
,
{x:32.9289308088402,y: 24.6926317915826}
,
{x:32.9289919637841,y: 24.6935700662466}
,
{x:32.9288974586057,y: 24.6953916422866}
,
{x:32.9286251096799,y: 24.6966266061184}
,
{x:32.9286250464307,y: 24.6966371178005}
,
{x:32.9289288894453,y: 24.6966719617104}
,
{x:32.929251874777,y: 24.6964378806269}
,
{x:32.92999717928,y: 24.695299763335}
,
{x:32.9301308722827,y: 24.694883187372}
,
{x:32.9301278080931,y: 24.6938136329239}
]}
,
{points:[
{x:32.9359532780591,y: 24.7004843037647}
,
{x:32.935801474316,y: 24.7002239811879}
,
{x:32.9357886591425,y: 24.7002336140543}
,
{x:32.9356399790571,y: 24.7003453649678}
,
{x:32.9354024519121,y: 24.7005881698196}
,
{x:32.9353357010653,y: 24.7011260063233}
,
{x:32.9347741497566,y: 24.7033063971709}
,
{x:32.9343155119516,y: 24.7055440351821}
,
{x:32.9345803620299,y: 24.7059679178579}
,
{x:32.9345811868437,y: 24.7059692368051}
,
{x:32.9347699295824,y: 24.7060596578682}
,
{x:32.9347805585575,y: 24.7060647498539}
,
{x:32.9349171023363,y: 24.7061382043761}
,
{x:32.9349419503285,y: 24.7061515716449}
,
{x:32.9352458131697,y: 24.7061864032094}
,
{x:32.935492822874,y: 24.7059783028744}
,
{x:32.9354742240969,y: 24.705206198225}
,
{x:32.9357831757501,y: 24.7034102505833}
,
{x:32.9358305344492,y: 24.7022586155847}
,
{x:32.9359532780591,y: 24.7004843037647}
]}
,
{points:[
{x:32.9283541767998,y: 24.7026626723457}
,
{x:32.928378384393,y: 24.7026489501266}
,
{x:32.9284062204289,y: 24.7027035878679}
,
{x:32.9282958223407,y: 24.7038531559937}
,
{x:32.9283080270123,y: 24.7049034785964}
,
{x:32.9284880185721,y: 24.7058492791804}
,
{x:32.9286242865129,y: 24.7064207296643}
,
{x:32.9289967611297,y: 24.7078603728546}
,
{x:32.9289378378514,y: 24.7090098156704}
,
{x:32.9292171642024,y: 24.7113352688402}
,
{x:32.9292892833277,y: 24.712652920268}
,
{x:32.9292901978439,y: 24.7126704480073}
,
{x:32.929565634163,y: 24.712627201525}
,
{x:32.9299932407263,y: 24.7121936400491}
,
{x:32.9306416779878,y: 24.7112995371153}
,
{x:32.931383176554,y: 24.7104633465581}
,
{x:32.9321539830153,y: 24.7099874462971}
,
{x:32.9325321839224,y: 24.7094872003276}
,
{x:32.9329234934731,y: 24.7089734689073}
,
{x:32.9331881499505,y: 24.7083402172446}
,
{x:32.9331757433794,y: 24.7075512943161}
,
{x:32.9334072504045,y: 24.7064519636027}
,
{x:32.9336400743663,y: 24.7044122997087}
,
{x:32.9336643046898,y: 24.7034673341325}
,
{x:32.9336035780811,y: 24.7022569339499}
,
{x:32.9332700520966,y: 24.7014539007155}
,
{x:32.9331261203406,y: 24.699366404057}
,
{x:32.9331740413896,y: 24.6981072087208}
,
{x:32.9330425298376,y: 24.6962038033159}
,
{x:32.9328816564863,y: 24.6951713762225}
,
{x:32.9324829967971,y: 24.6948762385797}
,
{x:32.9324790448901,y: 24.6948792650447}
,
{x:32.9312403744706,y: 24.6960125789165}
,
{x:32.9299341488992,y: 24.6972734383093}
,
{x:32.9291093763119,y: 24.6979619312135}
,
{x:32.9286008374806,y: 24.699453654554}
,
{x:32.9280629416164,y: 24.7003050834408}
,
{x:32.9270956955957,y: 24.701677422276}
,
{x:32.9265874117721,y: 24.7022552109768}
,
{x:32.9264644956437,y: 24.702357145296}
,
{x:32.9265047402766,y: 24.7036026711182}
,
{x:32.9264001458461,y: 24.7048232863745}
,
{x:32.9265088642728,y: 24.7053790555104}
,
{x:32.9267074269958,y: 24.7065028195954}
,
{x:32.9270006293858,y: 24.7077916825406}
,
{x:32.9272439366982,y: 24.7087696218084}
,
{x:32.9276519341097,y: 24.7094668484348}
,
{x:32.9277083692421,y: 24.7104036495674}
,
{x:32.9277932630238,y: 24.7115708190394}
,
{x:32.9279545812083,y: 24.7125815875923}
,
{x:32.9280991306352,y: 24.7137466496527}
,
{x:32.9282158175012,y: 24.7139847615695}
,
{x:32.9282224468774,y: 24.7139982902214}
,
{x:32.9284218853936,y: 24.7139983856148}
,
{x:32.9284981695762,y: 24.7134605576316}
,
{x:32.9284479032918,y: 24.7123777969722}
,
{x:32.9285239731286,y: 24.7117848949232}
,
{x:32.9283726871458,y: 24.7108541728527}
,
{x:32.9285537833565,y: 24.709780619859}
,
{x:32.9287818872305,y: 24.7094508051419}
,
{x:32.9287442094019,y: 24.7089843854777}
,
{x:32.9285356418066,y: 24.7084489855661}
,
{x:32.9282801103432,y: 24.7075290353529}
,
{x:32.9282376228917,y: 24.7072527274795}
,
{x:32.9280927914129,y: 24.706795613638}
,
{x:32.9277183025548,y: 24.7062421190385}
,
{x:32.9274540212697,y: 24.7054606274182}
,
{x:32.9273503854301,y: 24.7042788102001}
,
{x:32.9274641130945,y: 24.7033961577717}
,
{x:32.9276172633697,y: 24.7029847241512}
,
{x:32.9280420539172,y: 24.7027989864893}
,
{x:32.9283541767998,y: 24.7026626723457}
]}
,
{points:[
{x:32.9208162904096,y: 24.7770510958558}
,
{x:32.9211007337113,y: 24.776762878129}
,
{x:32.9211325033097,y: 24.7764745237737}
,
{x:32.9214090305648,y: 24.7762151374302}
,
{x:32.9218436284335,y: 24.7757179295297}
,
{x:32.9218674454671,y: 24.7755160821795}
,
{x:32.921820257919,y: 24.7752204768541}
,
{x:32.9217019007775,y: 24.7750906467883}
,
{x:32.9213704148419,y: 24.7748669826574}
,
{x:32.9212442093343,y: 24.7746650551688}
,
{x:32.9213313367462,y: 24.7742397542994}
,
{x:32.9214577034765,y: 24.7741893572256}
,
{x:32.92149725726,y: 24.7740740297348}
,
{x:32.9216422933842,y: 24.7740741070174}
,
{x:32.9216551740979,y: 24.7740741138741}
,
{x:32.921734082428,y: 24.7741534575602}
,
{x:32.9219235151274,y: 24.7742616979279}
,
{x:32.92201818807,y: 24.774384305546}
,
{x:32.9220178169056,y: 24.7749682571044}
,
{x:32.9221498100616,y: 24.7750571658027}
,
{x:32.9221677753913,y: 24.775069266495}
,
{x:32.9224019272746,y: 24.7751094803726}
,
{x:32.9224204185784,y: 24.7751126556152}
,
{x:32.9224914224834,y: 24.7752064132983}
,
{x:32.9225814539933,y: 24.7753847876753}
,
{x:32.9225860557514,y: 24.7753939045483}
,
{x:32.9227992193589,y: 24.7754372722542}
,
{x:32.923019404471,y: 24.7755022490613}
,
{x:32.9230439499346,y: 24.7755094924108}
,
{x:32.9230912218574,y: 24.7756753311517}
,
{x:32.9232251463708,y: 24.7761656316033}
,
{x:32.923232784689,y: 24.776576564383}
,
{x:32.9233273705262,y: 24.7768433567888}
,
{x:32.9234225032297,y: 24.7769241024584}
,
{x:32.9234378569525,y: 24.7769371345763}
,
{x:32.9235957739165,y: 24.7769444264127}
,
{x:32.9237616492274,y: 24.7768507922234}
,
{x:32.923832848666,y: 24.7766345505647}
,
{x:32.9239832486008,y: 24.7760290493154}
,
{x:32.9242047915688,y: 24.7752938173891}
,
{x:32.9244817271986,y: 24.774356753472}
,
{x:32.9247346829685,y: 24.7738882799036}
,
{x:32.9253702091745,y: 24.7720204393668}
,
{x:32.9256821486737,y: 24.771578073405}
,
{x:32.9256098051734,y: 24.7712457393048}
,
{x:32.9257282454079,y: 24.7703896022804}
,
{x:32.9259241064736,y: 24.7698263034784}
,
{x:32.9263130772184,y: 24.7690316482456}
,
{x:32.9264592112858,y: 24.7687555662208}
,
{x:32.9266496500376,y: 24.7681170488986}
,
{x:32.9267888897632,y: 24.7669590631455}
,
{x:32.9268849341731,y: 24.7665356932772}
,
{x:32.9268709337876,y: 24.7660546717921}
,
{x:32.926724402225,y: 24.7652881894561}
,
{x:32.9266930012489,y: 24.762678173805}
,
{x:32.9266648601911,y: 24.761683714863}
,
{x:32.9265732876792,y: 24.7609765843913}
,
{x:32.9264634955015,y: 24.7611008245826}
,
{x:32.92645625828,y: 24.7600050096003}
,
{x:32.9265435953009,y: 24.7591904040133}
,
{x:32.9264488878304,y: 24.7591326821956}
,
{x:32.9264016034968,y: 24.758988472522}
,
{x:32.9262755544517,y: 24.7585342238894}
,
{x:32.9261178214468,y: 24.7582529823664}
,
{x:32.9260956663604,y: 24.758246901223}
,
{x:32.9258810081714,y: 24.758187979745}
,
{x:32.9256361715433,y: 24.7583320410094}
,
{x:32.9253991694607,y: 24.7585770369395}
,
{x:32.9252568456882,y: 24.7589230108933}
,
{x:32.9251066617201,y: 24.7592113053964}
,
{x:32.9249327290853,y: 24.759600518671}
,
{x:32.9246934707416,y: 24.7595097332306}
,
{x:32.9242055687899,y: 24.7598143448404}
,
{x:32.9237668779038,y: 24.7601598226289}
,
{x:32.9236155871289,y: 24.7604076879388}
,
{x:32.9235598404595,y: 24.7607146888924}
,
{x:32.9236232751192,y: 24.7609424807659}
,
{x:32.9236149166569,y: 24.7615616772765}
,
{x:32.923503767919,y: 24.7617511736746}
,
{x:32.9230790711086,y: 24.7632133217508}
,
{x:32.9226935299506,y: 24.7642110825424}
,
{x:32.9224545584024,y: 24.7646291166184}
,
{x:32.9222831927447,y: 24.764972960526}
,
{x:32.9219351934721,y: 24.7661768023774}
,
{x:32.9217505487976,y: 24.766780370422}
,
{x:32.921609528302,y: 24.7671408129537}
,
{x:32.921316758495,y: 24.7675349452007}
,
{x:32.920938898736,y: 24.7683924405507}
,
{x:32.92083137408,y: 24.7686768984577}
,
{x:32.9206746268033,y: 24.7689764679615}
,
{x:32.9205160433852,y: 24.7699160822216}
,
{x:32.9200688038563,y: 24.7730658036102}
,
{x:32.9198469408266,y: 24.7735897941973}
,
{x:32.9200464679148,y: 24.773260560654}
,
{x:32.9200458813367,y: 24.7741610876857}
,
{x:32.920078831211,y: 24.7746164290312}
,
{x:32.919923076022,y: 24.7755472260004}
,
{x:32.9198538359187,y: 24.7757240684698}
,
{x:32.9197273632645,y: 24.7759330683902}
,
{x:32.9196402858313,y: 24.7762718568285}
,
{x:32.9196717142529,y: 24.7765097808206}
,
{x:32.9197820835578,y: 24.7767765840627}
,
{x:32.9199247029633,y: 24.7769591141622}
,
{x:32.9199398731204,y: 24.7769785290011}
,
{x:32.920145241427,y: 24.7768705017251}
,
{x:32.9203347564177,y: 24.776856185831}
,
{x:32.9204676826221,y: 24.7768818110377}
,
{x:32.9204847625125,y: 24.7768851040672}
,
{x:32.9206224517679,y: 24.7770374660924}
,
{x:32.9206346800874,y: 24.7770509980522}
,
{x:32.9208162904096,y: 24.7770510958558}
]}
,
{points:[
{x:32.9265952911567,y: 24.7755382600645}
,
{x:32.9264970013818,y: 24.7755278555926}
,
{x:32.926376944919,y: 24.7757548873527}
,
{x:32.9262923208249,y: 24.7761482014633}
,
{x:32.9261100128348,y: 24.7764887476701}
,
{x:32.9259321486701,y: 24.7768252416978}
,
{x:32.9257454253232,y: 24.777121178403}
,
{x:32.9256874664148,y: 24.7774820631026}
,
{x:32.9257114324813,y: 24.7775991198495}
,
{x:32.9257140371901,y: 24.7776118436441}
,
{x:32.9258339567799,y: 24.7776159592647}
,
{x:32.9260383567022,y: 24.7774700747909}
,
{x:32.9261850208485,y: 24.7773160499914}
,
{x:32.92632727493,y: 24.777109304969}
,
{x:32.9264740550811,y: 24.7767606305983}
,
{x:32.9265941560645,y: 24.7764606037288}
,
{x:32.9266341755091,y: 24.7763835753447}
,
{x:32.9267275635725,y: 24.7761889707636}
,
{x:32.9267322886059,y: 24.7757145131543}
,
{x:32.926679044876,y: 24.7756252711848}
,
{x:32.9266124728043,y: 24.775540078528}
,
{x:32.9265952911567,y: 24.7755382600645}
]}
,
{points:[
{x:33.4744317904032,y: 25.1187186066261}
,
{x:33.4762399603633,y: 24.7927394096184}
,
{x:33.1346860097658,y: 24.7238083860264}
,
{x:33.1337075660594,y: 24.7249478196243}
,
{x:33.1322961369637,y: 24.7266068136277}
,
{x:33.1161169438074,y: 24.7157146510795}
,
{x:33.109563562643,y: 24.7131034854894}
,
{x:33.1087693479163,y: 24.7023487564745}
,
{x:33.106693981545,y: 24.6941627135772}
,
{x:33.0968800749698,y: 24.6898925300026}
,
{x:33.0941770161559,y: 24.6840148716203}
,
{x:33.0904638781902,y: 24.6776673172273}
,
{x:33.0844741475306,y: 24.6783058498821}
,
{x:33.0821740392933,y: 24.6768404050772}
,
{x:33.075702739352,y: 24.6730690387762}
,
{x:33.0678502289971,y: 24.6702305644103}
,
{x:33.0678778235264,y: 24.6701018939693}
,
{x:33.0676729430859,y: 24.6702405099429}
,
{x:33.0586613121379,y: 24.6727883232178}
,
{x:33.053357682183,y: 24.6784566526708}
,
{x:33.0372443455072,y: 24.6843925993545}
,
{x:33.0358600835625,y: 24.684605729329}
,
{x:33.0125033881747,y: 24.6882384084197}
,
{x:33.0111204496743,y: 24.6869711322682}
,
{x:33.0120572050733,y: 24.686113428667}
,
{x:33.0178364853864,y: 24.6808097446782}
,
{x:33.0201606719374,y: 24.6744716960843}
,
{x:33.0231962991369,y: 24.6629720677839}
,
{x:32.9605614512104,y: 24.6603400305634}
,
{x:32.9604623109301,y: 24.6602745037656}
,
{x:32.9605543123669,y: 24.6599903042435}
,
{x:32.9606681731848,y: 24.6596385982667}
,
{x:32.9560560149134,y: 24.6596371781282}
,
{x:32.9417800888342,y: 24.6593874709673}
,
{x:32.9412779989811,y: 24.6573080127737}
,
{x:32.9384711597578,y: 24.6532535726058}
,
{x:32.9378392944048,y: 24.6522297487431}
,
{x:32.9388347595213,y: 24.6404924282935}
,
{x:32.9384869091901,y: 24.635777661254}
,
{x:32.9383017721416,y: 24.6332681674865}
,
{x:32.9380514065238,y: 24.6298743464617}
,
{x:32.9380051982889,y: 24.6286759403527}
,
{x:32.9379470308886,y: 24.6271673497766}
,
{x:32.9379076205847,y: 24.6261451893898}
,
{x:32.9411145045592,y: 24.622950161812}
,
{x:32.9431545196642,y: 24.6222850693659}
,
{x:32.9435619447106,y: 24.6220701657095}
,
{x:32.9436827836863,y: 24.6220064267634}
,
{x:32.9436863542461,y: 24.6143651023874}
,
{x:32.9441469037162,y: 24.6093986547591}
,
{x:32.944118149104,y: 24.6062819534253}
,
{x:32.9441197110332,y: 24.60619719906}
,
{x:32.9438976762607,y: 24.606201626789}
,
{x:32.9393736708041,y: 24.6063005711304}
,
{x:32.9328718706822,y: 24.6063002152629}
,
{x:32.9331050412975,y: 24.6048806206539}
,
{x:32.9354501652893,y: 24.6020230420472}
,
{x:32.9367406454081,y: 24.6002145715308}
,
{x:32.937397574752,y: 24.5974429948885}
,
{x:32.9345156041636,y: 24.5969499875398}
,
{x:32.93326407273,y: 24.5950589825101}
,
{x:32.9332559184796,y: 24.5950449301483}
,
{x:32.9292936413789,y: 24.5969322552563}
,
{x:32.9275278452337,y: 24.59830230506}
,
{x:32.925976163456,y: 24.5986046797086}
,
{x:32.9246647992723,y: 24.5992033259051}
,
{x:32.9233531860633,y: 24.6001765357055}
,
{x:32.9224523939545,y: 24.5993519910048}
,
{x:32.9244276345132,y: 24.5951939677992}
,
{x:32.9234162282738,y: 24.5906299886102}
,
{x:32.9241358552543,y: 24.5894738974141}
,
{x:32.9265408752368,y: 24.5855946214583}
,
{x:32.9319380959904,y: 24.5809444424616}
,
{x:32.9401314246661,y: 24.5760437300169}
,
{x:32.9424906006642,y: 24.573074325624}
,
{x:32.9424986784935,y: 24.5730641582669}
,
{x:32.9393489452679,y: 24.5694227771806}
,
{x:32.9385081078451,y: 24.5616611034652}
,
{x:32.940557236675,y: 24.5613499661831}
,
{x:32.9407957223015,y: 24.5607513089639}
,
{x:32.940697743204,y: 24.5597066463742}
,
{x:32.9391147753021,y: 24.5587456227167}
,
{x:32.9405068811319,y: 24.5579150952606}
,
{x:32.9422270858334,y: 24.5569339683061}
,
{x:32.9432271499957,y: 24.5576757041022}
,
{x:32.9458091367332,y: 24.5596788033102}
,
{x:32.9476017477938,y: 24.5581776173748}
,
{x:32.9492747525844,y: 24.5566735767016}
,
{x:32.9492511913614,y: 24.556096177144}
,
{x:32.9503405427627,y: 24.5556869162587}
,
{x:32.9530970184699,y: 24.5536961619533}
,
{x:32.9556286742089,y: 24.5569247945524}
,
{x:32.9558979203394,y: 24.5576432642052}
,
{x:32.9502287933394,y: 24.5606069318754}
,
{x:32.9504202988012,y: 24.5647309886811}
,
{x:32.9506233484707,y: 24.5659827472189}
,
{x:32.9505193712573,y: 24.566142681723}
,
{x:32.9511128190813,y: 24.5739328678197}
,
{x:32.9514699099922,y: 24.5834933494642}
,
{x:32.9514910578509,y: 24.5851231999027}
,
{x:32.9513813954569,y: 24.5885079842458}
,
{x:32.9512894249695,y: 24.5916466779756}
,
{x:32.9512884748212,y: 24.5916793122524}
,
{x:32.9555587008472,y: 24.5917584344959}
,
{x:32.9604359214414,y: 24.591764310316}
,
{x:32.9648725585428,y: 24.5923703382067}
,
{x:32.9696677047299,y: 24.5965211110189}
,
{x:32.9709015035753,y: 24.597491603433}
,
{x:32.9761630476761,y: 24.597507636907}
,
{x:32.9781000508768,y: 24.5984774002783}
,
{x:32.9790676339984,y: 24.5984768881389}
,
{x:32.9809999810352,y: 24.5969387418474}
,
{x:32.9829352836362,y: 24.597260124789}
,
{x:32.9870511970739,y: 24.5955041473729}
,
{x:32.9942398415528,y: 24.5925050631465}
,
{x:32.9955129978101,y: 24.5925020149665}
,
{x:32.9961840970488,y: 24.5925002862124}
,
{x:33.0032537726569,y: 24.5973931476321}
,
{x:33.0067005260133,y: 24.5990804827708}
,
{x:33.0089985932032,y: 24.6000438497836}
,
{x:33.0132524135669,y: 24.5953333613966}
,
{x:33.0166160583005,y: 24.5931476784054}
,
{x:33.0201566050147,y: 24.5908000174323}
,
{x:33.0196247650771,y: 24.5858627378405}
,
{x:33.0216961584709,y: 24.5833749272382}
,
{x:33.0241751774872,y: 24.5798105646358}
,
{x:33.0255275117658,y: 24.5776112097045}
,
{x:33.025802652298,y: 24.5771637267724}
,
{x:33.0253632439647,y: 24.5717040936168}
,
{x:33.0312405804262,y: 24.5677967902442}
,
{x:33.0315001109069,y: 24.5676850337327}
,
{x:33.0307374905092,y: 24.5657208148313}
,
{x:33.03110249906,y: 24.5650528230852}
,
{x:33.0313453926875,y: 24.5627150509625}
,
{x:33.0314664309926,y: 24.5598207000319}
,
{x:33.0301699980832,y: 24.5548855435074}
,
{x:33.0283628763424,y: 24.5496405339186}
,
{x:33.0283557802747,y: 24.5496447672136}
,
{x:33.0282051630951,y: 24.5492510829651}
,
{x:33.0217712838712,y: 24.5319425026369}
,
{x:33.0167113080963,y: 24.5150152866386}
,
{x:33.0146217249347,y: 24.510410519088}
,
{x:33.0188603622799,y: 24.5074104296653}
,
{x:33.0216629123631,y: 24.5055374422646}
,
{x:33.0217041640538,y: 24.5055098440247}
,
{x:33.0198673658199,y: 24.5028410441463}
,
{x:33.0195662463001,y: 24.5024047921136}
,
{x:33.0213938958727,y: 24.4987199830509}
,
{x:33.0253231235738,y: 24.4901599144432}
,
{x:33.0236314825865,y: 24.4900235752351}
,
{x:33.0211165363255,y: 24.490045622705}
,
{x:33.0197692817867,y: 24.4812562503028}
,
{x:33.0146991493817,y: 24.4813984473001}
,
{x:33.0146990647463,y: 24.4805635363906}
,
{x:33.0144853630028,y: 24.4805290414796}
,
{x:33.0144383124028,y: 24.4805362220035}
,
{x:33.0144506972708,y: 24.4803432330293}
,
{x:33.0143593202645,y: 24.4788404005011}
,
{x:33.0143709280354,y: 24.4650504147615}
,
{x:33.0139739466547,y: 24.4536992446627}
,
{x:33.0160307088039,y: 24.4459360173353}
,
{x:33.0182688220556,y: 24.4410295922151}
,
{x:33.0178957590495,y: 24.4404320879088}
,
{x:33.0195165001217,y: 24.4361274497718}
,
{x:33.017570438027,y: 24.4321200708915}
,
{x:33.0109024703084,y: 24.4248746697808}
,
{x:33.0082854270177,y: 24.4235191317602}
,
{x:33.0096737819095,y: 24.4223825476477}
,
{x:33.0044540899797,y: 24.4190363739803}
,
{x:32.9996374836326,y: 24.4155770252913}
,
{x:32.9915051457668,y: 24.4118534008961}
,
{x:32.9912400415724,y: 24.4108011377252}
,
{x:32.9932745755944,y: 24.4036086641156}
,
{x:32.9838945031547,y: 24.3990848839944}
,
{x:32.9780047384995,y: 24.3978223683787}
,
{x:32.9748664177674,y: 24.3975241633683}
,
{x:32.9675682211924,y: 24.3926711871733}
,
{x:32.9609818386934,y: 24.3937069668391}
,
{x:32.9608209511089,y: 24.3937305937064}
,
{x:32.9619806302833,y: 24.3984337624069}
,
{x:32.9626768345569,y: 24.3989872970705}
,
{x:32.9655672041403,y: 24.3979003519156}
,
{x:32.9674856803134,y: 24.398542634729}
,
{x:32.969041600144,y: 24.3993447203347}
,
{x:32.976368405672,y: 24.4004383282386}
,
{x:32.9754489293497,y: 24.4024385222602}
,
{x:32.9735058473554,y: 24.4098672789131}
,
{x:32.9721671016111,y: 24.4137310674117}
,
{x:32.9710266254581,y: 24.4153527544686}
,
{x:32.969352779879,y: 24.4174475178025}
,
{x:32.9669048925164,y: 24.4260155797427}
,
{x:32.9649578473013,y: 24.4353956880699}
,
{x:32.9629501075643,y: 24.4358901373565}
,
{x:32.9595826155141,y: 24.4382166069919}
,
{x:32.9571063666994,y: 24.4401584991403}
,
{x:32.9579018458352,y: 24.4408872059921}
,
{x:32.9606423957697,y: 24.4418592729383}
,
{x:32.9621718799804,y: 24.4435547558251}
,
{x:32.9636086009514,y: 24.4450867154261}
,
{x:32.9658179696213,y: 24.4489724433853}
,
{x:32.9657831848384,y: 24.4490967844592}
,
{x:32.9656872812147,y: 24.4488569960374}
,
{x:32.9584391895548,y: 24.453530144618}
,
{x:32.9582365660991,y: 24.4535968506956}
,
{x:32.9540542949719,y: 24.4536955182482}
,
{x:32.945722201565,y: 24.453785747949}
,
{x:32.9453265724529,y: 24.4486255787353}
,
{x:32.9424744003388,y: 24.4499600328403}
,
{x:32.9396220501061,y: 24.4515372567633}
,
{x:32.9374997929997,y: 24.4517792015638}
,
{x:32.9324240771026,y: 24.4501123486301}
,
{x:32.9321176631925,y: 24.4499634471808}
,
{x:32.9292920218524,y: 24.449729173774}
,
{x:32.9281284518618,y: 24.4512554572477}
,
{x:32.9275140872686,y: 24.4514954044511}
,
{x:32.9274944069544,y: 24.4515598743304}
,
{x:32.9274484430174,y: 24.451710440422}
,
{x:32.9274806553847,y: 24.4523854765016}
,
{x:32.9271393490264,y: 24.4533803732282}
,
{x:32.926678424472,y: 24.4541702679722}
,
{x:32.9259995670418,y: 24.4552878712202}
,
{x:32.9254368781261,y: 24.4564950986046}
,
{x:32.9256645667922,y: 24.4567663474892}
,
{x:32.9257308689091,y: 24.4571520902171}
,
{x:32.9257326850214,y: 24.45716265465}
,
{x:32.925718178649,y: 24.4571709439482}
,
{x:32.9251856532206,y: 24.4574752277054}
,
{x:32.9244332220766,y: 24.4583299636256}
,
{x:32.921765749381,y: 24.4608522187756}
,
{x:32.9215496695509,y: 24.4613088713053}
,
{x:32.9214006893959,y: 24.4616237165181}
,
{x:32.9205574361376,y: 24.4618944025}
,
{x:32.9207394578765,y: 24.4623116294567}
,
{x:32.9202838834556,y: 24.4620819643362}
,
{x:32.9201021334365,y: 24.4621175104617}
,
{x:32.9199648391812,y: 24.4621443619852}
,
{x:32.9179820137698,y: 24.4628106891301}
,
{x:32.9181225892719,y: 24.4632233063734}
,
{x:32.9183231497629,y: 24.463811988507}
,
{x:32.9183094198579,y: 24.4638320693402}
,
{x:32.9182091087511,y: 24.4639787780145}
,
{x:32.9178218227726,y: 24.4638534252626}
,
{x:32.9173712101452,y: 24.4633460744509}
,
{x:32.9170248979402,y: 24.4629561532969}
,
{x:32.9166147328349,y: 24.4629767808286}
,
{x:32.9158626196242,y: 24.4632266346336}
,
{x:32.9143130983837,y: 24.4633091761699}
,
{x:32.9134473506369,y: 24.463120966735}
,
{x:32.9129229477082,y: 24.4635795034448}
,
{x:32.911874778088,y: 24.4635788864262}
,
{x:32.9095686210679,y: 24.4638878913566}
,
{x:32.9095503487271,y: 24.4638903395972}
,
{x:32.9095214665313,y: 24.4638878627079}
,
{x:32.9085705964573,y: 24.4638063151168}
,
{x:32.9079098083929,y: 24.4637850518816}
,
{x:32.9077666148357,y: 24.4638120765222}
,
{x:32.9072489120412,y: 24.4639097799952}
,
{x:32.9068160333262,y: 24.4638260837151}
,
{x:32.9066362783388,y: 24.4635725796416}
,
{x:32.9065201233391,y: 24.4634087687462}
,
{x:32.9057683499884,y: 24.4631788737925}
,
{x:32.9029696824947,y: 24.4631353878309}
,
{x:32.9024678873666,y: 24.4631681754734}
,
{x:32.90105567952,y: 24.4632593092612}
,
{x:32.9000685936142,y: 24.4633220059821}
,
{x:32.8965041315348,y: 24.4633691975997}
,
{x:32.8942318468812,y: 24.4634010606622}
,
{x:32.8918522322889,y: 24.4637881159969}
,
{x:32.8900848037968,y: 24.4639673635775}
,
{x:32.8886716556412,y: 24.4644043034163}
,
{x:32.8866430703704,y: 24.4650493298351}
,
{x:32.8847059379289,y: 24.4653398401743}
,
{x:32.8836580603796,y: 24.4650053246929}
,
{x:32.8828835691607,y: 24.4647335871008}
,
{x:32.8822913140538,y: 24.464524557201}
,
{x:32.8808786484259,y: 24.4644191570506}
,
{x:32.8799215940977,y: 24.4644392481401}
,
{x:32.8786908403848,y: 24.4647302465895}
,
{x:32.8773001249196,y: 24.4654799452116}
,
{x:32.8772885508404,y: 24.4654611641922}
,
{x:32.8767373747814,y: 24.465782836649}
,
{x:32.8758171125834,y: 24.4670158179687}
,
{x:32.8748661268747,y: 24.4683188656159}
,
{x:32.873760857034,y: 24.4707013008467}
,
{x:32.8733147815418,y: 24.4725375147676}
,
{x:32.8728999402219,y: 24.4737709030003}
,
{x:32.8726689131862,y: 24.4750044472548}
,
{x:32.8722846806285,y: 24.4762518793058}
,
{x:32.8720989836596,y: 24.4780883101216}
,
{x:32.8719434469522,y: 24.480387418647}
,
{x:32.8716401710236,y: 24.4830125163849}
,
{x:32.8718358145877,y: 24.4831783979583}
,
{x:32.8722566687157,y: 24.4829036070144}
,
{x:32.8741180554374,y: 24.4810902511849}
,
{x:32.8745933152822,y: 24.4807261370689}
,
{x:32.8751908592654,y: 24.480628498218}
,
{x:32.8757426678876,y: 24.4803065031203}
,
{x:32.8766016835663,y: 24.4791435738083}
,
{x:32.8777058936218,y: 24.4778686815717}
,
{x:32.8788099322518,y: 24.476747998169}
,
{x:32.8792853378875,y: 24.4762016119267}
,
{x:32.8796685454564,y: 24.4759495647739}
,
{x:32.879867485422,y: 24.476160020805}
,
{x:32.8795300577604,y: 24.4765943625075}
,
{x:32.8788857665445,y: 24.4775331669997}
,
{x:32.8783949409088,y: 24.4781776778593}
,
{x:32.8771225277622,y: 24.4791440024978}
,
{x:32.8766159121313,y: 24.4802511461753}
,
{x:32.8760638008967,y: 24.4808815795938}
,
{x:32.8757725280882,y: 24.4810916339979}
,
{x:32.8755273099408,y: 24.481203588579}
,
{x:32.8754040450301,y: 24.481918494214}
,
{x:32.874974573653,y: 24.4824508861916}
,
{x:32.8737336729305,y: 24.4827272483921}
,
{x:32.8726036470046,y: 24.4838002498897}
,
{x:32.8721078596292,y: 24.484006085037}
,
{x:32.871954860593,y: 24.4840535509626}
,
{x:32.8717987455823,y: 24.4841019788974}
,
{x:32.8720682640643,y: 24.4870693951665}
,
{x:32.8721546542476,y: 24.4882465631805}
,
{x:32.872178860249,y: 24.4901325797125}
,
{x:32.8722678680517,y: 24.4912484258821}
,
{x:32.87238480514,y: 24.492344887601}
,
{x:32.8728243006747,y: 24.4945356686698}
,
{x:32.8731677306684,y: 24.4960276579172}
,
{x:32.8741879271708,y: 24.498377829612}
,
{x:32.8742746668915,y: 24.4985776000471}
,
{x:32.8744281657922,y: 24.4993424773663}
,
{x:32.8752638259839,y: 24.4997051677703}
,
{x:32.8756901250646,y: 24.5008463234882}
,
{x:32.8764854578696,y: 24.5023614218212}
,
{x:32.8770666152565,y: 24.5049247337276}
,
{x:32.8775493807895,y: 24.5059329012229}
,
{x:32.8787721094985,y: 24.5091303800434}
,
{x:32.8799040102717,y: 24.5112202189285}
,
{x:32.8811276650825,y: 24.5135484557585}
,
{x:32.8810960793104,y: 24.5135559353477}
,
{x:32.8811032939934,y: 24.5135584174999}
,
{x:32.8814089982616,y: 24.5143718006826}
,
{x:32.8823416397708,y: 24.5166156802865}
,
{x:32.8828612814673,y: 24.518088151059}
,
{x:32.8833813096697,y: 24.5191540500902}
,
{x:32.8839779292891,y: 24.5202620645861}
,
{x:32.8852787743661,y: 24.5221416943707}
,
{x:32.8861661723396,y: 24.5237125701648}
,
{x:32.8871915525482,y: 24.5252414830452}
,
{x:32.8887553540111,y: 24.527934632234}
,
{x:32.8905392859665,y: 24.5308603068156}
,
{x:32.8917045590535,y: 24.5325875190765}
,
{x:32.8934078376931,y: 24.5352892875048}
,
{x:32.895097926975,y: 24.5376504487648}
,
{x:32.8963847110216,y: 24.538442006447}
,
{x:32.8974324928709,y: 24.5391076485675}
,
{x:32.8980098051744,y: 24.5399341909838}
,
{x:32.8986113827301,y: 24.5412901898302}
,
{x:32.899437126513,y: 24.5424022204512}
,
{x:32.9011370992524,y: 24.544043641156}
,
{x:32.9024079160939,y: 24.5457408444754}
,
{x:32.9041688775486,y: 24.5479150158313}
,
{x:32.9054063325601,y: 24.5493344124896}
,
{x:32.9058687556634,y: 24.5498648141388}
,
{x:32.9072547710423,y: 24.5514522267472}
,
{x:32.9075063628739,y: 24.5521634773074}
,
{x:32.9077935016863,y: 24.5537100018099}
,
{x:32.9086331778805,y: 24.5575601644752}
,
{x:32.9089496928646,y: 24.5592875540288}
,
{x:32.9095507044518,y: 24.5606125463051}
,
{x:32.9099512021349,y: 24.5619215796379}
,
{x:32.9102935199248,y: 24.5633471868207}
,
{x:32.9104963843763,y: 24.5652972457503}
,
{x:32.9109371556711,y: 24.5668581496024}
,
{x:32.9110594174495,y: 24.5674733402064}
,
{x:32.9119250152785,y: 24.5706769741401}
,
{x:32.9121996561682,y: 24.5725137050113}
,
{x:32.9123978502729,y: 24.5740699984887}
,
{x:32.9122740824428,y: 24.5756681602607}
,
{x:32.9120890873644,y: 24.5771260888368}
,
{x:32.911720168454,y: 24.5785138109539}
,
{x:32.9108295269673,y: 24.5805461210864}
,
{x:32.910506699072,y: 24.5817656311906}
,
{x:32.9104597668357,y: 24.5830694250971}
,
{x:32.9102293222049,y: 24.5837282066431}
,
{x:32.9103814340772,y: 24.5853966286901}
,
{x:32.9107328534187,y: 24.5870791896776}
,
{x:32.9110846138012,y: 24.5882991032074}
,
{x:32.9110611675795,y: 24.5883034071914}
,
{x:32.9114109967479,y: 24.5892791109466}
,
{x:32.9123322538596,y: 24.5894890100766}
,
{x:32.9122132418383,y: 24.5900516929498}
,
{x:32.912677995947,y: 24.5908386617185}
,
{x:32.9132300219054,y: 24.5920520891353}
,
{x:32.9142375581257,y: 24.5936896983338}
,
{x:32.9153732081227,y: 24.5959669555765}
,
{x:32.9161954169062,y: 24.5960650877911}
,
{x:32.9165468622342,y: 24.5978457733524}
,
{x:32.9170977613339,y: 24.5994723565043}
,
{x:32.9179249784995,y: 24.600664486359}
,
{x:32.9190122263665,y: 24.602852145071}
,
{x:32.9195328359296,y: 24.6039880176211}
,
{x:32.92005263289,y: 24.6063716267045}
,
{x:32.9206803887137,y: 24.6078440216776}
,
{x:32.9218237549914,y: 24.6107660904485}
,
{x:32.9226728580168,y: 24.6129058136324}
,
{x:32.9233809233381,y: 24.6145842920042}
,
{x:32.9248527794672,y: 24.6169028530244}
,
{x:32.9262842086941,y: 24.6185261883942}
,
{x:32.927548950356,y: 24.6202604061722}
,
{x:32.9283108079115,y: 24.6217770603822}
,
{x:32.9297889590711,y: 24.6234943412971}
,
{x:32.9310862534797,y: 24.6252856575358}
,
{x:32.9317647470376,y: 24.6272935388356}
,
{x:32.9323469123533,y: 24.6284434102354}
,
{x:32.9324076356243,y: 24.6295649989427}
,
{x:32.932928320603,y: 24.6309812097507}
,
{x:32.9332034910109,y: 24.6326216173078}
,
{x:32.9334786916322,y: 24.6342199660057}
,
{x:32.9335850415993,y: 24.6360705874553}
,
{x:32.9338908625373,y: 24.6377951245266}
,
{x:32.9343961835524,y: 24.6393515163125}
,
{x:32.934742534322,y: 24.640977060185}
,
{x:32.9338846304493,y: 24.6426065493079}
,
{x:32.9333061170819,y: 24.6456694579079}
,
{x:32.9335428021607,y: 24.6475337861533}
,
{x:32.9334651912716,y: 24.6490223965714}
,
{x:32.9337406046447,y: 24.6504207418661}
,
{x:32.9341564018662,y: 24.6517757058689}
,
{x:32.9344186866408,y: 24.6525367013744}
,
{x:32.9345355444842,y: 24.6532627124578}
,
{x:32.9345599547491,y: 24.654002763353}
,
{x:32.9345733202194,y: 24.654600340024}
,
{x:32.9347841147191,y: 24.6558235003299}
,
{x:32.9349739757199,y: 24.6578134037326}
,
{x:32.9350818117384,y: 24.6592514609693}
,
{x:32.9351281255652,y: 24.6595279660513}
,
{x:32.935117134979,y: 24.659528817565}
,
{x:32.9350250891935,y: 24.6599054018994}
,
{x:32.9348707807736,y: 24.6607464812061}
,
{x:32.9349369987621,y: 24.6616221702179}
,
{x:32.9351993907479,y: 24.6625185978563}
,
{x:32.9354920103629,y: 24.6637202062262}
,
{x:32.9355012005733,y: 24.6646259936154}
,
{x:32.9355706460088,y: 24.6668459991914}
,
{x:32.9351894702441,y: 24.6690860303879}
,
{x:32.9351981885386,y: 24.6706892152292}
,
{x:32.9351170912726,y: 24.6720600356651}
,
{x:32.9351028589512,y: 24.672300003534}
,
{x:32.93497359024,y: 24.6734409909807}
,
{x:32.9346003179076,y: 24.6751371222348}
,
{x:32.934401395434,y: 24.6761274176997}
,
{x:32.9340289433417,y: 24.6770723485504}
,
{x:32.9337845488045,y: 24.6778424418576}
,
{x:32.9334547973161,y: 24.6790216011264}
,
{x:32.9331679008032,y: 24.6797275154423}
,
{x:32.9331535813395,y: 24.6804381855217}
,
{x:32.9333454389482,y: 24.6816346079095}
,
{x:32.9333042627723,y: 24.6830187346502}
,
{x:32.9335760588394,y: 24.6840504768157}
,
{x:32.9338794908192,y: 24.6852690176107}
,
{x:32.93407970237,y: 24.6868490800257}
,
{x:32.9343327975666,y: 24.6893640885765}
,
{x:32.9347685104386,y: 24.6906172983743}
,
{x:32.9351472953324,y: 24.6917055719386}
,
{x:32.9355633237969,y: 24.6926090096808}
,
{x:32.9356491300707,y: 24.6936197229112}
,
{x:32.9361423510662,y: 24.6963039116542}
,
{x:32.9371754512515,y: 24.6985972727033}
,
{x:32.9374552244995,y: 24.700501739863}
,
{x:32.9376308234516,y: 24.7024180611081}
,
{x:32.9375818562894,y: 24.70460511625}
,
{x:32.9372224611889,y: 24.7077656176362}
,
{x:32.9373841218653,y: 24.7075558649985}
,
{x:32.9366130274144,y: 24.7085763874999}
,
{x:32.9358954265757,y: 24.7092769224491}
,
{x:32.9348014207392,y: 24.7102131419909}
,
{x:32.9334237623154,y: 24.7116655632802}
,
{x:32.932088735961,y: 24.7127152782576}
,
{x:32.9313515468689,y: 24.7139204374873}
,
{x:32.9310291194109,y: 24.714615872806}
,
{x:32.9307751088903,y: 24.7166945426785}
,
{x:32.9305329132943,y: 24.7176219879823}
,
{x:32.9302097107003,y: 24.7192413851803}
,
{x:32.9300250932086,y: 24.7200191250692}
,
{x:32.9294255098064,y: 24.7217741377303}
,
{x:32.9289372050318,y: 24.7231195863497}
,
{x:32.928929734816,y: 24.7231401667347}
,
{x:32.9285492658332,y: 24.7241594344958}
,
{x:32.928513223313,y: 24.7249903103628}
,
{x:32.9283316256367,y: 24.72604261337}
,
{x:32.9283520632578,y: 24.726502395455}
,
{x:32.929291899499,y: 24.7274586132744}
,
{x:32.9294105395205,y: 24.7291726580119}
,
{x:32.929546635861,y: 24.7304124738804}
,
{x:32.9294498041599,y: 24.7319933637737}
,
{x:32.9291182603579,y: 24.732832454587}
,
{x:32.9292590938429,y: 24.7351377663496}
,
{x:32.929441434218,y: 24.7362063035906}
,
{x:32.9294593270074,y: 24.7369320418494}
,
{x:32.9295347023828,y: 24.7386906173833}
,
{x:32.9299173660719,y: 24.7409113121792}
,
{x:32.9299735558953,y: 24.7420185100343}
,
{x:32.9301778367877,y: 24.7436263996471}
,
{x:32.930198461766,y: 24.7447514064787}
,
{x:32.9298241206925,y: 24.7461493772315}
,
{x:32.9297372773706,y: 24.7476251402954}
,
{x:32.9289554969062,y: 24.752485772653}
,
{x:32.928747101161,y: 24.75375012468}
,
{x:32.9282521646155,y: 24.7557256546676}
,
{x:32.9279060574901,y: 24.7575746593587}
,
{x:32.9278135680367,y: 24.758215996165}
,
{x:32.9278593657313,y: 24.7586576253337}
,
{x:32.9282083451854,y: 24.7577208563067}
,
{x:32.9283909902611,y: 24.7578899813649}
,
{x:32.9286304425892,y: 24.7576290079785}
,
{x:32.928679272722,y: 24.7588885088206}
,
{x:32.9285869894456,y: 24.7592827550664}
,
{x:32.9286367267761,y: 24.7594422017018}
,
{x:32.9287298598988,y: 24.7595986335381}
,
{x:32.9288854653395,y: 24.7583385466581}
,
{x:32.9288889211632,y: 24.7583418321436}
,
{x:32.9289007436031,y: 24.7584995817718}
,
{x:32.9289231990461,y: 24.7587992276581}
,
{x:32.9288701448866,y: 24.7609283765588}
,
{x:32.9289910513447,y: 24.7609284351479}
,
{x:32.9287882143323,y: 24.7638993136603}
,
{x:32.9286796689393,y: 24.7653946215427}
,
{x:32.9287372812183,y: 24.7663090749012}
,
{x:32.9285288575449,y: 24.7669271454134}
,
{x:32.92831957007,y: 24.7674468650747}
,
{x:32.928145470014,y: 24.7681852679211}
,
{x:32.928040541619,y: 24.7694553668343}
,
{x:32.9277418944874,y: 24.7706823810053}
,
{x:32.927654239722,y: 24.7717200021784}
,
{x:32.9276089045484,y: 24.7724146904566}
,
{x:32.9275722946154,y: 24.7729770016992}
,
{x:32.9273281479343,y: 24.774807839751}
,
{x:32.9270351108341,y: 24.7768209316773}
,
{x:32.927337990197,y: 24.7763147817332}
,
{x:32.927013191311,y: 24.776531522535}
,
{x:32.9269837320037,y: 24.7765511809216}
,
{x:32.9267072055474,y: 24.7767876171354}
,
{x:32.9264391488429,y: 24.7773000618078}
,
{x:32.9260498337469,y: 24.7783723379014}
,
{x:32.9256001845332,y: 24.7792237791152}
,
{x:32.9254963846851,y: 24.779476072662}
,
{x:32.9251594653799,y: 24.7795863026974}
,
{x:32.9251247953737,y: 24.7797834305751}
,
{x:32.9247948516476,y: 24.7809935325255}
,
{x:32.9249646617194,y: 24.7810178383656}
,
{x:32.9251490493303,y: 24.7811522799507}
,
{x:32.9253391212652,y: 24.7814290799837}
,
{x:32.9254271650525,y: 24.781076071347}
,
{x:32.9254283484981,y: 24.781095544762}
,
{x:32.9253283607598,y: 24.781463524772}
,
{x:32.9250436535207,y: 24.7821005951104}
,
{x:32.9250264367755,y: 24.7821246890646}
,
{x:32.9244719640944,y: 24.7828875027354}
,
{x:32.9242690285557,y: 24.7832680940621}
,
{x:32.9240135614021,y: 24.7838514334696}
,
{x:32.9238299787036,y: 24.7841944482014}
,
{x:32.923838045906,y: 24.7846374081639}
,
{x:32.9238402209682,y: 24.7847138103397}
,
{x:32.9238560270538,y: 24.7852437317724}
,
{x:32.9236138936205,y: 24.7853694017258}
,
{x:32.9234623558351,y: 24.7854887948313}
,
{x:32.9231139462105,y: 24.7857556907311}
,
{x:32.9228073729393,y: 24.7862850426506}
,
{x:32.9226831502023,y: 24.7839974212002}
,
{x:32.9225532891422,y: 24.7844626155809}
,
{x:32.9223110401389,y: 24.7850775807088}
,
{x:32.9220945469937,y: 24.7859370194497}
,
{x:32.9217485000418,y: 24.7867648453347}
,
{x:32.9216999273838,y: 24.7870035206945}
,
{x:32.9215751956725,y: 24.7876164198515}
,
{x:32.921333046683,y: 24.7880578964998}
,
{x:32.9211054650413,y: 24.7885569941573}
,
{x:32.9210562363517,y: 24.7886649546755}
,
{x:32.9210546305681,y: 24.7886898351628}
,
{x:32.9209951601943,y: 24.7896112186885}
,
{x:32.920700676734,y: 24.7908254733627}
,
{x:32.9205188032516,y: 24.7915508692535}
,
{x:32.920216244767,y: 24.7918819095026}
,
{x:32.9198444587763,y: 24.7923942842644}
,
{x:32.9195873968631,y: 24.7935613587314}
,
{x:32.9194015170349,y: 24.794060059372}
,
{x:32.9193911154275,y: 24.7942563174771}
,
{x:32.9190771477351,y: 24.794567704191}
,
{x:32.9186393142288,y: 24.7951667408711}
,
{x:32.9185873388827,y: 24.7952591573295}
,
{x:32.9184546303872,y: 24.7954951710966}
,
{x:32.9181886766305,y: 24.7961845941351}
,
{x:32.918295551838,y: 24.7969800572191}
,
{x:32.9180815228979,y: 24.7977815099514}
,
{x:32.9178741092421,y: 24.7981605396523}
,
{x:32.9174313623337,y: 24.7985157485639}
,
{x:32.9173580334909,y: 24.798966216766}
,
{x:32.9172287165194,y: 24.7998826036419}
,
{x:32.9170397942108,y: 24.8006930264288}
,
{x:32.9166268632323,y: 24.801782811508}
,
{x:32.9163930799149,y: 24.8025633717648}
,
{x:32.9161418277955,y: 24.8036199252583}
,
{x:32.9158820393859,y: 24.8045187575214}
,
{x:32.9157428420785,y: 24.8059381194581}
,
{x:32.9156475392721,y: 24.806332353656}
,
{x:32.9151456053277,y: 24.8075701350416}
,
{x:32.9147303611289,y: 24.8083663592545}
,
{x:32.9142977559523,y: 24.8092729745952}
,
{x:32.9141992708051,y: 24.8101489005137}
,
{x:32.9134056363416,y: 24.8114203104863}
,
{x:32.9130101742781,y: 24.8124102465207}
,
{x:32.9127256057329,y: 24.8130466512639}
,
{x:32.9123016529284,y: 24.8139714448995}
,
{x:32.9118181950568,y: 24.8147644311867}
,
{x:32.9118132104355,y: 24.8158352528831}
,
{x:32.9110260245684,y: 24.8171359274064}
,
{x:32.9101698409462,y: 24.8182472968217}
,
{x:32.9096219043769,y: 24.819184411743}
,
{x:32.9096347267476,y: 24.8192003165851}
,
{x:32.9091504537458,y: 24.8197677915638}
,
{x:32.9078958498886,y: 24.8202057509515}
,
{x:32.9074984960777,y: 24.8204742676116}
,
{x:32.9067291425041,y: 24.821766160798}
,
{x:32.9057285551196,y: 24.8236309651356}
,
{x:32.9050887733982,y: 24.8245207429577}
,
{x:32.9037883092423,y: 24.8254541522264}
,
{x:32.9034537795725,y: 24.8260006829962}
,
{x:32.9030499007502,y: 24.826831054998}
,
{x:32.9029832042663,y: 24.826936019474}
,
{x:32.902669239321,y: 24.8274301251187}
,
{x:32.9020120842132,y: 24.8280079846996}
,
{x:32.9008358002951,y: 24.829426645114}
,
{x:32.900039770538,y: 24.8307509209604}
,
{x:32.8994300687631,y: 24.8316195340226}
,
{x:32.8994053647743,y: 24.8316547285781}
,
{x:32.8991622238374,y: 24.8321757467438}
,
{x:32.8990129533781,y: 24.8324956108809}
,
{x:32.8985974080316,y: 24.8334416194777}
,
{x:32.8982510631521,y: 24.8342930450317}
,
{x:32.8978589290621,y: 24.8347764370512}
,
{x:32.8974667476094,y: 24.835312399973}
,
{x:32.8969575963321,y: 24.8357558622709}
,
{x:32.8966826996026,y: 24.8359952913069}
,
{x:32.8963941983728,y: 24.8365418362841}
,
{x:32.8962122626649,y: 24.8371790393771}
,
{x:32.8961630843052,y: 24.8373512795893}
,
{x:32.8958627916944,y: 24.8382132453124}
,
{x:32.895654883583,y: 24.8388229310271}
,
{x:32.8951934590856,y: 24.8394639822948}
,
{x:32.8950635775822,y: 24.8396266853132}
,
{x:32.8950089092518,y: 24.8396951681062}
,
{x:32.8944435803428,y: 24.8405692104401}
,
{x:32.8945565195875,y: 24.841439778796}
,
{x:32.8943022117675,y: 24.8415219900716}
,
{x:32.894190109228,y: 24.8417715181375}
,
{x:32.894231726778,y: 24.8425387586869}
,
{x:32.8942345745765,y: 24.8425912748885}
,
{x:32.8943287761773,y: 24.8438666011175}
,
{x:32.8937575298907,y: 24.8446213029933}
,
{x:32.8932230605749,y: 24.8450745775207}
,
{x:32.8927884940776,y: 24.8456811451068}
,
{x:32.8926705164069,y: 24.8460549186866}
,
{x:32.8917663570225,y: 24.8478832664045}
,
{x:32.8909002523665,y: 24.8496646990135}
,
{x:32.8902980025054,y: 24.8508617898645}
,
{x:32.8908352376935,y: 24.8511172969076}
,
{x:32.8908996809991,y: 24.851147957379}
,
{x:32.8937835994337,y: 24.8527496645362}
,
{x:32.8955438496299,y: 24.8542349217164}
,
{x:32.8959270412336,y: 24.8550325789258}
,
{x:32.8994257469539,y: 24.8548905618399}
,
{x:32.9037891854298,y: 24.8544837412578}
,
{x:32.9056634375724,y: 24.8538119328173}
,
{x:32.9119228017722,y: 24.8520202167553}
,
{x:32.9160200430428,y: 24.8514450060516}
,
{x:32.9161853412503,y: 24.8515450747674}
,
{x:32.9162424546993,y: 24.8515115098829}
,
{x:32.9182630447518,y: 24.8513128168791}
,
{x:32.9209575126526,y: 24.8510129422786}
,
{x:32.924669086344,y: 24.8517583193709}
,
{x:32.9278117318929,y: 24.852982544901}
,
{x:32.9292709573927,y: 24.8523712468954}
,
{x:32.9318169850952,y: 24.8525796833606}
,
{x:32.9336391911536,y: 24.851708248895}
,
{x:32.9453425008659,y: 24.8539070144252}
,
{x:32.9568279474866,y: 24.8464814433184}
,
{x:32.9804849669071,y: 24.8356543168099}
,
{x:32.9900398454007,y: 24.8455389070718}
,
{x:32.989530781126,y: 24.8474122543946}
,
{x:32.9905621041816,y: 24.8469565863812}
,
{x:32.9906068520364,y: 24.8476974034454}
,
{x:32.9911044041365,y: 24.8559351053064}
,
{x:32.9957819032223,y: 24.8601918770721}
,
{x:32.9978253141553,y: 24.8701327440178}
,
{x:32.9976225070353,y: 24.8703126451725}
,
{x:32.9976623093172,y: 24.8703089318966}
,
{x:33.0247670562779,y: 25.0128841647688}
,
{x:33.0376796684278,y: 25.012829139629}
,
{x:33.050415493061,y: 25.01344003155}
,
{x:33.0630398992527,y: 25.0136712057918}
,
{x:33.062359169166,y: 25.0149764969917}
,
{x:33.0630409293024,y: 25.0147320144853}
,
{x:33.0700241456856,y: 25.0144035256714}
,
{x:33.0778221599905,y: 25.0223180106365}
,
{x:33.0823848640069,y: 25.0181484598058}
,
{x:33.0901704325144,y: 25.0132568485274}
,
{x:33.0902247083489,y: 25.0136802367035}
,
{x:33.090439095594,y: 25.0132769937907}
,
{x:33.0974240752101,y: 25.0134496433665}
,
{x:33.098860782988,y: 25.0163195449055}
,
{x:33.1067067331546,y: 25.0127411941409}
,
{x:33.1162597448036,y: 25.0133676427572}
,
{x:33.1185801664153,y: 25.0189383641595}
,
{x:33.1211298446881,y: 25.0180448589445}
,
{x:33.1505809986843,y: 25.0288776008302}
,
{x:33.1517199488609,y: 25.0282859228616}
,
{x:33.4744317904032,y: 25.1187186066261}
]}
]})
| amounir86/amounir86-2011-elections | voter-info/shapes/old_json/28_05.js | JavaScript | unlicense | 52,858 |
/*!
* ${copyright}
*/
// Provides class sap.ui.rta.plugin.Combine.
sap.ui.define([
'sap/ui/rta/plugin/Plugin',
'sap/ui/dt/Selection',
'sap/ui/dt/OverlayRegistry',
'sap/ui/rta/Utils'
], function(
Plugin,
Selection,
OverlayRegistry,
Utils
) {
"use strict";
/**
* Constructor for a new Combine Plugin.
*
* @class
* @extends sap.ui.rta.plugin.Plugin
* @author SAP SE
* @version ${version}
* @constructor
* @private
* @since 1.46
* @alias sap.ui.rta.plugin.Combine
* @experimental Since 1.46. This class is experimental and provides only limited functionality. Also the API might be changed in future.
*/
var Combine = Plugin.extend("sap.ui.rta.plugin.Combine", /** @lends sap.ui.rta.plugin.Combine.prototype */
{
metadata: {
// ---- object ----
// ---- control specific ----
library: "sap.ui.rta",
properties: {},
associations: {},
events: {}
}
});
/**
* check if the given overlay is editable
* @param {sap.ui.dt.ElementOverlay} oOverlay - overlay to be checked for editable
* @returns {boolean} whether it is editable or not
* @private
*/
Combine.prototype._isEditable = function(oOverlay) {
var oCombineAction = this.getAction(oOverlay);
if (oCombineAction && oCombineAction.changeType && oCombineAction.changeOnRelevantContainer) {
return this.hasChangeHandler(oCombineAction.changeType, oOverlay.getRelevantContainer()) && this.hasStableId(oOverlay);
} else {
return false;
}
};
Combine.prototype._checkForSameRelevantContainer = function(aSelectedOverlays) {
var aRelevantContainer = [];
for (var i = 0, n = aSelectedOverlays.length; i < n; i++) {
aRelevantContainer[i] = aSelectedOverlays[i].getRelevantContainer();
var oCombineAction = this.getAction(aSelectedOverlays[i]);
if (!oCombineAction || !oCombineAction.changeType){
return false;
}
if (i > 0) {
if ((aRelevantContainer[0] !== aRelevantContainer[i])
|| (this.getAction(aSelectedOverlays[0]).changeType !== oCombineAction.changeType)) {
return false;
}
}
}
return true;
};
/**
* Checks if Combine is available for oOverlay
*
* @param {sap.ui.dt.Overlay} oOverlay overlay object
* @return {boolean} true if available
* @public
*/
Combine.prototype.isAvailable = function(oOverlay) {
var aSelectedOverlays = this.getDesignTime().getSelection();
if (aSelectedOverlays.length <= 1) {
return false;
}
return (this._isEditableByPlugin(oOverlay) && this._checkForSameRelevantContainer(aSelectedOverlays));
};
/**
* Checks if Combine is enabled for oOverlay
*
* @param {sap.ui.dt.Overlay} oOverlay overlay object
* @return {boolean} true if enabled
* @public
*/
Combine.prototype.isEnabled = function(oOverlay) {
var aSelectedOverlays = this.getDesignTime().getSelection();
// check that at least 2 fields can be combined
if (!this.isAvailable(oOverlay) || aSelectedOverlays.length <= 1) {
return false;
}
var aSelectedControls = aSelectedOverlays.map(function (oSelectedOverlay) {
return oSelectedOverlay.getElementInstance();
});
// check that each selected element has an enabled action
var bActionCheck = aSelectedOverlays.every(function(oSelectedOverlay) {
var oAction = this.getAction(oSelectedOverlay);
if (!oAction) {
return false;
}
// when isEnabled is not defined the default is true
if (typeof oAction.isEnabled !== "undefined") {
if (typeof oAction.isEnabled === "function") {
return oAction.isEnabled(aSelectedControls);
} else {
return oAction.isEnabled;
}
}
return true;
}, this);
return bActionCheck;
};
/**
* @param {any} oCombineElement selected element
*/
Combine.prototype.handleCombine = function(oCombineElement) {
var oElementOverlay = OverlayRegistry.getOverlay(oCombineElement);
var oDesignTimeMetadata = oElementOverlay.getDesignTimeMetadata();
var aToCombineElements = [];
var aSelectedOverlays = this.getDesignTime().getSelection();
for (var i = 0; i < aSelectedOverlays.length; i++) {
var oSelectedElement = aSelectedOverlays[i].getElementInstance();
aToCombineElements.push(oSelectedElement);
}
var oCombineAction = this.getAction(oElementOverlay);
var sVariantManagementReference = this.getVariantManagementReference(oElementOverlay, oCombineAction);
var oCombineCommand = this.getCommandFactory().getCommandFor(oCombineElement, "combine", {
source : oCombineElement,
combineFields : aToCombineElements
}, oDesignTimeMetadata, sVariantManagementReference);
this.fireElementModified({
"command" : oCombineCommand
});
};
/**
* Retrieve the context menu item for the action.
* @param {sap.ui.dt.ElementOverlay} oOverlay Overlay for which the context menu was opened
* @return {object[]} Returns array containing the items with required data
*/
Combine.prototype.getMenuItems = function(oOverlay){
return this._getMenuItems(oOverlay, {pluginId : "CTX_GROUP_FIELDS", rank : 90});
};
/**
* Get the name of the action related to this plugin.
* @return {string} Returns the action name
*/
Combine.prototype.getActionName = function(){
return "combine";
};
/**
* Trigger the plugin execution.
* @param {sap.ui.dt.ElementOverlay[]} aOverlays Selected overlays; targets of the action
* @param {any} oEventItem ContextMenu item which triggers the event
* @param {any} oContextElement Element where the action is triggered
*/
Combine.prototype.handler = function(aOverlays, mPropertyBag){
//TODO: Handle "Stop Cut & Paste" depending on alignment with Dietrich!
this.handleCombine(mPropertyBag.contextElement);
};
return Combine;
}, /* bExport= */true);
| SQCLabs/openui5 | src/sap.ui.rta/src/sap/ui/rta/plugin/Combine.js | JavaScript | apache-2.0 | 5,703 |
//// [typeGuardFunctionOfFormThis.ts]
class RoyalGuard {
isLeader(): this is LeadGuard {
return this instanceof LeadGuard;
}
isFollower(): this is FollowerGuard {
return this instanceof FollowerGuard;
}
}
class LeadGuard extends RoyalGuard {
lead(): void {};
}
class FollowerGuard extends RoyalGuard {
follow(): void {};
}
let a: RoyalGuard = new FollowerGuard();
if (a.isLeader()) {
a.lead();
}
else if (a.isFollower()) {
a.follow();
}
interface GuardInterface extends RoyalGuard {}
let b: GuardInterface;
if (b.isLeader()) {
b.lead();
}
else if (b.isFollower()) {
b.follow();
}
// if (((a.isLeader)())) {
// a.lead();
// }
// else if (((a).isFollower())) {
// a.follow();
// }
// if (((a["isLeader"])())) {
// a.lead();
// }
// else if (((a)["isFollower"]())) {
// a.follow();
// }
var holder2 = {a};
if (holder2.a.isLeader()) {
holder2.a;
}
else {
holder2.a;
}
class ArrowGuard {
isElite = (): this is ArrowElite => {
return this instanceof ArrowElite;
}
isMedic = (): this is ArrowMedic => {
return this instanceof ArrowMedic;
}
}
class ArrowElite extends ArrowGuard {
defend(): void {}
}
class ArrowMedic extends ArrowGuard {
heal(): void {}
}
let guard = new ArrowGuard();
if (guard.isElite()) {
guard.defend();
}
else if (guard.isMedic()) {
guard.heal();
}
interface Supplies {
spoiled: boolean;
}
interface Sundries {
broken: boolean;
}
interface Crate<T> {
contents: T;
volume: number;
isSupplies(): this is Crate<Supplies>;
isSundries(): this is Crate<Sundries>;
}
let crate: Crate<{}>;
if (crate.isSundries()) {
crate.contents.broken = true;
}
else if (crate.isSupplies()) {
crate.contents.spoiled = true;
}
// Matching guards should be assignable
a.isFollower = b.isFollower;
a.isLeader = b.isLeader;
class MimicGuard {
isLeader(): this is MimicLeader { return this instanceof MimicLeader; };
isFollower(): this is MimicFollower { return this instanceof MimicFollower; };
}
class MimicLeader extends MimicGuard {
lead(): void {}
}
class MimicFollower extends MimicGuard {
follow(): void {}
}
let mimic = new MimicGuard();
a.isLeader = mimic.isLeader;
a.isFollower = mimic.isFollower;
if (mimic.isFollower()) {
mimic.follow();
mimic.isFollower = a.isFollower;
}
interface MimicGuardInterface {
isLeader(): this is LeadGuard;
isFollower(): this is FollowerGuard;
}
//// [typeGuardFunctionOfFormThis.js]
var __extends = (this && this.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var RoyalGuard = /** @class */ (function () {
function RoyalGuard() {
}
RoyalGuard.prototype.isLeader = function () {
return this instanceof LeadGuard;
};
RoyalGuard.prototype.isFollower = function () {
return this instanceof FollowerGuard;
};
return RoyalGuard;
}());
var LeadGuard = /** @class */ (function (_super) {
__extends(LeadGuard, _super);
function LeadGuard() {
return _super !== null && _super.apply(this, arguments) || this;
}
LeadGuard.prototype.lead = function () { };
;
return LeadGuard;
}(RoyalGuard));
var FollowerGuard = /** @class */ (function (_super) {
__extends(FollowerGuard, _super);
function FollowerGuard() {
return _super !== null && _super.apply(this, arguments) || this;
}
FollowerGuard.prototype.follow = function () { };
;
return FollowerGuard;
}(RoyalGuard));
var a = new FollowerGuard();
if (a.isLeader()) {
a.lead();
}
else if (a.isFollower()) {
a.follow();
}
var b;
if (b.isLeader()) {
b.lead();
}
else if (b.isFollower()) {
b.follow();
}
// if (((a.isLeader)())) {
// a.lead();
// }
// else if (((a).isFollower())) {
// a.follow();
// }
// if (((a["isLeader"])())) {
// a.lead();
// }
// else if (((a)["isFollower"]())) {
// a.follow();
// }
var holder2 = { a: a };
if (holder2.a.isLeader()) {
holder2.a;
}
else {
holder2.a;
}
var ArrowGuard = /** @class */ (function () {
function ArrowGuard() {
var _this = this;
this.isElite = function () {
return _this instanceof ArrowElite;
};
this.isMedic = function () {
return _this instanceof ArrowMedic;
};
}
return ArrowGuard;
}());
var ArrowElite = /** @class */ (function (_super) {
__extends(ArrowElite, _super);
function ArrowElite() {
return _super !== null && _super.apply(this, arguments) || this;
}
ArrowElite.prototype.defend = function () { };
return ArrowElite;
}(ArrowGuard));
var ArrowMedic = /** @class */ (function (_super) {
__extends(ArrowMedic, _super);
function ArrowMedic() {
return _super !== null && _super.apply(this, arguments) || this;
}
ArrowMedic.prototype.heal = function () { };
return ArrowMedic;
}(ArrowGuard));
var guard = new ArrowGuard();
if (guard.isElite()) {
guard.defend();
}
else if (guard.isMedic()) {
guard.heal();
}
var crate;
if (crate.isSundries()) {
crate.contents.broken = true;
}
else if (crate.isSupplies()) {
crate.contents.spoiled = true;
}
// Matching guards should be assignable
a.isFollower = b.isFollower;
a.isLeader = b.isLeader;
var MimicGuard = /** @class */ (function () {
function MimicGuard() {
}
MimicGuard.prototype.isLeader = function () { return this instanceof MimicLeader; };
;
MimicGuard.prototype.isFollower = function () { return this instanceof MimicFollower; };
;
return MimicGuard;
}());
var MimicLeader = /** @class */ (function (_super) {
__extends(MimicLeader, _super);
function MimicLeader() {
return _super !== null && _super.apply(this, arguments) || this;
}
MimicLeader.prototype.lead = function () { };
return MimicLeader;
}(MimicGuard));
var MimicFollower = /** @class */ (function (_super) {
__extends(MimicFollower, _super);
function MimicFollower() {
return _super !== null && _super.apply(this, arguments) || this;
}
MimicFollower.prototype.follow = function () { };
return MimicFollower;
}(MimicGuard));
var mimic = new MimicGuard();
a.isLeader = mimic.isLeader;
a.isFollower = mimic.isFollower;
if (mimic.isFollower()) {
mimic.follow();
mimic.isFollower = a.isFollower;
}
//// [typeGuardFunctionOfFormThis.d.ts]
declare class RoyalGuard {
isLeader(): this is LeadGuard;
isFollower(): this is FollowerGuard;
}
declare class LeadGuard extends RoyalGuard {
lead(): void;
}
declare class FollowerGuard extends RoyalGuard {
follow(): void;
}
declare let a: RoyalGuard;
interface GuardInterface extends RoyalGuard {
}
declare let b: GuardInterface;
declare var holder2: {
a: RoyalGuard;
};
declare class ArrowGuard {
isElite: () => this is ArrowElite;
isMedic: () => this is ArrowMedic;
}
declare class ArrowElite extends ArrowGuard {
defend(): void;
}
declare class ArrowMedic extends ArrowGuard {
heal(): void;
}
declare let guard: ArrowGuard;
interface Supplies {
spoiled: boolean;
}
interface Sundries {
broken: boolean;
}
interface Crate<T> {
contents: T;
volume: number;
isSupplies(): this is Crate<Supplies>;
isSundries(): this is Crate<Sundries>;
}
declare let crate: Crate<{}>;
declare class MimicGuard {
isLeader(): this is MimicLeader;
isFollower(): this is MimicFollower;
}
declare class MimicLeader extends MimicGuard {
lead(): void;
}
declare class MimicFollower extends MimicGuard {
follow(): void;
}
declare let mimic: MimicGuard;
interface MimicGuardInterface {
isLeader(): this is LeadGuard;
isFollower(): this is FollowerGuard;
}
| synaptek/TypeScript | tests/baselines/reference/typeGuardFunctionOfFormThis.js | JavaScript | apache-2.0 | 8,326 |
"use strict";
describe("Brisket server", function() {
var Brisket = require("../../lib/brisket");
var MockBrisketApp = require("../mock/MockBrisketApp");
var nock = require("nock");
var supertest = require("supertest");
var brisketServer;
beforeEach(function() {
MockBrisketApp.initialize();
nock("http://api.example.com")
.get("/fetch200")
.reply(200, { ok: true })
.get("/fetch404")
.reply(404, { ok: false })
.get("/fetch500")
.reply(500, { ok: false })
.get("/fetch410")
.reply(410, { ok: false });
brisketServer = Brisket.createServer({
apis: {
"api": {
host: "http://api.example.com",
proxy: null
}
}
});
});
afterEach(function() {
MockBrisketApp.cleanup();
nock.cleanAll();
});
it("returns 200 when route is working", function(done) {
supertest(brisketServer)
.get("/working")
.expect(200, mocha(done));
});
it("returns 500 when route is failing", function(done) {
supertest(brisketServer)
.get("/failing")
.expect(500, mocha(done));
});
it("returns 302 when route is redirecting", function(done) {
supertest(brisketServer)
.get("/redirecting")
.expect(302, mocha(done));
});
it("returns status from route when route sets status", function(done) {
supertest(brisketServer)
.get("/setsStatus")
.expect(206, mocha(done));
});
it("returns 200 when data fetch is 200 AND route code doesn't error", function(done) {
supertest(brisketServer)
.get("/fetch200")
.expect(200, mocha(done));
});
it("returns 500 when data fetch is 200 BUT route code errors", function(done) {
supertest(brisketServer)
.get("/fetch200ButRouteFails")
.expect(500, mocha(done));
});
it("returns 302 when data fetch is 200 BUT route code redirects", function(done) {
supertest(brisketServer)
.get("/fetch200ButRouteRedirects")
.expect(302, mocha(done));
});
it("returns status from route when data fetch is 200 BUT route sets status", function(done) {
supertest(brisketServer)
.get("/fetch200ButRouteSetsStatus")
.expect(206, mocha(done));
});
it("returns 404 when route does NOT exist", function(done) {
supertest(brisketServer)
.get("/doesntexist")
.expect(404, mocha(done));
});
it("returns 404 when data fetch is 404", function(done) {
supertest(brisketServer)
.get("/fetch404")
.expect(404, mocha(done));
});
it("returns 500 when data fetch is 500", function(done) {
supertest(brisketServer)
.get("/fetch500")
.expect(500, mocha(done));
});
it("returns 500 when data fetch is unexpected error code", function(done) {
supertest(brisketServer)
.get("/fetch410")
.expect(500, mocha(done));
});
function mocha(done) {
return function(err) {
if (err) {
done.fail(err);
} else {
done();
}
};
}
});
| wawjr3d/brisket | spec/server/brisketServerSpec.js | JavaScript | apache-2.0 | 3,439 |
/**
* @projectDescription The SDX controller library for the PatientRecordSet data-type.
* @namespace i2b2.sdx.TypeControllers.ENS
* @inherits i2b2.sdx.TypeControllers
* @author Mike Mendis
* @version 1.6
* @see i2b2.sdx
* ----------------------------------------------------------------------------------------
*/
console.group('Load & Execute component file: CRC > SDX > Encounter Record Set');
console.time('execute time');
i2b2.sdx.TypeControllers.ENS = {};
i2b2.sdx.TypeControllers.ENS.model = {};
// *********************************************************************************
// ENCAPSULATE DATA
// *********************************************************************************
i2b2.sdx.TypeControllers.ENS.getEncapsulateInfo = function() {
// this function returns the encapsulation head information
return {sdxType: 'ENS', sdxKeyName: 'result_instance_id', sdxControlCell:'CRC', sdxDisplayNameKey: 'title'};
}
i2b2.sdx.TypeControllers.ENS.SaveToDataModel = function(sdxData, sdxParentNode) {
// save to CRC data model
if (!sdxParentNode) { return false; }
var qm_id = sdxData.sdxInfo.sdxKeyValue;
var qm_hash = i2b2.sdx.Master._KeyHash(qm_id);
// class for all SDX communications
function i2b2_SDX_Encapsulation_EXTENDED() {}
// create an instance and populate with info
var t = new i2b2_SDX_Encapsulation_EXTENDED();
t.origData = Object.clone(sdxData.origData);
t.sdxInfo = Object.clone(sdxData.sdxInfo);
t.parent = sdxParentNode;
t.children = new Hash();
t.children.loaded = false;
// add to hash
sdxParentNode.children.set(qm_hash, t);
// TODO: send data update signal (use JOINING-MUTEX or AGGREGATING-MUTEX to avoid rapid fire of event!)
return t;
}
i2b2.sdx.TypeControllers.ENS.LoadFromDataModel = function(key_value) {}
i2b2.sdx.TypeControllers.ENS.ClearAllFromDataModel= function(sdxOptionalParent) {
if (sdxOptionalParent) {
try {
var findFunc = function(item_rec) {
// this function expects the second argument to be the target node's key value
var hash_key = item_rec[0];
var QM_rec = item_rec[1];
if (QM_rec.sdxInfo.sdxKeyValue == this.strip()) { return true; }
}
var dm_loc = 'i2b2.CRC.model.QueryMasters.'+i2b2.sdx.Master._KeyHash(sdxOptionalParent.sdxInfo.sdxKeyValue);
var targets = i2b2.CRC.model.QueryMasters.findAll(findFunc, sdxOptionalParent.sdxInfo.sdxKeyValue);
for (var i=0; i < targets.length; i++) {
var t = parent_QM[i].value;
t.children = new Hash();
}
} catch(e) { console.error('Could not clear children of given parent node!'); }
} else {
var dm_loc = 'i2b2.CRC.model.QueryMasters';
i2b2.CRC.model.QueryMasters.each(function(item_rec) {
try {
item_rec[1].children = new Hash();
} catch(e) { console.error('Could not clear children of all QueryMasters'); }
});
}
// TODO: send data update signal (use JOINING-MUTEX or AGGREGATING-MUTEX to avoid rapid fire of event!)
// updated dm_loc of the data model
return true;
}
// *********************************************************************************
// GENERATE HTML (DEFAULT HANDLER)
// *********************************************************************************
i2b2.sdx.TypeControllers.ENS.RenderHTML= function(sdxData, options, targetDiv) {
// OPTIONS:
// title: string
// showchildren: true | false
// cssClass: string
// icon: [data object]
// icon: (filename of img, appended to i2b2_root+cellDir + '/assets')
// iconExp: (filename of img, appended to i2b2_root+cellDir + '/assets')
// dragdrop: string (function name)
// context: string
// click: string
// dblclick: string
if (Object.isUndefined(options)) { options = {}; }
var render = {html: retHtml, htmlID: id};
var conceptId = sdxData.name;
var id = "CRC_ID-" + i2b2.GUID();
// process drag drop controllers
if (!Object.isUndefined(options.dragdrop)) {
// NOTE TO SELF: should attachment of node dragdrop controller be handled by the SDX system as well?
// This would ensure removal of the onmouseover call in a cross-browser way
var sDD = ' onmouseover="' + options.dragdrop + '(\''+ targetDiv.id +'\',\'' + id + '\')" ';
} else {
var sDD = '';
}
if (Object.isUndefined(options.cssClass)) { options.cssClass = 'sdxDefaultPRS';}
// user can override
bCanExp = true;
if (Object.isBoolean(options.showchildren)) {
bCanExp = options.showchildren;
}
render.canExpand = bCanExp;
render.iconType = "PRS";
if (!Object.isUndefined(options.icon)) { render.icon = i2b2.hive.cfg.urlFramework + 'cells/CRC/assets/'+ options.icon }
if (!Object.isUndefined(options.iconExp)) { render.iconExp = i2b2.hive.cfg.urlFramework + 'cells/CRC/assets/'+ options.iconExp }
// in cases of one set icon, copy valid icon to the missing icon
if (Object.isUndefined(render.icon) && !Object.isUndefined(render.iconExp)) { render.icon = render.iconExp; }
if (!Object.isUndefined(render.icon) && Object.isUndefined(render.iconExp)) { render.iconExp = render.icon; }
// handle the event controllers
var sMainEvents = sDD;
var sImgEvents = sDD;
// **** Render the HTML ***
var retHtml = '<DIV id="' + id + '" ' + sMainEvents + ' style="white-space:nowrap;cursor:pointer;">';
retHtml += '<DIV ';
if (Object.isString(options.cssClass)) {
retHtml += ' class="'+options.cssClass+'" ';
} else {
retHtml += ' class= "sdxDefaultPRS" ';
}
retHtml += sImgEvents;
retHtml += '>';
retHtml += '<IMG src="'+render.icon+'"/> ';
if (!Object.isUndefined(options.title)) {
retHtml += options.title;
} else {
console.warn('[SDX RenderHTML] no title was given in the creation options for an CRC > ENS node!');
retHtml += ' PRS '+id;
}
retHtml += '</DIV></DIV>';
render.html = retHtml;
render.htmlID = id;
var retObj = {};
Object.extend(retObj, sdxData);
retObj.renderData = render;
return retObj;
}
// *********************************************************************************
// HANDLE HOVER OVER TARGET ENTRY (DEFAULT HANDLER)
// *********************************************************************************
i2b2.sdx.TypeControllers.ENS.onHoverOver = function(e, id, ddProxy) {
var el = $(id);
if (el) { Element.addClassName(el,'ddPRSTarget'); }
}
// *********************************************************************************
// HANDLE HOVER OVER TARGET EXIT (DEFAULT HANDLER)
// *********************************************************************************
i2b2.sdx.TypeControllers.ENS.onHoverOut = function(e, id, ddProxy) {
var el = $(id);
if (el) { Element.removeClassName(el,'ddPRSTarget'); }
}
// *********************************************************************************
// ADD DATA TO TREENODE (DEFAULT HANDLER)
// *********************************************************************************
i2b2.sdx.TypeControllers.ENS.AppendTreeNode = function(yuiTree, yuiRootNode, sdxDataPack, callbackLoader) {
var myobj = { html: sdxDataPack.renderData.html, nodeid: sdxDataPack.renderData.htmlID}
var tmpNode = new YAHOO.widget.HTMLNode(myobj, yuiRootNode, false, true);
if (sdxDataPack.renderData.canExpand && !Object.isUndefined(callbackLoader)) {
// add the callback to load child nodes
sdxDataPack.sdxInfo.sdxLoadChildren = callbackLoader;
}
tmpNode.data.i2b2_SDX= sdxDataPack;
tmpNode.toggle = function() {
if (!this.tree.locked && ( this.hasChildren(true) ) ) {
var data = this.data.i2b2_SDX.renderData;
var img = this.getContentEl();
img = Element.select(img,'img')[0];
if (this.expanded) {
img.src = data.icon;
this.collapse();
} else {
img.src = data.iconExp;
this.expand();
}
}
};
if (!sdxDataPack.renderData.canExpand) { tmpNode.dynamicLoadComplete = true; }
return tmpNode;
}
// *********************************************************************************
// ATTACH DRAG TO DATA (DEFAULT HANDLER)
// *********************************************************************************
i2b2.sdx.TypeControllers.ENS.AttachDrag2Data = function(divParentID, divDataID){
if (Object.isUndefined($(divDataID))) { return false; }
// get the i2b2 data from the yuiTree node
var tvTree = YAHOO.widget.TreeView.getTree(divParentID);
var tvNode = tvTree.getNodeByProperty('nodeid', divDataID);
if (!Object.isUndefined(tvNode.DDProxy)) { return true; }
// attach DD
var t = new i2b2.sdx.TypeControllers.ENS.DragDrop(divDataID)
t.yuiTree = tvTree;
t.yuiTreeNode = tvNode;
tvNode.DDProxy = t;
// clear the mouseover attachment function
var tdn = $(divDataID);
if (!Object.isUndefined(tdn.onmouseover)) {
try {
delete tdn.onmouseover;
} catch(e) {
tdn.onmouseover;
}
}
if (!Object.isUndefined(tdn.attributes)) {
for (var i=0;i<tdn.attributes.length; i++) {
if (tdn.attributes[i].name=="onmouseover") {
try {
delete tdn.onmouseover;
} catch(e) {
tdn.onmouseover;
}
}
}
}
}
/**
* Get the child records for the given PatientRecordSet.
* @param {Object} sdxParentNode The parent node we want to find the children of.
* @param {ScopedCallback} onCompleteCallback A scoped-callback function to be executed using the results array.
* @return {Boolean} Returns true to the calling function.
* @return {Array} Returns an array of PatientRecord data represented as SDX Objects (without render data) to the callback function passed.
* @memberOf i2b2.sdx.TypeControllers.QI
* @method
* @author Nick Benik
* @version 1.0
* @alias i2b2.sdx.Master.getChildRecords
*/
i2b2.sdx.TypeControllers.ENS.getChildRecords = function(sdxParentNode, onCompleteCallback, options) {
var scopedCallback = new i2b2_scopedCallback();
scopedCallback.scope = sdxParentNode;
scopedCallback.callback = function(results) {
var cl_node = sdxParentNode;
var cl_onCompleteCB = onCompleteCallback;
// THIS function is used to process the AJAX results of the getChild call
// results data object contains the following attributes:
// refXML: xmlDomObject <--- for data processing
// msgRequest: xml (string)
// msgResponse: xml (string)
// error: boolean
// errorStatus: string [only with error=true]
// errorMsg: string [only with error=true]
var retMsg = {
error: results.error,
msgRequest: results.msgRequest,
msgResponse: results.msgResponse,
msgUrl: results.msgUrl,
results: null
};
var retChildren = [];
// extract records from XML msg
var ps = results.refXML.getElementsByTagName('event');
var dm = i2b2.CRC.model.QueryMasters;
for(var i1=0; i1<ps.length; i1++) {
var o = new Object;
o.xmlOrig = ps[i1];
o.patient_id = i2b2.h.getXNodeVal(ps[i1],'patient_id');
o.event_id = i2b2.h.getXNodeVal(ps[i1],'event_id');
//o.vital_status = i2b2.h.XPath(ps[i1],'param[@name="vital_status_cd"]/text()')[0].nodeValue;
//o.age = i2b2.h.XPath(ps[i1],'param[@name="age_in_years_num"]/text()')[0].nodeValue;
//o.sex = i2b2.h.XPath(ps[i1],'param[@name="sex_cd"]/text()')[0].nodeValue;
//o.race = i2b2.h.XPath(ps[i1],'param[@name="race_cd"]/text()')[0].nodeValue;
//o.title = o.patient_id+" ["+o.age+" y/o "+ o.sex+" "+o.race+"]";
var sdxDataNode = i2b2.sdx.Master.EncapsulateData('PR',o);
// save record in the SDX system
sdxDataNode = i2b2.sdx.Master.Save(sdxDataNode, cl_node);
// append the data node to our returned results
retChildren.push(sdxDataNode);
}
cl_node.children.loaded = true;
// TODO: broadcast a data update event of the CRC data model
retMsg.results = retChildren;
if (getObjectClass(cl_onCompleteCB)=='i2b2_scopedCallback') {
cl_onCompleteCB.callback.call(cl_onCompleteCB.scope, retMsg);
} else {
cl_onCompleteCB(retMsg);
}
}
var msg_filter = '<input_list>\n' +
' <event_list max="1000000" min="0">\n'+
' <patient_event_coll_id>'+sdxParentNode.sdxInfo.sdxKeyValue+'</patient_event_coll_id>\n'+
' </event_list>\n'+
'</input_list>\n'+
'<filter_list/>\n'+
'<output_option>\n'+
' <event_set select="using_input_list" onlykeys="true"/>\n'+
'</output_option>\n';
// AJAX CALL
var options = {
patient_limit: 0,
PDO_Request: msg_filter
};
i2b2.CRC.ajax.getPDO_fromInputList("CRC:SDX:PatientRecordSet", options, scopedCallback);
}
i2b2.sdx.TypeControllers.ENS.LoadChildrenFromTreeview = function(node, onCompleteCallback) {
var scopedCallback = new i2b2_scopedCallback();
scopedCallback.scope = node.data.i2b2_SDX;
scopedCallback.callback = function(retCellPack) {
var cl_node = node;
var cl_onCompleteCB = onCompleteCallback;
var results = retCellPack.results;
for(var i1=0; i1<1*results.length; i1++) {
var o = results[i1];
var renderOptions = {
dragdrop: "i2b2.sdx.TypeControllers.PRC.AttachDrag2Data",
icon: "sdx_CRC_PR.jpg",
title: o.sdxInfo.sdxDisplayName,
showchildren: false
};
var sdxRenderData = i2b2.sdx.Master.RenderHTML(cl_node.tree.id, o, renderOptions);
i2b2.sdx.Master.AppendTreeNode(cl_node.tree, cl_node, sdxRenderData);
}
// handle the callback
if (getObjectClass(cl_onCompleteCB)=='i2b2_scopedCallback') {
cl_onCompleteCB.callback.call(cl_onCompleteCB.scope, retCellPack);
} else {
cl_onCompleteCB(retCellPack);
}
}
var sdxParentNode = node.data.i2b2_SDX;
var options = i2b2.CRC.params;
i2b2.sdx.Master.getChildRecords(sdxParentNode, scopedCallback, options);
}
// *********************************************************************************
// DRAG DROP PROXY CONTROLLER
// *********************************************************************************
i2b2.sdx.TypeControllers.ENS.DragDrop = function(id, config) {
if (id) {
this.init(id, 'ENS',{isTarget:false});
this.initFrame();
}
var s = this.getDragEl().style;
s.borderColor = "transparent";
s.opacity = 0.75;
s.filter = "alpha(opacity=75)";
s.whiteSpace = "nowrap";
s.overflow = "hidden";
s.textOverflow = "ellipsis";
};
YAHOO.extend(i2b2.sdx.TypeControllers.ENS.DragDrop, YAHOO.util.DDProxy);
i2b2.sdx.TypeControllers.ENS.DragDrop.prototype.startDrag = function(x, y) {
var dragEl = this.getDragEl();
var clickEl = this.getEl();
dragEl.innerHTML = clickEl.innerHTML;
dragEl.className = clickEl.className;
dragEl.style.backgroundColor = '#FFFFEE';
dragEl.style.color = clickEl.style.color;
dragEl.style.border = "1px solid blue";
dragEl.style.width = "160px";
dragEl.style.height = "20px";
this.setDelta(15,10);
};
i2b2.sdx.TypeControllers.ENS.DragDrop.prototype.endDrag = function(e) {
// remove DragDrop targeting CCS
var targets = YAHOO.util.DDM.getRelated(this, true);
for (var i=0; i<targets.length; i++) {
var targetEl = targets[i]._domRef;
i2b2.sdx.Master.onHoverOut('ENS', e, targetEl, this);
}
};
i2b2.sdx.TypeControllers.ENS.DragDrop.prototype.alignElWithMouse = function(el, iPageX, iPageY) {
var oCoord = this.getTargetCoord(iPageX, iPageY);
if (!this.deltaSetXY) {
var aCoord = [oCoord.x, oCoord.y];
YAHOO.util.Dom.setXY(el, aCoord);
var newLeft = parseInt( YAHOO.util.Dom.getStyle(el, "left"), 10 );
var newTop = parseInt( YAHOO.util.Dom.getStyle(el, "top" ), 10 );
this.deltaSetXY = [ newLeft - oCoord.x, newTop - oCoord.y ];
} else {
var posX = (oCoord.x + this.deltaSetXY[0]);
var posY = (oCoord.y + this.deltaSetXY[1]);
var scrSize = document.viewport.getDimensions();
var maxX = parseInt(scrSize.width-25-160);
var maxY = parseInt(scrSize.height-25);
if (posX > maxX) {posX = maxX;}
if (posX < 6) {posX = 6;}
if (posY > maxY) {posY = maxY;}
if (posY < 6) {posY = 6;}
YAHOO.util.Dom.setStyle(el, "left", posX + "px");
YAHOO.util.Dom.setStyle(el, "top", posY + "px");
}
this.cachePosition(oCoord.x, oCoord.y);
this.autoScroll(oCoord.x, oCoord.y, el.offsetHeight, el.offsetWidth);
};
i2b2.sdx.TypeControllers.ENS.DragDrop.prototype.onDragOver = function(e, id) {
// fire the onHoverOver (use SDX so targets can override default event handler)
i2b2.sdx.Master.onHoverOver('ENS', e, id, this);
};
i2b2.sdx.TypeControllers.ENS.DragDrop.prototype.onDragOut = function(e, id) {
// fire the onHoverOut handler (use SDX so targets can override default event handlers)
i2b2.sdx.Master.onHoverOut('ENS', e, id, this);
};
i2b2.sdx.TypeControllers.ENS.DragDrop.prototype.onDragDrop = function(e, id) {
i2b2.sdx.Master.onHoverOut('ENS', e, id, this);
// retreive the concept data from the dragged element
draggedData = this.yuiTreeNode.data.i2b2_SDX;
i2b2.sdx.Master.ProcessDrop(draggedData, id);
};
// *********************************************************************************
// <BLANK> DROP HANDLER
// !!!! DO NOT EDIT - ATTACH YOUR OWN CUSTOM ROUTINE USING
// !!!! THE i2b2.sdx.Master.setHandlerCustom FUNCTION
// *********************************************************************************
i2b2.sdx.TypeControllers.ENS.DropHandler = function(sdxData) {
alert('[PatientRecordSet DROPPED] You need to create your own custom drop event handler.');
}
console.timeEnd('execute time');
console.groupEnd(); | rdalej/i2b2-shibboleth | build/web/webclient/js-i2b2/cells/CRC/CRC_sdx_ENS.js | JavaScript | apache-2.0 | 17,357 |
import AttributeCompression from "../Core/AttributeCompression.js";
import Cartesian3 from "../Core/Cartesian3.js";
import Cartographic from "../Core/Cartographic.js";
import Ellipsoid from "../Core/Ellipsoid.js";
import IndexDatatype from "../Core/IndexDatatype.js";
import CesiumMath from "../Core/Math.js";
import Rectangle from "../Core/Rectangle.js";
import createTaskProcessorWorker from "./createTaskProcessorWorker.js";
var maxShort = 32767;
var scratchBVCartographic = new Cartographic();
var scratchEncodedPosition = new Cartesian3();
function decodePositions(
positions,
rectangle,
minimumHeight,
maximumHeight,
ellipsoid
) {
var positionsLength = positions.length / 3;
var uBuffer = positions.subarray(0, positionsLength);
var vBuffer = positions.subarray(positionsLength, 2 * positionsLength);
var heightBuffer = positions.subarray(
2 * positionsLength,
3 * positionsLength
);
AttributeCompression.zigZagDeltaDecode(uBuffer, vBuffer, heightBuffer);
var decoded = new Float64Array(positions.length);
for (var i = 0; i < positionsLength; ++i) {
var u = uBuffer[i];
var v = vBuffer[i];
var h = heightBuffer[i];
var lon = CesiumMath.lerp(rectangle.west, rectangle.east, u / maxShort);
var lat = CesiumMath.lerp(rectangle.south, rectangle.north, v / maxShort);
var alt = CesiumMath.lerp(minimumHeight, maximumHeight, h / maxShort);
var cartographic = Cartographic.fromRadians(
lon,
lat,
alt,
scratchBVCartographic
);
var decodedPosition = ellipsoid.cartographicToCartesian(
cartographic,
scratchEncodedPosition
);
Cartesian3.pack(decodedPosition, decoded, i * 3);
}
return decoded;
}
var scratchRectangle = new Rectangle();
var scratchEllipsoid = new Ellipsoid();
var scratchCenter = new Cartesian3();
var scratchMinMaxHeights = {
min: undefined,
max: undefined,
};
function unpackBuffer(packedBuffer) {
packedBuffer = new Float64Array(packedBuffer);
var offset = 0;
scratchMinMaxHeights.min = packedBuffer[offset++];
scratchMinMaxHeights.max = packedBuffer[offset++];
Rectangle.unpack(packedBuffer, offset, scratchRectangle);
offset += Rectangle.packedLength;
Ellipsoid.unpack(packedBuffer, offset, scratchEllipsoid);
offset += Ellipsoid.packedLength;
Cartesian3.unpack(packedBuffer, offset, scratchCenter);
}
var scratchP0 = new Cartesian3();
var scratchP1 = new Cartesian3();
var scratchPrev = new Cartesian3();
var scratchCur = new Cartesian3();
var scratchNext = new Cartesian3();
function createVectorTilePolylines(parameters, transferableObjects) {
var encodedPositions = new Uint16Array(parameters.positions);
var widths = new Uint16Array(parameters.widths);
var counts = new Uint32Array(parameters.counts);
var batchIds = new Uint16Array(parameters.batchIds);
unpackBuffer(parameters.packedBuffer);
var rectangle = scratchRectangle;
var ellipsoid = scratchEllipsoid;
var center = scratchCenter;
var minimumHeight = scratchMinMaxHeights.min;
var maximumHeight = scratchMinMaxHeights.max;
var positions = decodePositions(
encodedPositions,
rectangle,
minimumHeight,
maximumHeight,
ellipsoid
);
var positionsLength = positions.length / 3;
var size = positionsLength * 4 - 4;
var curPositions = new Float32Array(size * 3);
var prevPositions = new Float32Array(size * 3);
var nextPositions = new Float32Array(size * 3);
var expandAndWidth = new Float32Array(size * 2);
var vertexBatchIds = new Uint16Array(size);
var positionIndex = 0;
var expandAndWidthIndex = 0;
var batchIdIndex = 0;
var i;
var offset = 0;
var length = counts.length;
for (i = 0; i < length; ++i) {
var count = counts[i];
var width = widths[i];
var batchId = batchIds[i];
for (var j = 0; j < count; ++j) {
var previous;
if (j === 0) {
var p0 = Cartesian3.unpack(positions, offset * 3, scratchP0);
var p1 = Cartesian3.unpack(positions, (offset + 1) * 3, scratchP1);
previous = Cartesian3.subtract(p0, p1, scratchPrev);
Cartesian3.add(p0, previous, previous);
} else {
previous = Cartesian3.unpack(
positions,
(offset + j - 1) * 3,
scratchPrev
);
}
var current = Cartesian3.unpack(positions, (offset + j) * 3, scratchCur);
var next;
if (j === count - 1) {
var p2 = Cartesian3.unpack(
positions,
(offset + count - 1) * 3,
scratchP0
);
var p3 = Cartesian3.unpack(
positions,
(offset + count - 2) * 3,
scratchP1
);
next = Cartesian3.subtract(p2, p3, scratchNext);
Cartesian3.add(p2, next, next);
} else {
next = Cartesian3.unpack(positions, (offset + j + 1) * 3, scratchNext);
}
Cartesian3.subtract(previous, center, previous);
Cartesian3.subtract(current, center, current);
Cartesian3.subtract(next, center, next);
var startK = j === 0 ? 2 : 0;
var endK = j === count - 1 ? 2 : 4;
for (var k = startK; k < endK; ++k) {
Cartesian3.pack(current, curPositions, positionIndex);
Cartesian3.pack(previous, prevPositions, positionIndex);
Cartesian3.pack(next, nextPositions, positionIndex);
positionIndex += 3;
var direction = k - 2 < 0 ? -1.0 : 1.0;
expandAndWidth[expandAndWidthIndex++] = 2 * (k % 2) - 1;
expandAndWidth[expandAndWidthIndex++] = direction * width;
vertexBatchIds[batchIdIndex++] = batchId;
}
}
offset += count;
}
var indices = IndexDatatype.createTypedArray(size, positionsLength * 6 - 6);
var index = 0;
var indicesIndex = 0;
length = positionsLength - 1;
for (i = 0; i < length; ++i) {
indices[indicesIndex++] = index;
indices[indicesIndex++] = index + 2;
indices[indicesIndex++] = index + 1;
indices[indicesIndex++] = index + 1;
indices[indicesIndex++] = index + 2;
indices[indicesIndex++] = index + 3;
index += 4;
}
transferableObjects.push(
curPositions.buffer,
prevPositions.buffer,
nextPositions.buffer
);
transferableObjects.push(
expandAndWidth.buffer,
vertexBatchIds.buffer,
indices.buffer
);
return {
indexDatatype:
indices.BYTES_PER_ELEMENT === 2
? IndexDatatype.UNSIGNED_SHORT
: IndexDatatype.UNSIGNED_INT,
currentPositions: curPositions.buffer,
previousPositions: prevPositions.buffer,
nextPositions: nextPositions.buffer,
expandAndWidth: expandAndWidth.buffer,
batchIds: vertexBatchIds.buffer,
indices: indices.buffer,
};
}
export default createTaskProcessorWorker(createVectorTilePolylines);
| progsung/cesium | Source/WorkersES6/createVectorTilePolylines.js | JavaScript | apache-2.0 | 6,753 |
'use strict';
angular.module('publisherApp')
.config(function ($stateProvider) {
$stateProvider
.state('settings', {
parent: 'account',
url: '/settings',
data: {
roles: ['ROLE_USER'],
pageTitle: 'global.menu.account.settings'
},
views: {
'container@': {
templateUrl: 'scripts/app/account/settings/settings.html',
controller: 'SettingsController'
}
},
resolve: {
translatePartialLoader: ['$translate', '$translatePartialLoader', function ($translate, $translatePartialLoader) {
$translatePartialLoader.addPart('settings');
return $translate.refresh();
}]
}
});
});
| GIP-RECIA/esup-publisher-ui | src/main/webapp/scripts/app/account/settings/settings.js | JavaScript | apache-2.0 | 949 |
/**
* @author caspar - chengzhihang
* @contact [email protected]
* @date 2016/12/29
* @file admin/view-partial/main/order/widget/form/value-widget/TpNameText
*/
define([
'zh/widget/text/ValidationTextBox',
'admin/services/enums/OrderPropertyEnum',
"dojo/_base/declare"
], function (TextBox, OrderPropertyEnum, declare) {
return declare('admin/view-partial/main/order/widget/form/value-widget/TpNameText', [TextBox], {
label: OrderPropertyEnum.TpName.text,
name: OrderPropertyEnum.TpName.id,
placeHolder: OrderPropertyEnum.TpName.text,
});
}); | Caspar12/zh.sw | zh-site-manager-web-ui-admin/target/classes/static/app/admin/view-partial/main/order/widget/form/value-widget/TpNameText.js | JavaScript | apache-2.0 | 590 |
import React, { Component, Fragment } from 'react';
import { navigate } from '@reach/router';
import PropTypes from 'prop-types';
import { Dropdown, DropdownToggle, DropdownMenu, DropdownItem } from 'reactstrap';
import { siteRoot, gettext, orgID } from '../../utils/constants';
import { seafileAPI } from '../../utils/seafile-api';
import { Utils } from '../../utils/utils';
import toaster from '../../components/toast';
import OrgGroupInfo from '../../models/org-group';
import MainPanelTopbar from './main-panel-topbar';
class Search extends React.Component {
constructor(props) {
super(props);
this.state = {
value: ''
};
}
handleInputChange = (e) => {
this.setState({
value: e.target.value
});
}
handleKeyPress = (e) => {
if (e.key == 'Enter') {
e.preventDefault();
this.handleSubmit();
}
}
handleSubmit = () => {
const value = this.state.value.trim();
if (!value) {
return false;
}
this.props.submit(value);
}
render() {
return (
<div className="input-icon">
<i className="d-flex input-icon-addon fas fa-search"></i>
<input
type="text"
className="form-control search-input h-6 mr-1"
style={{width: '15rem'}}
placeholder={this.props.placeholder}
value={this.state.value}
onChange={this.handleInputChange}
onKeyPress={this.handleKeyPress}
autoComplete="off"
/>
</div>
);
}
}
class OrgGroups extends Component {
constructor(props) {
super(props);
this.state = {
page: 1,
pageNext: false,
orgGroups: [],
isItemFreezed: false
};
}
componentDidMount() {
let page = this.state.page;
this.initData(page);
}
initData = (page) => {
seafileAPI.orgAdminListOrgGroups(orgID, page).then(res => {
let orgGroups = res.data.groups.map(item => {
return new OrgGroupInfo(item);
});
this.setState({
orgGroups: orgGroups,
pageNext: res.data.page_next,
page: res.data.page,
});
}).catch(error => {
let errMessage = Utils.getErrorMsg(error);
toaster.danger(errMessage);
});
}
onChangePageNum = (e, num) => {
e.preventDefault();
let page = this.state.page;
if (num == 1) {
page = page + 1;
} else {
page = page - 1;
}
this.initData(page);
}
onFreezedItem = () => {
this.setState({isItemFreezed: true});
}
onUnfreezedItem = () => {
this.setState({isItemFreezed: false});
}
deleteGroupItem = (group) => {
seafileAPI.orgAdminDeleteOrgGroup(orgID, group.id).then(res => {
this.setState({
orgGroups: this.state.orgGroups.filter(item => item.id != group.id)
});
let msg = gettext('Successfully deleted {name}');
msg = msg.replace('{name}', group.groupName);
toaster.success(msg);
}).catch(error => {
let errMessage = Utils.getErrorMsg(error);
toaster.danger(errMessage);
});
}
searchItems = (keyword) => {
navigate(`${siteRoot}org/groupadmin/search-groups/?query=${encodeURIComponent(keyword)}`);
}
getSearch = () => {
return <Search
placeholder={gettext('Search groups by name')}
submit={this.searchItems}
/>;
}
render() {
let groups = this.state.orgGroups;
return (
<Fragment>
<MainPanelTopbar search={this.getSearch()}/>
<div className="main-panel-center flex-row">
<div className="cur-view-container">
<div className="cur-view-path">
<h3 className="sf-heading">{gettext('All Groups')}</h3>
</div>
<div className="cur-view-content">
<table>
<thead>
<tr>
<th width="30%">{gettext('Name')}</th>
<th width="35%">{gettext('Creator')}</th>
<th width="23%">{gettext('Created At')}</th>
<th width="12%" className="text-center">{gettext('Operations')}</th>
</tr>
</thead>
<tbody>
{groups.map(item => {
return (
<GroupItem
key={item.id}
group={item}
isItemFreezed={this.state.isItemFreezed}
onFreezedItem={this.onFreezedItem}
onUnfreezedItem={this.onUnfreezedItem}
deleteGroupItem={this.deleteGroupItem}
/>
);
})}
</tbody>
</table>
<div className="paginator">
{this.state.page != 1 && <a href="#" onClick={(e) => this.onChangePageNum(e, -1)}>{gettext('Previous')}</a>}
{(this.state.page != 1 && this.state.pageNext) && <span> | </span>}
{this.state.pageNext && <a href="#" onClick={(e) => this.onChangePageNum(e, 1)}>{gettext('Next')}</a>}
</div>
</div>
</div>
</div>
</Fragment>
);
}
}
const GroupItemPropTypes = {
group: PropTypes.object.isRequired,
isItemFreezed: PropTypes.bool.isRequired,
onFreezedItem: PropTypes.func.isRequired,
onUnfreezedItem: PropTypes.func.isRequired,
deleteGroupItem: PropTypes.func.isRequired,
};
class GroupItem extends React.Component {
constructor(props) {
super(props);
this.state = {
highlight: false,
showMenu: false,
isItemMenuShow: false
};
}
onMouseEnter = () => {
if (!this.props.isItemFreezed) {
this.setState({
showMenu: true,
highlight: true,
});
}
}
onMouseLeave = () => {
if (!this.props.isItemFreezed) {
this.setState({
showMenu: false,
highlight: false
});
}
}
onDropdownToggleClick = (e) => {
e.preventDefault();
this.toggleOperationMenu(e);
}
toggleOperationMenu = (e) => {
e.stopPropagation();
this.setState(
{isItemMenuShow: !this.state.isItemMenuShow }, () => {
if (this.state.isItemMenuShow) {
this.props.onFreezedItem();
} else {
this.setState({
highlight: false,
showMenu: false,
});
this.props.onUnfreezedItem();
}
}
);
}
toggleDelete = () => {
this.props.deleteGroupItem(this.props.group);
}
renderGroupHref = (group) => {
let groupInfoHref;
if (group.creatorName == 'system admin') {
groupInfoHref = siteRoot + 'org/departmentadmin/groups/' + group.id + '/';
} else {
groupInfoHref = siteRoot + 'org/groupadmin/' + group.id + '/';
}
return groupInfoHref;
}
renderGroupCreator = (group) => {
let userInfoHref = siteRoot + 'org/useradmin/info/' + group.creatorEmail + '/';
if (group.creatorName == 'system admin') {
return (
<td> -- </td>
);
} else {
return(
<td>
<a href={userInfoHref} className="font-weight-normal">{group.creatorName}</a>
</td>
);
}
}
render() {
let { group } = this.props;
let isOperationMenuShow = (group.creatorName != 'system admin') && this.state.showMenu;
return (
<tr className={this.state.highlight ? 'tr-highlight' : ''} onMouseEnter={this.onMouseEnter} onMouseLeave={this.onMouseLeave}>
<td>
<a href={this.renderGroupHref(group)} className="font-weight-normal">{group.groupName}</a>
</td>
{this.renderGroupCreator(group)}
<td>{group.ctime}</td>
<td className="text-center cursor-pointer">
{isOperationMenuShow &&
<Dropdown isOpen={this.state.isItemMenuShow} toggle={this.toggleOperationMenu}>
<DropdownToggle
tag="a"
className="attr-action-icon fas fa-ellipsis-v"
title={gettext('More Operations')}
data-toggle="dropdown"
aria-expanded={this.state.isItemMenuShow}
onClick={this.onDropdownToggleClick}
/>
<DropdownMenu>
<DropdownItem onClick={this.toggleDelete}>{gettext('Delete')}</DropdownItem>
</DropdownMenu>
</Dropdown>
}
</td>
</tr>
);
}
}
GroupItem.propTypes = GroupItemPropTypes;
export default OrgGroups;
| miurahr/seahub | frontend/src/pages/org-admin/org-groups.js | JavaScript | apache-2.0 | 8,470 |
import {boolean, number, object, text, withKnobs} from '@storybook/addon-knobs';
import {
BentoAccordion,
BentoAccordionContent,
BentoAccordionHeader,
BentoAccordionSection,
} from '#bento/components/bento-accordion/1.0/component';
import {BentoVideo} from '#bento/components/bento-video/1.0/component';
import * as Preact from '#preact';
import '#bento/components/bento-video/1.0/component.jss';
export default {
title: 'Video',
component: BentoVideo,
decorators: [withKnobs],
};
const VideoTagPlayer = ({i}) => {
const group = `Player ${i + 1}`;
const width = text('width', '640px', group);
const height = text('height', '360px', group);
const ariaLabel = text('aria-label', 'Video Player', group);
const autoplay = boolean('autoplay', true, group);
const controls = boolean('controls', true, group);
const mediasession = boolean('mediasession', true, group);
const noaudio = boolean('noaudio', false, group);
const loop = boolean('loop', false, group);
const poster = text(
'poster',
'https://amp.dev/static/inline-examples/images/kitten-playing.png',
group
);
const artist = text('artist', '', group);
const album = text('album', '', group);
const artwork = text('artwork', '', group);
const title = text('title', '', group);
const sources = object(
'sources',
[
{
src: 'https://amp.dev/static/inline-examples/videos/kitten-playing.webm',
type: 'video/webm',
},
{
src: 'https://amp.dev/static/inline-examples/videos/kitten-playing.mp4',
type: 'video/mp4',
},
],
group
);
return (
<BentoVideo
component="video"
aria-label={ariaLabel}
autoplay={autoplay}
controls={controls}
mediasession={mediasession}
noaudio={noaudio}
loop={loop}
poster={poster}
artist={artist}
album={album}
artwork={artwork}
title={title}
style={{width, height}}
sources={sources.map((props) => (
<source {...props}></source>
))}
/>
);
};
const Spacer = ({height}) => {
return (
<div
style={{
height,
background: `linear-gradient(to bottom, #bbb, #bbb 10%, #fff 10%, #fff)`,
backgroundSize: '100% 10px',
}}
></div>
);
};
export const Default = () => {
const amount = number('Amount', 1, {}, 'Page');
const spacerHeight = text('Space', '80vh', 'Page');
const spaceAbove = boolean('Space above', false, 'Page');
const spaceBelow = boolean('Space below', false, 'Page');
const players = [];
for (let i = 0; i < amount; i++) {
players.push(<VideoTagPlayer key={i} i={i} />);
if (i < amount - 1) {
players.push(<Spacer height={spacerHeight} />);
}
}
return (
<>
{spaceAbove && <Spacer height={spacerHeight} />}
{players}
{spaceBelow && <Spacer height={spacerHeight} />}
</>
);
};
export const InsideAccordion = () => {
const width = text('width', '320px');
const height = text('height', '180px');
return (
<BentoAccordion expandSingleSection>
<BentoAccordionSection key={1} expanded>
<BentoAccordionHeader>
<h2>Controls</h2>
</BentoAccordionHeader>
<BentoAccordionContent>
<BentoVideo
component="video"
controls={true}
loop={true}
style={{width, height}}
src="https://amp.dev/static/inline-examples/videos/kitten-playing.mp4"
poster="https://amp.dev/static/inline-examples/images/kitten-playing.png"
/>
</BentoAccordionContent>
</BentoAccordionSection>
<BentoAccordionSection key={2}>
<BentoAccordionHeader>
<h2>Autoplay</h2>
</BentoAccordionHeader>
<BentoAccordionContent>
<BentoVideo
component="video"
autoplay={true}
loop={true}
style={{width, height}}
src="https://amp.dev/static/inline-examples/videos/kitten-playing.mp4"
poster="https://amp.dev/static/inline-examples/images/kitten-playing.png"
sources={[
<source
type="video/mp4"
src="https://amp.dev/static/inline-examples/videos/kitten-playing.mp4"
/>,
]}
/>
</BentoAccordionContent>
</BentoAccordionSection>
</BentoAccordion>
);
};
| ampproject/amphtml | extensions/amp-video/1.0/storybook/Basic.js | JavaScript | apache-2.0 | 4,420 |
import { registerBidder } from '../src/adapters/bidderFactory.js';
import { BANNER, NATIVE, VIDEO } from '../src/mediaTypes.js';
import * as utils from '../src/utils.js';
import { config } from '../src/config.js';
const BIDDER_CODE = 'gothamads';
const ACCOUNTID_MACROS = '[account_id]';
const URL_ENDPOINT = `https://us-e-node1.gothamads.com/bid?pass=${ACCOUNTID_MACROS}&integration=prebidjs`;
const NATIVE_ASSET_IDS = {
0: 'title',
2: 'icon',
3: 'image',
5: 'sponsoredBy',
4: 'body',
1: 'cta'
};
const NATIVE_PARAMS = {
title: {
id: 0,
name: 'title'
},
icon: {
id: 2,
type: 1,
name: 'img'
},
image: {
id: 3,
type: 3,
name: 'img'
},
sponsoredBy: {
id: 5,
name: 'data',
type: 1
},
body: {
id: 4,
name: 'data',
type: 2
},
cta: {
id: 1,
type: 12,
name: 'data'
}
};
const NATIVE_VERSION = '1.2';
export const spec = {
code: BIDDER_CODE,
supportedMediaTypes: [BANNER, VIDEO, NATIVE],
/**
* Determines whether or not the given bid request is valid.
*
* @param {object} bid The bid to validate.
* @return boolean True if this is a valid bid, and false otherwise.
*/
isBidRequestValid: (bid) => {
return Boolean(bid.params.accountId) && Boolean(bid.params.placementId)
},
/**
* Make a server request from the list of BidRequests.
*
* @param {BidRequest[]} validBidRequests A non-empty list of valid bid requests that should be sent to the Server.
* @return ServerRequest Info describing the request to the server.
*/
buildRequests: (validBidRequests, bidderRequest) => {
if (validBidRequests && validBidRequests.length === 0) return []
let accuontId = validBidRequests[0].params.accountId;
const endpointURL = URL_ENDPOINT.replace(ACCOUNTID_MACROS, accuontId);
let winTop = window;
let location;
try {
location = new URL(bidderRequest.refererInfo.referer)
winTop = window.top;
} catch (e) {
location = winTop.location;
utils.logMessage(e);
};
let bids = [];
for (let bidRequest of validBidRequests) {
let impObject = prepareImpObject(bidRequest);
let data = {
id: bidRequest.bidId,
test: config.getConfig('debug') ? 1 : 0,
cur: ['USD'],
device: {
w: winTop.screen.width,
h: winTop.screen.height,
language: (navigator && navigator.language) ? navigator.language.indexOf('-') != -1 ? navigator.language.split('-')[0] : navigator.language : '',
},
site: {
page: location.pathname,
host: location.host
},
source: {
tid: bidRequest.transactionId
},
regs: {
coppa: config.getConfig('coppa') === true ? 1 : 0,
ext: {}
},
tmax: bidRequest.timeout,
imp: [impObject],
};
if (bidRequest.gdprConsent && bidRequest.gdprConsent.gdprApplies) {
utils.deepSetValue(data, 'regs.ext.gdpr', bidRequest.gdprConsent.gdprApplies ? 1 : 0);
utils.deepSetValue(data, 'user.ext.consent', bidRequest.gdprConsent.consentString);
}
if (bidRequest.uspConsent !== undefined) {
utils.deepSetValue(data, 'regs.ext.us_privacy', bidRequest.uspConsent);
}
bids.push(data)
}
return {
method: 'POST',
url: endpointURL,
data: bids
};
},
/**
* Unpack the response from the server into a list of bids.
*
* @param {*} serverResponse A successful response from the server.
* @return {Bid[]} An array of bids which were nested inside the server.
*/
interpretResponse: (serverResponse) => {
if (!serverResponse || !serverResponse.body) return []
let GothamAdsResponse = serverResponse.body;
let bids = [];
for (let response of GothamAdsResponse) {
let mediaType = response.seatbid[0].bid[0].ext && response.seatbid[0].bid[0].ext.mediaType ? response.seatbid[0].bid[0].ext.mediaType : BANNER;
let bid = {
requestId: response.id,
cpm: response.seatbid[0].bid[0].price,
width: response.seatbid[0].bid[0].w,
height: response.seatbid[0].bid[0].h,
ttl: response.ttl || 1200,
currency: response.cur || 'USD',
netRevenue: true,
creativeId: response.seatbid[0].bid[0].crid,
dealId: response.seatbid[0].bid[0].dealid,
mediaType: mediaType
};
bid.meta = {};
if (response.seatbid[0].bid[0].adomain && response.seatbid[0].bid[0].adomain.length > 0) {
bid.meta.advertiserDomains = response.seatbid[0].bid[0].adomain;
}
switch (mediaType) {
case VIDEO:
bid.vastXml = response.seatbid[0].bid[0].adm;
bid.vastUrl = response.seatbid[0].bid[0].ext.vastUrl;
break;
case NATIVE:
bid.native = parseNative(response.seatbid[0].bid[0].adm);
break;
default:
bid.ad = response.seatbid[0].bid[0].adm;
}
bids.push(bid);
}
return bids;
},
};
/**
* Determine type of request
*
* @param bidRequest
* @param type
* @returns {boolean}
*/
const checkRequestType = (bidRequest, type) => {
return (typeof utils.deepAccess(bidRequest, `mediaTypes.${type}`) !== 'undefined');
}
const parseNative = admObject => {
const {
assets,
link,
imptrackers,
jstracker
} = admObject.native;
const result = {
clickUrl: link.url,
clickTrackers: link.clicktrackers || undefined,
impressionTrackers: imptrackers || undefined,
javascriptTrackers: jstracker ? [jstracker] : undefined
};
assets.forEach(asset => {
const kind = NATIVE_ASSET_IDS[asset.id];
const content = kind && asset[NATIVE_PARAMS[kind].name];
if (content) {
result[kind] = content.text || content.value || {
url: content.url,
width: content.w,
height: content.h
};
}
});
return result;
}
const prepareImpObject = (bidRequest) => {
let impObject = {
id: bidRequest.transactionId,
secure: 1,
ext: {
placementId: bidRequest.params.placementId
}
};
if (checkRequestType(bidRequest, BANNER)) {
impObject.banner = addBannerParameters(bidRequest);
}
if (checkRequestType(bidRequest, VIDEO)) {
impObject.video = addVideoParameters(bidRequest);
}
if (checkRequestType(bidRequest, NATIVE)) {
impObject.native = {
ver: NATIVE_VERSION,
request: addNativeParameters(bidRequest)
};
}
return impObject
};
const addNativeParameters = bidRequest => {
let impObject = {
id: bidRequest.transactionId,
ver: NATIVE_VERSION,
};
const assets = utils._map(bidRequest.mediaTypes.native, (bidParams, key) => {
const props = NATIVE_PARAMS[key];
const asset = {
required: bidParams.required & 1,
};
if (props) {
asset.id = props.id;
let wmin, hmin;
let aRatios = bidParams.aspect_ratios;
if (aRatios && aRatios[0]) {
aRatios = aRatios[0];
wmin = aRatios.min_width || 0;
hmin = aRatios.ratio_height * wmin / aRatios.ratio_width | 0;
}
if (bidParams.sizes) {
const sizes = flatten(bidParams.sizes);
wmin = sizes[0];
hmin = sizes[1];
}
asset[props.name] = {}
if (bidParams.len) asset[props.name]['len'] = bidParams.len;
if (props.type) asset[props.name]['type'] = props.type;
if (wmin) asset[props.name]['wmin'] = wmin;
if (hmin) asset[props.name]['hmin'] = hmin;
return asset;
}
}).filter(Boolean);
impObject.assets = assets;
return impObject
}
const addBannerParameters = (bidRequest) => {
let bannerObject = {};
const size = parseSizes(bidRequest, 'banner');
bannerObject.w = size[0];
bannerObject.h = size[1];
return bannerObject;
};
const parseSizes = (bid, mediaType) => {
let mediaTypes = bid.mediaTypes;
if (mediaType === 'video') {
let size = [];
if (mediaTypes.video && mediaTypes.video.w && mediaTypes.video.h) {
size = [
mediaTypes.video.w,
mediaTypes.video.h
];
} else if (Array.isArray(utils.deepAccess(bid, 'mediaTypes.video.playerSize')) && bid.mediaTypes.video.playerSize.length === 1) {
size = bid.mediaTypes.video.playerSize[0];
} else if (Array.isArray(bid.sizes) && bid.sizes.length > 0 && Array.isArray(bid.sizes[0]) && bid.sizes[0].length > 1) {
size = bid.sizes[0];
}
return size;
}
let sizes = [];
if (Array.isArray(mediaTypes.banner.sizes)) {
sizes = mediaTypes.banner.sizes[0];
} else if (Array.isArray(bid.sizes) && bid.sizes.length > 0) {
sizes = bid.sizes
} else {
utils.logWarn('no sizes are setup or found');
}
return sizes
}
const addVideoParameters = (bidRequest) => {
let videoObj = {};
let supportParamsList = ['mimes', 'minduration', 'maxduration', 'protocols', 'startdelay', 'placement', 'skip', 'skipafter', 'minbitrate', 'maxbitrate', 'delivery', 'playbackmethod', 'api', 'linearity']
for (let param of supportParamsList) {
if (bidRequest.mediaTypes.video[param] !== undefined) {
videoObj[param] = bidRequest.mediaTypes.video[param];
}
}
const size = parseSizes(bidRequest, 'video');
videoObj.w = size[0];
videoObj.h = size[1];
return videoObj;
}
const flatten = arr => {
return [].concat(...arr);
}
registerBidder(spec);
| tchibirev/Prebid.js | modules/gothamadsBidAdapter.js | JavaScript | apache-2.0 | 9,383 |
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is
* regenerated.
*/
'use strict';
/**
* @class
* Initializes a new instance of the USqlExternalDataSourceList class.
* @constructor
* A Data Lake Analytics catalog U-SQL external datasource item list.
*
*/
class USqlExternalDataSourceList extends Array {
constructor() {
super();
}
/**
* Defines the metadata of USqlExternalDataSourceList
*
* @returns {object} metadata of USqlExternalDataSourceList
*
*/
mapper() {
return {
required: false,
serializedName: 'USqlExternalDataSourceList',
type: {
name: 'Composite',
className: 'USqlExternalDataSourceList',
modelProperties: {
nextLink: {
required: false,
serializedName: 'nextLink',
type: {
name: 'String'
}
},
value: {
required: false,
readOnly: true,
serializedName: '',
type: {
name: 'Sequence',
element: {
required: false,
serializedName: 'USqlExternalDataSourceElementType',
type: {
name: 'Composite',
className: 'USqlExternalDataSource'
}
}
}
}
}
}
};
}
}
module.exports = USqlExternalDataSourceList;
| AuxMon/azure-sdk-for-node | lib/services/dataLake.Analytics/lib/catalog/models/uSqlExternalDataSourceList.js | JavaScript | apache-2.0 | 1,673 |
/**
* @license
* Copyright 2015 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*/
CLASS({
name: 'LogEntryView',
package: 'foam.flow',
extends: 'foam.flow.Element',
constants: { ELEMENT_NAME: 'log-entry' },
properties: [
{
name: 'data',
// type: 'foam.flow.LogEntry'
}
],
templates: [
function toInnerHTML() {/*
<num>{{this.data.id}}</num><{{{this.data.mode}}}>{{this.data.contents}}</{{{this.data.mode}}}>
*/},
function CSS() {/*
log-entry {
display: flex;
}
log-entry > num {
min-width: 35px;
max-width: 35px;
display: inline-block;
text-align: right;
padding-right: 13px;
font-weight: bold;
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
background: #E0E0E0;
}
log-entry > log, log-entry > warn, log-entry > error {
padding-left: 4px;
white-space: pre-wrap;
}
log-entry > log {
color: #333;
}
log-entry > warn {
color: #CC9900;
}
log-entry > error {
color: #C00;
}
*/}
]
});
| jlhughes/foam | js/foam/flow/LogEntryView.js | JavaScript | apache-2.0 | 1,487 |
(function() {
function LandingCtrl() {
this.heroTitle = "Turn the Music Up!";
}
angular
.module('blocJams')
.controller('LandingCtrl', LandingCtrl);
})();
| ganaraja/bloc-jams-angular | dist/scripts/controllers/LandingCtrl.js | JavaScript | apache-2.0 | 195 |
/**
Copyright (c) 2013 The Chromium Authors. All rights reserved.
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file.
**/
require("../base/extension_registry.js");
require("./event.js");
require("./object_snapshot.js");
require("../base/range.js");
require("../base/sorted_array_utils.js");
'use strict';
/**
* @fileoverview Provides the ObjectSnapshot and ObjectHistory classes.
*/
global.tr.exportTo('tr.model', function() {
var ObjectSnapshot = tr.model.ObjectSnapshot;
/**
* An object with a specific id, whose state has been snapshotted several
* times.
*
* @constructor
*/
function ObjectInstance(
parent, id, category, name, creationTs, opt_baseTypeName) {
tr.model.Event.call(this);
this.parent = parent;
this.id = id;
this.category = category;
this.baseTypeName = opt_baseTypeName ? opt_baseTypeName : name;
this.name = name;
this.creationTs = creationTs;
this.creationTsWasExplicit = false;
this.deletionTs = Number.MAX_VALUE;
this.deletionTsWasExplicit = false;
this.colorId = 0;
this.bounds = new tr.b.Range();
this.snapshots = [];
this.hasImplicitSnapshots = false;
}
ObjectInstance.prototype = {
__proto__: tr.model.Event.prototype,
get typeName() {
return this.name;
},
addBoundsToRange: function(range) {
range.addRange(this.bounds);
},
addSnapshot: function(ts, args, opt_name, opt_baseTypeName) {
if (ts < this.creationTs)
throw new Error('Snapshots must be >= instance.creationTs');
if (ts >= this.deletionTs)
throw new Error('Snapshots cannot be added after ' +
'an objects deletion timestamp.');
var lastSnapshot;
if (this.snapshots.length > 0) {
lastSnapshot = this.snapshots[this.snapshots.length - 1];
if (lastSnapshot.ts == ts)
throw new Error('Snapshots already exists at this time!');
if (ts < lastSnapshot.ts) {
throw new Error(
'Snapshots must be added in increasing timestamp order');
}
}
// Update baseTypeName if needed.
if (opt_name &&
(this.name != opt_name)) {
if (!opt_baseTypeName)
throw new Error('Must provide base type name for name update');
if (this.baseTypeName != opt_baseTypeName)
throw new Error('Cannot update type name: base types dont match');
this.name = opt_name;
}
var snapshotConstructor =
tr.model.ObjectSnapshot.getConstructor(
this.category, this.name);
var snapshot = new snapshotConstructor(this, ts, args);
this.snapshots.push(snapshot);
return snapshot;
},
wasDeleted: function(ts) {
var lastSnapshot;
if (this.snapshots.length > 0) {
lastSnapshot = this.snapshots[this.snapshots.length - 1];
if (lastSnapshot.ts > ts)
throw new Error(
'Instance cannot be deleted at ts=' +
ts + '. A snapshot exists that is older.');
}
this.deletionTs = ts;
this.deletionTsWasExplicit = true;
},
/**
* See ObjectSnapshot constructor notes on object initialization.
*/
preInitialize: function() {
for (var i = 0; i < this.snapshots.length; i++)
this.snapshots[i].preInitialize();
},
/**
* See ObjectSnapshot constructor notes on object initialization.
*/
initialize: function() {
for (var i = 0; i < this.snapshots.length; i++)
this.snapshots[i].initialize();
},
getSnapshotAt: function(ts) {
if (ts < this.creationTs) {
if (this.creationTsWasExplicit)
throw new Error('ts must be within lifetime of this instance');
return this.snapshots[0];
}
if (ts > this.deletionTs)
throw new Error('ts must be within lifetime of this instance');
var snapshots = this.snapshots;
var i = tr.b.findIndexInSortedIntervals(
snapshots,
function(snapshot) { return snapshot.ts; },
function(snapshot, i) {
if (i == snapshots.length - 1)
return snapshots[i].objectInstance.deletionTs;
return snapshots[i + 1].ts - snapshots[i].ts;
},
ts);
if (i < 0) {
// Note, this is a little bit sketchy: this lets early ts point at the
// first snapshot, even before it is taken. We do this because raster
// tasks usually post before their tile snapshots are dumped. This may
// be a good line of code to re-visit if we start seeing strange and
// confusing object references showing up in the traces.
return this.snapshots[0];
}
if (i >= this.snapshots.length)
return this.snapshots[this.snapshots.length - 1];
return this.snapshots[i];
},
updateBounds: function() {
this.bounds.reset();
this.bounds.addValue(this.creationTs);
if (this.deletionTs != Number.MAX_VALUE)
this.bounds.addValue(this.deletionTs);
else if (this.snapshots.length > 0)
this.bounds.addValue(this.snapshots[this.snapshots.length - 1].ts);
},
shiftTimestampsForward: function(amount) {
this.creationTs += amount;
if (this.deletionTs != Number.MAX_VALUE)
this.deletionTs += amount;
this.snapshots.forEach(function(snapshot) {
snapshot.ts += amount;
});
},
get userFriendlyName() {
return this.typeName + ' object ' + this.id;
}
};
tr.model.EventRegistry.register(
ObjectInstance,
{
name: 'objectInstance',
pluralName: 'objectInstances',
singleViewElementName: 'tr-ui-a-single-object-instance-sub-view',
multiViewElementName: 'tr-ui-a-multi-object-sub-view'
});
var options = new tr.b.ExtensionRegistryOptions(
tr.b.TYPE_BASED_REGISTRY_MODE);
options.mandatoryBaseClass = ObjectInstance;
options.defaultConstructor = ObjectInstance;
tr.b.decorateExtensionRegistry(ObjectInstance, options);
return {
ObjectInstance: ObjectInstance
};
});
| googlearchive/node-big-rig | lib/third_party/tracing/model/object_instance.js | JavaScript | apache-2.0 | 6,147 |
/*
* Copyright (c) 2014 DataTorrent, Inc. ALL Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
angular.module('ui.widgets')
.directive('wtNvd3LineChart', function ($filter) {
return {
restrict: 'A',
replace: true,
templateUrl: 'template/widgets/nvd3LineChart/nvd3LineChart.html',
scope: {
data: '=data',
showLegend: '@',
showTimeRange: '=?',
timeAxisFormat: '=?'
},
controller: function ($scope) {
var filter = $filter('date');
var numberFilter = $filter('number');
$scope.xAxisTickFormatFunction = function () {
return function (d) {
return filter(d, $scope.timeAxisFormat);
};
};
$scope.yAxisTickFormatFunction = function () {
return function (d) {
if (d > 999) {
var value;
var scale;
if (d < 999999) {
value = Math.round(d/1000);
scale = 'k';
} else {
value = Math.round(d/1000000);
scale = 'm';
}
return numberFilter(value) + scale;
} else {
return numberFilter(d);
}
};
};
$scope.xFunction = function () {
return function (d) {
return d.timestamp;
};
};
$scope.yFunction = function () {
return function (d) {
return d.value;
};
};
},
link: function postLink(scope, element, attrs) {
if (!_.has(attrs, 'showTimeRange')) {
scope.showTimeRange = true;
}
scope.timeAxisFormat = scope.timeAxisFormat || 'HH:mm';
scope.$watch('data', function (data) {
if (data && data[0] && data[0].values && (data[0].values.length > 1)) {
var timeseries = _.sortBy(data[0].values, function (item) {
return item.timestamp;
});
var start = timeseries[0].timestamp;
var end = timeseries[timeseries.length - 1].timestamp;
scope.start = start;
scope.end = end;
}
});
}
};
}); | DataTorrent/malhar-angular-widgets | src/widgets/nvd3LineChart/nvd3LineChart.js | JavaScript | apache-2.0 | 2,754 |
/*
Copyright 2018 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
try { Object.defineProperty(Array.prototype, "peek", { value: function () { return (this.length > 0 ? this[this.length - 1] : undefined); } }); } catch (e) { }
try { Object.defineProperty(String.prototype, "replaceAll", { value: function replaceAll(oldVal, newVal) { return (this.split(oldVal).join(newVal)); } }); } catch (e) { }
var RSMB = 1381190978;
var memoryLocation = { 0x1: 'Other', 0x2: 'Unknown', 0x3: 'System Board', 0x4: 'ISA', 0x5: 'EISA', 0x6: 'PCI', 0x7: 'MCA', 0x8: 'PCMCIA', 0x9: 'Proprietary', 0xA: 'NuBus', 0xA0: 'PC-98/C20', 0xA1: 'PC-98/C24', 0xA2: 'PC-98/E', 0xA3: 'PC-98/LB' };
var wakeReason = ['Reserved', 'Other', 'Unknown', 'APM Timer', 'Modem Ring', 'LAN', 'Power Switch', 'PCI', 'AC Power'];
// Fill the left with zeros until the string is of a given length
function zeroLeftPad(str, len)
{
if ((len == null) && (typeof (len) != 'number')) { return null; }
if (str == null) str = ''; // If null, this is to generate zero leftpad string
var zlp = '';
for (var i = 0; i < len - str.length; i++) { zlp += '0'; }
return zlp + str;
}
function SMBiosTables()
{
this._ObjectID = 'SMBiosTable';
if (process.platform == 'win32') {
this._marshal = require('_GenericMarshal');
this._native = this._marshal.CreateNativeProxy("Kernel32.dll");
this._native.CreateMethod('EnumSystemFirmwareTables');
this._native.CreateMethod('GetSystemFirmwareTable');
}
if (process.platform == 'linux') {
this._canonicalizeData = function _canonicalizeData(data) {
var lines = data.toString().split('Header and Data:\x0A');
var MemoryStream = require('MemoryStream');
var ms = new MemoryStream();
for (var i = 1; i < lines.length; ++i) {
var tokens = lines[i].split('Strings:\x0A');
var header = tokens[0].split('\x0A\x0A')[0].replaceAll('\x0A', '').trim().replaceAll(' ', '').replaceAll('\x09', '');
ms.write(Buffer.from(header, 'hex'));
if (tokens.length > 1) {
var strings = tokens[1].split('\x0A\x0A')[0].split('\x0A');
var stringsFinal = [];
for (var strx in strings) {
var tmp = strings[strx].trim().replaceAll(' ', '').replaceAll('\x09', '');
if (!(tmp[0] == '"')) { stringsFinal.push(tmp); }
}
ms.write(Buffer.from(stringsFinal.join(''), 'hex'));
ms.write(Buffer.from('00', 'hex'));
}
else {
ms.write(Buffer.from('0000', 'hex'));
}
}
var retVal = ms.buffer;
retVal.ms = ms;
return (retVal);
};
}
this._parse = function _parse(SMData) {
var ret = {};
var pbyte;
var i = 0
var SMData;
var structcount = 0;
while (SMData && i < SMData.length)
{
var SMtype = SMData[i];
var SMlength = SMData[i + 1];
if (!ret[SMtype]) { ret[SMtype] = []; }
ret[SMtype].push(SMData.slice(i + 4, i + SMlength));
if (process.platform == 'win32') { ret[SMtype].peek()._ext = pbyte; }
i += SMlength;
ret[SMtype].peek()._strings = [];
while (SMData[i] != 0 && i <= SMData.length)
{
var strstart = i;
// Start of String, find end of string
while (SMData[i++] != 0 && i <= SMData.length);
try
{
ret[SMtype].peek()._strings.push(SMData.slice(strstart, i).toString().trim());
}
catch (ee)
{
}
}
i += (ret[SMtype].peek()._strings.length == 0) ? 2 : 1;
++structcount;
//console.log('End of Table[' + SMtype + ']: ' + i);
}
//console.log('Struct Count = ' + structcount);
return (ret);
};
this.get = function get(callback) {
if (process.platform == 'win32') {
var size = this._native.GetSystemFirmwareTable(RSMB, 0, 0, 0).Val;
//console.log('Table Size: ' + size);
var PtrSize = this._marshal.CreatePointer()._size;
var buffer = this._marshal.CreateVariable(size);
var written = this._native.GetSystemFirmwareTable(RSMB, 0, buffer, size).Val;
//console.log('Written Size: ' + written);
var rawBuffer = buffer.toBuffer();
var length = buffer.Deref(4, 4).toBuffer().readUInt32LE(0);
pbyte = buffer.Deref(8, length);
SMData = pbyte.toBuffer();
if (callback) { callback.apply(this, [this._parse(SMData)]); return; } else { return (this._parse(SMData)); }
}
if (process.platform == 'linux') {
var MemoryStream = require('MemoryStream');
this.child = require('child_process').execFile('/usr/sbin/dmidecode', ['dmidecode', '-u']);
this.child.SMBiosTable = this;
this.child.ms = new MemoryStream();
this.child.ms.callback = callback;
this.child.ms.child = this.child;
this.child.stdout.on('data', function (buffer) { this.parent.ms.write(buffer); });
this.child.on('exit', function () { this.ms.end(); });
this.child.ms.on('end', function () {
//console.log('read ' + this.buffer.length + ' bytes');
if (this.buffer.length < 300) {
//console.log('Not enough permission to read SMBiosTable');
if (this.callback) { this.callback.apply(this.child.SMBiosTable, []); }
}
else {
var SMData = this.child.SMBiosTable._canonicalizeData(this.buffer);
var j = this.child.SMBiosTable._parse(SMData);
if (this.callback) { this.callback.apply(this.child.SMBiosTable, [j]); }
}
});
return;
}
if (callback) { callback.apply(this, [null]); return; } else { return (null); }
};
this.parse = function parse(data) {
var r = {};
try
{
r.processorInfo = this.processorInfo(data);
}
catch(e)
{
}
try
{
r.memoryInfo = this.memoryInfo(data);
}
catch(e)
{
}
try
{
r.systemInfo = this.systemInfo(data);
}
catch(e)
{
}
try
{
r.systemSlots = this.systemInfo(data);
}
catch(e)
{
}
try
{
r.amtInfo = this.amtInfo(data);
}
catch(e)
{
}
try
{
if (JSON.stringify(r).length > 65535) { r = {}; }
}
catch(ee)
{}
return r;
}
this.processorInfo = function processorInfo(data) {
if (!data) { throw ('no data'); }
var ret = [];
var ptype = ['ERROR', 'Other', 'Unknown', 'CPU', 'ALU', 'DSP', 'GPU'];
var statusString = ['Unknown', 'Enabled', 'Disabled by user', 'Disabled by BIOS', 'Idle', 'Reserved', 'Reserved', 'Other'];
var cpuid = 0;
while (data[4] && data[4].length > 0) {
var p = data[4].pop();
var populated = p[20] & 0x40;
var status = p[20] & 0x07
if (populated) {
var j = { _ObjectID: 'SMBiosTables.processorInfo' };
j.Processor = ptype[p[1]];
j.MaxSpeed = p.readUInt16LE(16) + ' Mhz';
if (p[31]) { j.Cores = p[31]; }
if (p[33]) { j.Threads = p[33]; }
j.Populated = 1;
j.Status = statusString[status];
j.Socket = p._strings[p[0] - 1];
j.Manufacturer = p._strings[p[3] - 1];
j.Version = p._strings[p[12] - 1];
ret.push(j);
}
}
return (ret);
};
this.memoryInfo = function memoryInfo(data) {
if (!data) { throw ('no data'); }
var retVal = { _ObjectID: 'SMBiosTables.memoryInfo' };
if (data[16]) {
var m = data[16].peek();
retVal.location = memoryLocation[m[0]];
if ((retVal.maxCapacityKb = m.readUInt32LE(3)) == 0x80000000) {
retVal.maxCapacityKb = 'A really big number';
}
}
return (retVal);
};
this.systemInfo = function systemInfo(data)
{
if (!data) { throw ('no data'); }
var retVal = { _ObjectID: 'SMBiosTables.systemInfo' };
if (data[1])
{
var si = data[1].peek();
var uuid = si.slice(4, 20);
retVal.uuid = [zeroLeftPad(uuid.readUInt32LE(0).toString(16), 8),
zeroLeftPad(uuid.readUInt16LE(4).toString(16), 4),
zeroLeftPad(uuid.readUInt16LE(6).toString(16), 4),
zeroLeftPad(uuid.readUInt16BE(8).toString(16), 4),
zeroLeftPad(uuid.slice(10).toString('hex').toLowerCase(), 12)].join('-');
retVal.wakeReason = wakeReason[si[20]];
}
return (retVal);
};
this.systemSlots = function systemSlots(data) {
if (!data) { throw ('no data'); }
var retVal = [];
if (data[9]) {
while (data[9].length > 0) {
var ss = data[9].pop();
retVal.push({ name: ss._strings[ss[0] - 1] });
}
}
return (retVal);
};
this.amtInfo = function amtInfo(data) {
if (!data) { throw ('no data'); }
var retVal = { AMT: false };
if (data[130] && data[130].peek().slice(0, 4).toString() == '$AMT') {
var amt = data[130].peek();
retVal.AMT = amt[4] ? true : false;
if (retVal.AMT) {
retVal.enabled = amt[5] ? true : false;
retVal.storageRedirection = amt[6] ? true : false;
retVal.serialOverLan = amt[7] ? true : false;
retVal.kvm = amt[14] ? true : false;
if (data[131].peek() && data[131].peek().slice(52, 56).toString() == 'vPro') {
var settings = data[131].peek();
if (settings[0] & 0x04) { retVal.TXT = (settings[0] & 0x08) ? true : false; }
if (settings[0] & 0x10) { retVal.VMX = (settings[0] & 0x20) ? true : false; }
retVal.MEBX = settings.readUInt16LE(4).toString() + '.' + settings.readUInt16LE(6).toString() + '.' + settings.readUInt16LE(8).toString() + '.' + settings.readUInt16LE(10).toString();
var mecap = settings.slice(20, 32);
retVal.ManagementEngine = mecap.readUInt16LE(6).toString() + '.' + mecap.readUInt16LE(4).toString() + '.' + mecap.readUInt16LE(10).toString() + '.' + mecap.readUInt16LE(8).toString();
//var lan = settings.slice(36, 48);
//console.log(lan.toString('hex'));
//retVal.LAN = (lan.readUInt16LE(10) & 0x03).toString() + '/' + ((lan.readUInt16LE(10) & 0xF8) >> 3).toString();
//console.log(lan.readUInt16LE(3));
//retVal.WLAN = (lan.readUInt16LE(3) & 0x07).toString() + '/' + ((lan.readUInt16LE(3) & 0xF8) >> 3).toString() + '/' + (lan.readUInt16LE(3) >> 8).toString();
}
}
}
return (retVal);
};
this.smTableTypes = {
0: 'BIOS information',
1: 'System information',
2: 'Baseboard (or Module) information',
4: 'Processor information',
5: 'memory controller information',
6: 'Memory module information',
7: 'Cache information',
8: 'Port connector information',
9: 'System slots',
10: 'On board devices information',
11: 'OEM strings',
12: 'System configuration options',
13: 'BIOS language information',
14: 'Group associations',
15: 'System event log',
16: 'Physical memory array',
17: 'Memory device',
18: '32bit memory error information',
19: 'Memory array mapped address',
20: 'Memory device mapped address',
21: 'Built-in pointing device',
22: 'Portable battery',
23: 'System reset',
24: 'Hardware security',
25: 'System power controls',
26: 'Voltage probe',
27: 'Cooling device',
28: 'Temperature probe',
29: 'Electrical current probe',
30: 'Out-of-band remote access',
31: 'Boot integrity services (BIS) entry point',
32: 'System boot information',
33: '64bit memory error information',
34: 'Management device',
35: 'Management device component',
36: 'Management device threshold data',
37: 'Memory channel',
38: 'IPMI device information',
39: 'System power supply',
40: 'Additional information',
41: 'Onboard devices extended information',
42: 'Management controller host interface',
126: 'Inactive',
127: 'End-of-table'
}
}
module.exports = new SMBiosTables(); | Ylianst/MeshCentral | agents/modules_meshcore/smbios.js | JavaScript | apache-2.0 | 13,897 |
/**
* vue app
* Created by HC on 2016/7/19.
*/
var header = Vue.extend({
template: '#header'
});
// 全局注册组件
Vue.component('my-header', header);
var footer = Vue.extend({
template: '#footer'
});
// 全局注册组件
Vue.component('my-footer', footer);
var index = Vue.extend({
template: '#index'
});
var App = Vue.extend({});
var router = new VueRouter();
router.map({
'/': {
component: index
},
'/bar': {
component: footer
}
});
// Now we can start the app!
// The router will create an instance of App and mount to
// the element matching the selector #app.
router.start(App, '#app'); | jlkm2010/blog | src/main/resources/static/front/app.js | JavaScript | apache-2.0 | 653 |
'use strict';
/* global describe, it */
var fs = require('fs');
var expect = require('chai').expect;
var bigrig = require('../');
describe('Big Rig', function () {
it ('throws if no processes are found', function () {
expect(function () {
bigrig.analyze(null);
}).to.throw('Zero processes (tabs) found.');
});
it ('throws if given invalid input data is given', function () {
expect(function () {
bigrig.analyze('wobble');
}).to.throw('Invalid trace contents; not JSON');
});
it ('throws if given a trace with extensions and strict mode is enabled',
function (done) {
fs.readFile('./test/data/load-extensions.json', 'utf8',
function (err, data) {
if (err) {
throw err;
}
var error = 'Extensions running during capture; ' +
'see http://bit.ly/bigrig-extensions';
expect(function () {
bigrig.analyze(data, {
strict: true
});
}).to.throw(error);
done();
});
});
// TODO(paullewis) Add multiprocess test.
it ('returns JSON for a file with a single process', function (done) {
fs.readFile('./test/data/load.json', 'utf8',
function (err, data) {
if (err) {
throw err;
}
var jsonData = bigrig.analyze(data);
expect(jsonData).to.be.an('array');
expect(jsonData[0]).to.be.an('object');
done();
});
});
it ('generates valid JSON', function (done) {
fs.readFile('./test/data/load.json', 'utf8',
function (err, data) {
if (err) {
throw err;
}
var jsonData = bigrig.analyze(data);
jsonData = JSON.parse(JSON.stringify(jsonData));
expect(jsonData).to.be.an('array');
done();
});
});
it ('supports timed ranges', function (done) {
fs.readFile('./test/data/animation.json', 'utf8',
function (err, data) {
if (err) {
throw err;
}
var jsonData = bigrig.analyze(data);
expect(jsonData[0]).to.be.an('object');
expect(jsonData[0].title).to.equal('sideNavAnimation');
expect(jsonData[0].start).to.be.above(0);
expect(jsonData[0].end).to.be.within(1179, 1180);
done();
});
});
it ('correctly applies RAIL type when time range is specified',
function (done) {
fs.readFile('./test/data/animation.json', 'utf8',
function (err, data) {
if (err) {
throw err;
}
var jsonData = bigrig.analyze(data, {
types: {
'sideNavAnimation': bigrig.ANIMATION
}
});
expect(jsonData[0].type).to.equal(bigrig.ANIMATION);
done();
});
});
it ('correctly infers RAIL Load when time range not specified',
function (done) {
fs.readFile('./test/data/load.json', 'utf8',
function (err, data) {
if (err) {
throw err;
}
var jsonData = bigrig.analyze(data);
expect(jsonData[0].type).to.equal(bigrig.LOAD);
expect(jsonData[0].title).to.equal('Load');
done();
});
});
it ('correctly infers RAIL Response when time range not specified',
function (done) {
fs.readFile('./test/data/response.json', 'utf8',
function (err, data) {
if (err) {
throw err;
}
var jsonData = bigrig.analyze(data);
expect(jsonData[0].type).to.equal(bigrig.RESPONSE);
expect(jsonData[0].title).to.equal('sideNavResponse');
done();
});
});
it ('correctly infers RAIL Animation when time range not specified',
function (done) {
fs.readFile('./test/data/animation.json', 'utf8',
function (err, data) {
if (err) {
throw err;
}
var jsonData = bigrig.analyze(data);
expect(jsonData[0].type).to.equal(bigrig.ANIMATION);
expect(jsonData[0].title).to.equal('sideNavAnimation');
done();
});
});
it ('correctly infers multiple RAIL regions', function (done) {
fs.readFile('./test/data/response-animation.json', 'utf8',
function (err, data) {
if (err) {
throw err;
}
var jsonData = bigrig.analyze(data);
expect(jsonData.length).to.equal(2);
expect(jsonData[0].type).to.equal(bigrig.RESPONSE);
expect(jsonData[0].title).to.equal('sideNavResponse');
expect(jsonData[1].type).to.equal(bigrig.ANIMATION);
expect(jsonData[1].title).to.equal('sideNavAnimation');
done();
});
});
it ('returns the correct fps for animations', function (done) {
fs.readFile('./test/data/animation.json', 'utf8',
function (err, data) {
if (err) {
throw err;
}
var jsonData = bigrig.analyze(data);
expect(jsonData[0].fps).to.be.within(59, 61);
done();
});
});
it ('returns the correct JS breakdown', function (done) {
fs.readFile('./test/data/load.json', 'utf8',
function (err, data) {
if (err) {
throw err;
}
var jsonData = bigrig.analyze(data);
expect(
jsonData[0].extendedInfo.javaScript['localhost:11080']
).to.be.within(245, 246);
expect(
jsonData[0].extendedInfo.javaScript['www.google-analytics.com']
).to.be.within(59, 60);
done();
});
});
it ('correctly captures forced layouts and recalcs', function (done) {
fs.readFile('./test/data/forced-recalc-layout.json', 'utf8',
function (err, data) {
if (err) {
throw err;
}
var jsonData = bigrig.analyze(data);
expect(
jsonData[0].extendedInfo.forcedRecalcs
).to.equal(1);
expect(
jsonData[0].extendedInfo.forcedLayouts
).to.equal(1);
done();
});
});
});
| googlearchive/node-big-rig | test/bigrig_tests.js | JavaScript | apache-2.0 | 6,062 |
function TorneoGolfWindow(Window) {
window1 = Titanium.UI.createWindow({
tabBarHidden : true,
backgroundColor : "white",
width : '100%',
height : '100%',
layout : 'vertical'
});
table = Ti.UI.createTableView({
width : '90%',
height : '100%'
});
scrollView_1 = Titanium.UI.createView({
id : "scrollView_1",
backgroundImage : '/images/background.png',
height : '100%',
width : '100%',
layout : 'vertical'
});
scrollView_1.add(table);
imageViewBar = Titanium.UI.createView({
id : "imageViewBar",
backgroundColor : Ti.App.Properties.getString('viewcolor'),
height : 80,
left : 0,
top : 0,
width : '100%',
layout : 'horizontal'
});
imageView = Titanium.UI.createImageView({
id : "imageView",
image : "/images/icongolf.png",
width : 60,
height : 60,
top : 7,
right : 3
});
imageViewBar.add(imageView);
labelTitulo = Titanium.UI.createLabel({
id : "labelTitulo",
height : 'auto',
width : '70%',
text : L('golf'),
font : {
fontSize : '22dp'
},
color : 'white',
textAlign : Ti.UI.TEXT_ALIGNMENT_CENTER
});
imageViewBar.add(labelTitulo);
buttonClose = Titanium.UI.createImageView({
id : "buttonClose",
image : "/images/close.png",
width : 30,
height : 30,
top : 25
});
imageViewBar.add(buttonClose);
window1.add(imageViewBar);
window1.add(scrollView_1);
function populateTable() {
var data = [];
var row = Titanium.UI.createTableViewRow({
id : 2,
title : 'Horarios',
leftImage : '/images/horarios.png',
isparent : true,
opened : false,
hasChild : false,
font : {
fontSize : '22dp'
},
color : 'black'
});
data.push(row);
var row = Titanium.UI.createTableViewRow({
id : 3,
title : 'Mapa',
leftImage : '/images/mapa.png',
isparent : true,
opened : false,
hasChild : false,
font : {
fontSize : '22dp'
},
color : 'black'
});
data.push(row);
table.setData(data);
}
populateTable();
table.addEventListener('click', function(e) {
if (e.rowData.id == 2) {
var Window;
var mainWindow = require("ui/handheld/golf/HorariosWindow");
new mainWindow(Window).open();
} else if (e.rowData.id == 3) {
var Window;
var mainWindow = require("ui/handheld/mapa/MapaWindow");
new mainWindow(Window).open();
}
});
buttonClose.addEventListener('click', function(e) {
Ti.Media.vibrate();
var Window;
var mainWindow = require("ui/handheld/MainWindow");
new mainWindow(Window).open();
});
window1.addEventListener('android:back', function(e) {
Ti.Media.vibrate();
var Window;
var mainWindow = require("ui/handheld/MainWindow");
new mainWindow(Window).open();
});
return window1;
}
module.exports = TorneoGolfWindow;
| emobile/expomobile_mobile | Resources/ui/tablet/TorneoGolfWindow.js | JavaScript | apache-2.0 | 2,863 |
/*--------------------------------------------------------------------------
* linq.js - LINQ for JavaScript
* ver 3.0.3-Beta4 (Oct. 9th, 2012)
*
* created and maintained by neuecc <[email protected]>
* licensed under MIT License
* http://linqjs.codeplex.com/
*------------------------------------------------------------------------*/
(function (root, undefined) {
// ReadOnly Function
var Functions = {
Identity: function (x) { return x; },
True: function () { return true; },
Blank: function () { }
};
// const Type
var Types = {
Boolean: typeof true,
Number: typeof 0,
String: typeof "",
Object: typeof {},
Undefined: typeof undefined,
Function: typeof function () { }
};
// private utility methods
var Utils = {
// Create anonymous function from lambda expression string
createLambda: function (expression) {
if (expression == null) return Functions.Identity;
if (typeof expression == Types.String) {
if (expression == "") {
return Functions.Identity;
}
else if (expression.indexOf("=>") == -1) {
var regexp = new RegExp("[$]+", "g");
var maxLength = 0;
var match;
while (match = regexp.exec(expression)) {
var paramNumber = match[0].length;
if (paramNumber > maxLength) {
maxLength = paramNumber;
}
}
var argArray = [];
for (var i = 1; i <= maxLength; i++) {
var dollar = "";
for (var j = 0; j < i; j++) {
dollar += "$";
}
argArray.push(dollar);
}
var args = Array.prototype.join.call(argArray, ",");
return new Function(args, "return " + expression);
}
else {
var expr = expression.match(/^[(\s]*([^()]*?)[)\s]*=>(.*)/);
return new Function(expr[1], "return " + expr[2]);
}
}
return expression;
},
isIEnumerable: function (obj) {
if (typeof Enumerator !== Types.Undefined) {
try {
new Enumerator(obj); // check JScript(IE)'s Enumerator
return true;
}
catch (e) { }
}
return false;
},
// IE8's defineProperty is defined but cannot use, therefore check defineProperties
defineProperty: (Object.defineProperties != null)
? function (target, methodName, value) {
Object.defineProperty(target, methodName, {
enumerable: false,
configurable: true,
writable: true,
value: value
})
}
: function (target, methodName, value) {
target[methodName] = value;
},
compare: function (a, b) {
return (a === b) ? 0
: (a > b) ? 1
: -1;
},
dispose: function (obj) {
if (obj != null) obj.dispose();
}
};
// IEnumerator State
var State = { Before: 0, Running: 1, After: 2 };
// "Enumerator" is conflict JScript's "Enumerator"
var IEnumerator = function (initialize, tryGetNext, dispose) {
var yielder = new Yielder();
var state = State.Before;
this.current = yielder.current;
this.moveNext = function () {
try {
switch (state) {
case State.Before:
state = State.Running;
initialize();
// fall through
case State.Running:
if (tryGetNext.apply(yielder)) {
return true;
}
else {
this.dispose();
return false;
}
case State.After:
return false;
}
}
catch (e) {
this.dispose();
throw e;
}
};
this.dispose = function () {
if (state != State.Running) return;
try {
dispose();
}
finally {
state = State.After;
}
};
};
// for tryGetNext
var Yielder = function () {
var current = null;
this.current = function () { return current; };
this.yieldReturn = function (value) {
current = value;
return true;
};
this.yieldBreak = function () {
return false;
};
};
// Enumerable constuctor
var Enumerable = function (getEnumerator) {
this.getEnumerator = getEnumerator;
};
// Utility
Enumerable.Utils = {}; // container
Enumerable.Utils.createLambda = function (expression) {
return Utils.createLambda(expression);
};
Enumerable.Utils.createEnumerable = function (getEnumerator) {
return new Enumerable(getEnumerator);
};
Enumerable.Utils.createEnumerator = function (initialize, tryGetNext, dispose) {
return new IEnumerator(initialize, tryGetNext, dispose);
};
Enumerable.Utils.extendTo = function (type) {
var typeProto = type.prototype;
var enumerableProto;
if (type === Array) {
enumerableProto = ArrayEnumerable.prototype;
Utils.defineProperty(typeProto, "getSource", function () {
return this;
});
}
else {
enumerableProto = Enumerable.prototype;
Utils.defineProperty(typeProto, "getEnumerator", function () {
return Enumerable.from(this).getEnumerator();
});
}
for (var methodName in enumerableProto) {
var func = enumerableProto[methodName];
// already extended
if (typeProto[methodName] == func) continue;
// already defined(example Array#reverse/join/forEach...)
if (typeProto[methodName] != null) {
methodName = methodName + "ByLinq";
if (typeProto[methodName] == func) continue; // recheck
}
if (func instanceof Function) {
Utils.defineProperty(typeProto, methodName, func);
}
}
};
// Generator
Enumerable.choice = function () // variable argument
{
var args = arguments;
return new Enumerable(function () {
return new IEnumerator(
function () {
args = (args[0] instanceof Array) ? args[0]
: (args[0].getEnumerator != null) ? args[0].toArray()
: args;
},
function () {
return this.yieldReturn(args[Math.floor(Math.random() * args.length)]);
},
Functions.Blank);
});
};
Enumerable.cycle = function () // variable argument
{
var args = arguments;
return new Enumerable(function () {
var index = 0;
return new IEnumerator(
function () {
args = (args[0] instanceof Array) ? args[0]
: (args[0].getEnumerator != null) ? args[0].toArray()
: args;
},
function () {
if (index >= args.length) index = 0;
return this.yieldReturn(args[index++]);
},
Functions.Blank);
});
};
Enumerable.empty = function () {
return new Enumerable(function () {
return new IEnumerator(
Functions.Blank,
function () { return false; },
Functions.Blank);
});
};
Enumerable.from = function (obj) {
if (obj == null) {
return Enumerable.empty();
}
if (obj instanceof Enumerable) {
return obj;
}
if (typeof obj == Types.Number || typeof obj == Types.Boolean) {
return Enumerable.repeat(obj, 1);
}
if (typeof obj == Types.String) {
return new Enumerable(function () {
var index = 0;
return new IEnumerator(
Functions.Blank,
function () {
return (index < obj.length) ? this.yieldReturn(obj.charAt(index++)) : false;
},
Functions.Blank);
});
}
if (typeof obj != Types.Function) {
// array or array like object
if (typeof obj.length == Types.Number) {
return new ArrayEnumerable(obj);
}
// JScript's IEnumerable
if (!(obj instanceof Object) && Utils.isIEnumerable(obj)) {
return new Enumerable(function () {
var isFirst = true;
var enumerator;
return new IEnumerator(
function () { enumerator = new Enumerator(obj); },
function () {
if (isFirst) isFirst = false;
else enumerator.moveNext();
return (enumerator.atEnd()) ? false : this.yieldReturn(enumerator.item());
},
Functions.Blank);
});
}
// WinMD IIterable<T>
if (typeof Windows === Types.Object && typeof obj.first === Types.Function) {
return new Enumerable(function () {
var isFirst = true;
var enumerator;
return new IEnumerator(
function () { enumerator = obj.first(); },
function () {
if (isFirst) isFirst = false;
else enumerator.moveNext();
return (enumerator.hasCurrent) ? this.yieldReturn(enumerator.current) : this.yieldBreak();
},
Functions.Blank);
});
}
}
// case function/object : Create keyValuePair[]
return new Enumerable(function () {
var array = [];
var index = 0;
return new IEnumerator(
function () {
for (var key in obj) {
var value = obj[key];
if (!(value instanceof Function) && Object.prototype.hasOwnProperty.call(obj, key)) {
array.push({ key: key, value: value });
}
}
},
function () {
return (index < array.length)
? this.yieldReturn(array[index++])
: false;
},
Functions.Blank);
});
},
Enumerable.make = function (element) {
return Enumerable.repeat(element, 1);
};
// Overload:function(input, pattern)
// Overload:function(input, pattern, flags)
Enumerable.matches = function (input, pattern, flags) {
if (flags == null) flags = "";
if (pattern instanceof RegExp) {
flags += (pattern.ignoreCase) ? "i" : "";
flags += (pattern.multiline) ? "m" : "";
pattern = pattern.source;
}
if (flags.indexOf("g") === -1) flags += "g";
return new Enumerable(function () {
var regex;
return new IEnumerator(
function () { regex = new RegExp(pattern, flags); },
function () {
var match = regex.exec(input);
return (match) ? this.yieldReturn(match) : false;
},
Functions.Blank);
});
};
// Overload:function(start, count)
// Overload:function(start, count, step)
Enumerable.range = function (start, count, step) {
if (step == null) step = 1;
return new Enumerable(function () {
var value;
var index = 0;
return new IEnumerator(
function () { value = start - step; },
function () {
return (index++ < count)
? this.yieldReturn(value += step)
: this.yieldBreak();
},
Functions.Blank);
});
};
// Overload:function(start, count)
// Overload:function(start, count, step)
Enumerable.rangeDown = function (start, count, step) {
if (step == null) step = 1;
return new Enumerable(function () {
var value;
var index = 0;
return new IEnumerator(
function () { value = start + step; },
function () {
return (index++ < count)
? this.yieldReturn(value -= step)
: this.yieldBreak();
},
Functions.Blank);
});
};
// Overload:function(start, to)
// Overload:function(start, to, step)
Enumerable.rangeTo = function (start, to, step) {
if (step == null) step = 1;
if (start < to) {
return new Enumerable(function () {
var value;
return new IEnumerator(
function () { value = start - step; },
function () {
var next = value += step;
return (next <= to)
? this.yieldReturn(next)
: this.yieldBreak();
},
Functions.Blank);
});
}
else {
return new Enumerable(function () {
var value;
return new IEnumerator(
function () { value = start + step; },
function () {
var next = value -= step;
return (next >= to)
? this.yieldReturn(next)
: this.yieldBreak();
},
Functions.Blank);
});
}
};
// Overload:function(element)
// Overload:function(element, count)
Enumerable.repeat = function (element, count) {
if (count != null) return Enumerable.repeat(element).take(count);
return new Enumerable(function () {
return new IEnumerator(
Functions.Blank,
function () { return this.yieldReturn(element); },
Functions.Blank);
});
};
Enumerable.repeatWithFinalize = function (initializer, finalizer) {
initializer = Utils.createLambda(initializer);
finalizer = Utils.createLambda(finalizer);
return new Enumerable(function () {
var element;
return new IEnumerator(
function () { element = initializer(); },
function () { return this.yieldReturn(element); },
function () {
if (element != null) {
finalizer(element);
element = null;
}
});
});
};
// Overload:function(func)
// Overload:function(func, count)
Enumerable.generate = function (func, count) {
if (count != null) return Enumerable.generate(func).take(count);
func = Utils.createLambda(func);
return new Enumerable(function () {
return new IEnumerator(
Functions.Blank,
function () { return this.yieldReturn(func()); },
Functions.Blank);
});
};
// Overload:function()
// Overload:function(start)
// Overload:function(start, step)
Enumerable.toInfinity = function (start, step) {
if (start == null) start = 0;
if (step == null) step = 1;
return new Enumerable(function () {
var value;
return new IEnumerator(
function () { value = start - step; },
function () { return this.yieldReturn(value += step); },
Functions.Blank);
});
};
// Overload:function()
// Overload:function(start)
// Overload:function(start, step)
Enumerable.toNegativeInfinity = function (start, step) {
if (start == null) start = 0;
if (step == null) step = 1;
return new Enumerable(function () {
var value;
return new IEnumerator(
function () { value = start + step; },
function () { return this.yieldReturn(value -= step); },
Functions.Blank);
});
};
Enumerable.unfold = function (seed, func) {
func = Utils.createLambda(func);
return new Enumerable(function () {
var isFirst = true;
var value;
return new IEnumerator(
Functions.Blank,
function () {
if (isFirst) {
isFirst = false;
value = seed;
return this.yieldReturn(value);
}
value = func(value);
return this.yieldReturn(value);
},
Functions.Blank);
});
};
Enumerable.defer = function (enumerableFactory) {
return new Enumerable(function () {
var enumerator;
return new IEnumerator(
function () { enumerator = Enumerable.from(enumerableFactory()).getEnumerator(); },
function () {
return (enumerator.moveNext())
? this.yieldReturn(enumerator.current())
: this.yieldBreak();
},
function () {
Utils.dispose(enumerator);
});
});
};
// Extension Methods
/* Projection and Filtering Methods */
// Overload:function(func)
// Overload:function(func, resultSelector<element>)
// Overload:function(func, resultSelector<element, nestLevel>)
Enumerable.prototype.traverseBreadthFirst = function (func, resultSelector) {
var source = this;
func = Utils.createLambda(func);
resultSelector = Utils.createLambda(resultSelector);
return new Enumerable(function () {
var enumerator;
var nestLevel = 0;
var buffer = [];
return new IEnumerator(
function () { enumerator = source.getEnumerator(); },
function () {
while (true) {
if (enumerator.moveNext()) {
buffer.push(enumerator.current());
return this.yieldReturn(resultSelector(enumerator.current(), nestLevel));
}
var next = Enumerable.from(buffer).selectMany(function (x) { return func(x); });
if (!next.any()) {
return false;
}
else {
nestLevel++;
buffer = [];
Utils.dispose(enumerator);
enumerator = next.getEnumerator();
}
}
},
function () { Utils.dispose(enumerator); });
});
};
// Overload:function(func)
// Overload:function(func, resultSelector<element>)
// Overload:function(func, resultSelector<element, nestLevel>)
Enumerable.prototype.traverseDepthFirst = function (func, resultSelector) {
var source = this;
func = Utils.createLambda(func);
resultSelector = Utils.createLambda(resultSelector);
return new Enumerable(function () {
var enumeratorStack = [];
var enumerator;
return new IEnumerator(
function () { enumerator = source.getEnumerator(); },
function () {
while (true) {
if (enumerator.moveNext()) {
var value = resultSelector(enumerator.current(), enumeratorStack.length);
enumeratorStack.push(enumerator);
enumerator = Enumerable.from(func(enumerator.current())).getEnumerator();
return this.yieldReturn(value);
}
if (enumeratorStack.length <= 0) return false;
Utils.dispose(enumerator);
enumerator = enumeratorStack.pop();
}
},
function () {
try {
Utils.dispose(enumerator);
}
finally {
Enumerable.from(enumeratorStack).forEach(function (s) { s.dispose(); });
}
});
});
};
Enumerable.prototype.flatten = function () {
var source = this;
return new Enumerable(function () {
var enumerator;
var middleEnumerator = null;
return new IEnumerator(
function () { enumerator = source.getEnumerator(); },
function () {
while (true) {
if (middleEnumerator != null) {
if (middleEnumerator.moveNext()) {
return this.yieldReturn(middleEnumerator.current());
}
else {
middleEnumerator = null;
}
}
if (enumerator.moveNext()) {
if (enumerator.current() instanceof Array) {
Utils.dispose(middleEnumerator);
middleEnumerator = Enumerable.from(enumerator.current())
.selectMany(Functions.Identity)
.flatten()
.getEnumerator();
continue;
}
else {
return this.yieldReturn(enumerator.current());
}
}
return false;
}
},
function () {
try {
Utils.dispose(enumerator);
}
finally {
Utils.dispose(middleEnumerator);
}
});
});
};
Enumerable.prototype.pairwise = function (selector) {
var source = this;
selector = Utils.createLambda(selector);
return new Enumerable(function () {
var enumerator;
return new IEnumerator(
function () {
enumerator = source.getEnumerator();
enumerator.moveNext();
},
function () {
var prev = enumerator.current();
return (enumerator.moveNext())
? this.yieldReturn(selector(prev, enumerator.current()))
: false;
},
function () { Utils.dispose(enumerator); });
});
};
// Overload:function(func)
// Overload:function(seed,func<value,element>)
Enumerable.prototype.scan = function (seed, func) {
var isUseSeed;
if (func == null) {
func = Utils.createLambda(seed); // arguments[0]
isUseSeed = false;
} else {
func = Utils.createLambda(func);
isUseSeed = true;
}
var source = this;
return new Enumerable(function () {
var enumerator;
var value;
var isFirst = true;
return new IEnumerator(
function () { enumerator = source.getEnumerator(); },
function () {
if (isFirst) {
isFirst = false;
if (!isUseSeed) {
if (enumerator.moveNext()) {
return this.yieldReturn(value = enumerator.current());
}
}
else {
return this.yieldReturn(value = seed);
}
}
return (enumerator.moveNext())
? this.yieldReturn(value = func(value, enumerator.current()))
: false;
},
function () { Utils.dispose(enumerator); });
});
};
// Overload:function(selector<element>)
// Overload:function(selector<element,index>)
Enumerable.prototype.select = function (selector) {
selector = Utils.createLambda(selector);
if (selector.length <= 1) {
return new WhereSelectEnumerable(this, null, selector);
}
else {
var source = this;
return new Enumerable(function () {
var enumerator;
var index = 0;
return new IEnumerator(
function () { enumerator = source.getEnumerator(); },
function () {
return (enumerator.moveNext())
? this.yieldReturn(selector(enumerator.current(), index++))
: false;
},
function () { Utils.dispose(enumerator); });
});
}
};
// Overload:function(collectionSelector<element>)
// Overload:function(collectionSelector<element,index>)
// Overload:function(collectionSelector<element>,resultSelector)
// Overload:function(collectionSelector<element,index>,resultSelector)
Enumerable.prototype.selectMany = function (collectionSelector, resultSelector) {
var source = this;
collectionSelector = Utils.createLambda(collectionSelector);
if (resultSelector == null) resultSelector = function (a, b) { return b; };
resultSelector = Utils.createLambda(resultSelector);
return new Enumerable(function () {
var enumerator;
var middleEnumerator = undefined;
var index = 0;
return new IEnumerator(
function () { enumerator = source.getEnumerator(); },
function () {
if (middleEnumerator === undefined) {
if (!enumerator.moveNext()) return false;
}
do {
if (middleEnumerator == null) {
var middleSeq = collectionSelector(enumerator.current(), index++);
middleEnumerator = Enumerable.from(middleSeq).getEnumerator();
}
if (middleEnumerator.moveNext()) {
return this.yieldReturn(resultSelector(enumerator.current(), middleEnumerator.current()));
}
Utils.dispose(middleEnumerator);
middleEnumerator = null;
} while (enumerator.moveNext());
return false;
},
function () {
try {
Utils.dispose(enumerator);
}
finally {
Utils.dispose(middleEnumerator);
}
});
});
};
// Overload:function(predicate<element>)
// Overload:function(predicate<element,index>)
Enumerable.prototype.where = function (predicate) {
predicate = Utils.createLambda(predicate);
if (predicate.length <= 1) {
return new WhereEnumerable(this, predicate);
}
else {
var source = this;
return new Enumerable(function () {
var enumerator;
var index = 0;
return new IEnumerator(
function () { enumerator = source.getEnumerator(); },
function () {
while (enumerator.moveNext()) {
if (predicate(enumerator.current(), index++)) {
return this.yieldReturn(enumerator.current());
}
}
return false;
},
function () { Utils.dispose(enumerator); });
});
}
};
// Overload:function(selector<element>)
// Overload:function(selector<element,index>)
Enumerable.prototype.choose = function (selector) {
selector = Utils.createLambda(selector);
var source = this;
return new Enumerable(function () {
var enumerator;
var index = 0;
return new IEnumerator(
function () { enumerator = source.getEnumerator(); },
function () {
while (enumerator.moveNext()) {
var result = selector(enumerator.current(), index++);
if (result != null) {
return this.yieldReturn(result);
}
}
return this.yieldBreak();
},
function () { Utils.dispose(enumerator); });
});
};
Enumerable.prototype.ofType = function (type) {
var typeName;
switch (type) {
case Number:
typeName = Types.Number;
break;
case String:
typeName = Types.String;
break;
case Boolean:
typeName = Types.Boolean;
break;
case Function:
typeName = Types.Function;
break;
default:
typeName = null;
break;
}
return (typeName === null)
? this.where(function (x) { return x instanceof type; })
: this.where(function (x) { return typeof x === typeName; });
};
// mutiple arguments, last one is selector, others are enumerable
Enumerable.prototype.zip = function () {
var args = arguments;
var selector = Utils.createLambda(arguments[arguments.length - 1]);
var source = this;
// optimized case:argument is 2
if (arguments.length == 2) {
var second = arguments[0];
return new Enumerable(function () {
var firstEnumerator;
var secondEnumerator;
var index = 0;
return new IEnumerator(
function () {
firstEnumerator = source.getEnumerator();
secondEnumerator = Enumerable.from(second).getEnumerator();
},
function () {
if (firstEnumerator.moveNext() && secondEnumerator.moveNext()) {
return this.yieldReturn(selector(firstEnumerator.current(), secondEnumerator.current(), index++));
}
return false;
},
function () {
try {
Utils.dispose(firstEnumerator);
} finally {
Utils.dispose(secondEnumerator);
}
});
});
}
else {
return new Enumerable(function () {
var enumerators;
var index = 0;
return new IEnumerator(
function () {
var array = Enumerable.make(source)
.concat(Enumerable.from(args).takeExceptLast().select(Enumerable.from))
.select(function (x) { return x.getEnumerator() })
.toArray();
enumerators = Enumerable.from(array);
},
function () {
if (enumerators.all(function (x) { return x.moveNext() })) {
var array = enumerators
.select(function (x) { return x.current() })
.toArray();
array.push(index++);
return this.yieldReturn(selector.apply(null, array));
}
else {
return this.yieldBreak();
}
},
function () {
Enumerable.from(enumerators).forEach(Utils.dispose);
});
});
}
};
// mutiple arguments
Enumerable.prototype.merge = function () {
var args = arguments;
var source = this;
return new Enumerable(function () {
var enumerators;
var index = -1;
return new IEnumerator(
function () {
enumerators = Enumerable.make(source)
.concat(Enumerable.from(args).select(Enumerable.from))
.select(function (x) { return x.getEnumerator() })
.toArray();
},
function () {
while (enumerators.length > 0) {
index = (index >= enumerators.length - 1) ? 0 : index + 1;
var enumerator = enumerators[index];
if (enumerator.moveNext()) {
return this.yieldReturn(enumerator.current());
}
else {
enumerator.dispose();
enumerators.splice(index--, 1);
}
}
return this.yieldBreak();
},
function () {
Enumerable.from(enumerators).forEach(Utils.dispose);
});
});
};
/* Join Methods */
// Overload:function (inner, outerKeySelector, innerKeySelector, resultSelector)
// Overload:function (inner, outerKeySelector, innerKeySelector, resultSelector, compareSelector)
Enumerable.prototype.join = function (inner, outerKeySelector, innerKeySelector, resultSelector, compareSelector) {
outerKeySelector = Utils.createLambda(outerKeySelector);
innerKeySelector = Utils.createLambda(innerKeySelector);
resultSelector = Utils.createLambda(resultSelector);
compareSelector = Utils.createLambda(compareSelector);
var source = this;
return new Enumerable(function () {
var outerEnumerator;
var lookup;
var innerElements = null;
var innerCount = 0;
return new IEnumerator(
function () {
outerEnumerator = source.getEnumerator();
lookup = Enumerable.from(inner).toLookup(innerKeySelector, Functions.Identity, compareSelector);
},
function () {
while (true) {
if (innerElements != null) {
var innerElement = innerElements[innerCount++];
if (innerElement !== undefined) {
return this.yieldReturn(resultSelector(outerEnumerator.current(), innerElement));
}
innerElement = null;
innerCount = 0;
}
if (outerEnumerator.moveNext()) {
var key = outerKeySelector(outerEnumerator.current());
innerElements = lookup.get(key).toArray();
} else {
return false;
}
}
},
function () { Utils.dispose(outerEnumerator); });
});
};
// Overload:function (inner, outerKeySelector, innerKeySelector, resultSelector)
// Overload:function (inner, outerKeySelector, innerKeySelector, resultSelector, compareSelector)
Enumerable.prototype.groupJoin = function (inner, outerKeySelector, innerKeySelector, resultSelector, compareSelector) {
outerKeySelector = Utils.createLambda(outerKeySelector);
innerKeySelector = Utils.createLambda(innerKeySelector);
resultSelector = Utils.createLambda(resultSelector);
compareSelector = Utils.createLambda(compareSelector);
var source = this;
return new Enumerable(function () {
var enumerator = source.getEnumerator();
var lookup = null;
return new IEnumerator(
function () {
enumerator = source.getEnumerator();
lookup = Enumerable.from(inner).toLookup(innerKeySelector, Functions.Identity, compareSelector);
},
function () {
if (enumerator.moveNext()) {
var innerElement = lookup.get(outerKeySelector(enumerator.current()));
return this.yieldReturn(resultSelector(enumerator.current(), innerElement));
}
return false;
},
function () { Utils.dispose(enumerator); });
});
};
/* Set Methods */
Enumerable.prototype.all = function (predicate) {
predicate = Utils.createLambda(predicate);
var result = true;
this.forEach(function (x) {
if (!predicate(x)) {
result = false;
return false; // break
}
});
return result;
};
// Overload:function()
// Overload:function(predicate)
Enumerable.prototype.any = function (predicate) {
predicate = Utils.createLambda(predicate);
var enumerator = this.getEnumerator();
try {
if (arguments.length == 0) return enumerator.moveNext(); // case:function()
while (enumerator.moveNext()) // case:function(predicate)
{
if (predicate(enumerator.current())) return true;
}
return false;
}
finally {
Utils.dispose(enumerator);
}
};
Enumerable.prototype.isEmpty = function () {
return !this.any();
};
// multiple arguments
Enumerable.prototype.concat = function () {
var source = this;
if (arguments.length == 1) {
var second = arguments[0];
return new Enumerable(function () {
var firstEnumerator;
var secondEnumerator;
return new IEnumerator(
function () { firstEnumerator = source.getEnumerator(); },
function () {
if (secondEnumerator == null) {
if (firstEnumerator.moveNext()) return this.yieldReturn(firstEnumerator.current());
secondEnumerator = Enumerable.from(second).getEnumerator();
}
if (secondEnumerator.moveNext()) return this.yieldReturn(secondEnumerator.current());
return false;
},
function () {
try {
Utils.dispose(firstEnumerator);
}
finally {
Utils.dispose(secondEnumerator);
}
});
});
}
else {
var args = arguments;
return new Enumerable(function () {
var enumerators;
return new IEnumerator(
function () {
enumerators = Enumerable.make(source)
.concat(Enumerable.from(args).select(Enumerable.from))
.select(function (x) { return x.getEnumerator() })
.toArray();
},
function () {
while (enumerators.length > 0) {
var enumerator = enumerators[0];
if (enumerator.moveNext()) {
return this.yieldReturn(enumerator.current());
}
else {
enumerator.dispose();
enumerators.splice(0, 1);
}
}
return this.yieldBreak();
},
function () {
Enumerable.from(enumerators).forEach(Utils.dispose);
});
});
}
};
Enumerable.prototype.insert = function (index, second) {
var source = this;
return new Enumerable(function () {
var firstEnumerator;
var secondEnumerator;
var count = 0;
var isEnumerated = false;
return new IEnumerator(
function () {
firstEnumerator = source.getEnumerator();
secondEnumerator = Enumerable.from(second).getEnumerator();
},
function () {
if (count == index && secondEnumerator.moveNext()) {
isEnumerated = true;
return this.yieldReturn(secondEnumerator.current());
}
if (firstEnumerator.moveNext()) {
count++;
return this.yieldReturn(firstEnumerator.current());
}
if (!isEnumerated && secondEnumerator.moveNext()) {
return this.yieldReturn(secondEnumerator.current());
}
return false;
},
function () {
try {
Utils.dispose(firstEnumerator);
}
finally {
Utils.dispose(secondEnumerator);
}
});
});
};
Enumerable.prototype.alternate = function (alternateValueOrSequence) {
var source = this;
return new Enumerable(function () {
var buffer;
var enumerator;
var alternateSequence;
var alternateEnumerator;
return new IEnumerator(
function () {
if (alternateValueOrSequence instanceof Array || alternateValueOrSequence.getEnumerator != null) {
alternateSequence = Enumerable.from(Enumerable.from(alternateValueOrSequence).toArray()); // freeze
}
else {
alternateSequence = Enumerable.make(alternateValueOrSequence);
}
enumerator = source.getEnumerator();
if (enumerator.moveNext()) buffer = enumerator.current();
},
function () {
while (true) {
if (alternateEnumerator != null) {
if (alternateEnumerator.moveNext()) {
return this.yieldReturn(alternateEnumerator.current());
}
else {
alternateEnumerator = null;
}
}
if (buffer == null && enumerator.moveNext()) {
buffer = enumerator.current(); // hasNext
alternateEnumerator = alternateSequence.getEnumerator();
continue; // GOTO
}
else if (buffer != null) {
var retVal = buffer;
buffer = null;
return this.yieldReturn(retVal);
}
return this.yieldBreak();
}
},
function () {
try {
Utils.dispose(enumerator);
}
finally {
Utils.dispose(alternateEnumerator);
}
});
});
};
// Overload:function(value)
// Overload:function(value, compareSelector)
Enumerable.prototype.contains = function (value, compareSelector) {
compareSelector = Utils.createLambda(compareSelector);
var enumerator = this.getEnumerator();
try {
while (enumerator.moveNext()) {
if (compareSelector(enumerator.current()) === value) return true;
}
return false;
}
finally {
Utils.dispose(enumerator);
}
};
Enumerable.prototype.defaultIfEmpty = function (defaultValue) {
var source = this;
if (defaultValue === undefined) defaultValue = null;
return new Enumerable(function () {
var enumerator;
var isFirst = true;
return new IEnumerator(
function () { enumerator = source.getEnumerator(); },
function () {
if (enumerator.moveNext()) {
isFirst = false;
return this.yieldReturn(enumerator.current());
}
else if (isFirst) {
isFirst = false;
return this.yieldReturn(defaultValue);
}
return false;
},
function () { Utils.dispose(enumerator); });
});
};
// Overload:function()
// Overload:function(compareSelector)
Enumerable.prototype.distinct = function (compareSelector) {
return this.except(Enumerable.empty(), compareSelector);
};
Enumerable.prototype.distinctUntilChanged = function (compareSelector) {
compareSelector = Utils.createLambda(compareSelector);
var source = this;
return new Enumerable(function () {
var enumerator;
var compareKey;
var initial;
return new IEnumerator(
function () {
enumerator = source.getEnumerator();
},
function () {
while (enumerator.moveNext()) {
var key = compareSelector(enumerator.current());
if (initial) {
initial = false;
compareKey = key;
return this.yieldReturn(enumerator.current());
}
if (compareKey === key) {
continue;
}
compareKey = key;
return this.yieldReturn(enumerator.current());
}
return this.yieldBreak();
},
function () { Utils.dispose(enumerator); });
});
};
// Overload:function(second)
// Overload:function(second, compareSelector)
Enumerable.prototype.except = function (second, compareSelector) {
compareSelector = Utils.createLambda(compareSelector);
var source = this;
return new Enumerable(function () {
var enumerator;
var keys;
return new IEnumerator(
function () {
enumerator = source.getEnumerator();
keys = new Dictionary(compareSelector);
Enumerable.from(second).forEach(function (key) { keys.add(key); });
},
function () {
while (enumerator.moveNext()) {
var current = enumerator.current();
if (!keys.contains(current)) {
keys.add(current);
return this.yieldReturn(current);
}
}
return false;
},
function () { Utils.dispose(enumerator); });
});
};
// Overload:function(second)
// Overload:function(second, compareSelector)
Enumerable.prototype.intersect = function (second, compareSelector) {
compareSelector = Utils.createLambda(compareSelector);
var source = this;
return new Enumerable(function () {
var enumerator;
var keys;
var outs;
return new IEnumerator(
function () {
enumerator = source.getEnumerator();
keys = new Dictionary(compareSelector);
Enumerable.from(second).forEach(function (key) { keys.add(key); });
outs = new Dictionary(compareSelector);
},
function () {
while (enumerator.moveNext()) {
var current = enumerator.current();
if (!outs.contains(current) && keys.contains(current)) {
outs.add(current);
return this.yieldReturn(current);
}
}
return false;
},
function () { Utils.dispose(enumerator); });
});
};
// Overload:function(second)
// Overload:function(second, compareSelector)
Enumerable.prototype.sequenceEqual = function (second, compareSelector) {
compareSelector = Utils.createLambda(compareSelector);
var firstEnumerator = this.getEnumerator();
try {
var secondEnumerator = Enumerable.from(second).getEnumerator();
try {
while (firstEnumerator.moveNext()) {
if (!secondEnumerator.moveNext()
|| compareSelector(firstEnumerator.current()) !== compareSelector(secondEnumerator.current())) {
return false;
}
}
if (secondEnumerator.moveNext()) return false;
return true;
}
finally {
Utils.dispose(secondEnumerator);
}
}
finally {
Utils.dispose(firstEnumerator);
}
};
Enumerable.prototype.union = function (second, compareSelector) {
compareSelector = Utils.createLambda(compareSelector);
var source = this;
return new Enumerable(function () {
var firstEnumerator;
var secondEnumerator;
var keys;
return new IEnumerator(
function () {
firstEnumerator = source.getEnumerator();
keys = new Dictionary(compareSelector);
},
function () {
var current;
if (secondEnumerator === undefined) {
while (firstEnumerator.moveNext()) {
current = firstEnumerator.current();
if (!keys.contains(current)) {
keys.add(current);
return this.yieldReturn(current);
}
}
secondEnumerator = Enumerable.from(second).getEnumerator();
}
while (secondEnumerator.moveNext()) {
current = secondEnumerator.current();
if (!keys.contains(current)) {
keys.add(current);
return this.yieldReturn(current);
}
}
return false;
},
function () {
try {
Utils.dispose(firstEnumerator);
}
finally {
Utils.dispose(secondEnumerator);
}
});
});
};
/* Ordering Methods */
Enumerable.prototype.orderBy = function (keySelector) {
return new OrderedEnumerable(this, keySelector, false);
};
Enumerable.prototype.orderByDescending = function (keySelector) {
return new OrderedEnumerable(this, keySelector, true);
};
Enumerable.prototype.reverse = function () {
var source = this;
return new Enumerable(function () {
var buffer;
var index;
return new IEnumerator(
function () {
buffer = source.toArray();
index = buffer.length;
},
function () {
return (index > 0)
? this.yieldReturn(buffer[--index])
: false;
},
Functions.Blank);
});
};
Enumerable.prototype.shuffle = function () {
var source = this;
return new Enumerable(function () {
var buffer;
return new IEnumerator(
function () { buffer = source.toArray(); },
function () {
if (buffer.length > 0) {
var i = Math.floor(Math.random() * buffer.length);
return this.yieldReturn(buffer.splice(i, 1)[0]);
}
return false;
},
Functions.Blank);
});
};
Enumerable.prototype.weightedSample = function (weightSelector) {
weightSelector = Utils.createLambda(weightSelector);
var source = this;
return new Enumerable(function () {
var sortedByBound;
var totalWeight = 0;
return new IEnumerator(
function () {
sortedByBound = source
.choose(function (x) {
var weight = weightSelector(x);
if (weight <= 0) return null; // ignore 0
totalWeight += weight;
return { value: x, bound: totalWeight };
})
.toArray();
},
function () {
if (sortedByBound.length > 0) {
var draw = Math.floor(Math.random() * totalWeight) + 1;
var lower = -1;
var upper = sortedByBound.length;
while (upper - lower > 1) {
var index = Math.floor((lower + upper) / 2);
if (sortedByBound[index].bound >= draw) {
upper = index;
}
else {
lower = index;
}
}
return this.yieldReturn(sortedByBound[upper].value);
}
return this.yieldBreak();
},
Functions.Blank);
});
};
/* Grouping Methods */
// Overload:function(keySelector)
// Overload:function(keySelector,elementSelector)
// Overload:function(keySelector,elementSelector,resultSelector)
// Overload:function(keySelector,elementSelector,resultSelector,compareSelector)
Enumerable.prototype.groupBy = function (keySelector, elementSelector, resultSelector, compareSelector) {
var source = this;
keySelector = Utils.createLambda(keySelector);
elementSelector = Utils.createLambda(elementSelector);
if (resultSelector != null) resultSelector = Utils.createLambda(resultSelector);
compareSelector = Utils.createLambda(compareSelector);
return new Enumerable(function () {
var enumerator;
return new IEnumerator(
function () {
enumerator = source.toLookup(keySelector, elementSelector, compareSelector)
.toEnumerable()
.getEnumerator();
},
function () {
while (enumerator.moveNext()) {
return (resultSelector == null)
? this.yieldReturn(enumerator.current())
: this.yieldReturn(resultSelector(enumerator.current().key(), enumerator.current()));
}
return false;
},
function () { Utils.dispose(enumerator); });
});
};
// Overload:function(keySelector)
// Overload:function(keySelector,elementSelector)
// Overload:function(keySelector,elementSelector,resultSelector)
// Overload:function(keySelector,elementSelector,resultSelector,compareSelector)
Enumerable.prototype.partitionBy = function (keySelector, elementSelector, resultSelector, compareSelector) {
var source = this;
keySelector = Utils.createLambda(keySelector);
elementSelector = Utils.createLambda(elementSelector);
compareSelector = Utils.createLambda(compareSelector);
var hasResultSelector;
if (resultSelector == null) {
hasResultSelector = false;
resultSelector = function (key, group) { return new Grouping(key, group); };
}
else {
hasResultSelector = true;
resultSelector = Utils.createLambda(resultSelector);
}
return new Enumerable(function () {
var enumerator;
var key;
var compareKey;
var group = [];
return new IEnumerator(
function () {
enumerator = source.getEnumerator();
if (enumerator.moveNext()) {
key = keySelector(enumerator.current());
compareKey = compareSelector(key);
group.push(elementSelector(enumerator.current()));
}
},
function () {
var hasNext;
while ((hasNext = enumerator.moveNext()) == true) {
if (compareKey === compareSelector(keySelector(enumerator.current()))) {
group.push(elementSelector(enumerator.current()));
}
else break;
}
if (group.length > 0) {
var result = (hasResultSelector)
? resultSelector(key, Enumerable.from(group))
: resultSelector(key, group);
if (hasNext) {
key = keySelector(enumerator.current());
compareKey = compareSelector(key);
group = [elementSelector(enumerator.current())];
}
else group = [];
return this.yieldReturn(result);
}
return false;
},
function () { Utils.dispose(enumerator); });
});
};
Enumerable.prototype.buffer = function (count) {
var source = this;
return new Enumerable(function () {
var enumerator;
return new IEnumerator(
function () { enumerator = source.getEnumerator(); },
function () {
var array = [];
var index = 0;
while (enumerator.moveNext()) {
array.push(enumerator.current());
if (++index >= count) return this.yieldReturn(array);
}
if (array.length > 0) return this.yieldReturn(array);
return false;
},
function () { Utils.dispose(enumerator); });
});
};
/* Aggregate Methods */
// Overload:function(func)
// Overload:function(seed,func)
// Overload:function(seed,func,resultSelector)
Enumerable.prototype.aggregate = function (seed, func, resultSelector) {
resultSelector = Utils.createLambda(resultSelector);
return resultSelector(this.scan(seed, func, resultSelector).last());
};
// Overload:function()
// Overload:function(selector)
Enumerable.prototype.average = function (selector) {
selector = Utils.createLambda(selector);
var sum = 0;
var count = 0;
this.forEach(function (x) {
sum += selector(x);
++count;
});
return sum / count;
};
// Overload:function()
// Overload:function(predicate)
Enumerable.prototype.count = function (predicate) {
predicate = (predicate == null) ? Functions.True : Utils.createLambda(predicate);
var count = 0;
this.forEach(function (x, i) {
if (predicate(x, i))++count;
});
return count;
};
// Overload:function()
// Overload:function(selector)
Enumerable.prototype.max = function (selector) {
if (selector == null) selector = Functions.Identity;
return this.select(selector).aggregate(function (a, b) { return (a > b) ? a : b; });
};
// Overload:function()
// Overload:function(selector)
Enumerable.prototype.min = function (selector) {
if (selector == null) selector = Functions.Identity;
return this.select(selector).aggregate(function (a, b) { return (a < b) ? a : b; });
};
Enumerable.prototype.maxBy = function (keySelector) {
keySelector = Utils.createLambda(keySelector);
return this.aggregate(function (a, b) { return (keySelector(a) > keySelector(b)) ? a : b; });
};
Enumerable.prototype.minBy = function (keySelector) {
keySelector = Utils.createLambda(keySelector);
return this.aggregate(function (a, b) { return (keySelector(a) < keySelector(b)) ? a : b; });
};
// Overload:function()
// Overload:function(selector)
Enumerable.prototype.sum = function (selector) {
if (selector == null) selector = Functions.Identity;
return this.select(selector).aggregate(0, function (a, b) { return a + b; });
};
/* Paging Methods */
Enumerable.prototype.elementAt = function (index) {
var value;
var found = false;
this.forEach(function (x, i) {
if (i == index) {
value = x;
found = true;
return false;
}
});
if (!found) throw new Error("index is less than 0 or greater than or equal to the number of elements in source.");
return value;
};
Enumerable.prototype.elementAtOrDefault = function (index, defaultValue) {
if (defaultValue === undefined) defaultValue = null;
var value;
var found = false;
this.forEach(function (x, i) {
if (i == index) {
value = x;
found = true;
return false;
}
});
return (!found) ? defaultValue : value;
};
// Overload:function()
// Overload:function(predicate)
Enumerable.prototype.first = function (predicate) {
if (predicate != null) return this.where(predicate).first();
var value;
var found = false;
this.forEach(function (x) {
value = x;
found = true;
return false;
});
if (!found) throw new Error("first:No element satisfies the condition.");
return value;
};
Enumerable.prototype.firstOrDefault = function (predicate, defaultValue) {
if (defaultValue === undefined) defaultValue = null;
if (predicate != null) return this.where(predicate).firstOrDefault(null, defaultValue);
var value;
var found = false;
this.forEach(function (x) {
value = x;
found = true;
return false;
});
return (!found) ? defaultValue : value;
};
// Overload:function()
// Overload:function(predicate)
Enumerable.prototype.last = function (predicate) {
if (predicate != null) return this.where(predicate).last();
var value;
var found = false;
this.forEach(function (x) {
found = true;
value = x;
});
if (!found) throw new Error("last:No element satisfies the condition.");
return value;
};
// Overload:function(defaultValue)
// Overload:function(defaultValue,predicate)
Enumerable.prototype.lastOrDefault = function (predicate, defaultValue) {
if (defaultValue === undefined) defaultValue = null;
if (predicate != null) return this.where(predicate).lastOrDefault(null, defaultValue);
var value;
var found = false;
this.forEach(function (x) {
found = true;
value = x;
});
return (!found) ? defaultValue : value;
};
// Overload:function()
// Overload:function(predicate)
Enumerable.prototype.single = function (predicate) {
if (predicate != null) return this.where(predicate).single();
var value;
var found = false;
this.forEach(function (x) {
if (!found) {
found = true;
value = x;
} else throw new Error("single:sequence contains more than one element.");
});
if (!found) throw new Error("single:No element satisfies the condition.");
return value;
};
// Overload:function(defaultValue)
// Overload:function(defaultValue,predicate)
Enumerable.prototype.singleOrDefault = function (predicate, defaultValue) {
if (defaultValue === undefined) defaultValue = null;
if (predicate != null) return this.where(predicate).singleOrDefault(null, defaultValue);
var value;
var found = false;
this.forEach(function (x) {
if (!found) {
found = true;
value = x;
} else throw new Error("single:sequence contains more than one element.");
});
return (!found) ? defaultValue : value;
};
Enumerable.prototype.skip = function (count) {
var source = this;
return new Enumerable(function () {
var enumerator;
var index = 0;
return new IEnumerator(
function () {
enumerator = source.getEnumerator();
while (index++ < count && enumerator.moveNext()) {
}
;
},
function () {
return (enumerator.moveNext())
? this.yieldReturn(enumerator.current())
: false;
},
function () { Utils.dispose(enumerator); });
});
};
// Overload:function(predicate<element>)
// Overload:function(predicate<element,index>)
Enumerable.prototype.skipWhile = function (predicate) {
predicate = Utils.createLambda(predicate);
var source = this;
return new Enumerable(function () {
var enumerator;
var index = 0;
var isSkipEnd = false;
return new IEnumerator(
function () { enumerator = source.getEnumerator(); },
function () {
while (!isSkipEnd) {
if (enumerator.moveNext()) {
if (!predicate(enumerator.current(), index++)) {
isSkipEnd = true;
return this.yieldReturn(enumerator.current());
}
continue;
} else return false;
}
return (enumerator.moveNext())
? this.yieldReturn(enumerator.current())
: false;
},
function () { Utils.dispose(enumerator); });
});
};
Enumerable.prototype.take = function (count) {
var source = this;
return new Enumerable(function () {
var enumerator;
var index = 0;
return new IEnumerator(
function () { enumerator = source.getEnumerator(); },
function () {
return (index++ < count && enumerator.moveNext())
? this.yieldReturn(enumerator.current())
: false;
},
function () { Utils.dispose(enumerator); }
);
});
};
// Overload:function(predicate<element>)
// Overload:function(predicate<element,index>)
Enumerable.prototype.takeWhile = function (predicate) {
predicate = Utils.createLambda(predicate);
var source = this;
return new Enumerable(function () {
var enumerator;
var index = 0;
return new IEnumerator(
function () { enumerator = source.getEnumerator(); },
function () {
return (enumerator.moveNext() && predicate(enumerator.current(), index++))
? this.yieldReturn(enumerator.current())
: false;
},
function () { Utils.dispose(enumerator); });
});
};
// Overload:function()
// Overload:function(count)
Enumerable.prototype.takeExceptLast = function (count) {
if (count == null) count = 1;
var source = this;
return new Enumerable(function () {
if (count <= 0) return source.getEnumerator(); // do nothing
var enumerator;
var q = [];
return new IEnumerator(
function () { enumerator = source.getEnumerator(); },
function () {
while (enumerator.moveNext()) {
if (q.length == count) {
q.push(enumerator.current());
return this.yieldReturn(q.shift());
}
q.push(enumerator.current());
}
return false;
},
function () { Utils.dispose(enumerator); });
});
};
Enumerable.prototype.takeFromLast = function (count) {
if (count <= 0 || count == null) return Enumerable.empty();
var source = this;
return new Enumerable(function () {
var sourceEnumerator;
var enumerator;
var q = [];
return new IEnumerator(
function () { sourceEnumerator = source.getEnumerator(); },
function () {
while (sourceEnumerator.moveNext()) {
if (q.length == count) q.shift();
q.push(sourceEnumerator.current());
}
if (enumerator == null) {
enumerator = Enumerable.from(q).getEnumerator();
}
return (enumerator.moveNext())
? this.yieldReturn(enumerator.current())
: false;
},
function () { Utils.dispose(enumerator); });
});
};
// Overload:function(item)
// Overload:function(predicate)
Enumerable.prototype.indexOf = function (item) {
var found = null;
// item as predicate
if (typeof (item) === Types.Function) {
this.forEach(function (x, i) {
if (item(x, i)) {
found = i;
return false;
}
});
}
else {
this.forEach(function (x, i) {
if (x === item) {
found = i;
return false;
}
});
}
return (found !== null) ? found : -1;
};
// Overload:function(item)
// Overload:function(predicate)
Enumerable.prototype.lastIndexOf = function (item) {
var result = -1;
// item as predicate
if (typeof (item) === Types.Function) {
this.forEach(function (x, i) {
if (item(x, i)) result = i;
});
}
else {
this.forEach(function (x, i) {
if (x === item) result = i;
});
}
return result;
};
/* Convert Methods */
Enumerable.prototype.asEnumerable = function () {
return Enumerable.from(this);
};
Enumerable.prototype.toArray = function () {
var array = [];
this.forEach(function (x) { array.push(x); });
return array;
};
// Overload:function(keySelector)
// Overload:function(keySelector, elementSelector)
// Overload:function(keySelector, elementSelector, compareSelector)
Enumerable.prototype.toLookup = function (keySelector, elementSelector, compareSelector) {
keySelector = Utils.createLambda(keySelector);
elementSelector = Utils.createLambda(elementSelector);
compareSelector = Utils.createLambda(compareSelector);
var dict = new Dictionary(compareSelector);
this.forEach(function (x) {
var key = keySelector(x);
var element = elementSelector(x);
var array = dict.get(key);
if (array !== undefined) array.push(element);
else dict.add(key, [element]);
});
return new Lookup(dict);
};
Enumerable.prototype.toObject = function (keySelector, elementSelector) {
keySelector = Utils.createLambda(keySelector);
elementSelector = Utils.createLambda(elementSelector);
var obj = {};
this.forEach(function (x) {
obj[keySelector(x)] = elementSelector(x);
});
return obj;
};
// Overload:function(keySelector, elementSelector)
// Overload:function(keySelector, elementSelector, compareSelector)
Enumerable.prototype.toDictionary = function (keySelector, elementSelector, compareSelector) {
keySelector = Utils.createLambda(keySelector);
elementSelector = Utils.createLambda(elementSelector);
compareSelector = Utils.createLambda(compareSelector);
var dict = new Dictionary(compareSelector);
this.forEach(function (x) {
dict.add(keySelector(x), elementSelector(x));
});
return dict;
};
// Overload:function()
// Overload:function(replacer)
// Overload:function(replacer, space)
Enumerable.prototype.toJSONString = function (replacer, space) {
if (typeof JSON === Types.Undefined || JSON.stringify == null) {
throw new Error("toJSONString can't find JSON.stringify. This works native JSON support Browser or include json2.js");
}
return JSON.stringify(this.toArray(), replacer, space);
};
// Overload:function()
// Overload:function(separator)
// Overload:function(separator,selector)
Enumerable.prototype.toJoinedString = function (separator, selector) {
if (separator == null) separator = "";
if (selector == null) selector = Functions.Identity;
return this.select(selector).toArray().join(separator);
};
/* Action Methods */
// Overload:function(action<element>)
// Overload:function(action<element,index>)
Enumerable.prototype.doAction = function (action) {
var source = this;
action = Utils.createLambda(action);
return new Enumerable(function () {
var enumerator;
var index = 0;
return new IEnumerator(
function () { enumerator = source.getEnumerator(); },
function () {
if (enumerator.moveNext()) {
action(enumerator.current(), index++);
return this.yieldReturn(enumerator.current());
}
return false;
},
function () { Utils.dispose(enumerator); });
});
};
// Overload:function(action<element>)
// Overload:function(action<element,index>)
// Overload:function(func<element,bool>)
// Overload:function(func<element,index,bool>)
Enumerable.prototype.forEach = function (action) {
action = Utils.createLambda(action);
var index = 0;
var enumerator = this.getEnumerator();
try {
while (enumerator.moveNext()) {
if (action(enumerator.current(), index++) === false) break;
}
} finally {
Utils.dispose(enumerator);
}
};
// Overload:function()
// Overload:function(separator)
// Overload:function(separator,selector)
Enumerable.prototype.write = function (separator, selector) {
if (separator == null) separator = "";
selector = Utils.createLambda(selector);
var isFirst = true;
this.forEach(function (item) {
if (isFirst) isFirst = false;
else document.write(separator);
document.write(selector(item));
});
};
// Overload:function()
// Overload:function(selector)
Enumerable.prototype.writeLine = function (selector) {
selector = Utils.createLambda(selector);
this.forEach(function (item) {
document.writeln(selector(item) + "<br />");
});
};
Enumerable.prototype.force = function () {
var enumerator = this.getEnumerator();
try {
while (enumerator.moveNext()) {
}
}
finally {
Utils.dispose(enumerator);
}
};
/* Functional Methods */
Enumerable.prototype.letBind = function (func) {
func = Utils.createLambda(func);
var source = this;
return new Enumerable(function () {
var enumerator;
return new IEnumerator(
function () {
enumerator = Enumerable.from(func(source)).getEnumerator();
},
function () {
return (enumerator.moveNext())
? this.yieldReturn(enumerator.current())
: false;
},
function () { Utils.dispose(enumerator); });
});
};
Enumerable.prototype.share = function () {
var source = this;
var sharedEnumerator;
var disposed = false;
return new DisposableEnumerable(function () {
return new IEnumerator(
function () {
if (sharedEnumerator == null) {
sharedEnumerator = source.getEnumerator();
}
},
function () {
if (disposed) throw new Error("enumerator is disposed");
return (sharedEnumerator.moveNext())
? this.yieldReturn(sharedEnumerator.current())
: false;
},
Functions.Blank
);
}, function () {
disposed = true;
Utils.dispose(sharedEnumerator);
});
};
Enumerable.prototype.memoize = function () {
var source = this;
var cache;
var enumerator;
var disposed = false;
return new DisposableEnumerable(function () {
var index = -1;
return new IEnumerator(
function () {
if (enumerator == null) {
enumerator = source.getEnumerator();
cache = [];
}
},
function () {
if (disposed) throw new Error("enumerator is disposed");
index++;
if (cache.length <= index) {
return (enumerator.moveNext())
? this.yieldReturn(cache[index] = enumerator.current())
: false;
}
return this.yieldReturn(cache[index]);
},
Functions.Blank
);
}, function () {
disposed = true;
Utils.dispose(enumerator);
cache = null;
});
};
/* Error Handling Methods */
Enumerable.prototype.catchError = function (handler) {
handler = Utils.createLambda(handler);
var source = this;
return new Enumerable(function () {
var enumerator;
return new IEnumerator(
function () { enumerator = source.getEnumerator(); },
function () {
try {
return (enumerator.moveNext())
? this.yieldReturn(enumerator.current())
: false;
} catch (e) {
handler(e);
return false;
}
},
function () { Utils.dispose(enumerator); });
});
};
Enumerable.prototype.finallyAction = function (finallyAction) {
finallyAction = Utils.createLambda(finallyAction);
var source = this;
return new Enumerable(function () {
var enumerator;
return new IEnumerator(
function () { enumerator = source.getEnumerator(); },
function () {
return (enumerator.moveNext())
? this.yieldReturn(enumerator.current())
: false;
},
function () {
try {
Utils.dispose(enumerator);
} finally {
finallyAction();
}
});
});
};
/* For Debug Methods */
// Overload:function()
// Overload:function(selector)
Enumerable.prototype.log = function (selector) {
selector = Utils.createLambda(selector);
return this.doAction(function (item) {
if (typeof console !== Types.Undefined) {
console.log(selector(item));
}
});
};
// Overload:function()
// Overload:function(message)
// Overload:function(message,selector)
Enumerable.prototype.trace = function (message, selector) {
if (message == null) message = "Trace";
selector = Utils.createLambda(selector);
return this.doAction(function (item) {
if (typeof console !== Types.Undefined) {
console.log(message, selector(item));
}
});
};
// private
var OrderedEnumerable = function (source, keySelector, descending, parent) {
this.source = source;
this.keySelector = Utils.createLambda(keySelector);
this.descending = descending;
this.parent = parent;
};
OrderedEnumerable.prototype = new Enumerable();
OrderedEnumerable.prototype.createOrderedEnumerable = function (keySelector, descending) {
return new OrderedEnumerable(this.source, keySelector, descending, this);
};
OrderedEnumerable.prototype.thenBy = function (keySelector) {
return this.createOrderedEnumerable(keySelector, false);
};
OrderedEnumerable.prototype.thenByDescending = function (keySelector) {
return this.createOrderedEnumerable(keySelector, true);
};
OrderedEnumerable.prototype.getEnumerator = function () {
var self = this;
var buffer;
var indexes;
var index = 0;
return new IEnumerator(
function () {
buffer = [];
indexes = [];
self.source.forEach(function (item, index) {
buffer.push(item);
indexes.push(index);
});
var sortContext = SortContext.create(self, null);
sortContext.GenerateKeys(buffer);
indexes.sort(function (a, b) { return sortContext.compare(a, b); });
},
function () {
return (index < indexes.length)
? this.yieldReturn(buffer[indexes[index++]])
: false;
},
Functions.Blank
);
};
var SortContext = function (keySelector, descending, child) {
this.keySelector = keySelector;
this.descending = descending;
this.child = child;
this.keys = null;
};
SortContext.create = function (orderedEnumerable, currentContext) {
var context = new SortContext(orderedEnumerable.keySelector, orderedEnumerable.descending, currentContext);
if (orderedEnumerable.parent != null) return SortContext.create(orderedEnumerable.parent, context);
return context;
};
SortContext.prototype.GenerateKeys = function (source) {
var len = source.length;
var keySelector = this.keySelector;
var keys = new Array(len);
for (var i = 0; i < len; i++) keys[i] = keySelector(source[i]);
this.keys = keys;
if (this.child != null) this.child.GenerateKeys(source);
};
SortContext.prototype.compare = function (index1, index2) {
var comparison = Utils.compare(this.keys[index1], this.keys[index2]);
if (comparison == 0) {
if (this.child != null) return this.child.compare(index1, index2);
return Utils.compare(index1, index2);
}
return (this.descending) ? -comparison : comparison;
};
var DisposableEnumerable = function (getEnumerator, dispose) {
this.dispose = dispose;
Enumerable.call(this, getEnumerator);
};
DisposableEnumerable.prototype = new Enumerable();
// optimize array or arraylike object
var ArrayEnumerable = function (source) {
this.getSource = function () { return source; };
};
ArrayEnumerable.prototype = new Enumerable();
ArrayEnumerable.prototype.any = function (predicate) {
return (predicate == null)
? (this.getSource().length > 0)
: Enumerable.prototype.any.apply(this, arguments);
};
ArrayEnumerable.prototype.count = function (predicate) {
return (predicate == null)
? this.getSource().length
: Enumerable.prototype.count.apply(this, arguments);
};
ArrayEnumerable.prototype.elementAt = function (index) {
var source = this.getSource();
return (0 <= index && index < source.length)
? source[index]
: Enumerable.prototype.elementAt.apply(this, arguments);
};
ArrayEnumerable.prototype.elementAtOrDefault = function (index, defaultValue) {
if (defaultValue === undefined) defaultValue = null;
var source = this.getSource();
return (0 <= index && index < source.length)
? source[index]
: defaultValue;
};
ArrayEnumerable.prototype.first = function (predicate) {
var source = this.getSource();
return (predicate == null && source.length > 0)
? source[0]
: Enumerable.prototype.first.apply(this, arguments);
};
ArrayEnumerable.prototype.firstOrDefault = function (predicate, defaultValue) {
if (defaultValue === undefined) defaultValue = null;
if (predicate != null) {
return Enumerable.prototype.firstOrDefault.apply(this, arguments);
}
var source = this.getSource();
return source.length > 0 ? source[0] : defaultValue;
};
ArrayEnumerable.prototype.last = function (predicate) {
var source = this.getSource();
return (predicate == null && source.length > 0)
? source[source.length - 1]
: Enumerable.prototype.last.apply(this, arguments);
};
ArrayEnumerable.prototype.lastOrDefault = function (predicate, defaultValue) {
if (defaultValue === undefined) defaultValue = null;
if (predicate != null) {
return Enumerable.prototype.lastOrDefault.apply(this, arguments);
}
var source = this.getSource();
return source.length > 0 ? source[source.length - 1] : defaultValue;
};
ArrayEnumerable.prototype.skip = function (count) {
var source = this.getSource();
return new Enumerable(function () {
var index;
return new IEnumerator(
function () { index = (count < 0) ? 0 : count; },
function () {
return (index < source.length)
? this.yieldReturn(source[index++])
: false;
},
Functions.Blank);
});
};
ArrayEnumerable.prototype.takeExceptLast = function (count) {
if (count == null) count = 1;
return this.take(this.getSource().length - count);
};
ArrayEnumerable.prototype.takeFromLast = function (count) {
return this.skip(this.getSource().length - count);
};
ArrayEnumerable.prototype.reverse = function () {
var source = this.getSource();
return new Enumerable(function () {
var index;
return new IEnumerator(
function () {
index = source.length;
},
function () {
return (index > 0)
? this.yieldReturn(source[--index])
: false;
},
Functions.Blank);
});
};
ArrayEnumerable.prototype.sequenceEqual = function (second, compareSelector) {
if ((second instanceof ArrayEnumerable || second instanceof Array)
&& compareSelector == null
&& Enumerable.from(second).count() != this.count()) {
return false;
}
return Enumerable.prototype.sequenceEqual.apply(this, arguments);
};
ArrayEnumerable.prototype.toJoinedString = function (separator, selector) {
var source = this.getSource();
if (selector != null || !(source instanceof Array)) {
return Enumerable.prototype.toJoinedString.apply(this, arguments);
}
if (separator == null) separator = "";
return source.join(separator);
};
ArrayEnumerable.prototype.getEnumerator = function () {
var source = this.getSource();
var index = -1;
// fast and simple enumerator
return {
current: function () { return source[index]; },
moveNext: function () {
return ++index < source.length;
},
dispose: Functions.Blank
};
};
// optimization for multiple where and multiple select and whereselect
var WhereEnumerable = function (source, predicate) {
this.prevSource = source;
this.prevPredicate = predicate; // predicate.length always <= 1
};
WhereEnumerable.prototype = new Enumerable();
WhereEnumerable.prototype.where = function (predicate) {
predicate = Utils.createLambda(predicate);
if (predicate.length <= 1) {
var prevPredicate = this.prevPredicate;
var composedPredicate = function (x) { return prevPredicate(x) && predicate(x); };
return new WhereEnumerable(this.prevSource, composedPredicate);
}
else {
// if predicate use index, can't compose
return Enumerable.prototype.where.call(this, predicate);
}
};
WhereEnumerable.prototype.select = function (selector) {
selector = Utils.createLambda(selector);
return (selector.length <= 1)
? new WhereSelectEnumerable(this.prevSource, this.prevPredicate, selector)
: Enumerable.prototype.select.call(this, selector);
};
WhereEnumerable.prototype.getEnumerator = function () {
var predicate = this.prevPredicate;
var source = this.prevSource;
var enumerator;
return new IEnumerator(
function () { enumerator = source.getEnumerator(); },
function () {
while (enumerator.moveNext()) {
if (predicate(enumerator.current())) {
return this.yieldReturn(enumerator.current());
}
}
return false;
},
function () { Utils.dispose(enumerator); });
};
var WhereSelectEnumerable = function (source, predicate, selector) {
this.prevSource = source;
this.prevPredicate = predicate; // predicate.length always <= 1 or null
this.prevSelector = selector; // selector.length always <= 1
};
WhereSelectEnumerable.prototype = new Enumerable();
WhereSelectEnumerable.prototype.where = function (predicate) {
predicate = Utils.createLambda(predicate);
return (predicate.length <= 1)
? new WhereEnumerable(this, predicate)
: Enumerable.prototype.where.call(this, predicate);
};
WhereSelectEnumerable.prototype.select = function (selector) {
selector = Utils.createLambda(selector);
if (selector.length <= 1) {
var prevSelector = this.prevSelector;
var composedSelector = function (x) { return selector(prevSelector(x)); };
return new WhereSelectEnumerable(this.prevSource, this.prevPredicate, composedSelector);
}
else {
// if selector use index, can't compose
return Enumerable.prototype.select.call(this, selector);
}
};
WhereSelectEnumerable.prototype.getEnumerator = function () {
var predicate = this.prevPredicate;
var selector = this.prevSelector;
var source = this.prevSource;
var enumerator;
return new IEnumerator(
function () { enumerator = source.getEnumerator(); },
function () {
while (enumerator.moveNext()) {
if (predicate == null || predicate(enumerator.current())) {
return this.yieldReturn(selector(enumerator.current()));
}
}
return false;
},
function () { Utils.dispose(enumerator); });
};
// Collections
var Dictionary = (function () {
// static utility methods
var callHasOwnProperty = function (target, key) {
return Object.prototype.hasOwnProperty.call(target, key);
};
var computeHashCode = function (obj) {
if (obj === null) return "null";
if (obj === undefined) return "undefined";
return (typeof obj.toString === Types.Function)
? obj.toString()
: Object.prototype.toString.call(obj);
};
// LinkedList for Dictionary
var HashEntry = function (key, value) {
this.key = key;
this.value = value;
this.prev = null;
this.next = null;
};
var EntryList = function () {
this.first = null;
this.last = null;
};
EntryList.prototype =
{
addLast: function (entry) {
if (this.last != null) {
this.last.next = entry;
entry.prev = this.last;
this.last = entry;
} else this.first = this.last = entry;
},
replace: function (entry, newEntry) {
if (entry.prev != null) {
entry.prev.next = newEntry;
newEntry.prev = entry.prev;
} else this.first = newEntry;
if (entry.next != null) {
entry.next.prev = newEntry;
newEntry.next = entry.next;
} else this.last = newEntry;
},
remove: function (entry) {
if (entry.prev != null) entry.prev.next = entry.next;
else this.first = entry.next;
if (entry.next != null) entry.next.prev = entry.prev;
else this.last = entry.prev;
}
};
// Overload:function()
// Overload:function(compareSelector)
var Dictionary = function (compareSelector) {
this.countField = 0;
this.entryList = new EntryList();
this.buckets = {}; // as Dictionary<string,List<object>>
this.compareSelector = (compareSelector == null) ? Functions.Identity : compareSelector;
};
Dictionary.prototype =
{
add: function (key, value) {
var compareKey = this.compareSelector(key);
var hash = computeHashCode(compareKey);
var entry = new HashEntry(key, value);
if (callHasOwnProperty(this.buckets, hash)) {
var array = this.buckets[hash];
for (var i = 0; i < array.length; i++) {
if (this.compareSelector(array[i].key) === compareKey) {
this.entryList.replace(array[i], entry);
array[i] = entry;
return;
}
}
array.push(entry);
} else {
this.buckets[hash] = [entry];
}
this.countField++;
this.entryList.addLast(entry);
},
get: function (key) {
var compareKey = this.compareSelector(key);
var hash = computeHashCode(compareKey);
if (!callHasOwnProperty(this.buckets, hash)) return undefined;
var array = this.buckets[hash];
for (var i = 0; i < array.length; i++) {
var entry = array[i];
if (this.compareSelector(entry.key) === compareKey) return entry.value;
}
return undefined;
},
set: function (key, value) {
var compareKey = this.compareSelector(key);
var hash = computeHashCode(compareKey);
if (callHasOwnProperty(this.buckets, hash)) {
var array = this.buckets[hash];
for (var i = 0; i < array.length; i++) {
if (this.compareSelector(array[i].key) === compareKey) {
var newEntry = new HashEntry(key, value);
this.entryList.replace(array[i], newEntry);
array[i] = newEntry;
return true;
}
}
}
return false;
},
contains: function (key) {
var compareKey = this.compareSelector(key);
var hash = computeHashCode(compareKey);
if (!callHasOwnProperty(this.buckets, hash)) return false;
var array = this.buckets[hash];
for (var i = 0; i < array.length; i++) {
if (this.compareSelector(array[i].key) === compareKey) return true;
}
return false;
},
clear: function () {
this.countField = 0;
this.buckets = {};
this.entryList = new EntryList();
},
remove: function (key) {
var compareKey = this.compareSelector(key);
var hash = computeHashCode(compareKey);
if (!callHasOwnProperty(this.buckets, hash)) return;
var array = this.buckets[hash];
for (var i = 0; i < array.length; i++) {
if (this.compareSelector(array[i].key) === compareKey) {
this.entryList.remove(array[i]);
array.splice(i, 1);
if (array.length == 0) delete this.buckets[hash];
this.countField--;
return;
}
}
},
count: function () {
return this.countField;
},
toEnumerable: function () {
var self = this;
return new Enumerable(function () {
var currentEntry;
return new IEnumerator(
function () { currentEntry = self.entryList.first; },
function () {
if (currentEntry != null) {
var result = { key: currentEntry.key, value: currentEntry.value };
currentEntry = currentEntry.next;
return this.yieldReturn(result);
}
return false;
},
Functions.Blank);
});
}
};
return Dictionary;
})();
// dictionary = Dictionary<TKey, TValue[]>
var Lookup = function (dictionary) {
this.count = function () {
return dictionary.count();
};
this.get = function (key) {
return Enumerable.from(dictionary.get(key));
};
this.contains = function (key) {
return dictionary.contains(key);
};
this.toEnumerable = function () {
return dictionary.toEnumerable().select(function (kvp) {
return new Grouping(kvp.key, kvp.value);
});
};
};
var Grouping = function (groupKey, elements) {
this.key = function () {
return groupKey;
};
ArrayEnumerable.call(this, elements);
};
Grouping.prototype = new ArrayEnumerable();
// module export
if (typeof define === Types.Function && define.amd) { // AMD
define("linqjs", [], function () { return Enumerable; });
}
else if (typeof module !== Types.Undefined && module.exports) { // Node
module.exports = Enumerable;
}
else {
root.Enumerable = Enumerable;
}
})(this); | codemonkeychris/rainbow | linqjs/linq.js | JavaScript | apache-2.0 | 107,573 |
/** vim: et:ts=4:sw=4:sts=4
* @license RequireJS 2.1.15 Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
* Available via the MIT or new BSD license.
* see: http://github.com/jrburke/requirejs for details
*/
//Not using strict: uneven strict support in browsers, #392, and causes
//problems with requirejs.exec()/transpiler plugins that may not be strict.
/*jslint regexp: true, nomen: true, sloppy: true */
/*global window, navigator, document, importScripts, setTimeout, opera */
var requirejs, require, define;
(function (global) {
var req, s, head, baseElement, dataMain, src,
interactiveScript, currentlyAddingScript, mainScript, subPath,
version = '2.1.15',
commentRegExp = /(\/\*([\s\S]*?)\*\/|([^:]|^)\/\/(.*)$)/mg,
cjsRequireRegExp = /[^.]\s*require\s*\(\s*["']([^'"\s]+)["']\s*\)/g,
jsSuffixRegExp = /\.js$/,
currDirRegExp = /^\.\//,
op = Object.prototype,
ostring = op.toString,
hasOwn = op.hasOwnProperty,
ap = Array.prototype,
apsp = ap.splice,
isBrowser = !!(typeof window !== 'undefined' && typeof navigator !== 'undefined' && window.document),
isWebWorker = !isBrowser && typeof importScripts !== 'undefined',
//PS3 indicates loaded and complete, but need to wait for complete
//specifically. Sequence is 'loading', 'loaded', execution,
// then 'complete'. The UA check is unfortunate, but not sure how
//to feature test w/o causing perf issues.
readyRegExp = isBrowser && navigator.platform === 'PLAYSTATION 3' ?
/^complete$/ : /^(complete|loaded)$/,
defContextName = '_',
//Oh the tragedy, detecting opera. See the usage of isOpera for reason.
isOpera = typeof opera !== 'undefined' && opera.toString() === '[object Opera]',
contexts = {},
cfg = {},
globalDefQueue = [],
useInteractive = false;
function isFunction(it) {
return ostring.call(it) === '[object Function]';
}
function isArray(it) {
return ostring.call(it) === '[object Array]';
}
/**
* Helper function for iterating over an array. If the func returns
* a true value, it will break out of the loop.
*/
function each(ary, func) {
if (ary) {
var i;
for (i = 0; i < ary.length; i += 1) {
if (ary[i] && func(ary[i], i, ary)) {
break;
}
}
}
}
/**
* Helper function for iterating over an array backwards. If the func
* returns a true value, it will break out of the loop.
*/
function eachReverse(ary, func) {
if (ary) {
var i;
for (i = ary.length - 1; i > -1; i -= 1) {
if (ary[i] && func(ary[i], i, ary)) {
break;
}
}
}
}
function hasProp(obj, prop) {
return hasOwn.call(obj, prop);
}
function getOwn(obj, prop) {
return hasProp(obj, prop) && obj[prop];
}
/**
* Cycles over properties in an object and calls a function for each
* property value. If the function returns a truthy value, then the
* iteration is stopped.
*/
function eachProp(obj, func) {
var prop;
for (prop in obj) {
if (hasProp(obj, prop)) {
if (func(obj[prop], prop)) {
break;
}
}
}
}
/**
* Simple function to mix in properties from source into target,
* but only if target does not already have a property of the same name.
*/
function mixin(target, source, force, deepStringMixin) {
if (source) {
eachProp(source, function (value, prop) {
if (force || !hasProp(target, prop)) {
if (deepStringMixin && typeof value === 'object' && value &&
!isArray(value) && !isFunction(value) &&
!(value instanceof RegExp)) {
if (!target[prop]) {
target[prop] = {};
}
mixin(target[prop], value, force, deepStringMixin);
} else {
target[prop] = value;
}
}
});
}
return target;
}
//Similar to Function.prototype.bind, but the 'this' object is specified
//first, since it is easier to read/figure out what 'this' will be.
function bind(obj, fn) {
return function () {
return fn.apply(obj, arguments);
};
}
function scripts() {
return document.getElementsByTagName('script');
}
function defaultOnError(err) {
throw err;
}
//Allow getting a global that is expressed in
//dot notation, like 'a.b.c'.
function getGlobal(value) {
if (!value) {
return value;
}
var g = global;
each(value.split('.'), function (part) {
g = g[part];
});
return g;
}
/**
* Constructs an error with a pointer to an URL with more information.
* @param {String} id the error ID that maps to an ID on a web page.
* @param {String} message human readable error.
* @param {Error} [err] the original error, if there is one.
*
* @returns {Error}
*/
function makeError(id, msg, err, requireModules) {
var e = new Error(msg + '\nhttp://requirejs.org/docs/errors.html#' + id);
e.requireType = id;
e.requireModules = requireModules;
if (err) {
e.originalError = err;
}
return e;
}
if (typeof define !== 'undefined') {
//If a define is already in play via another AMD loader,
//do not overwrite.
return;
}
if (typeof requirejs !== 'undefined') {
if (isFunction(requirejs)) {
//Do not overwrite an existing requirejs instance.
return;
}
cfg = requirejs;
requirejs = undefined;
}
//Allow for a require config object
if (typeof require !== 'undefined' && !isFunction(require)) {
//assume it is a config object.
cfg = require;
require = undefined;
}
function newContext(contextName) {
var inCheckLoaded, Module, context, handlers,
checkLoadedTimeoutId,
config = {
//Defaults. Do not set a default for map
//config to speed up normalize(), which
//will run faster if there is no default.
waitSeconds: 7,
baseUrl: './',
paths: {},
bundles: {},
pkgs: {},
shim: {},
config: {}
},
registry = {},
//registry of just enabled modules, to speed
//cycle breaking code when lots of modules
//are registered, but not activated.
enabledRegistry = {},
undefEvents = {},
defQueue = [],
defined = {},
urlFetched = {},
bundlesMap = {},
requireCounter = 1,
unnormalizedCounter = 1;
/**
* Trims the . and .. from an array of path segments.
* It will keep a leading path segment if a .. will become
* the first path segment, to help with module name lookups,
* which act like paths, but can be remapped. But the end result,
* all paths that use this function should look normalized.
* NOTE: this method MODIFIES the input array.
* @param {Array} ary the array of path segments.
*/
function trimDots(ary) {
var i, part;
for (i = 0; i < ary.length; i++) {
part = ary[i];
if (part === '.') {
ary.splice(i, 1);
i -= 1;
} else if (part === '..') {
// If at the start, or previous value is still ..,
// keep them so that when converted to a path it may
// still work when converted to a path, even though
// as an ID it is less than ideal. In larger point
// releases, may be better to just kick out an error.
if (i === 0 || (i == 1 && ary[2] === '..') || ary[i - 1] === '..') {
continue;
} else if (i > 0) {
ary.splice(i - 1, 2);
i -= 2;
}
}
}
}
/**
* Given a relative module name, like ./something, normalize it to
* a real name that can be mapped to a path.
* @param {String} name the relative name
* @param {String} baseName a real name that the name arg is relative
* to.
* @param {Boolean} applyMap apply the map config to the value. Should
* only be done if this normalization is for a dependency ID.
* @returns {String} normalized name
*/
function normalize(name, baseName, applyMap) {
var pkgMain, mapValue, nameParts, i, j, nameSegment, lastIndex,
foundMap, foundI, foundStarMap, starI, normalizedBaseParts,
baseParts = (baseName && baseName.split('/')),
map = config.map,
starMap = map && map['*'];
//Adjust any relative paths.
if (name) {
name = name.split('/');
lastIndex = name.length - 1;
// If wanting node ID compatibility, strip .js from end
// of IDs. Have to do this here, and not in nameToUrl
// because node allows either .js or non .js to map
// to same file.
if (config.nodeIdCompat && jsSuffixRegExp.test(name[lastIndex])) {
name[lastIndex] = name[lastIndex].replace(jsSuffixRegExp, '');
}
// Starts with a '.' so need the baseName
if (name[0].charAt(0) === '.' && baseParts) {
//Convert baseName to array, and lop off the last part,
//so that . matches that 'directory' and not name of the baseName's
//module. For instance, baseName of 'one/two/three', maps to
//'one/two/three.js', but we want the directory, 'one/two' for
//this normalization.
normalizedBaseParts = baseParts.slice(0, baseParts.length - 1);
name = normalizedBaseParts.concat(name);
}
trimDots(name);
name = name.join('/');
}
//Apply map config if available.
if (applyMap && map && (baseParts || starMap)) {
nameParts = name.split('/');
outerLoop: for (i = nameParts.length; i > 0; i -= 1) {
nameSegment = nameParts.slice(0, i).join('/');
if (baseParts) {
//Find the longest baseName segment match in the config.
//So, do joins on the biggest to smallest lengths of baseParts.
for (j = baseParts.length; j > 0; j -= 1) {
mapValue = getOwn(map, baseParts.slice(0, j).join('/'));
//baseName segment has config, find if it has one for
//this name.
if (mapValue) {
mapValue = getOwn(mapValue, nameSegment);
if (mapValue) {
//Match, update name to the new value.
foundMap = mapValue;
foundI = i;
break outerLoop;
}
}
}
}
//Check for a star map match, but just hold on to it,
//if there is a shorter segment match later in a matching
//config, then favor over this star map.
if (!foundStarMap && starMap && getOwn(starMap, nameSegment)) {
foundStarMap = getOwn(starMap, nameSegment);
starI = i;
}
}
if (!foundMap && foundStarMap) {
foundMap = foundStarMap;
foundI = starI;
}
if (foundMap) {
nameParts.splice(0, foundI, foundMap);
name = nameParts.join('/');
}
}
// If the name points to a package's name, use
// the package main instead.
pkgMain = getOwn(config.pkgs, name);
return pkgMain ? pkgMain : name;
}
function removeScript(name) {
if (isBrowser) {
each(scripts(), function (scriptNode) {
if (scriptNode.getAttribute('data-requiremodule') === name &&
scriptNode.getAttribute('data-requirecontext') === context.contextName) {
scriptNode.parentNode.removeChild(scriptNode);
return true;
}
});
}
}
function hasPathFallback(id) {
var pathConfig = getOwn(config.paths, id);
if (pathConfig && isArray(pathConfig) && pathConfig.length > 1) {
//Pop off the first array value, since it failed, and
//retry
pathConfig.shift();
context.require.undef(id);
//Custom require that does not do map translation, since
//ID is "absolute", already mapped/resolved.
context.makeRequire(null, {
skipMap: true
})([id]);
return true;
}
}
//Turns a plugin!resource to [plugin, resource]
//with the plugin being undefined if the name
//did not have a plugin prefix.
function splitPrefix(name) {
var prefix,
index = name ? name.indexOf('!') : -1;
if (index > -1) {
prefix = name.substring(0, index);
name = name.substring(index + 1, name.length);
}
return [prefix, name];
}
/**
* Creates a module mapping that includes plugin prefix, module
* name, and path. If parentModuleMap is provided it will
* also normalize the name via require.normalize()
*
* @param {String} name the module name
* @param {String} [parentModuleMap] parent module map
* for the module name, used to resolve relative names.
* @param {Boolean} isNormalized: is the ID already normalized.
* This is true if this call is done for a define() module ID.
* @param {Boolean} applyMap: apply the map config to the ID.
* Should only be true if this map is for a dependency.
*
* @returns {Object}
*/
function makeModuleMap(name, parentModuleMap, isNormalized, applyMap) {
var url, pluginModule, suffix, nameParts,
prefix = null,
parentName = parentModuleMap ? parentModuleMap.name : null,
originalName = name,
isDefine = true,
normalizedName = '';
//If no name, then it means it is a require call, generate an
//internal name.
if (!name) {
isDefine = false;
name = '_@r' + (requireCounter += 1);
}
nameParts = splitPrefix(name);
prefix = nameParts[0];
name = nameParts[1];
if (prefix) {
prefix = normalize(prefix, parentName, applyMap);
pluginModule = getOwn(defined, prefix);
}
//Account for relative paths if there is a base name.
if (name) {
if (prefix) {
if (pluginModule && pluginModule.normalize) {
//Plugin is loaded, use its normalize method.
normalizedName = pluginModule.normalize(name, function (name) {
return normalize(name, parentName, applyMap);
});
} else {
// If nested plugin references, then do not try to
// normalize, as it will not normalize correctly. This
// places a restriction on resourceIds, and the longer
// term solution is not to normalize until plugins are
// loaded and all normalizations to allow for async
// loading of a loader plugin. But for now, fixes the
// common uses. Details in #1131
normalizedName = name.indexOf('!') === -1 ?
normalize(name, parentName, applyMap) :
name;
}
} else {
//A regular module.
normalizedName = normalize(name, parentName, applyMap);
//Normalized name may be a plugin ID due to map config
//application in normalize. The map config values must
//already be normalized, so do not need to redo that part.
nameParts = splitPrefix(normalizedName);
prefix = nameParts[0];
normalizedName = nameParts[1];
isNormalized = true;
url = context.nameToUrl(normalizedName);
}
}
//If the id is a plugin id that cannot be determined if it needs
//normalization, stamp it with a unique ID so two matching relative
//ids that may conflict can be separate.
suffix = prefix && !pluginModule && !isNormalized ?
'_unnormalized' + (unnormalizedCounter += 1) :
'';
return {
prefix: prefix,
name: normalizedName,
parentMap: parentModuleMap,
unnormalized: !!suffix,
url: url,
originalName: originalName,
isDefine: isDefine,
id: (prefix ?
prefix + '!' + normalizedName :
normalizedName) + suffix
};
}
function getModule(depMap) {
var id = depMap.id,
mod = getOwn(registry, id);
if (!mod) {
mod = registry[id] = new context.Module(depMap);
}
return mod;
}
function on(depMap, name, fn) {
var id = depMap.id,
mod = getOwn(registry, id);
if (hasProp(defined, id) &&
(!mod || mod.defineEmitComplete)) {
if (name === 'defined') {
fn(defined[id]);
}
} else {
mod = getModule(depMap);
if (mod.error && name === 'error') {
fn(mod.error);
} else {
mod.on(name, fn);
}
}
}
function onError(err, errback) {
var ids = err.requireModules,
notified = false;
if (errback) {
errback(err);
} else {
each(ids, function (id) {
var mod = getOwn(registry, id);
if (mod) {
//Set error on module, so it skips timeout checks.
mod.error = err;
if (mod.events.error) {
notified = true;
mod.emit('error', err);
}
}
});
if (!notified) {
req.onError(err);
}
}
}
/**
* Internal method to transfer globalQueue items to this context's
* defQueue.
*/
function takeGlobalQueue() {
//Push all the globalDefQueue items into the context's defQueue
if (globalDefQueue.length) {
//Array splice in the values since the context code has a
//local var ref to defQueue, so cannot just reassign the one
//on context.
apsp.apply(defQueue,
[defQueue.length, 0].concat(globalDefQueue));
globalDefQueue = [];
}
}
handlers = {
'require': function (mod) {
if (mod.require) {
return mod.require;
} else {
return (mod.require = context.makeRequire(mod.map));
}
},
'exports': function (mod) {
mod.usingExports = true;
if (mod.map.isDefine) {
if (mod.exports) {
return (defined[mod.map.id] = mod.exports);
} else {
return (mod.exports = defined[mod.map.id] = {});
}
}
},
'module': function (mod) {
if (mod.module) {
return mod.module;
} else {
return (mod.module = {
id: mod.map.id,
uri: mod.map.url,
config: function () {
return getOwn(config.config, mod.map.id) || {};
},
exports: mod.exports || (mod.exports = {})
});
}
}
};
function cleanRegistry(id) {
//Clean up machinery used for waiting modules.
delete registry[id];
delete enabledRegistry[id];
}
function breakCycle(mod, traced, processed) {
var id = mod.map.id;
if (mod.error) {
mod.emit('error', mod.error);
} else {
traced[id] = true;
each(mod.depMaps, function (depMap, i) {
var depId = depMap.id,
dep = getOwn(registry, depId);
//Only force things that have not completed
//being defined, so still in the registry,
//and only if it has not been matched up
//in the module already.
if (dep && !mod.depMatched[i] && !processed[depId]) {
if (getOwn(traced, depId)) {
mod.defineDep(i, defined[depId]);
mod.check(); //pass false?
} else {
breakCycle(dep, traced, processed);
}
}
});
processed[id] = true;
}
}
function checkLoaded() {
var err, usingPathFallback,
waitInterval = config.waitSeconds * 1000,
//It is possible to disable the wait interval by using waitSeconds of 0.
expired = waitInterval && (context.startTime + waitInterval) < new Date().getTime(),
noLoads = [],
reqCalls = [],
stillLoading = false,
needCycleCheck = true;
//Do not bother if this call was a result of a cycle break.
if (inCheckLoaded) {
return;
}
inCheckLoaded = true;
//Figure out the state of all the modules.
eachProp(enabledRegistry, function (mod) {
var map = mod.map,
modId = map.id;
//Skip things that are not enabled or in error state.
if (!mod.enabled) {
return;
}
if (!map.isDefine) {
reqCalls.push(mod);
}
if (!mod.error) {
//If the module should be executed, and it has not
//been inited and time is up, remember it.
if (!mod.inited && expired) {
if (hasPathFallback(modId)) {
usingPathFallback = true;
stillLoading = true;
} else {
noLoads.push(modId);
removeScript(modId);
}
} else if (!mod.inited && mod.fetched && map.isDefine) {
stillLoading = true;
if (!map.prefix) {
//No reason to keep looking for unfinished
//loading. If the only stillLoading is a
//plugin resource though, keep going,
//because it may be that a plugin resource
//is waiting on a non-plugin cycle.
return (needCycleCheck = false);
}
}
}
});
if (expired && noLoads.length) {
//If wait time expired, throw error of unloaded modules.
err = makeError('timeout', 'Load timeout for modules: ' + noLoads, null, noLoads);
err.contextName = context.contextName;
return onError(err);
}
//Not expired, check for a cycle.
if (needCycleCheck) {
each(reqCalls, function (mod) {
breakCycle(mod, {}, {});
});
}
//If still waiting on loads, and the waiting load is something
//other than a plugin resource, or there are still outstanding
//scripts, then just try back later.
if ((!expired || usingPathFallback) && stillLoading) {
//Something is still waiting to load. Wait for it, but only
//if a timeout is not already in effect.
if ((isBrowser || isWebWorker) && !checkLoadedTimeoutId) {
checkLoadedTimeoutId = setTimeout(function () {
checkLoadedTimeoutId = 0;
checkLoaded();
}, 50);
}
}
inCheckLoaded = false;
}
Module = function (map) {
this.events = getOwn(undefEvents, map.id) || {};
this.map = map;
this.shim = getOwn(config.shim, map.id);
this.depExports = [];
this.depMaps = [];
this.depMatched = [];
this.pluginMaps = {};
this.depCount = 0;
/* this.exports this.factory
this.depMaps = [],
this.enabled, this.fetched
*/
};
Module.prototype = {
init: function (depMaps, factory, errback, options) {
options = options || {};
//Do not do more inits if already done. Can happen if there
//are multiple define calls for the same module. That is not
//a normal, common case, but it is also not unexpected.
if (this.inited) {
return;
}
this.factory = factory;
if (errback) {
//Register for errors on this module.
this.on('error', errback);
} else if (this.events.error) {
//If no errback already, but there are error listeners
//on this module, set up an errback to pass to the deps.
errback = bind(this, function (err) {
this.emit('error', err);
});
}
//Do a copy of the dependency array, so that
//source inputs are not modified. For example
//"shim" deps are passed in here directly, and
//doing a direct modification of the depMaps array
//would affect that config.
this.depMaps = depMaps && depMaps.slice(0);
this.errback = errback;
//Indicate this module has be initialized
this.inited = true;
this.ignore = options.ignore;
//Could have option to init this module in enabled mode,
//or could have been previously marked as enabled. However,
//the dependencies are not known until init is called. So
//if enabled previously, now trigger dependencies as enabled.
if (options.enabled || this.enabled) {
//Enable this module and dependencies.
//Will call this.check()
this.enable();
} else {
this.check();
}
},
defineDep: function (i, depExports) {
//Because of cycles, defined callback for a given
//export can be called more than once.
if (!this.depMatched[i]) {
this.depMatched[i] = true;
this.depCount -= 1;
this.depExports[i] = depExports;
}
},
fetch: function () {
if (this.fetched) {
return;
}
this.fetched = true;
context.startTime = (new Date()).getTime();
var map = this.map;
//If the manager is for a plugin managed resource,
//ask the plugin to load it now.
if (this.shim) {
context.makeRequire(this.map, {
enableBuildCallback: true
})(this.shim.deps || [], bind(this, function () {
return map.prefix ? this.callPlugin() : this.load();
}));
} else {
//Regular dependency.
return map.prefix ? this.callPlugin() : this.load();
}
},
load: function () {
var url = this.map.url;
//Regular dependency.
if (!urlFetched[url]) {
urlFetched[url] = true;
context.load(this.map.id, url);
}
},
/**
* Checks if the module is ready to define itself, and if so,
* define it.
*/
check: function () {
if (!this.enabled || this.enabling) {
return;
}
var err, cjsModule,
id = this.map.id,
depExports = this.depExports,
exports = this.exports,
factory = this.factory;
if (!this.inited) {
this.fetch();
} else if (this.error) {
this.emit('error', this.error);
} else if (!this.defining) {
//The factory could trigger another require call
//that would result in checking this module to
//define itself again. If already in the process
//of doing that, skip this work.
this.defining = true;
if (this.depCount < 1 && !this.defined) {
if (isFunction(factory)) {
//If there is an error listener, favor passing
//to that instead of throwing an error. However,
//only do it for define()'d modules. require
//errbacks should not be called for failures in
//their callbacks (#699). However if a global
//onError is set, use that.
if ((this.events.error && this.map.isDefine) ||
req.onError !== defaultOnError) {
try {
exports = context.execCb(id, factory, depExports, exports);
} catch (e) {
err = e;
}
} else {
exports = context.execCb(id, factory, depExports, exports);
}
// Favor return value over exports. If node/cjs in play,
// then will not have a return value anyway. Favor
// module.exports assignment over exports object.
if (this.map.isDefine && exports === undefined) {
cjsModule = this.module;
if (cjsModule) {
exports = cjsModule.exports;
} else if (this.usingExports) {
//exports already set the defined value.
exports = this.exports;
}
}
if (err) {
err.requireMap = this.map;
err.requireModules = this.map.isDefine ? [this.map.id] : null;
err.requireType = this.map.isDefine ? 'define' : 'require';
return onError((this.error = err));
}
} else {
//Just a literal value
exports = factory;
}
this.exports = exports;
if (this.map.isDefine && !this.ignore) {
defined[id] = exports;
if (req.onResourceLoad) {
req.onResourceLoad(context, this.map, this.depMaps);
}
}
//Clean up
cleanRegistry(id);
this.defined = true;
}
//Finished the define stage. Allow calling check again
//to allow define notifications below in the case of a
//cycle.
this.defining = false;
if (this.defined && !this.defineEmitted) {
this.defineEmitted = true;
this.emit('defined', this.exports);
this.defineEmitComplete = true;
}
}
},
callPlugin: function () {
var map = this.map,
id = map.id,
//Map already normalized the prefix.
pluginMap = makeModuleMap(map.prefix);
//Mark this as a dependency for this plugin, so it
//can be traced for cycles.
this.depMaps.push(pluginMap);
on(pluginMap, 'defined', bind(this, function (plugin) {
var load, normalizedMap, normalizedMod,
bundleId = getOwn(bundlesMap, this.map.id),
name = this.map.name,
parentName = this.map.parentMap ? this.map.parentMap.name : null,
localRequire = context.makeRequire(map.parentMap, {
enableBuildCallback: true
});
//If current map is not normalized, wait for that
//normalized name to load instead of continuing.
if (this.map.unnormalized) {
//Normalize the ID if the plugin allows it.
if (plugin.normalize) {
name = plugin.normalize(name, function (name) {
return normalize(name, parentName, true);
}) || '';
}
//prefix and name should already be normalized, no need
//for applying map config again either.
normalizedMap = makeModuleMap(map.prefix + '!' + name,
this.map.parentMap);
on(normalizedMap,
'defined', bind(this, function (value) {
this.init([], function () { return value; }, null, {
enabled: true,
ignore: true
});
}));
normalizedMod = getOwn(registry, normalizedMap.id);
if (normalizedMod) {
//Mark this as a dependency for this plugin, so it
//can be traced for cycles.
this.depMaps.push(normalizedMap);
if (this.events.error) {
normalizedMod.on('error', bind(this, function (err) {
this.emit('error', err);
}));
}
normalizedMod.enable();
}
return;
}
//If a paths config, then just load that file instead to
//resolve the plugin, as it is built into that paths layer.
if (bundleId) {
this.map.url = context.nameToUrl(bundleId);
this.load();
return;
}
load = bind(this, function (value) {
this.init([], function () { return value; }, null, {
enabled: true
});
});
load.error = bind(this, function (err) {
this.inited = true;
this.error = err;
err.requireModules = [id];
//Remove temp unnormalized modules for this module,
//since they will never be resolved otherwise now.
eachProp(registry, function (mod) {
if (mod.map.id.indexOf(id + '_unnormalized') === 0) {
cleanRegistry(mod.map.id);
}
});
onError(err);
});
//Allow plugins to load other code without having to know the
//context or how to 'complete' the load.
load.fromText = bind(this, function (text, textAlt) {
/*jslint evil: true */
var moduleName = map.name,
moduleMap = makeModuleMap(moduleName),
hasInteractive = useInteractive;
//As of 2.1.0, support just passing the text, to reinforce
//fromText only being called once per resource. Still
//support old style of passing moduleName but discard
//that moduleName in favor of the internal ref.
if (textAlt) {
text = textAlt;
}
//Turn off interactive script matching for IE for any define
//calls in the text, then turn it back on at the end.
if (hasInteractive) {
useInteractive = false;
}
//Prime the system by creating a module instance for
//it.
getModule(moduleMap);
//Transfer any config to this other module.
if (hasProp(config.config, id)) {
config.config[moduleName] = config.config[id];
}
try {
req.exec(text);
} catch (e) {
return onError(makeError('fromtexteval',
'fromText eval for ' + id +
' failed: ' + e,
e,
[id]));
}
if (hasInteractive) {
useInteractive = true;
}
//Mark this as a dependency for the plugin
//resource
this.depMaps.push(moduleMap);
//Support anonymous modules.
context.completeLoad(moduleName);
//Bind the value of that module to the value for this
//resource ID.
localRequire([moduleName], load);
});
//Use parentName here since the plugin's name is not reliable,
//could be some weird string with no path that actually wants to
//reference the parentName's path.
plugin.load(map.name, localRequire, load, config);
}));
context.enable(pluginMap, this);
this.pluginMaps[pluginMap.id] = pluginMap;
},
enable: function () {
enabledRegistry[this.map.id] = this;
this.enabled = true;
//Set flag mentioning that the module is enabling,
//so that immediate calls to the defined callbacks
//for dependencies do not trigger inadvertent load
//with the depCount still being zero.
this.enabling = true;
//Enable each dependency
each(this.depMaps, bind(this, function (depMap, i) {
var id, mod, handler;
if (typeof depMap === 'string') {
//Dependency needs to be converted to a depMap
//and wired up to this module.
depMap = makeModuleMap(depMap,
(this.map.isDefine ? this.map : this.map.parentMap),
false,
!this.skipMap);
this.depMaps[i] = depMap;
handler = getOwn(handlers, depMap.id);
if (handler) {
this.depExports[i] = handler(this);
return;
}
this.depCount += 1;
on(depMap, 'defined', bind(this, function (depExports) {
this.defineDep(i, depExports);
this.check();
}));
if (this.errback) {
on(depMap, 'error', bind(this, this.errback));
}
}
id = depMap.id;
mod = registry[id];
//Skip special modules like 'require', 'exports', 'module'
//Also, don't call enable if it is already enabled,
//important in circular dependency cases.
if (!hasProp(handlers, id) && mod && !mod.enabled) {
context.enable(depMap, this);
}
}));
//Enable each plugin that is used in
//a dependency
eachProp(this.pluginMaps, bind(this, function (pluginMap) {
var mod = getOwn(registry, pluginMap.id);
if (mod && !mod.enabled) {
context.enable(pluginMap, this);
}
}));
this.enabling = false;
this.check();
},
on: function (name, cb) {
var cbs = this.events[name];
if (!cbs) {
cbs = this.events[name] = [];
}
cbs.push(cb);
},
emit: function (name, evt) {
each(this.events[name], function (cb) {
cb(evt);
});
if (name === 'error') {
//Now that the error handler was triggered, remove
//the listeners, since this broken Module instance
//can stay around for a while in the registry.
delete this.events[name];
}
}
};
function callGetModule(args) {
//Skip modules already defined.
if (!hasProp(defined, args[0])) {
getModule(makeModuleMap(args[0], null, true)).init(args[1], args[2]);
}
}
function removeListener(node, func, name, ieName) {
//Favor detachEvent because of IE9
//issue, see attachEvent/addEventListener comment elsewhere
//in this file.
if (node.detachEvent && !isOpera) {
//Probably IE. If not it will throw an error, which will be
//useful to know.
if (ieName) {
node.detachEvent(ieName, func);
}
} else {
node.removeEventListener(name, func, false);
}
}
/**
* Given an event from a script node, get the requirejs info from it,
* and then removes the event listeners on the node.
* @param {Event} evt
* @returns {Object}
*/
function getScriptData(evt) {
//Using currentTarget instead of target for Firefox 2.0's sake. Not
//all old browsers will be supported, but this one was easy enough
//to support and still makes sense.
var node = evt.currentTarget || evt.srcElement;
//Remove the listeners once here.
removeListener(node, context.onScriptLoad, 'load', 'onreadystatechange');
removeListener(node, context.onScriptError, 'error');
return {
node: node,
id: node && node.getAttribute('data-requiremodule')
};
}
function intakeDefines() {
var args;
//Any defined modules in the global queue, intake them now.
takeGlobalQueue();
//Make sure any remaining defQueue items get properly processed.
while (defQueue.length) {
args = defQueue.shift();
if (args[0] === null) {
return onError(makeError('mismatch', 'Mismatched anonymous define() module: ' + args[args.length - 1]));
} else {
//args are id, deps, factory. Should be normalized by the
//define() function.
callGetModule(args);
}
}
}
context = {
config: config,
contextName: contextName,
registry: registry,
defined: defined,
urlFetched: urlFetched,
defQueue: defQueue,
Module: Module,
makeModuleMap: makeModuleMap,
nextTick: req.nextTick,
onError: onError,
/**
* Set a configuration for the context.
* @param {Object} cfg config object to integrate.
*/
configure: function (cfg) {
//Make sure the baseUrl ends in a slash.
if (cfg.baseUrl) {
if (cfg.baseUrl.charAt(cfg.baseUrl.length - 1) !== '/') {
cfg.baseUrl += '/';
}
}
//Save off the paths since they require special processing,
//they are additive.
var shim = config.shim,
objs = {
paths: true,
bundles: true,
config: true,
map: true
};
eachProp(cfg, function (value, prop) {
if (objs[prop]) {
if (!config[prop]) {
config[prop] = {};
}
mixin(config[prop], value, true, true);
} else {
config[prop] = value;
}
});
//Reverse map the bundles
if (cfg.bundles) {
eachProp(cfg.bundles, function (value, prop) {
each(value, function (v) {
if (v !== prop) {
bundlesMap[v] = prop;
}
});
});
}
//Merge shim
if (cfg.shim) {
eachProp(cfg.shim, function (value, id) {
//Normalize the structure
if (isArray(value)) {
value = {
deps: value
};
}
if ((value.exports || value.init) && !value.exportsFn) {
value.exportsFn = context.makeShimExports(value);
}
shim[id] = value;
});
config.shim = shim;
}
//Adjust packages if necessary.
if (cfg.packages) {
each(cfg.packages, function (pkgObj) {
var location, name;
pkgObj = typeof pkgObj === 'string' ? { name: pkgObj } : pkgObj;
name = pkgObj.name;
location = pkgObj.location;
if (location) {
config.paths[name] = pkgObj.location;
}
//Save pointer to main module ID for pkg name.
//Remove leading dot in main, so main paths are normalized,
//and remove any trailing .js, since different package
//envs have different conventions: some use a module name,
//some use a file name.
config.pkgs[name] = pkgObj.name + '/' + (pkgObj.main || 'main')
.replace(currDirRegExp, '')
.replace(jsSuffixRegExp, '');
});
}
//If there are any "waiting to execute" modules in the registry,
//update the maps for them, since their info, like URLs to load,
//may have changed.
eachProp(registry, function (mod, id) {
//If module already has init called, since it is too
//late to modify them, and ignore unnormalized ones
//since they are transient.
if (!mod.inited && !mod.map.unnormalized) {
mod.map = makeModuleMap(id);
}
});
//If a deps array or a config callback is specified, then call
//require with those args. This is useful when require is defined as a
//config object before require.js is loaded.
if (cfg.deps || cfg.callback) {
context.require(cfg.deps || [], cfg.callback);
}
},
makeShimExports: function (value) {
function fn() {
var ret;
if (value.init) {
ret = value.init.apply(global, arguments);
}
return ret || (value.exports && getGlobal(value.exports));
}
return fn;
},
makeRequire: function (relMap, options) {
options = options || {};
function localRequire(deps, callback, errback) {
var id, map, requireMod;
if (options.enableBuildCallback && callback && isFunction(callback)) {
callback.__requireJsBuild = true;
}
if (typeof deps === 'string') {
if (isFunction(callback)) {
//Invalid call
return onError(makeError('requireargs', 'Invalid require call'), errback);
}
//If require|exports|module are requested, get the
//value for them from the special handlers. Caveat:
//this only works while module is being defined.
if (relMap && hasProp(handlers, deps)) {
return handlers[deps](registry[relMap.id]);
}
//Synchronous access to one module. If require.get is
//available (as in the Node adapter), prefer that.
if (req.get) {
return req.get(context, deps, relMap, localRequire);
}
//Normalize module name, if it contains . or ..
map = makeModuleMap(deps, relMap, false, true);
id = map.id;
if (!hasProp(defined, id)) {
return onError(makeError('notloaded', 'Module name "' +
id +
'" has not been loaded yet for context: ' +
contextName +
(relMap ? '' : '. Use require([])')));
}
return defined[id];
}
//Grab defines waiting in the global queue.
intakeDefines();
//Mark all the dependencies as needing to be loaded.
context.nextTick(function () {
//Some defines could have been added since the
//require call, collect them.
intakeDefines();
requireMod = getModule(makeModuleMap(null, relMap));
//Store if map config should be applied to this require
//call for dependencies.
requireMod.skipMap = options.skipMap;
requireMod.init(deps, callback, errback, {
enabled: true
});
checkLoaded();
});
return localRequire;
}
mixin(localRequire, {
isBrowser: isBrowser,
/**
* Converts a module name + .extension into an URL path.
* *Requires* the use of a module name. It does not support using
* plain URLs like nameToUrl.
*/
toUrl: function (moduleNamePlusExt) {
var ext,
index = moduleNamePlusExt.lastIndexOf('.'),
segment = moduleNamePlusExt.split('/')[0],
isRelative = segment === '.' || segment === '..';
//Have a file extension alias, and it is not the
//dots from a relative path.
if (index !== -1 && (!isRelative || index > 1)) {
ext = moduleNamePlusExt.substring(index, moduleNamePlusExt.length);
moduleNamePlusExt = moduleNamePlusExt.substring(0, index);
}
return context.nameToUrl(normalize(moduleNamePlusExt,
relMap && relMap.id, true), ext, true);
},
defined: function (id) {
return hasProp(defined, makeModuleMap(id, relMap, false, true).id);
},
specified: function (id) {
id = makeModuleMap(id, relMap, false, true).id;
return hasProp(defined, id) || hasProp(registry, id);
}
});
//Only allow undef on top level require calls
if (!relMap) {
localRequire.undef = function (id) {
//Bind any waiting define() calls to this context,
//fix for #408
takeGlobalQueue();
var map = makeModuleMap(id, relMap, true),
mod = getOwn(registry, id);
removeScript(id);
delete defined[id];
delete urlFetched[map.url];
delete undefEvents[id];
//Clean queued defines too. Go backwards
//in array so that the splices do not
//mess up the iteration.
eachReverse(defQueue, function (args, i) {
if (args[0] === id) {
defQueue.splice(i, 1);
}
});
if (mod) {
//Hold on to listeners in case the
//module will be attempted to be reloaded
//using a different config.
if (mod.events.defined) {
undefEvents[id] = mod.events;
}
cleanRegistry(id);
}
};
}
return localRequire;
},
/**
* Called to enable a module if it is still in the registry
* awaiting enablement. A second arg, parent, the parent module,
* is passed in for context, when this method is overridden by
* the optimizer. Not shown here to keep code compact.
*/
enable: function (depMap) {
var mod = getOwn(registry, depMap.id);
if (mod) {
getModule(depMap).enable();
}
},
/**
* Internal method used by environment adapters to complete a load event.
* A load event could be a script load or just a load pass from a synchronous
* load call.
* @param {String} moduleName the name of the module to potentially complete.
*/
completeLoad: function (moduleName) {
var found, args, mod,
shim = getOwn(config.shim, moduleName) || {},
shExports = shim.exports;
takeGlobalQueue();
while (defQueue.length) {
args = defQueue.shift();
if (args[0] === null) {
args[0] = moduleName;
//If already found an anonymous module and bound it
//to this name, then this is some other anon module
//waiting for its completeLoad to fire.
if (found) {
break;
}
found = true;
} else if (args[0] === moduleName) {
//Found matching define call for this script!
found = true;
}
callGetModule(args);
}
//Do this after the cycle of callGetModule in case the result
//of those calls/init calls changes the registry.
mod = getOwn(registry, moduleName);
if (!found && !hasProp(defined, moduleName) && mod && !mod.inited) {
if (config.enforceDefine && (!shExports || !getGlobal(shExports))) {
if (hasPathFallback(moduleName)) {
return;
} else {
return onError(makeError('nodefine',
'No define call for ' + moduleName,
null,
[moduleName]));
}
} else {
//A script that does not call define(), so just simulate
//the call for it.
callGetModule([moduleName, (shim.deps || []), shim.exportsFn]);
}
}
checkLoaded();
},
/**
* Converts a module name to a file path. Supports cases where
* moduleName may actually be just an URL.
* Note that it **does not** call normalize on the moduleName,
* it is assumed to have already been normalized. This is an
* internal API, not a public one. Use toUrl for the public API.
*/
nameToUrl: function (moduleName, ext, skipExt) {
var paths, syms, i, parentModule, url,
parentPath, bundleId,
pkgMain = getOwn(config.pkgs, moduleName);
if (pkgMain) {
moduleName = pkgMain;
}
bundleId = getOwn(bundlesMap, moduleName);
if (bundleId) {
return context.nameToUrl(bundleId, ext, skipExt);
}
//If a colon is in the URL, it indicates a protocol is used and it is just
//an URL to a file, or if it starts with a slash, contains a query arg (i.e. ?)
//or ends with .js, then assume the user meant to use an url and not a module id.
//The slash is important for protocol-less URLs as well as full paths.
if (req.jsExtRegExp.test(moduleName)) {
//Just a plain path, not module name lookup, so just return it.
//Add extension if it is included. This is a bit wonky, only non-.js things pass
//an extension, this method probably needs to be reworked.
url = moduleName + (ext || '');
} else {
//A module that needs to be converted to a path.
paths = config.paths;
syms = moduleName.split('/');
//For each module name segment, see if there is a path
//registered for it. Start with most specific name
//and work up from it.
for (i = syms.length; i > 0; i -= 1) {
parentModule = syms.slice(0, i).join('/');
parentPath = getOwn(paths, parentModule);
if (parentPath) {
//If an array, it means there are a few choices,
//Choose the one that is desired
if (isArray(parentPath)) {
parentPath = parentPath[0];
}
syms.splice(0, i, parentPath);
break;
}
}
//Join the path parts together, then figure out if baseUrl is needed.
url = syms.join('/');
url += (ext || (/^data\:|\?/.test(url) || skipExt ? '' : '.js'));
url = (url.charAt(0) === '/' || url.match(/^[\w\+\.\-]+:/) ? '' : config.baseUrl) + url;
}
return config.urlArgs ? url +
((url.indexOf('?') === -1 ? '?' : '&') +
config.urlArgs) : url;
},
//Delegates to req.load. Broken out as a separate function to
//allow overriding in the optimizer.
load: function (id, url) {
req.load(context, id, url);
},
/**
* Executes a module callback function. Broken out as a separate function
* solely to allow the build system to sequence the files in the built
* layer in the right sequence.
*
* @private
*/
execCb: function (name, callback, args, exports) {
return callback.apply(exports, args);
},
/**
* callback for script loads, used to check status of loading.
*
* @param {Event} evt the event from the browser for the script
* that was loaded.
*/
onScriptLoad: function (evt) {
//Using currentTarget instead of target for Firefox 2.0's sake. Not
//all old browsers will be supported, but this one was easy enough
//to support and still makes sense.
if (evt.type === 'load' ||
(readyRegExp.test((evt.currentTarget || evt.srcElement).readyState))) {
//Reset interactive script so a script node is not held onto for
//to long.
interactiveScript = null;
//Pull out the name of the module and the context.
var data = getScriptData(evt);
context.completeLoad(data.id);
}
},
/**
* Callback for script errors.
*/
onScriptError: function (evt) {
var data = getScriptData(evt);
if (!hasPathFallback(data.id)) {
return onError(makeError('scripterror', 'Script error for: ' + data.id, evt, [data.id]));
}
}
};
context.require = context.makeRequire();
return context;
}
/**
* Main entry point.
*
* If the only argument to require is a string, then the module that
* is represented by that string is fetched for the appropriate context.
*
* If the first argument is an array, then it will be treated as an array
* of dependency string names to fetch. An optional function callback can
* be specified to execute when all of those dependencies are available.
*
* Make a local req variable to help Caja compliance (it assumes things
* on a require that are not standardized), and to give a short
* name for minification/local scope use.
*/
req = requirejs = function (deps, callback, errback, optional) {
//Find the right context, use default
var context, config,
contextName = defContextName;
// Determine if have config object in the call.
if (!isArray(deps) && typeof deps !== 'string') {
// deps is a config object
config = deps;
if (isArray(callback)) {
// Adjust args if there are dependencies
deps = callback;
callback = errback;
errback = optional;
} else {
deps = [];
}
}
if (config && config.context) {
contextName = config.context;
}
context = getOwn(contexts, contextName);
if (!context) {
context = contexts[contextName] = req.s.newContext(contextName);
}
if (config) {
context.configure(config);
}
return context.require(deps, callback, errback);
};
/**
* Support require.config() to make it easier to cooperate with other
* AMD loaders on globally agreed names.
*/
req.config = function (config) {
return req(config);
};
/**
* Execute something after the current tick
* of the event loop. Override for other envs
* that have a better solution than setTimeout.
* @param {Function} fn function to execute later.
*/
req.nextTick = typeof setTimeout !== 'undefined' ? function (fn) {
setTimeout(fn, 4);
} : function (fn) { fn(); };
/**
* Export require as a global, but only if it does not already exist.
*/
if (!require) {
require = req;
}
req.version = version;
//Used to filter out dependencies that are already paths.
req.jsExtRegExp = /^\/|:|\?|\.js$/;
req.isBrowser = isBrowser;
s = req.s = {
contexts: contexts,
newContext: newContext
};
//Create default context.
req({});
//Exports some context-sensitive methods on global require.
each([
'toUrl',
'undef',
'defined',
'specified'
], function (prop) {
//Reference from contexts instead of early binding to default context,
//so that during builds, the latest instance of the default context
//with its config gets used.
req[prop] = function () {
var ctx = contexts[defContextName];
return ctx.require[prop].apply(ctx, arguments);
};
});
if (isBrowser) {
head = s.head = document.getElementsByTagName('head')[0];
//If BASE tag is in play, using appendChild is a problem for IE6.
//When that browser dies, this can be removed. Details in this jQuery bug:
//http://dev.jquery.com/ticket/2709
baseElement = document.getElementsByTagName('base')[0];
if (baseElement) {
head = s.head = baseElement.parentNode;
}
}
/**
* Any errors that require explicitly generates will be passed to this
* function. Intercept/override it if you want custom error handling.
* @param {Error} err the error object.
*/
req.onError = defaultOnError;
/**
* Creates the node for the load command. Only used in browser envs.
*/
req.createNode = function (config, moduleName, url) {
var node = config.xhtml ?
document.createElementNS('http://www.w3.org/1999/xhtml', 'html:script') :
document.createElement('script');
node.type = config.scriptType || 'text/javascript';
node.charset = 'utf-8';
node.async = true;
return node;
};
/**
* Does the request to load a module for the browser case.
* Make this a separate function to allow other environments
* to override it.
*
* @param {Object} context the require context to find state.
* @param {String} moduleName the name of the module.
* @param {Object} url the URL to the module.
*/
req.load = function (context, moduleName, url) {
var config = (context && context.config) || {},
node;
if (isBrowser) {
//In the browser so use a script tag
node = req.createNode(config, moduleName, url);
node.setAttribute('data-requirecontext', context.contextName);
node.setAttribute('data-requiremodule', moduleName);
//Set up load listener. Test attachEvent first because IE9 has
//a subtle issue in its addEventListener and script onload firings
//that do not match the behavior of all other browsers with
//addEventListener support, which fire the onload event for a
//script right after the script execution. See:
//https://connect.microsoft.com/IE/feedback/details/648057/script-onload-event-is-not-fired-immediately-after-script-execution
//UNFORTUNATELY Opera implements attachEvent but does not follow the script
//script execution mode.
if (node.attachEvent &&
//Check if node.attachEvent is artificially added by custom script or
//natively supported by browser
//read https://github.com/jrburke/requirejs/issues/187
//if we can NOT find [native code] then it must NOT natively supported.
//in IE8, node.attachEvent does not have toString()
//Note the test for "[native code" with no closing brace, see:
//https://github.com/jrburke/requirejs/issues/273
!(node.attachEvent.toString && node.attachEvent.toString().indexOf('[native code') < 0) &&
!isOpera) {
//Probably IE. IE (at least 6-8) do not fire
//script onload right after executing the script, so
//we cannot tie the anonymous define call to a name.
//However, IE reports the script as being in 'interactive'
//readyState at the time of the define call.
useInteractive = true;
node.attachEvent('onreadystatechange', context.onScriptLoad);
//It would be great to add an error handler here to catch
//404s in IE9+. However, onreadystatechange will fire before
//the error handler, so that does not help. If addEventListener
//is used, then IE will fire error before load, but we cannot
//use that pathway given the connect.microsoft.com issue
//mentioned above about not doing the 'script execute,
//then fire the script load event listener before execute
//next script' that other browsers do.
//Best hope: IE10 fixes the issues,
//and then destroys all installs of IE 6-9.
//node.attachEvent('onerror', context.onScriptError);
} else {
node.addEventListener('load', context.onScriptLoad, false);
node.addEventListener('error', context.onScriptError, false);
}
node.src = url;
//For some cache cases in IE 6-8, the script executes before the end
//of the appendChild execution, so to tie an anonymous define
//call to the module name (which is stored on the node), hold on
//to a reference to this node, but clear after the DOM insertion.
currentlyAddingScript = node;
if (baseElement) {
head.insertBefore(node, baseElement);
} else {
head.appendChild(node);
}
currentlyAddingScript = null;
return node;
} else if (isWebWorker) {
try {
//In a web worker, use importScripts. This is not a very
//efficient use of importScripts, importScripts will block until
//its script is downloaded and evaluated. However, if web workers
//are in play, the expectation that a build has been done so that
//only one script needs to be loaded anyway. This may need to be
//reevaluated if other use cases become common.
importScripts(url);
//Account for anonymous modules
context.completeLoad(moduleName);
} catch (e) {
context.onError(makeError('importscripts',
'importScripts failed for ' +
moduleName + ' at ' + url,
e,
[moduleName]));
}
}
};
function getInteractiveScript() {
if (interactiveScript && interactiveScript.readyState === 'interactive') {
return interactiveScript;
}
eachReverse(scripts(), function (script) {
if (script.readyState === 'interactive') {
return (interactiveScript = script);
}
});
return interactiveScript;
}
//Look for a data-main script attribute, which could also adjust the baseUrl.
if (isBrowser && !cfg.skipDataMain) {
//Figure out baseUrl. Get it from the script tag with require.js in it.
eachReverse(scripts(), function (script) {
//Set the 'head' where we can append children by
//using the script's parent.
if (!head) {
head = script.parentNode;
}
//Look for a data-main attribute to set main script for the page
//to load. If it is there, the path to data main becomes the
//baseUrl, if it is not already set.
dataMain = script.getAttribute('data-main');
if (dataMain) {
//Preserve dataMain in case it is a path (i.e. contains '?')
mainScript = dataMain;
//Set final baseUrl if there is not already an explicit one.
if (!cfg.baseUrl) {
//Pull off the directory of data-main for use as the
//baseUrl.
src = mainScript.split('/');
mainScript = src.pop();
subPath = src.length ? src.join('/') + '/' : './';
cfg.baseUrl = subPath;
}
//Strip off any trailing .js since mainScript is now
//like a module name.
mainScript = mainScript.replace(jsSuffixRegExp, '');
//If mainScript is still a path, fall back to dataMain
if (req.jsExtRegExp.test(mainScript)) {
mainScript = dataMain;
}
//Put the data-main script in the files to load.
cfg.deps = cfg.deps ? cfg.deps.concat(mainScript) : [mainScript];
return true;
}
});
}
/**
* The function that handles definitions of modules. Differs from
* require() in that a string for the module should be the first argument,
* and the function to execute after dependencies are loaded should
* return a value to define the module corresponding to the first argument's
* name.
*/
define = function (name, deps, callback) {
var node, context;
//Allow for anonymous modules
if (typeof name !== 'string') {
//Adjust args appropriately
callback = deps;
deps = name;
name = null;
}
//This module may not have dependencies
if (!isArray(deps)) {
callback = deps;
deps = null;
}
//If no name, and callback is a function, then figure out if it a
//CommonJS thing with dependencies.
if (!deps && isFunction(callback)) {
deps = [];
//Remove comments from the callback string,
//look for require calls, and pull them into the dependencies,
//but only if there are function args.
if (callback.length) {
callback
.toString()
.replace(commentRegExp, '')
.replace(cjsRequireRegExp, function (match, dep) {
deps.push(dep);
});
//May be a CommonJS thing even without require calls, but still
//could use exports, and module. Avoid doing exports and module
//work though if it just needs require.
//REQUIRES the function to expect the CommonJS variables in the
//order listed below.
deps = (callback.length === 1 ? ['require'] : ['require', 'exports', 'module']).concat(deps);
}
}
//If in IE 6-8 and hit an anonymous define() call, do the interactive
//work.
if (useInteractive) {
node = currentlyAddingScript || getInteractiveScript();
if (node) {
if (!name) {
name = node.getAttribute('data-requiremodule');
}
context = contexts[node.getAttribute('data-requirecontext')];
}
}
//Always save off evaluating the def call until the script onload handler.
//This allows multiple modules to be in a file without prematurely
//tracing dependencies, and allows for anonymous module support,
//where the module name is not known until the script onload event
//occurs. If no context, use the global queue, and get it processed
//in the onscript load callback.
(context ? context.defQueue : globalDefQueue).push([name, deps, callback]);
};
define.amd = {
jQuery: true
};
/**
* Executes the text. Normally just uses eval, but can be modified
* to use a better, environment-specific call. Only used for transpiling
* loader plugins, not for plain JS modules.
* @param {String} text the text to execute/evaluate.
*/
req.exec = function (text) {
/*jslint evil: true */
return eval(text);
};
//Set up with config info.
req(cfg);
}(this)); | suttonj/YoutubePlaylistCuratorChromeExtension | src/js/thirdParty/require.js | JavaScript | apache-2.0 | 83,052 |
//// [variadicTuples1.ts]
// Variadics in tuple types
type TV0<T extends unknown[]> = [string, ...T];
type TV1<T extends unknown[]> = [string, ...T, number];
type TV2<T extends unknown[]> = [string, ...T, number, ...T];
type TV3<T extends unknown[]> = [string, ...T, ...number[], ...T];
// Normalization
type TN1 = TV1<[boolean, string]>;
type TN2 = TV1<[]>;
type TN3 = TV1<[boolean?]>;
type TN4 = TV1<string[]>;
type TN5 = TV1<[boolean] | [symbol, symbol]>;
type TN6 = TV1<any>;
type TN7 = TV1<never>;
// Variadics in array literals
function tup2<T extends unknown[], U extends unknown[]>(t: [...T], u: [...U]) {
return [1, ...t, 2, ...u, 3] as const;
}
const t2 = tup2(['hello'], [10, true]);
function concat<T extends unknown[], U extends unknown[]>(t: [...T], u: [...U]): [...T, ...U] {
return [...t, ...u];
}
declare const sa: string[];
const tc1 = concat([], []);
const tc2 = concat(['hello'], [42]);
const tc3 = concat([1, 2, 3], sa);
const tc4 = concat(sa, [1, 2, 3]); // Ideally would be [...string[], number, number, number]
function concat2<T extends readonly unknown[], U extends readonly unknown[]>(t: T, u: U) {
return [...t, ...u]; // (T[number] | U[number])[]
}
const tc5 = concat2([1, 2, 3] as const, [4, 5, 6] as const); // (1 | 2 | 3 | 4 | 5 | 6)[]
// Spread arguments
declare function foo1(a: number, b: string, c: boolean, ...d: number[]): void;
function foo2(t1: [number, string], t2: [boolean], a1: number[]) {
foo1(1, 'abc', true, 42, 43, 44);
foo1(...t1, true, 42, 43, 44);
foo1(...t1, ...t2, 42, 43, 44);
foo1(...t1, ...t2, ...a1);
foo1(...t1); // Error
foo1(...t1, 45); // Error
}
declare function foo3<T extends unknown[]>(x: number, ...args: [...T, number]): T;
function foo4<U extends unknown[]>(u: U) {
foo3(1, 2);
foo3(1, 'hello', true, 2);
foo3(1, ...u, 'hi', 2);
foo3(1);
}
// Contextual typing of array literals
declare function ft1<T extends unknown[]>(t: T): T;
declare function ft2<T extends unknown[]>(t: T): readonly [...T];
declare function ft3<T extends unknown[]>(t: [...T]): T;
declare function ft4<T extends unknown[]>(t: [...T]): readonly [...T];
ft1(['hello', 42]); // (string | number)[]
ft2(['hello', 42]); // readonly (string | number)[]
ft3(['hello', 42]); // [string, number]
ft4(['hello', 42]); // readonly [string, number]
// Indexing variadic tuple types
function f0<T extends unknown[]>(t: [string, ...T], n: number) {
const a = t[0]; // string
const b = t[1]; // [string, ...T][1]
const c = t[2]; // [string, ...T][2]
const d = t[n]; // [string, ...T][number]
}
function f1<T extends unknown[]>(t: [string, ...T, number], n: number) {
const a = t[0]; // string
const b = t[1]; // [string, ...T, number][1]
const c = t[2]; // [string, ...T, number][2]
const d = t[n]; // [string, ...T, number][number]
}
// Destructuring variadic tuple types
function f2<T extends unknown[]>(t: [string, ...T]) {
let [...ax] = t; // [string, ...T]
let [b1, ...bx] = t; // string, [...T]
let [c1, c2, ...cx] = t; // string, [string, ...T][1], T[number][]
}
function f3<T extends unknown[]>(t: [string, ...T, number]) {
let [...ax] = t; // [string, ...T, number]
let [b1, ...bx] = t; // string, [...T, number]
let [c1, c2, ...cx] = t; // string, [string, ...T, number][1], (number | T[number])[]
}
// Mapped types applied to variadic tuple types
type Arrayify<T> = { [P in keyof T]: T[P][] };
type TM1<U extends unknown[]> = Arrayify<readonly [string, number?, ...U, ...boolean[]]>; // [string[], (number | undefined)[]?, Arrayify<U>, ...boolean[][]]
type TP1<T extends unknown[]> = Partial<[string, ...T, number]>; // [string?, Partial<T>, number?]
type TP2<T extends unknown[]> = Partial<[string, ...T, ...number[]]>; // [string?, Partial<T>, ...(number | undefined)[]]
// Reverse mapping through mapped type applied to variadic tuple type
declare function fm1<T extends unknown[]>(t: Arrayify<[string, number, ...T]>): T;
let tm1 = fm1([['abc'], [42], [true], ['def']]); // [boolean, string]
// Spread of readonly array-like infers mutable array-like
declare function fx1<T extends unknown[]>(a: string, ...args: T): T;
function gx1<U extends unknown[], V extends readonly unknown[]>(u: U, v: V) {
fx1('abc'); // []
fx1('abc', ...u); // U
fx1('abc', ...v); // [...V]
fx1<U>('abc', ...u); // U
fx1<V>('abc', ...v); // Error
}
declare function fx2<T extends readonly unknown[]>(a: string, ...args: T): T;
function gx2<U extends unknown[], V extends readonly unknown[]>(u: U, v: V) {
fx2('abc'); // []
fx2('abc', ...u); // U
fx2('abc', ...v); // [...V]
fx2<U>('abc', ...u); // U
fx2<V>('abc', ...v); // V
}
// Relations involving variadic tuple types
function f10<T extends string[], U extends T>(x: [string, ...unknown[]], y: [string, ...T], z: [string, ...U]) {
x = y;
x = z;
y = x; // Error
y = z;
z = x; // Error
z = y; // Error
}
// For a generic type T, [...T] is assignable to T, T is assignable to readonly [...T], and T is assignable
// to [...T] when T is constrained to a mutable array or tuple type.
function f11<T extends unknown[]>(t: T, m: [...T], r: readonly [...T]) {
t = m;
t = r; // Error
m = t;
m = r; // Error
r = t;
r = m;
}
function f12<T extends readonly unknown[]>(t: T, m: [...T], r: readonly [...T]) {
t = m;
t = r; // Error
m = t; // Error
m = r; // Error
r = t;
r = m;
}
function f13<T extends string[], U extends T>(t0: T, t1: [...T], t2: [...U]) {
t0 = t1;
t0 = t2;
t1 = t0;
t1 = t2;
t2 = t0; // Error
t2 = t1; // Error
}
function f14<T extends readonly string[], U extends T>(t0: T, t1: [...T], t2: [...U]) {
t0 = t1;
t0 = t2;
t1 = t0; // Error
t1 = t2;
t2 = t0; // Error
t2 = t1; // Error
}
function f15<T extends string[], U extends T>(k0: keyof T, k1: keyof [...T], k2: keyof [...U], k3: keyof [1, 2, ...T]) {
k0 = 'length';
k1 = 'length';
k2 = 'length';
k0 = 'slice';
k1 = 'slice';
k2 = 'slice';
k3 = '0';
k3 = '1';
k3 = '2'; // Error
}
// Inference between variadic tuple types
type First<T extends readonly unknown[]> =
T extends readonly [unknown, ...unknown[]] ? T[0] :
T[0] | undefined;
type DropFirst<T extends readonly unknown[]> = T extends readonly [unknown?, ...infer U] ? U : [...T];
type Last<T extends readonly unknown[]> =
T extends readonly [...unknown[], infer U] ? U :
T extends readonly [unknown, ...unknown[]] ? T[number] :
T[number] | undefined;
type DropLast<T extends readonly unknown[]> = T extends readonly [...infer U, unknown] ? U : [...T];
type T00 = First<[number, symbol, string]>;
type T01 = First<[symbol, string]>;
type T02 = First<[string]>;
type T03 = First<[number, symbol, ...string[]]>;
type T04 = First<[symbol, ...string[]]>;
type T05 = First<[string?]>;
type T06 = First<string[]>;
type T07 = First<[]>;
type T08 = First<any>;
type T09 = First<never>;
type T10 = DropFirst<[number, symbol, string]>;
type T11 = DropFirst<[symbol, string]>;
type T12 = DropFirst<[string]>;
type T13 = DropFirst<[number, symbol, ...string[]]>;
type T14 = DropFirst<[symbol, ...string[]]>;
type T15 = DropFirst<[string?]>;
type T16 = DropFirst<string[]>;
type T17 = DropFirst<[]>;
type T18 = DropFirst<any>;
type T19 = DropFirst<never>;
type T20 = Last<[number, symbol, string]>;
type T21 = Last<[symbol, string]>;
type T22 = Last<[string]>;
type T23 = Last<[number, symbol, ...string[]]>;
type T24 = Last<[symbol, ...string[]]>;
type T25 = Last<[string?]>;
type T26 = Last<string[]>;
type T27 = Last<[]>;
type T28 = Last<any>;
type T29 = Last<never>;
type T30 = DropLast<[number, symbol, string]>;
type T31 = DropLast<[symbol, string]>;
type T32 = DropLast<[string]>;
type T33 = DropLast<[number, symbol, ...string[]]>;
type T34 = DropLast<[symbol, ...string[]]>;
type T35 = DropLast<[string?]>;
type T36 = DropLast<string[]>;
type T37 = DropLast<[]>; // unknown[], maybe should be []
type T38 = DropLast<any>;
type T39 = DropLast<never>;
type R00 = First<readonly [number, symbol, string]>;
type R01 = First<readonly [symbol, string]>;
type R02 = First<readonly [string]>;
type R03 = First<readonly [number, symbol, ...string[]]>;
type R04 = First<readonly [symbol, ...string[]]>;
type R05 = First<readonly string[]>;
type R06 = First<readonly []>;
type R10 = DropFirst<readonly [number, symbol, string]>;
type R11 = DropFirst<readonly [symbol, string]>;
type R12 = DropFirst<readonly [string]>;
type R13 = DropFirst<readonly [number, symbol, ...string[]]>;
type R14 = DropFirst<readonly [symbol, ...string[]]>;
type R15 = DropFirst<readonly string[]>;
type R16 = DropFirst<readonly []>;
type R20 = Last<readonly [number, symbol, string]>;
type R21 = Last<readonly [symbol, string]>;
type R22 = Last<readonly [string]>;
type R23 = Last<readonly [number, symbol, ...string[]]>;
type R24 = Last<readonly [symbol, ...string[]]>;
type R25 = Last<readonly string[]>;
type R26 = Last<readonly []>;
type R30 = DropLast<readonly [number, symbol, string]>;
type R31 = DropLast<readonly [symbol, string]>;
type R32 = DropLast<readonly [string]>;
type R33 = DropLast<readonly [number, symbol, ...string[]]>;
type R34 = DropLast<readonly [symbol, ...string[]]>;
type R35 = DropLast<readonly string[]>;
type R36 = DropLast<readonly []>;
// Inference to [...T, ...U] with implied arity for T
function curry<T extends unknown[], U extends unknown[], R>(f: (...args: [...T, ...U]) => R, ...a: T) {
return (...b: U) => f(...a, ...b);
}
const fn1 = (a: number, b: string, c: boolean, d: string[]) => 0;
const c0 = curry(fn1); // (a: number, b: string, c: boolean, d: string[]) => number
const c1 = curry(fn1, 1); // (b: string, c: boolean, d: string[]) => number
const c2 = curry(fn1, 1, 'abc'); // (c: boolean, d: string[]) => number
const c3 = curry(fn1, 1, 'abc', true); // (d: string[]) => number
const c4 = curry(fn1, 1, 'abc', true, ['x', 'y']); // () => number
const fn2 = (x: number, b: boolean, ...args: string[]) => 0;
const c10 = curry(fn2); // (x: number, b: boolean, ...args: string[]) => number
const c11 = curry(fn2, 1); // (b: boolean, ...args: string[]) => number
const c12 = curry(fn2, 1, true); // (...args: string[]) => number
const c13 = curry(fn2, 1, true, 'abc', 'def'); // (...args: string[]) => number
const fn3 = (...args: string[]) => 0;
const c20 = curry(fn3); // (...args: string[]) => number
const c21 = curry(fn3, 'abc', 'def'); // (...args: string[]) => number
const c22 = curry(fn3, ...sa); // (...args: string[]) => number
// No inference to [...T, ...U] when there is no implied arity
function curry2<T extends unknown[], U extends unknown[], R>(f: (...args: [...T, ...U]) => R, t: [...T], u: [...U]) {
return f(...t, ...u);
}
declare function fn10(a: string, b: number, c: boolean): string[];
curry2(fn10, ['hello', 42], [true]);
curry2(fn10, ['hello'], [42, true]);
// Inference to [...T] has higher priority than inference to [...T, number?]
declare function ft<T extends unknown[]>(t1: [...T], t2: [...T, number?]): T;
ft([1, 2, 3], [1, 2, 3]);
ft([1, 2], [1, 2, 3]);
ft(['a', 'b'], ['c', 'd'])
ft(['a', 'b'], ['c', 'd', 42])
// Last argument is contextually typed
declare function call<T extends unknown[], R>(...args: [...T, (...args: T) => R]): [T, R];
call('hello', 32, (a, b) => 42);
call(...sa, (...x) => 42);
// No inference to ending optional elements (except with identical structure)
declare function f20<T extends unknown[] = []>(args: [...T, number?]): T;
function f21<U extends string[]>(args: [...U, number?]) {
let v1 = f20(args); // U
let v2 = f20(["foo", "bar"]); // [string]
let v3 = f20(["foo", 42]); // [string]
}
declare function f22<T extends unknown[] = []>(args: [...T, number]): T;
declare function f22<T extends unknown[] = []>(args: [...T]): T;
function f23<U extends string[]>(args: [...U, number]) {
let v1 = f22(args); // U
let v2 = f22(["foo", "bar"]); // [string, string]
let v3 = f22(["foo", 42]); // [string]
}
// Repro from #39327
interface Desc<A extends unknown[], T> {
readonly f: (...args: A) => T;
bind<T extends unknown[], U extends unknown[], R>(this: Desc<[...T, ...U], R>, ...args: T): Desc<[...U], R>;
}
declare const a: Desc<[string, number, boolean], object>;
const b = a.bind("", 1); // Desc<[boolean], object>
// Repro from #39607
declare function getUser(id: string, options?: { x?: string }): string;
declare function getOrgUser(id: string, orgId: number, options?: { y?: number, z?: boolean }): void;
function callApi<T extends unknown[] = [], U = void>(method: (...args: [...T, object]) => U) {
return (...args: [...T]) => method(...args, {});
}
callApi(getUser);
callApi(getOrgUser);
// Repro from #40235
type Numbers = number[];
type Unbounded = [...Numbers, boolean];
const data: Unbounded = [false, false]; // Error
type U1 = [string, ...Numbers, boolean];
type U2 = [...[string, ...Numbers], boolean];
type U3 = [...[string, number], boolean];
//// [variadicTuples1.js]
"use strict";
// Variadics in tuple types
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
if (ar || !(i in from)) {
if (!ar) ar = Array.prototype.slice.call(from, 0, i);
ar[i] = from[i];
}
}
return to.concat(ar || Array.prototype.slice.call(from));
};
// Variadics in array literals
function tup2(t, u) {
return __spreadArray(__spreadArray(__spreadArray(__spreadArray([1], t, true), [2], false), u, true), [3], false);
}
var t2 = tup2(['hello'], [10, true]);
function concat(t, u) {
return __spreadArray(__spreadArray([], t, true), u, true);
}
var tc1 = concat([], []);
var tc2 = concat(['hello'], [42]);
var tc3 = concat([1, 2, 3], sa);
var tc4 = concat(sa, [1, 2, 3]); // Ideally would be [...string[], number, number, number]
function concat2(t, u) {
return __spreadArray(__spreadArray([], t, true), u, true); // (T[number] | U[number])[]
}
var tc5 = concat2([1, 2, 3], [4, 5, 6]); // (1 | 2 | 3 | 4 | 5 | 6)[]
function foo2(t1, t2, a1) {
foo1(1, 'abc', true, 42, 43, 44);
foo1.apply(void 0, __spreadArray(__spreadArray([], t1, false), [true, 42, 43, 44], false));
foo1.apply(void 0, __spreadArray(__spreadArray(__spreadArray([], t1, false), t2, false), [42, 43, 44], false));
foo1.apply(void 0, __spreadArray(__spreadArray(__spreadArray([], t1, false), t2, false), a1, false));
foo1.apply(void 0, t1); // Error
foo1.apply(void 0, __spreadArray(__spreadArray([], t1, false), [45], false)); // Error
}
function foo4(u) {
foo3(1, 2);
foo3(1, 'hello', true, 2);
foo3.apply(void 0, __spreadArray(__spreadArray([1], u, false), ['hi', 2], false));
foo3(1);
}
ft1(['hello', 42]); // (string | number)[]
ft2(['hello', 42]); // readonly (string | number)[]
ft3(['hello', 42]); // [string, number]
ft4(['hello', 42]); // readonly [string, number]
// Indexing variadic tuple types
function f0(t, n) {
var a = t[0]; // string
var b = t[1]; // [string, ...T][1]
var c = t[2]; // [string, ...T][2]
var d = t[n]; // [string, ...T][number]
}
function f1(t, n) {
var a = t[0]; // string
var b = t[1]; // [string, ...T, number][1]
var c = t[2]; // [string, ...T, number][2]
var d = t[n]; // [string, ...T, number][number]
}
// Destructuring variadic tuple types
function f2(t) {
var ax = t.slice(0); // [string, ...T]
var b1 = t[0], bx = t.slice(1); // string, [...T]
var c1 = t[0], c2 = t[1], cx = t.slice(2); // string, [string, ...T][1], T[number][]
}
function f3(t) {
var ax = t.slice(0); // [string, ...T, number]
var b1 = t[0], bx = t.slice(1); // string, [...T, number]
var c1 = t[0], c2 = t[1], cx = t.slice(2); // string, [string, ...T, number][1], (number | T[number])[]
}
var tm1 = fm1([['abc'], [42], [true], ['def']]); // [boolean, string]
function gx1(u, v) {
fx1('abc'); // []
fx1.apply(void 0, __spreadArray(['abc'], u, false)); // U
fx1.apply(void 0, __spreadArray(['abc'], v, false)); // [...V]
fx1.apply(void 0, __spreadArray(['abc'], u, false)); // U
fx1.apply(void 0, __spreadArray(['abc'], v, false)); // Error
}
function gx2(u, v) {
fx2('abc'); // []
fx2.apply(void 0, __spreadArray(['abc'], u, false)); // U
fx2.apply(void 0, __spreadArray(['abc'], v, false)); // [...V]
fx2.apply(void 0, __spreadArray(['abc'], u, false)); // U
fx2.apply(void 0, __spreadArray(['abc'], v, false)); // V
}
// Relations involving variadic tuple types
function f10(x, y, z) {
x = y;
x = z;
y = x; // Error
y = z;
z = x; // Error
z = y; // Error
}
// For a generic type T, [...T] is assignable to T, T is assignable to readonly [...T], and T is assignable
// to [...T] when T is constrained to a mutable array or tuple type.
function f11(t, m, r) {
t = m;
t = r; // Error
m = t;
m = r; // Error
r = t;
r = m;
}
function f12(t, m, r) {
t = m;
t = r; // Error
m = t; // Error
m = r; // Error
r = t;
r = m;
}
function f13(t0, t1, t2) {
t0 = t1;
t0 = t2;
t1 = t0;
t1 = t2;
t2 = t0; // Error
t2 = t1; // Error
}
function f14(t0, t1, t2) {
t0 = t1;
t0 = t2;
t1 = t0; // Error
t1 = t2;
t2 = t0; // Error
t2 = t1; // Error
}
function f15(k0, k1, k2, k3) {
k0 = 'length';
k1 = 'length';
k2 = 'length';
k0 = 'slice';
k1 = 'slice';
k2 = 'slice';
k3 = '0';
k3 = '1';
k3 = '2'; // Error
}
// Inference to [...T, ...U] with implied arity for T
function curry(f) {
var a = [];
for (var _i = 1; _i < arguments.length; _i++) {
a[_i - 1] = arguments[_i];
}
return function () {
var b = [];
for (var _i = 0; _i < arguments.length; _i++) {
b[_i] = arguments[_i];
}
return f.apply(void 0, __spreadArray(__spreadArray([], a, false), b, false));
};
}
var fn1 = function (a, b, c, d) { return 0; };
var c0 = curry(fn1); // (a: number, b: string, c: boolean, d: string[]) => number
var c1 = curry(fn1, 1); // (b: string, c: boolean, d: string[]) => number
var c2 = curry(fn1, 1, 'abc'); // (c: boolean, d: string[]) => number
var c3 = curry(fn1, 1, 'abc', true); // (d: string[]) => number
var c4 = curry(fn1, 1, 'abc', true, ['x', 'y']); // () => number
var fn2 = function (x, b) {
var args = [];
for (var _i = 2; _i < arguments.length; _i++) {
args[_i - 2] = arguments[_i];
}
return 0;
};
var c10 = curry(fn2); // (x: number, b: boolean, ...args: string[]) => number
var c11 = curry(fn2, 1); // (b: boolean, ...args: string[]) => number
var c12 = curry(fn2, 1, true); // (...args: string[]) => number
var c13 = curry(fn2, 1, true, 'abc', 'def'); // (...args: string[]) => number
var fn3 = function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
return 0;
};
var c20 = curry(fn3); // (...args: string[]) => number
var c21 = curry(fn3, 'abc', 'def'); // (...args: string[]) => number
var c22 = curry.apply(void 0, __spreadArray([fn3], sa, false)); // (...args: string[]) => number
// No inference to [...T, ...U] when there is no implied arity
function curry2(f, t, u) {
return f.apply(void 0, __spreadArray(__spreadArray([], t, false), u, false));
}
curry2(fn10, ['hello', 42], [true]);
curry2(fn10, ['hello'], [42, true]);
ft([1, 2, 3], [1, 2, 3]);
ft([1, 2], [1, 2, 3]);
ft(['a', 'b'], ['c', 'd']);
ft(['a', 'b'], ['c', 'd', 42]);
call('hello', 32, function (a, b) { return 42; });
call.apply(void 0, __spreadArray(__spreadArray([], sa, false), [function () {
var x = [];
for (var _i = 0; _i < arguments.length; _i++) {
x[_i] = arguments[_i];
}
return 42;
}], false));
function f21(args) {
var v1 = f20(args); // U
var v2 = f20(["foo", "bar"]); // [string]
var v3 = f20(["foo", 42]); // [string]
}
function f23(args) {
var v1 = f22(args); // U
var v2 = f22(["foo", "bar"]); // [string, string]
var v3 = f22(["foo", 42]); // [string]
}
var b = a.bind("", 1); // Desc<[boolean], object>
function callApi(method) {
return function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
return method.apply(void 0, __spreadArray(__spreadArray([], args, false), [{}], false));
};
}
callApi(getUser);
callApi(getOrgUser);
var data = [false, false]; // Error
//// [variadicTuples1.d.ts]
declare type TV0<T extends unknown[]> = [string, ...T];
declare type TV1<T extends unknown[]> = [string, ...T, number];
declare type TV2<T extends unknown[]> = [string, ...T, number, ...T];
declare type TV3<T extends unknown[]> = [string, ...T, ...number[], ...T];
declare type TN1 = TV1<[boolean, string]>;
declare type TN2 = TV1<[]>;
declare type TN3 = TV1<[boolean?]>;
declare type TN4 = TV1<string[]>;
declare type TN5 = TV1<[boolean] | [symbol, symbol]>;
declare type TN6 = TV1<any>;
declare type TN7 = TV1<never>;
declare function tup2<T extends unknown[], U extends unknown[]>(t: [...T], u: [...U]): readonly [1, ...T, 2, ...U, 3];
declare const t2: readonly [1, string, 2, number, boolean, 3];
declare function concat<T extends unknown[], U extends unknown[]>(t: [...T], u: [...U]): [...T, ...U];
declare const sa: string[];
declare const tc1: [];
declare const tc2: [string, number];
declare const tc3: [number, number, number, ...string[]];
declare const tc4: [...string[], number, number, number];
declare function concat2<T extends readonly unknown[], U extends readonly unknown[]>(t: T, u: U): (T[number] | U[number])[];
declare const tc5: (2 | 4 | 1 | 3 | 6 | 5)[];
declare function foo1(a: number, b: string, c: boolean, ...d: number[]): void;
declare function foo2(t1: [number, string], t2: [boolean], a1: number[]): void;
declare function foo3<T extends unknown[]>(x: number, ...args: [...T, number]): T;
declare function foo4<U extends unknown[]>(u: U): void;
declare function ft1<T extends unknown[]>(t: T): T;
declare function ft2<T extends unknown[]>(t: T): readonly [...T];
declare function ft3<T extends unknown[]>(t: [...T]): T;
declare function ft4<T extends unknown[]>(t: [...T]): readonly [...T];
declare function f0<T extends unknown[]>(t: [string, ...T], n: number): void;
declare function f1<T extends unknown[]>(t: [string, ...T, number], n: number): void;
declare function f2<T extends unknown[]>(t: [string, ...T]): void;
declare function f3<T extends unknown[]>(t: [string, ...T, number]): void;
declare type Arrayify<T> = {
[P in keyof T]: T[P][];
};
declare type TM1<U extends unknown[]> = Arrayify<readonly [string, number?, ...U, ...boolean[]]>;
declare type TP1<T extends unknown[]> = Partial<[string, ...T, number]>;
declare type TP2<T extends unknown[]> = Partial<[string, ...T, ...number[]]>;
declare function fm1<T extends unknown[]>(t: Arrayify<[string, number, ...T]>): T;
declare let tm1: [boolean, string];
declare function fx1<T extends unknown[]>(a: string, ...args: T): T;
declare function gx1<U extends unknown[], V extends readonly unknown[]>(u: U, v: V): void;
declare function fx2<T extends readonly unknown[]>(a: string, ...args: T): T;
declare function gx2<U extends unknown[], V extends readonly unknown[]>(u: U, v: V): void;
declare function f10<T extends string[], U extends T>(x: [string, ...unknown[]], y: [string, ...T], z: [string, ...U]): void;
declare function f11<T extends unknown[]>(t: T, m: [...T], r: readonly [...T]): void;
declare function f12<T extends readonly unknown[]>(t: T, m: [...T], r: readonly [...T]): void;
declare function f13<T extends string[], U extends T>(t0: T, t1: [...T], t2: [...U]): void;
declare function f14<T extends readonly string[], U extends T>(t0: T, t1: [...T], t2: [...U]): void;
declare function f15<T extends string[], U extends T>(k0: keyof T, k1: keyof [...T], k2: keyof [...U], k3: keyof [1, 2, ...T]): void;
declare type First<T extends readonly unknown[]> = T extends readonly [unknown, ...unknown[]] ? T[0] : T[0] | undefined;
declare type DropFirst<T extends readonly unknown[]> = T extends readonly [unknown?, ...infer U] ? U : [...T];
declare type Last<T extends readonly unknown[]> = T extends readonly [...unknown[], infer U] ? U : T extends readonly [unknown, ...unknown[]] ? T[number] : T[number] | undefined;
declare type DropLast<T extends readonly unknown[]> = T extends readonly [...infer U, unknown] ? U : [...T];
declare type T00 = First<[number, symbol, string]>;
declare type T01 = First<[symbol, string]>;
declare type T02 = First<[string]>;
declare type T03 = First<[number, symbol, ...string[]]>;
declare type T04 = First<[symbol, ...string[]]>;
declare type T05 = First<[string?]>;
declare type T06 = First<string[]>;
declare type T07 = First<[]>;
declare type T08 = First<any>;
declare type T09 = First<never>;
declare type T10 = DropFirst<[number, symbol, string]>;
declare type T11 = DropFirst<[symbol, string]>;
declare type T12 = DropFirst<[string]>;
declare type T13 = DropFirst<[number, symbol, ...string[]]>;
declare type T14 = DropFirst<[symbol, ...string[]]>;
declare type T15 = DropFirst<[string?]>;
declare type T16 = DropFirst<string[]>;
declare type T17 = DropFirst<[]>;
declare type T18 = DropFirst<any>;
declare type T19 = DropFirst<never>;
declare type T20 = Last<[number, symbol, string]>;
declare type T21 = Last<[symbol, string]>;
declare type T22 = Last<[string]>;
declare type T23 = Last<[number, symbol, ...string[]]>;
declare type T24 = Last<[symbol, ...string[]]>;
declare type T25 = Last<[string?]>;
declare type T26 = Last<string[]>;
declare type T27 = Last<[]>;
declare type T28 = Last<any>;
declare type T29 = Last<never>;
declare type T30 = DropLast<[number, symbol, string]>;
declare type T31 = DropLast<[symbol, string]>;
declare type T32 = DropLast<[string]>;
declare type T33 = DropLast<[number, symbol, ...string[]]>;
declare type T34 = DropLast<[symbol, ...string[]]>;
declare type T35 = DropLast<[string?]>;
declare type T36 = DropLast<string[]>;
declare type T37 = DropLast<[]>;
declare type T38 = DropLast<any>;
declare type T39 = DropLast<never>;
declare type R00 = First<readonly [number, symbol, string]>;
declare type R01 = First<readonly [symbol, string]>;
declare type R02 = First<readonly [string]>;
declare type R03 = First<readonly [number, symbol, ...string[]]>;
declare type R04 = First<readonly [symbol, ...string[]]>;
declare type R05 = First<readonly string[]>;
declare type R06 = First<readonly []>;
declare type R10 = DropFirst<readonly [number, symbol, string]>;
declare type R11 = DropFirst<readonly [symbol, string]>;
declare type R12 = DropFirst<readonly [string]>;
declare type R13 = DropFirst<readonly [number, symbol, ...string[]]>;
declare type R14 = DropFirst<readonly [symbol, ...string[]]>;
declare type R15 = DropFirst<readonly string[]>;
declare type R16 = DropFirst<readonly []>;
declare type R20 = Last<readonly [number, symbol, string]>;
declare type R21 = Last<readonly [symbol, string]>;
declare type R22 = Last<readonly [string]>;
declare type R23 = Last<readonly [number, symbol, ...string[]]>;
declare type R24 = Last<readonly [symbol, ...string[]]>;
declare type R25 = Last<readonly string[]>;
declare type R26 = Last<readonly []>;
declare type R30 = DropLast<readonly [number, symbol, string]>;
declare type R31 = DropLast<readonly [symbol, string]>;
declare type R32 = DropLast<readonly [string]>;
declare type R33 = DropLast<readonly [number, symbol, ...string[]]>;
declare type R34 = DropLast<readonly [symbol, ...string[]]>;
declare type R35 = DropLast<readonly string[]>;
declare type R36 = DropLast<readonly []>;
declare function curry<T extends unknown[], U extends unknown[], R>(f: (...args: [...T, ...U]) => R, ...a: T): (...b: U) => R;
declare const fn1: (a: number, b: string, c: boolean, d: string[]) => number;
declare const c0: (a: number, b: string, c: boolean, d: string[]) => number;
declare const c1: (b: string, c: boolean, d: string[]) => number;
declare const c2: (c: boolean, d: string[]) => number;
declare const c3: (d: string[]) => number;
declare const c4: () => number;
declare const fn2: (x: number, b: boolean, ...args: string[]) => number;
declare const c10: (x: number, b: boolean, ...args: string[]) => number;
declare const c11: (b: boolean, ...args: string[]) => number;
declare const c12: (...b: string[]) => number;
declare const c13: (...b: string[]) => number;
declare const fn3: (...args: string[]) => number;
declare const c20: (...b: string[]) => number;
declare const c21: (...b: string[]) => number;
declare const c22: (...b: string[]) => number;
declare function curry2<T extends unknown[], U extends unknown[], R>(f: (...args: [...T, ...U]) => R, t: [...T], u: [...U]): R;
declare function fn10(a: string, b: number, c: boolean): string[];
declare function ft<T extends unknown[]>(t1: [...T], t2: [...T, number?]): T;
declare function call<T extends unknown[], R>(...args: [...T, (...args: T) => R]): [T, R];
declare function f20<T extends unknown[] = []>(args: [...T, number?]): T;
declare function f21<U extends string[]>(args: [...U, number?]): void;
declare function f22<T extends unknown[] = []>(args: [...T, number]): T;
declare function f22<T extends unknown[] = []>(args: [...T]): T;
declare function f23<U extends string[]>(args: [...U, number]): void;
interface Desc<A extends unknown[], T> {
readonly f: (...args: A) => T;
bind<T extends unknown[], U extends unknown[], R>(this: Desc<[...T, ...U], R>, ...args: T): Desc<[...U], R>;
}
declare const a: Desc<[string, number, boolean], object>;
declare const b: Desc<[boolean], object>;
declare function getUser(id: string, options?: {
x?: string;
}): string;
declare function getOrgUser(id: string, orgId: number, options?: {
y?: number;
z?: boolean;
}): void;
declare function callApi<T extends unknown[] = [], U = void>(method: (...args: [...T, object]) => U): (...args_0: T) => U;
declare type Numbers = number[];
declare type Unbounded = [...Numbers, boolean];
declare const data: Unbounded;
declare type U1 = [string, ...Numbers, boolean];
declare type U2 = [...[string, ...Numbers], boolean];
declare type U3 = [...[string, number], boolean];
| Microsoft/TypeScript | tests/baselines/reference/variadicTuples1.js | JavaScript | apache-2.0 | 30,820 |
function ChangeTo(to) {
if (to == "text") {
$('#admincommentlinks').ghide();
$('#admincomment').gshow();
resize('admincomment');
var buttons = document.getElementsByName('admincommentbutton');
for (var i = 0; i < buttons.length; i++) {
buttons[i].setAttribute('onclick',"ChangeTo('links'); return false;");
}
} else if (to == "links") {
ajax.post("ajax.php?action=preview","form", function(response) {
$('#admincommentlinks').raw().innerHTML = response;
$('#admincomment').ghide();
$('#admincommentlinks').gshow();
var buttons = document.getElementsByName('admincommentbutton');
for (var i = 0; i < buttons.length; i++) {
buttons[i].setAttribute('onclick',"ChangeTo('text'); return false;");
}
})
}
}
function UncheckIfDisabled(checkbox) {
if (checkbox.disabled) {
checkbox.checked = false;
}
}
function AlterParanoia() {
// Required Ratio is almost deducible from downloaded, the count of seeding and the count of snatched
// we will "warn" the user by automatically checking the required ratio box when they are
// revealing that information elsewhere
if (!$('input[name=p_ratio]').raw()) {
return;
}
var showDownload = $('input[name=p_downloaded]').raw().checked || ($('input[name=p_uploaded]').raw().checked && $('input[name=p_ratio]').raw().checked);
if (($('input[name=p_seeding_c]').raw().checked) && ($('input[name=p_snatched_c]').raw().checked) && showDownload) {
$('input[type=checkbox][name=p_requiredratio]').raw().checked = true;
$('input[type=checkbox][name=p_requiredratio]').raw().disabled = true;
} else {
$('input[type=checkbox][name=p_requiredratio]').raw().disabled = false;
}
$('input[name=p_torrentcomments_l]').raw().disabled = !$('input[name=p_torrentcomments_c]').raw().checked;
$('input[name=p_collagecontribs_l]').raw().disabled = !$('input[name=p_collagecontribs_c]').raw().checked;
$('input[name=p_requestsfilled_list]').raw().disabled = !($('input[name=p_requestsfilled_count]').raw().checked && $('input[name=p_requestsfilled_bounty]').raw().checked);
$('input[name=p_requestsvoted_list]').raw().disabled = !($('input[name=p_requestsvoted_count]').raw().checked && $('input[name=p_requestsvoted_bounty]').raw().checked);
$('input[name=p_uploads_l]').raw().disabled = !$('input[name=p_uploads_c]').raw().checked;
$('input[name=p_uniquegroups_l]').raw().disabled = !$('input[name=p_uniquegroups_c]').raw().checked;
$('input[name=p_perfectflacs_l]').raw().disabled = !$('input[name=p_perfectflacs_c]').raw().checked;
$('input[name=p_seeding_l]').raw().disabled = !$('input[name=p_seeding_c]').raw().checked;
$('input[name=p_leeching_l]').raw().disabled = !$('input[name=p_leeching_c]').raw().checked;
$('input[name=p_snatched_l]').raw().disabled = !$('input[name=p_snatched_c]').raw().checked;
UncheckIfDisabled($('input[name=p_torrentcomments_l]').raw());
UncheckIfDisabled($('input[name=p_collagecontribs_l]').raw());
UncheckIfDisabled($('input[name=p_requestsfilled_list]').raw());
UncheckIfDisabled($('input[name=p_requestsvoted_list]').raw());
UncheckIfDisabled($('input[name=p_uploads_l]').raw());
UncheckIfDisabled($('input[name=p_uniquegroups_l]').raw());
UncheckIfDisabled($('input[name=p_perfectflacs_l]').raw());
UncheckIfDisabled($('input[name=p_seeding_l]').raw());
UncheckIfDisabled($('input[name=p_leeching_l]').raw());
UncheckIfDisabled($('input[name=p_snatched_l]').raw());
// unique groups, "Perfect" FLACs and artists added are deducible from the list of uploads
if ($('input[name=p_uploads_l]').raw().checked) {
$('input[name=p_uniquegroups_c]').raw().checked = true;
$('input[name=p_uniquegroups_l]').raw().checked = true;
$('input[name=p_uniquegroups_c]').raw().disabled = true;
$('input[name=p_uniquegroups_l]').raw().disabled = true;
$('input[name=p_perfectflacs_c]').raw().checked = true;
$('input[name=p_perfectflacs_l]').raw().checked = true;
$('input[name=p_perfectflacs_c]').raw().disabled = true;
$('input[name=p_perfectflacs_l]').raw().disabled = true;
$('input[type=checkbox][name=p_artistsadded]').raw().checked = true;
$('input[type=checkbox][name=p_artistsadded]').raw().disabled = true;
} else {
$('input[name=p_uniquegroups_c]').raw().disabled = false;
$('input[name=p_uniquegroups_l]').raw().checked = false;
$('input[name=p_uniquegroups_l]').raw().disabled = true;
$('input[name=p_perfectflacs_c]').raw().disabled = false;
$('input[type=checkbox][name=p_artistsadded]').raw().disabled = false;
}
if ($('input[name=p_collagecontribs_l]').raw().checked) {
$('input[name=p_collages_c]').raw().disabled = true;
$('input[name=p_collages_l]').raw().disabled = true;
$('input[name=p_collages_c]').raw().checked = true;
$('input[name=p_collages_l]').raw().checked = true;
} else {
$('input[name=p_collages_c]').raw().disabled = false;
$('input[name=p_collages_l]').raw().disabled = !$('input[name=p_collages_c]').raw().checked;
UncheckIfDisabled($('input[name=p_collages_l]').raw());
}
}
function ParanoiaReset(checkbox, drops) {
var selects = $('select');
for (var i = 0; i < selects.results(); i++) {
if (selects.raw(i).name.match(/^p_/)) {
if (drops == 0) {
selects.raw(i).selectedIndex = 0;
} else if (drops == 1) {
selects.raw(i).selectedIndex = selects.raw(i).options.length - 2;
} else if (drops == 2) {
selects.raw(i).selectedIndex = selects.raw(i).options.length - 1;
}
AlterParanoia();
}
}
var checkboxes = $(':checkbox');
for (var i = 0; i < checkboxes.results(); i++) {
if (checkboxes.raw(i).name.match(/^p_/) && (checkboxes.raw(i).name != 'p_lastseen')) {
if (checkbox == 3) {
checkboxes.raw(i).checked = !(checkboxes.raw(i).name.match(/_list$/) || checkboxes.raw(i).name.match(/_l$/));
} else {
checkboxes.raw(i).checked = checkbox;
}
AlterParanoia();
}
}
}
function ParanoiaResetOff() {
ParanoiaReset(true, 0);
}
function ParanoiaResetStats() {
ParanoiaReset(3, 0);
$('input[name=p_collages_l]').raw().checked = false;
}
function ParanoiaResetOn() {
ParanoiaReset(false, 0);
$('input[name=p_collages_c]').raw().checked = false;
$('input[name=p_collages_l]').raw().checked = false;
}
addDOMLoadEvent(AlterParanoia);
function ToggleWarningAdjust(selector) {
if (selector.options[selector.selectedIndex].value == '---') {
$('#ReduceWarningTR').gshow();
$('#ReduceWarning').raw().disabled = false;
} else {
$('#ReduceWarningTR').ghide();
$('#ReduceWarning').raw().disabled = true;
}
}
addDOMLoadEvent(ToggleIdenticons);
function ToggleIdenticons() {
var disableAvatars = $('#disableavatars');
if (disableAvatars.size()) {
var selected = disableAvatars[0].selectedIndex;
if (selected == 2 || selected == 3) {
$('#identicons').gshow();
} else {
$('#identicons').ghide();
}
}
}
function userform_submit() {
if ($('#resetpasskey').is(':checked')) {
if (!confirm('Are you sure you want to reset your passkey?')) {
return false;
}
}
return formVal();
}
function togglePassKey(key) {
if ($('#passkey').raw().innerHTML == 'View') {
$('#passkey').raw().innerHTML = key;
} else {
$('#passkey').raw().innerHTML = 'View';
}
}
function commStats(userid) {
$('.user_commstats').html('Loading...');
ajax.get('ajax.php?action=community_stats&userid=' + userid, function(JSONresponse) {
var response = JSON.parse(JSONresponse) || false;
if (!response || response.status == 'failure') {
$('.user_commstats').html('An error occurred');
return;
}
displayCommStats(response.response);
});
}
function displayCommStats(stats) {
var baseid = '#user_commstats_';
for (x in stats) {
if (stats[x] === false) {
continue;
}
switch (x) {
case 'leeching':
$(baseid + x).html(stats[x]);
break;
case 'seeding':
$(baseid + x).html(stats[x]);
break;
case 'downloaded':
$(baseid + x).html(stats[x]);
break;
case 'snatched':
$(baseid + x).html(stats[x]);
break;
case 'usnatched':
$(baseid + x).html('(' + stats[x] + ')');
break;
case 'udownloaded':
$(baseid + x).html('(' + stats[x] + ')');
break;
case 'seedingperc':
$(baseid + x).html('(' + stats[x] + '%)');
break;
}
}
}
$(document).ready(function() {
$("#random_password").click(function() {
var length = 15,
charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()_+-=<>?",
password = "";
for (var i = 0, n = charset.length; i < length; ++i) {
password += charset.charAt(Math.floor(Math.random() * n));
}
$('#change_password').val(password);
});
});
| tisnats/tisnats.com | static/functions/user.js | JavaScript | apache-2.0 | 8,556 |
const NamingMixin = {
_name: null,
getName() {
return this._name;
},
_shortName: null,
getShortName() {
return this._shortName || this.getName();
},
_abbreviation: null,
getAbbreviation() {
return this._abbreviation || this.getShortName();
},
};
export default NamingMixin;
| kjirou/reversi-tactics | src/mixins/NamingMixin.js | JavaScript | apache-2.0 | 309 |
var searchData=
[
['value',['value',['../structguac__pool__int.html#af76ff5f21c6e0f69d95cdd1385ea24a4',1,'guac_pool_int']]],
['vguac_5fclient_5fabort',['vguac_client_abort',['../client_8h.html#a4c0eccd7d0ed3dbf3e7941ce297e0224',1,'client.h']]],
['vguac_5fclient_5flog',['vguac_client_log',['../client_8h.html#a37a0fa9cfc4c02236085e3852972f494',1,'client.h']]],
['vguac_5fprotocol_5fsend_5flog',['vguac_protocol_send_log',['../protocol_8h.html#a3a783d771e1727ba2a82b2298acf4ee4',1,'protocol.h']]],
['video_5fmimetypes',['video_mimetypes',['../structguac__client__info.html#aa58dc4ee1e3b8801e9b0abbf9135d8b6',1,'guac_client_info']]]
];
| mike-jumper/incubator-guacamole-website | doc/0.9.9/libguac/search/all_12.js | JavaScript | apache-2.0 | 644 |
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is
* regenerated.
*/
'use strict';
/**
* @class
* Initializes a new instance of the DataSourceListResult class.
* @constructor
* The list data source by workspace operation response.
*
* @member {string} [nextLink] The link (url) to the next page of datasources.
*
*/
class DataSourceListResult extends Array {
constructor() {
super();
}
/**
* Defines the metadata of DataSourceListResult
*
* @returns {object} metadata of DataSourceListResult
*
*/
mapper() {
return {
required: false,
serializedName: 'DataSourceListResult',
type: {
name: 'Composite',
className: 'DataSourceListResult',
modelProperties: {
value: {
required: false,
serializedName: '',
type: {
name: 'Sequence',
element: {
required: false,
serializedName: 'DataSourceElementType',
type: {
name: 'Composite',
className: 'DataSource'
}
}
}
},
nextLink: {
required: false,
serializedName: 'nextLink',
type: {
name: 'String'
}
}
}
}
};
}
}
module.exports = DataSourceListResult;
| AuxMon/azure-sdk-for-node | lib/services/operationalInsightsManagement/lib/models/dataSourceListResult.js | JavaScript | apache-2.0 | 1,648 |
/*!
* UI development toolkit for HTML5 (OpenUI5)
* (c) Copyright 2009-2016 SAP SE or an SAP affiliate company.
* Licensed under the Apache License, Version 2.0 - see LICENSE.txt.
*/
// Provides control sap.m.PageAccessibleLandmarkInfo.
sap.ui.define(['sap/ui/core/Element', './library'],
function(Element, library) {
"use strict";
/**
* Constructor for a new <code>sap.m.PageAccessibleLandmarkInfo</code> element.
*
* @param {string} [sId] Id for the new element, generated automatically if no id is given
* @param {object} [mSettings] Initial settings for the new element
*
* @class
* Settings for accessible landmarks which can be applied to the container elements of a <code>sap.m.Page</code> control.
* These landmarks are e.g. used by assistive technologies (like screenreaders) to provide a meaningful page overview.
* @extends sap.ui.core.Element
*
* @author SAP SE
* @version 1.42.8
*
* @constructor
* @public
* @alias sap.m.PageAccessibleLandmarkInfo
* @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
*/
var PageAccessibleLandmarkInfo = Element.extend("sap.m.PageAccessibleLandmarkInfo", /** @lends sap.m.PageAccessibleLandmarkInfo.prototype */ { metadata : {
library : "sap.m",
properties : {
/**
* Landmark role of the root container of the corresponding <code>sap.m.Page</code> control.
*
* If set to <code>sap.ui.core.AccessibleLandmarkRole.None</code>, no landmark will be added to the container.
*/
rootRole : {type : "sap.ui.core.AccessibleLandmarkRole", defaultValue : "Region"},
/**
* Texts which describes the landmark of the root container of the corresponding <code>sap.m.Page</code> control.
*
* If not set (and a landmark different than <code>sap.ui.core.AccessibleLandmarkRole.None</code> is defined), a predefined text
* is used.
*/
rootLabel : {type : "string", defaultValue : null},
/**
* Landmark role of the content container of the corresponding <code>sap.m.Page</code> control.
*
* If set to <code>sap.ui.core.AccessibleLandmarkRole.None</code>, no landmark will be added to the container.
*/
contentRole : {type : "sap.ui.core.AccessibleLandmarkRole", defaultValue : "Main"},
/**
* Texts which describes the landmark of the content container of the corresponding <code>sap.m.Page</code> control.
*
* If not set (and a landmark different than <code>sap.ui.core.AccessibleLandmarkRole.None</code> is defined), a predefined text
* is used.
*/
contentLabel : {type : "string", defaultValue : null},
/**
* Landmark role of the header container of the corresponding <code>sap.m.Page</code> control.
*
* If set to <code>sap.ui.core.AccessibleLandmarkRole.None</code>, no landmark will be added to the container.
*/
headerRole : {type : "sap.ui.core.AccessibleLandmarkRole", defaultValue : "Region"},
/**
* Texts which describes the landmark of the header container of the corresponding <code>sap.m.Page</code> control.
*
* If not set (and a landmark different than <code>sap.ui.core.AccessibleLandmarkRole.None</code> is defined), a predefined text
* is used.
*/
headerLabel : {type : "string", defaultValue : null},
/**
* Landmark role of the subheader container of the corresponding <code>sap.m.Page</code> control.
*
* If set to <code>sap.ui.core.AccessibleLandmarkRole.None</code>, no landmark will be added to the container.
*/
subHeaderRole : {type : "sap.ui.core.AccessibleLandmarkRole", defaultValue : null},
/**
* Texts which describes the landmark of the subheader container of the corresponding <code>sap.m.Page</code> control.
*
* If not set (and a landmark different than <code>sap.ui.core.AccessibleLandmarkRole.None</code> is defined), a predefined text
* is used.
*/
subHeaderLabel : {type : "string", defaultValue : null},
/**
* Landmark role of the footer container of the corresponding <code>sap.m.Page</code> control.
*
* If set to <code>sap.ui.core.AccessibleLandmarkRole.None</code>, no landmark will be added to the container.
*/
footerRole : {type : "sap.ui.core.AccessibleLandmarkRole", defaultValue : "Region"},
/**
* Texts which describes the landmark of the header container of the corresponding <code>sap.m.Page</code> control.
*
* If not set (and a landmark different than <code>sap.ui.core.AccessibleLandmarkRole.None</code> is defined), a predefined text
* is used.
*/
footerLabel : {type : "string", defaultValue : null}
}
}});
/**
* Returns the landmark information of the given <code>sap.m.PageAccessibleLandmarkInfo</code> instance
* of the given area (e.g. <code>"root"</code>).
*
* Must only be used with the <code>sap.m.Page</code> control!
*
* @private
*/
PageAccessibleLandmarkInfo._getLandmarkInfo = function(oInstance, sArea) {
if (!oInstance) {
return null;
}
var sRole = null;
var sText = null;
var oPropertyInfo = oInstance.getMetadata().getProperty(sArea + "Role");
if (oPropertyInfo) {
sRole = oInstance[oPropertyInfo._sGetter]();
}
if (!sRole) {
return null;
}
oPropertyInfo = oInstance.getMetadata().getProperty(sArea + "Label");
if (oPropertyInfo) {
sText = oInstance[oPropertyInfo._sGetter]();
}
return [sRole.toLowerCase(), sText];
};
/**
* Writes the landmark information of the given page and area (e.g. <code>"root"</code>).
*
* Must only be used with the <code>sap.m.Page</code> control!
*
* @private
*/
PageAccessibleLandmarkInfo._writeLandmarkInfo = function(oRm, oPage, sArea) {
if (!sap.ui.getCore().getConfiguration().getAccessibility()) {
return;
}
var oInfo = PageAccessibleLandmarkInfo._getLandmarkInfo(oPage.getLandmarkInfo(), sArea);
if (!oInfo) {
return;
}
var oLandMarks = {
role: oInfo[0]
};
if (oInfo[1]) {
oLandMarks["label"] = oInfo[1];
}
oRm.writeAccessibilityState(oPage, oLandMarks);
};
return PageAccessibleLandmarkInfo;
});
| icgretethe/AwarenessApp | resources/sap/m/PageAccessibleLandmarkInfo-dbg.js | JavaScript | apache-2.0 | 6,098 |
/**
* File: app/project/ProjOpen.js
* Author: liusha
*/
Ext.define('xdfn.project.ProjOpen', {
extend: 'xdfn.project.ui.ProjOpen',
grid: null,
initComponent: function() {
var me = this;
me.openStore = Ext.create('xdfn.project.store.ProjOpenJsonStore');
me.rowEditing = Ext.create('Ext.grid.plugin.RowEditing', {
errorSummary: false
});
me.callParent(arguments);
me.down('button[text="增加记录"]').on('click', me.OnAddProjOpenBtnClick, me);
me.down('button[text="删除记录"]').on('click', me.OnDeleteProjOpenBtnClick, me);
me.down('button[text="导出"]').on('click', me.OnExportProjOpenBtnClick, me);
me.rowEditing.on('edit', me.OnGridEdit, me);
me.rowEditing.on('beforeedit', me.OnGridBeforeEdit, me);
},
OnGridBeforeEdit: function(editor, e, epts) {
xdfn.user.Rights.noRights('XMGL-XMZL-31', function() {
editor.cancelEdit();
});
},
OnGridEdit: function(editor, e) {
var me = this;
if (!e.record.dirty) return;
var url = './proExec.do?method=modifyKbjl';
if (Ext.isEmpty(e.record.get('ID_VIEW'))) {
var rows = me.grid.getSelectionModel().getSelection();
e.record.set('ID_VIEW', rows[0].get('ID_VIEW'));
url = './proExec.do?method=addProKbjl';
}
e.record.commit();
Ext.Ajax.request({
url: url,
method: 'post',
params: {
ID: e.record.get('ID_VIEW'),
V_MANU: e.record.get('V_MANU_VIEW'),
V_MACHINE: e.record.get('V_MACHINE_VIEW'),
N_CAP: e.record.get('N_CAP_VIEW'),
N_SUM_NUM: e.record.get('N_SUM_NUM_VIEW'),
N_SUM_MONEY: e.record.get('N_SUM_MONEY_VIEW'),
V_MEMO: e.record.get('V_MEMO_VIEW')
},
success: function(response, opts) {
var result = Ext.JSON.decode(response.responseText); //服务端返回新建ID
e.record.set(result.data);
e.record.commit();
},
failure: function(response, opts) {
Ext.Msg.alert('提示','提交失败!');
}
});
},
OnAddProjOpenBtnClick: function(self, e, options) {
var me = this,
sm = me.grid.getSelectionModel(),
rows = sm.getSelection();
xdfn.user.Rights.hasRights('XMGL-XMZL-30', function() {
if (rows.length > 0) {
me.rowEditing.cancelEdit();
me.openStore.insert(0, {});
me.rowEditing.startEdit(0, 0);
} else {
Ext.Msg.alert('提示','请先选择相应的项目!');
}
});
},
OnDeleteProjOpenBtnClick: function(self, e, options) {
var me = this,
grid = self.up('gridpanel'),
store = grid.getStore(),
sm = grid.getSelectionModel(),
rows = sm.getSelection();
xdfn.user.Rights.hasRights('XMGL-XMZL-32', function() {
if (rows.length > 0) {
if (Ext.isEmpty(rows[0].get('ID_VIEW'))) {
me.rowEditing.cancelEdit();
var i = store.indexOf(rows[0]);
store.remove(rows);
var count = store.getCount();
if (count > 0) {
sm.select((i == count)? --i : i);
}
return;
}
Ext.MessageBox.confirm('提示', '确定删除该记录吗?', function(id) {
if (id == 'yes') {
//TODO 删除记录
Ext.Ajax.request({
url: './proExec.do?method=deleteKbjl', //改为实际的删除请求url
method: 'get',
params: {
ID: rows[0].get('ID_VIEW')
},
success: function(response, opts) {
me.rowEditing.cancelEdit();
var i = store.indexOf(rows[0]);
store.remove(rows);
var count = store.getCount();
if (count > 0) {
sm.select((i == count)? --i : i);
}
},
failure: function(response, opts) {
Ext.Msg.alert('提示','删除失败!');
}
});
}
});
} else {
Ext.Msg.alert('提示','请选择要删除的记录!');
}
});
},
OnExportProjOpenBtnClick: function(self, e, options) {
var me = this;
//导出为excel文件
xdfn.user.Rights.hasRights('XMGL-XMZL-33', function() {
me.openStore.load({
limit: me.openStore.getTotalCount(),
scope: this,
callback: function(records, operation, success) {
var excelXml = Ext.ux.exporter.Exporter.exportGrid(self.up('gridpanel'), 'excel', {title: '项目开标记录'});
document.location = 'data:application/vnd.ms-excel;base64,' + Ext.ux.exporter.Base64.encode(excelXml);
}
});
});
}
}); | flowsha/zhwh | web_root/app/static/app/project/ProjOpen.js | JavaScript | apache-2.0 | 4,986 |
/**
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
define(['lodash', 'log', 'event_channel', './abstract-source-gen-visitor', './connector-action-visitor',
'./variable-declaration-visitor', './connector-declaration-visitor', './statement-visitor-factory'],
function(_, log, EventChannel, AbstractSourceGenVisitor, ConnectorActionVisitor,
VariableDeclarationVisitor, ConnectorDeclarationVisitor, StatementVisitorFactory) {
/**
* @param {ASTVisitor} parent - parent visitor
* @constructor
*/
var ConnectorDefinitionVisitor = function (parent) {
AbstractSourceGenVisitor.call(this, parent);
};
ConnectorDefinitionVisitor.prototype = Object.create(AbstractSourceGenVisitor.prototype);
ConnectorDefinitionVisitor.prototype.constructor = ConnectorDefinitionVisitor;
ConnectorDefinitionVisitor.prototype.canVisitConnectorDefinition = function(connectorDefinition){
return true;
};
/**
* Begin the visit and generate the source
* @param {ConnectorDefinition} connectorDefinition - Connector Definition
*/
ConnectorDefinitionVisitor.prototype.beginVisitConnectorDefinition = function(connectorDefinition){
/**
* set the configuration start for the connector definition language construct
* If we need to add additional parameters which are dynamically added to the configuration start
* that particular source generation has to be constructed here
*/
var self = this;
var argumentsSrc = "";
_.forEach(connectorDefinition.getAnnotations(), function(annotation) {
if (!_.isEmpty(annotation.value)) {
var constructedPathAnnotation;
if (annotation.key.indexOf(":") === -1) {
constructedPathAnnotation = '@' + annotation.key + '("' + annotation.value + '")\n';
} else {
constructedPathAnnotation = '@' + annotation.key.split(":")[0] + '(' + annotation.key.split(":")[1] +
' = "' + annotation.value + '")\n';
}
self.appendSource(constructedPathAnnotation);
}
});
_.forEach(connectorDefinition.getArguments(), function(argument, index){
argumentsSrc += argument.type + " ";
argumentsSrc += argument.identifier;
if (connectorDefinition.getArguments().length - 1 != index) {
argumentsSrc += ", ";
}
});
var constructedSourceSegment = 'connector ' + connectorDefinition.getConnectorName() +
' (' + argumentsSrc + ')' + ' {\n';
this.appendSource(constructedSourceSegment);
log.debug('Begin Visit Connector Definition');
};
ConnectorDefinitionVisitor.prototype.visitConnectorDefinition = function(connectorDefinition){
log.debug('Visit Connector Definition');
};
/**
* End visiting the connector definition
* @param {ConnectorDefinition} connectorDefinition - Connector Definition
*/
ConnectorDefinitionVisitor.prototype.endVisitConnectorDefinition = function(connectorDefinition){
this.appendSource("}\n");
this.getParent().appendSource(this.getGeneratedSource());
log.debug('End Visit Connector Definition');
};
/**
* Visit Connector Action
* @param {ConnectorAction} connectorAction
*/
ConnectorDefinitionVisitor.prototype.visitConnectorAction = function(connectorAction){
var connectorActionVisitor = new ConnectorActionVisitor(this);
connectorAction.accept(connectorActionVisitor);
};
/**
* Visit Connector Declaration
* @param {ConnectorDeclaration} connectorDeclaration
*/
ConnectorDefinitionVisitor.prototype.visitConnectorDeclaration = function(connectorDeclaration){
var connectorDeclarationVisitor = new ConnectorDeclarationVisitor(this);
connectorDeclaration.accept(connectorDeclarationVisitor);
};
/**
* Visit Variable Declaration
* @param {VariableDeclaration} variableDeclaration
*/
ConnectorDefinitionVisitor.prototype.visitVariableDeclaration = function(variableDeclaration){
var variableDeclarationVisitor = new VariableDeclarationVisitor(this);
variableDeclaration.accept(variableDeclarationVisitor);
};
/**
* Visit Statements
* @param {Statement} statement
*/
ConnectorDefinitionVisitor.prototype.visitStatement = function (statement) {
var statementVisitorFactory = new StatementVisitorFactory();
var statementVisitor = statementVisitorFactory.getStatementVisitor(statement, this);
statement.accept(statementVisitor);
};
return ConnectorDefinitionVisitor;
}); | nu1silva/product-apim | product/carbon-home/resources/composer/web/js/ballerina/visitors/source-gen/connector-definition-visitor.js | JavaScript | apache-2.0 | 5,798 |
function __processArg(obj, key) {
var arg = null;
if (obj) {
arg = obj[key] || null;
delete obj[key];
}
return arg;
}
function Controller() {
function goSlide(event) {
var index = event.source.mod;
var arrViews = $.scrollableView.getViews();
switch (index) {
case "0":
$.lbl1.backgroundColor = "#453363";
$.lbl1.color = "#AA9DB6";
$.lbl2.backgroundColor = "#E6E7E9";
$.lbl2.color = "#4CC4D2";
$.lbl3.backgroundColor = "#E6E7E9";
$.lbl3.color = "#4CC4D2";
break;
case "1":
$.lbl1.backgroundColor = "#E6E7E9";
$.lbl1.color = "#4CC4D2";
$.lbl2.backgroundColor = "#453363";
$.lbl2.color = "#AA9DB6";
$.lbl3.backgroundColor = "#E6E7E9";
$.lbl3.color = "#4CC4D2";
break;
case "2":
$.lbl1.backgroundColor = "#E6E7E9";
$.lbl1.color = "#4CC4D2";
$.lbl2.backgroundColor = "#E6E7E9";
$.lbl2.color = "#4CC4D2";
$.lbl3.backgroundColor = "#453363";
$.lbl3.color = "#AA9DB6";
}
$.scrollableView.scrollToView(arrViews[index]);
}
require("alloy/controllers/BaseController").apply(this, Array.prototype.slice.call(arguments));
this.__controllerPath = "contact";
if (arguments[0]) {
var __parentSymbol = __processArg(arguments[0], "__parentSymbol");
{
__processArg(arguments[0], "$model");
}
{
__processArg(arguments[0], "__itemTemplate");
}
}
var $ = this;
var exports = {};
var __defers = {};
$.__views.win = Ti.UI.createView({
layout: "vertical",
id: "win",
backgroundColor: "white"
});
$.__views.win && $.addTopLevelView($.__views.win);
$.__views.__alloyId87 = Alloy.createController("_header", {
id: "__alloyId87",
__parentSymbol: $.__views.win
});
$.__views.__alloyId87.setParent($.__views.win);
$.__views.__alloyId88 = Ti.UI.createView({
height: "20%",
backgroundColor: "#836EAF",
id: "__alloyId88"
});
$.__views.win.add($.__views.__alloyId88);
$.__views.__alloyId89 = Ti.UI.createLabel({
text: "Contact us",
left: "10",
top: "10",
color: "white",
id: "__alloyId89"
});
$.__views.__alloyId88.add($.__views.__alloyId89);
$.__views.menu = Ti.UI.createView({
id: "menu",
layout: "horizontal",
height: "50",
width: "100%"
});
$.__views.win.add($.__views.menu);
$.__views.lbl1 = Ti.UI.createLabel({
text: "Our Offices",
id: "lbl1",
mod: "0",
height: "100%",
width: "33%",
textAlign: "center",
backgroundColor: "#453363",
color: "#AA9DB6"
});
$.__views.menu.add($.__views.lbl1);
goSlide ? $.__views.lbl1.addEventListener("touchend", goSlide) : __defers["$.__views.lbl1!touchend!goSlide"] = true;
$.__views.__alloyId90 = Ti.UI.createView({
backgroundColor: "#4CC4D2",
height: "100%",
width: "0.45%",
id: "__alloyId90"
});
$.__views.menu.add($.__views.__alloyId90);
$.__views.lbl2 = Ti.UI.createLabel({
text: "Care Center",
id: "lbl2",
mod: "1",
height: "100%",
width: "33%",
textAlign: "center",
backgroundColor: "#E6E7E9",
color: "#4CC4D2"
});
$.__views.menu.add($.__views.lbl2);
goSlide ? $.__views.lbl2.addEventListener("touchend", goSlide) : __defers["$.__views.lbl2!touchend!goSlide"] = true;
$.__views.__alloyId91 = Ti.UI.createView({
backgroundColor: "#4CC4D2",
height: "100%",
width: "0.45%",
id: "__alloyId91"
});
$.__views.menu.add($.__views.__alloyId91);
$.__views.lbl3 = Ti.UI.createLabel({
text: "XOX Dealers",
id: "lbl3",
mod: "2",
height: "100%",
width: "33%",
textAlign: "center",
backgroundColor: "#E6E7E9",
color: "#4CC4D2"
});
$.__views.menu.add($.__views.lbl3);
goSlide ? $.__views.lbl3.addEventListener("touchend", goSlide) : __defers["$.__views.lbl3!touchend!goSlide"] = true;
var __alloyId92 = [];
$.__views.__alloyId93 = Alloy.createController("contact1", {
id: "__alloyId93",
__parentSymbol: __parentSymbol
});
__alloyId92.push($.__views.__alloyId93.getViewEx({
recurse: true
}));
$.__views.__alloyId94 = Alloy.createController("contact2", {
id: "__alloyId94",
__parentSymbol: __parentSymbol
});
__alloyId92.push($.__views.__alloyId94.getViewEx({
recurse: true
}));
$.__views.__alloyId95 = Alloy.createController("contact3", {
id: "__alloyId95",
__parentSymbol: __parentSymbol
});
__alloyId92.push($.__views.__alloyId95.getViewEx({
recurse: true
}));
$.__views.scrollableView = Ti.UI.createScrollableView({
views: __alloyId92,
id: "scrollableView",
showPagingControl: "false",
scrollingEnabled: "false"
});
$.__views.win.add($.__views.scrollableView);
exports.destroy = function() {};
_.extend($, $.__views);
var storeModel = Alloy.createCollection("storeLocator");
var details = storeModel.getStoreList();
console.log(details);
__defers["$.__views.lbl1!touchend!goSlide"] && $.__views.lbl1.addEventListener("touchend", goSlide);
__defers["$.__views.lbl2!touchend!goSlide"] && $.__views.lbl2.addEventListener("touchend", goSlide);
__defers["$.__views.lbl3!touchend!goSlide"] && $.__views.lbl3.addEventListener("touchend", goSlide);
_.extend($, exports);
}
var Alloy = require("alloy"), Backbone = Alloy.Backbone, _ = Alloy._;
module.exports = Controller; | hardikamal/xox | Resources/iphone/alloy/controllers/contact.js | JavaScript | apache-2.0 | 5,935 |
/**
* Copyright 2016 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
goog.provide('audioCat.audio.record.RecordingJobCreatedEvent');
goog.require('audioCat.audio.record.Event');
goog.require('audioCat.utility.Event');
/**
* An event marking the creation of a new recording job.
* @param {!audioCat.audio.record.RecordingJob} recordingJob The newly created
* job recording.
* @constructor
* @extends {audioCat.utility.Event}
*/
audioCat.audio.record.RecordingJobCreatedEvent = function(recordingJob) {
goog.base(this, audioCat.audio.record.Event.DEFAULT_RECORDING_JOB_CREATED);
/**
* The newly made recording job.
* @type {!audioCat.audio.record.RecordingJob}
*/
this.recordingJob = recordingJob;
};
goog.inherits(
audioCat.audio.record.RecordingJobCreatedEvent, audioCat.utility.Event);
| google/beautiful-audio-editor | src/js/original/audio/record/recording-job-created-event.js | JavaScript | apache-2.0 | 1,347 |
/**
* Copyright 2016 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS-IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {Poller} from './poller';
import {Services} from '../../../src/services';
import {addParamToUrl} from '../../../src/url';
import {fetchDocument} from '../../../src/document-fetcher';
import {getMode} from '../../../src/mode';
import {getServicePromiseForDoc} from '../../../src/service';
import {toArray} from '../../../src/types';
import {userAssert} from '../../../src/log';
/** @const {string} */
export const SERVICE_ID = 'liveListManager';
const TRANSFORMED_PREFIX = 'google;v=';
/**
* Property used for storing id of custom slot. This custom slot can be used to
* replace the default "items" and "update" slot.
* @const {string}
*/
export const AMP_LIVE_LIST_CUSTOM_SLOT_ID = 'AMP_LIVE_LIST_CUSTOM_SLOT_ID';
/**
* Manages registered AmpLiveList components.
* Primarily handles network requests and updates the components
* if necessary.
* @implements {../../../src/service.Disposable}
*/
export class LiveListManager {
/**
* @param {!../../../src/service/ampdoc-impl.AmpDoc} ampdoc
*/
constructor(ampdoc) {
/** @const */
this.ampdoc = ampdoc;
/** @private @const {!Object<string, !./amp-live-list.AmpLiveList>} */
this.liveLists_ = Object.create(null);
/** @private @const {!../../../src/service/extensions-impl.Extensions} */
this.extensions_ = Services.extensionsFor(this.ampdoc.win);
/** @private {number} */
this.interval_ = 15000;
/** @private @const {!Array<number>} */
this.intervals_ = [this.interval_];
/** @private {?Poller} */
this.poller_ = null;
/** @private @const {string} */
this.url_ = this.ampdoc.getUrl();
/** @private {time} */
this.latestUpdateTime_ = 0;
/** @private @const {function(): Promise} */
this.work_ = this.fetchDocument_.bind(this);
/** @private @const {boolean} */
this.isTransformed_ = isDocTransformed(ampdoc.getRootNode());
// Only start polling when doc is ready and when the doc is visible.
this.whenDocReady_().then(() => {
// Switch out the poller interval if we can find a lower one and
// then make sure to stop polling if doc is not visible.
this.interval_ = Math.min.apply(Math, this.intervals_);
const initialUpdateTimes = Object.keys(this.liveLists_).map((key) =>
this.liveLists_[key].getUpdateTime()
);
this.latestUpdateTime_ = Math.max.apply(Math, initialUpdateTimes);
// For testing purposes only, we speed up the interval of the update.
// This should NEVER be allowed in production.
if (getMode().localDev) {
const path = this.ampdoc.win.location.pathname;
if (
path.indexOf('/examples/live-list-update.amp.html') != -1 ||
path.indexOf('/examples/live-blog.amp.html') != -1 ||
path.indexOf('/examples/live-blog-non-floating-button.amp.html') != -1
) {
this.interval_ = 5000;
}
}
this.poller_ = new Poller(this.ampdoc.win, this.interval_, this.work_);
// If no live-list is active on dom ready, we don't need to poll at all.
if (this.ampdoc.isVisible() && this.hasActiveLiveLists_()) {
this.poller_.start();
}
this.setupVisibilityHandler_();
});
}
/** @override */
dispose() {
this.poller_.stop();
}
/**
* @param {!Element} element
* @return {!Promise<!LiveListManager>}
*/
static forDoc(element) {
return /** @type {!Promise<!LiveListManager>} */ (getServicePromiseForDoc(
element,
SERVICE_ID
));
}
/**
* Checks if any of the registered amp-live-list components is active/
*
* @return {boolean}
* @private
*/
hasActiveLiveLists_() {
return Object.keys(this.liveLists_).some((key) => {
return this.liveLists_[key].isEnabled();
});
}
/**
* Makes a request to the given url for the latest document.
*
* @private
*/
fetchDocument_() {
let url = this.url_;
if (this.latestUpdateTime_ > 0) {
url = addParamToUrl(
url,
'amp_latest_update_time',
String(this.latestUpdateTime_)
);
}
if (this.isTransformed_) {
const urlService = Services.urlForDoc(this.ampdoc.getBody());
url = urlService.getCdnUrlOnOrigin(url);
}
// TODO(erwinm): add update time here when possible.
return fetchDocument(this.ampdoc.win, url, {}).then(
this.updateLiveLists_.bind(this)
);
}
/**
* Gets all live lists and updates them with their corresponding counterparts.
* Saves latest update time.
*
* @param {!Document} doc
* @private
*/
updateLiveLists_(doc) {
this.installExtensionsForDoc_(doc);
const allLiveLists = this.getLiveLists_(doc).concat(
this.getCustomSlots_(doc)
);
const updateTimes = allLiveLists.map(this.updateLiveList_.bind(this));
const latestUpdateTime = Math.max.apply(Math, [0].concat(updateTimes));
if (latestUpdateTime > 0) {
this.latestUpdateTime_ = latestUpdateTime;
}
// We need to do this after calling `updateLiveList` since that
// would apply the disabled attribute if any exist from the server.
if (!this.hasActiveLiveLists_()) {
this.poller_.stop();
}
}
/**
* Queries the document for all `amp-live-list` tags.
*
* @param {!Document} doc
* @return {!Array<!Element>}
* @private
*/
getLiveLists_(doc) {
return Array.prototype.slice.call(
doc.getElementsByTagName('amp-live-list')
);
}
/**
* Queries for custom slots that will be used to host the live elements. This
* overrides looking for live elements inside the default <amp-live-list>
* element.
*
* @param {!Document} doc
* @return {!Array<!Element>}
* @private
*/
getCustomSlots_(doc) {
const liveListsWithCustomSlots = Object.keys(this.liveLists_).filter((id) =>
this.liveLists_[id].hasCustomSlot()
);
return liveListsWithCustomSlots.map((id) => {
const customSlotId = this.liveLists_[id].element[
AMP_LIVE_LIST_CUSTOM_SLOT_ID
];
return doc.getElementById(customSlotId);
});
}
/**
* Updates the appropriate `amp-live-list` with its updates from the server.
*
* @param {!Element} liveList Live list or custom element that built it.
* @return {number}
*/
updateLiveList_(liveList) {
// amp-live-list elements can be appended dynamically in the client by
// another component using the `i-amphtml-` + `other-component-id` +
// `-dynamic-list` combination as the ID of the amp-live-list.
//
// The fact that we know how this ID is built allows us to find the
// amp-live-list element in the server document. See live-story-manager.js
// for an example.
const dynamicId = 'i-amphtml-' + liveList.id + '-dynamic-list';
const id =
dynamicId in this.liveLists_ ? dynamicId : liveList.getAttribute('id');
userAssert(id, 'amp-live-list must have an id.');
userAssert(
id in this.liveLists_,
'amp-live-list#%s found but did not exist on original page load.',
id
);
const inClientDomLiveList = this.liveLists_[id];
inClientDomLiveList.toggle(
!liveList.hasAttribute('disabled') &&
// When the live list is an amp-story, we use an amp-story specific
// attribute so publishers can disable the live story functionality.
!liveList.hasAttribute('live-story-disabled')
);
if (inClientDomLiveList.isEnabled()) {
return inClientDomLiveList.update(liveList);
}
return 0;
}
/**
* Register an `amp-live-list` instance for updates.
*
* @param {string} id
* @param {!./amp-live-list.AmpLiveList} liveList
*/
register(id, liveList) {
if (id in this.liveLists_) {
return;
}
this.liveLists_[id] = liveList;
this.intervals_.push(liveList.getInterval());
// Polling may not be started yet if no live lists were registered by
// doc ready in LiveListManager's constructor.
if (liveList.isEnabled() && this.poller_ && this.ampdoc.isVisible()) {
this.poller_.start();
}
}
/**
* Returns a promise that is resolved when the document is ready.
* @return {!Promise}
* @private
*/
whenDocReady_() {
return this.ampdoc.whenReady();
}
/**
* Listens to he doc visibility changed event.
* @private
*/
setupVisibilityHandler_() {
// Polling should always be stopped when document is no longer visible.
this.ampdoc.onVisibilityChanged(() => {
if (this.ampdoc.isVisible() && this.hasActiveLiveLists_()) {
// We use immediate so that the user starts getting updates
// right away when they've switched back to the page.
this.poller_.start(/** immediate */ true);
} else {
this.poller_.stop();
}
});
}
/**
* @param {!Document} doc
*/
installExtensionsForDoc_(doc) {
const extensions = toArray(
doc.querySelectorAll('script[custom-element], script[custom-template]')
);
extensions.forEach((script) => {
const extensionName =
script.getAttribute('custom-element') ||
script.getAttribute('custom-template');
// This is a cheap operation if extension is already installed so no need
// to over optimize checks.
this.extensions_.installExtensionForDoc(this.ampdoc, extensionName);
});
}
/**
* Default minimum data poll interval value.
*
* @return {number}
*/
static getMinDataPollInterval() {
// TODO(erwinm): determine if value is too low
return 15000;
}
/**
* Default minimum data max items per page value.
*
* @return {number}
*/
static getMinDataMaxItemsPerPage() {
return 1;
}
}
/**
* Detects if a document has had transforms applied
* e.g. by a domain with signed exchange domain enabled.
* @param {!Document|!ShadowRoot} root
* @return {boolean}
*/
function isDocTransformed(root) {
if (!root.ownerDocument) {
return false;
}
const {documentElement} = root.ownerDocument;
const transformed = documentElement.getAttribute('transformed');
return Boolean(transformed) && transformed.startsWith(TRANSFORMED_PREFIX);
}
| zhouyx/amphtml | extensions/amp-live-list/0.1/live-list-manager.js | JavaScript | apache-2.0 | 10,792 |
var spawn = require('child_process').spawn
var port = exports.port = 1337
exports.registry = "http://localhost:" + port
exports.run = run
function run (cmd, t, opts, cb) {
if (!opts)
opts = {}
if (!Array.isArray(cmd))
throw new Error("cmd must be an Array")
if (!t || !t.end)
throw new Error("node-tap instance is missing")
var stdout = ""
, stderr = ""
, node = process.execPath
, child = spawn(node, cmd, opts)
child.stderr.on("data", function (chunk) {
stderr += chunk
})
child.stdout.on("data", function (chunk) {
stdout += chunk
})
child.on("close", function (code) {
if (cb)
cb(t, stdout, stderr, code, { cmd: cmd, opts: opts })
else
t.end()
})
}
| jplusui/xfly | xfly/node/node_modules/npm/test/common-tap.js | JavaScript | apache-2.0 | 731 |
(function() {
var head = document.head || document.getElementsByTagName('head')[0];
var style = null;
var mobileScreenWidth = 768;
// Make sure this value is equal to the width of .wy-nav-content in overrides.css.
var initialContentWidth = 960;
// Make sure this value is equal to the width of .wy-nav-side in theme.css.
var sideWidth = 300;
// Keeps the current width of .wy-nav-content.
var contentWidth = initialContentWidth;
// Centers the page content dynamically.
function centerPage() {
if (style) {
head.removeChild(style);
style = null;
}
var windowWidth = window.innerWidth;
if (windowWidth <= mobileScreenWidth) {
return;
}
var leftMargin = Math.max(0, (windowWidth - sideWidth - contentWidth) / 2);
var scrollbarWidth = document.body ? windowWidth - document.body.clientWidth : 0;
var css = '';
css += '.wy-nav-side { left: ' + leftMargin + 'px; }';
css += "\n";
css += '.wy-nav-content-wrap { margin-left: ' + (sideWidth + leftMargin) + 'px; }';
css += "\n";
css += '.github-fork-ribbon { margin-right: ' + (leftMargin - scrollbarWidth) + 'px; }';
css += "\n";
var newStyle = document.createElement('style');
newStyle.type = 'text/css';
if (newStyle.styleSheet) {
newStyle.styleSheet.cssText = css;
} else {
newStyle.appendChild(document.createTextNode(css));
}
head.appendChild(newStyle);
style = newStyle;
}
centerPage();
window.addEventListener('resize', centerPage);
// Adjust the position of the 'fork me at GitHub' ribbon after document.body is available,
// so that we can calculate the width of the scroll bar correctly.
window.addEventListener('DOMContentLoaded', centerPage);
// Allow a user to drag the left or right edge of the content to resize the content.
if (interact) {
interact('.wy-nav-content').resizable({
edges: {left: true, right: true, bottom: false, top: false},
modifiers: [
interact.modifiers.restrictEdges({
outer: 'parent',
endOnly: true
}),
interact.modifiers.restrictSize({
min: {
width: initialContentWidth,
height: 0
}
})
]
}).on('resizemove', function (event) {
var style = event.target.style;
// Double the amount of change because the page is centered.
contentWidth += event.deltaRect.width * 2;
style.maxWidth = contentWidth + 'px';
centerPage();
});
}
})(); | trustin/sphinx-gradle-plugin | src/site/sphinx/_static/center_page.js | JavaScript | apache-2.0 | 2,528 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// script.aculo.us unittest.js v1.8.0_pre1, Fri Oct 12 21:34:51 +0200 2007
// Copyright (c) 2005-2007 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
// (c) 2005-2007 Jon Tirsen (http://www.tirsen.com)
// (c) 2005-2007 Michael Schuerig (http://www.schuerig.de/michael/)
//
// script.aculo.us is freely distributable under the terms of an MIT-style license.
// For details, see the script.aculo.us web site: http://script.aculo.us/
// experimental, Firefox-only
Event.simulateMouse = function(element, eventName) {
var options = Object.extend({
pointerX: 0,
pointerY: 0,
buttons: 0,
ctrlKey: false,
altKey: false,
shiftKey: false,
metaKey: false
}, arguments[2] || {});
var oEvent = document.createEvent("MouseEvents");
oEvent.initMouseEvent(eventName, true, true, document.defaultView,
options.buttons, options.pointerX, options.pointerY, options.pointerX, options.pointerY,
options.ctrlKey, options.altKey, options.shiftKey, options.metaKey, 0, $(element));
if(this.mark) Element.remove(this.mark);
this.mark = document.createElement('div');
this.mark.appendChild(document.createTextNode(" "));
document.body.appendChild(this.mark);
this.mark.style.position = 'absolute';
this.mark.style.top = options.pointerY + "px";
this.mark.style.left = options.pointerX + "px";
this.mark.style.width = "5px";
this.mark.style.height = "5px;";
this.mark.style.borderTop = "1px solid red;"
this.mark.style.borderLeft = "1px solid red;"
if(this.step)
alert('['+new Date().getTime().toString()+'] '+eventName+'/'+Test.Unit.inspect(options));
$(element).dispatchEvent(oEvent);
};
// Note: Due to a fix in Firefox 1.0.5/6 that probably fixed "too much", this doesn't work in 1.0.6 or DP2.
// You need to downgrade to 1.0.4 for now to get this working
// See https://bugzilla.mozilla.org/show_bug.cgi?id=289940 for the fix that fixed too much
Event.simulateKey = function(element, eventName) {
var options = Object.extend({
ctrlKey: false,
altKey: false,
shiftKey: false,
metaKey: false,
keyCode: 0,
charCode: 0
}, arguments[2] || {});
var oEvent = document.createEvent("KeyEvents");
oEvent.initKeyEvent(eventName, true, true, window,
options.ctrlKey, options.altKey, options.shiftKey, options.metaKey,
options.keyCode, options.charCode );
$(element).dispatchEvent(oEvent);
};
Event.simulateKeys = function(element, command) {
for(var i=0; i<command.length; i++) {
Event.simulateKey(element,'keypress',{charCode:command.charCodeAt(i)});
}
};
var Test = {}
Test.Unit = {};
// security exception workaround
Test.Unit.inspect = Object.inspect;
Test.Unit.Logger = Class.create();
Test.Unit.Logger.prototype = {
initialize: function(log) {
this.log = $(log);
if (this.log) {
this._createLogTable();
}
},
start: function(testName) {
if (!this.log) return;
this.testName = testName;
this.lastLogLine = document.createElement('tr');
this.statusCell = document.createElement('td');
this.nameCell = document.createElement('td');
this.nameCell.className = "nameCell";
this.nameCell.appendChild(document.createTextNode(testName));
this.messageCell = document.createElement('td');
this.lastLogLine.appendChild(this.statusCell);
this.lastLogLine.appendChild(this.nameCell);
this.lastLogLine.appendChild(this.messageCell);
this.loglines.appendChild(this.lastLogLine);
},
finish: function(status, summary) {
if (!this.log) return;
this.lastLogLine.className = status;
this.statusCell.innerHTML = status;
this.messageCell.innerHTML = this._toHTML(summary);
this.addLinksToResults();
},
message: function(message) {
if (!this.log) return;
this.messageCell.innerHTML = this._toHTML(message);
},
summary: function(summary) {
if (!this.log) return;
this.logsummary.innerHTML = this._toHTML(summary);
},
_createLogTable: function() {
this.log.innerHTML =
'<div id="logsummary"></div>' +
'<table id="logtable">' +
'<thead><tr><th>Status</th><th>Test</th><th>Message</th></tr></thead>' +
'<tbody id="loglines"></tbody>' +
'</table>';
this.logsummary = $('logsummary')
this.loglines = $('loglines');
},
_toHTML: function(txt) {
return txt.escapeHTML().replace(/\n/g,"<br/>");
},
addLinksToResults: function(){
$$("tr.failed .nameCell").each( function(td){ // todo: limit to children of this.log
td.title = "Run only this test"
Event.observe(td, 'click', function(){ window.location.search = "?tests=" + td.innerHTML;});
});
$$("tr.passed .nameCell").each( function(td){ // todo: limit to children of this.log
td.title = "Run all tests"
Event.observe(td, 'click', function(){ window.location.search = "";});
});
}
}
Test.Unit.Runner = Class.create();
Test.Unit.Runner.prototype = {
initialize: function(testcases) {
this.options = Object.extend({
testLog: 'testlog'
}, arguments[1] || {});
this.options.resultsURL = this.parseResultsURLQueryParameter();
this.options.tests = this.parseTestsQueryParameter();
if (this.options.testLog) {
this.options.testLog = $(this.options.testLog) || null;
}
if(this.options.tests) {
this.tests = [];
for(var i = 0; i < this.options.tests.length; i++) {
if(/^test/.test(this.options.tests[i])) {
this.tests.push(new Test.Unit.Testcase(this.options.tests[i], testcases[this.options.tests[i]], testcases["setup"], testcases["teardown"]));
}
}
} else {
if (this.options.test) {
this.tests = [new Test.Unit.Testcase(this.options.test, testcases[this.options.test], testcases["setup"], testcases["teardown"])];
} else {
this.tests = [];
for(var testcase in testcases) {
if(/^test/.test(testcase)) {
this.tests.push(
new Test.Unit.Testcase(
this.options.context ? ' -> ' + this.options.titles[testcase] : testcase,
testcases[testcase], testcases["setup"], testcases["teardown"]
));
}
}
}
}
this.currentTest = 0;
this.logger = new Test.Unit.Logger(this.options.testLog);
setTimeout(this.runTests.bind(this), 1000);
},
parseResultsURLQueryParameter: function() {
return window.location.search.parseQuery()["resultsURL"];
},
parseTestsQueryParameter: function(){
if (window.location.search.parseQuery()["tests"]){
return window.location.search.parseQuery()["tests"].split(',');
};
},
// Returns:
// "ERROR" if there was an error,
// "FAILURE" if there was a failure, or
// "SUCCESS" if there was neither
getResult: function() {
var hasFailure = false;
for(var i=0;i<this.tests.length;i++) {
if (this.tests[i].errors > 0) {
return "ERROR";
}
if (this.tests[i].failures > 0) {
hasFailure = true;
}
}
if (hasFailure) {
return "FAILURE";
} else {
return "SUCCESS";
}
},
postResults: function() {
if (this.options.resultsURL) {
new Ajax.Request(this.options.resultsURL,
{ method: 'get', parameters: 'result=' + this.getResult(), asynchronous: false });
}
},
runTests: function() {
var test = this.tests[this.currentTest];
if (!test) {
// finished!
this.postResults();
this.logger.summary(this.summary());
return;
}
if(!test.isWaiting) {
this.logger.start(test.name);
}
test.run();
if(test.isWaiting) {
this.logger.message("Waiting for " + test.timeToWait + "ms");
setTimeout(this.runTests.bind(this), test.timeToWait || 1000);
} else {
this.logger.finish(test.status(), test.summary());
this.currentTest++;
// tail recursive, hopefully the browser will skip the stackframe
this.runTests();
}
},
summary: function() {
var assertions = 0;
var failures = 0;
var errors = 0;
var messages = [];
for(var i=0;i<this.tests.length;i++) {
assertions += this.tests[i].assertions;
failures += this.tests[i].failures;
errors += this.tests[i].errors;
}
return (
(this.options.context ? this.options.context + ': ': '') +
this.tests.length + " tests, " +
assertions + " assertions, " +
failures + " failures, " +
errors + " errors");
}
}
Test.Unit.Assertions = Class.create();
Test.Unit.Assertions.prototype = {
initialize: function() {
this.assertions = 0;
this.failures = 0;
this.errors = 0;
this.messages = [];
},
summary: function() {
return (
this.assertions + " assertions, " +
this.failures + " failures, " +
this.errors + " errors" + "\n" +
this.messages.join("\n"));
},
pass: function() {
this.assertions++;
},
fail: function(message) {
this.failures++;
this.messages.push("Failure: " + message);
},
info: function(message) {
this.messages.push("Info: " + message);
},
error: function(error) {
this.errors++;
this.messages.push(error.name + ": "+ error.message + "(" + Test.Unit.inspect(error) +")");
},
status: function() {
if (this.failures > 0) return 'failed';
if (this.errors > 0) return 'error';
return 'passed';
},
assert: function(expression) {
var message = arguments[1] || 'assert: got "' + Test.Unit.inspect(expression) + '"';
try { expression ? this.pass() :
this.fail(message); }
catch(e) { this.error(e); }
},
assertEqual: function(expected, actual) {
var message = arguments[2] || "assertEqual";
try { (expected == actual) ? this.pass() :
this.fail(message + ': expected "' + Test.Unit.inspect(expected) +
'", actual "' + Test.Unit.inspect(actual) + '"'); }
catch(e) { this.error(e); }
},
assertInspect: function(expected, actual) {
var message = arguments[2] || "assertInspect";
try { (expected == actual.inspect()) ? this.pass() :
this.fail(message + ': expected "' + Test.Unit.inspect(expected) +
'", actual "' + Test.Unit.inspect(actual) + '"'); }
catch(e) { this.error(e); }
},
assertEnumEqual: function(expected, actual) {
var message = arguments[2] || "assertEnumEqual";
try { $A(expected).length == $A(actual).length &&
expected.zip(actual).all(function(pair) { return pair[0] == pair[1] }) ?
this.pass() : this.fail(message + ': expected ' + Test.Unit.inspect(expected) +
', actual ' + Test.Unit.inspect(actual)); }
catch(e) { this.error(e); }
},
assertNotEqual: function(expected, actual) {
var message = arguments[2] || "assertNotEqual";
try { (expected != actual) ? this.pass() :
this.fail(message + ': got "' + Test.Unit.inspect(actual) + '"'); }
catch(e) { this.error(e); }
},
assertIdentical: function(expected, actual) {
var message = arguments[2] || "assertIdentical";
try { (expected === actual) ? this.pass() :
this.fail(message + ': expected "' + Test.Unit.inspect(expected) +
'", actual "' + Test.Unit.inspect(actual) + '"'); }
catch(e) { this.error(e); }
},
assertNotIdentical: function(expected, actual) {
var message = arguments[2] || "assertNotIdentical";
try { !(expected === actual) ? this.pass() :
this.fail(message + ': expected "' + Test.Unit.inspect(expected) +
'", actual "' + Test.Unit.inspect(actual) + '"'); }
catch(e) { this.error(e); }
},
assertNull: function(obj) {
var message = arguments[1] || 'assertNull'
try { (obj==null) ? this.pass() :
this.fail(message + ': got "' + Test.Unit.inspect(obj) + '"'); }
catch(e) { this.error(e); }
},
assertMatch: function(expected, actual) {
var message = arguments[2] || 'assertMatch';
var regex = new RegExp(expected);
try { (regex.exec(actual)) ? this.pass() :
this.fail(message + ' : regex: "' + Test.Unit.inspect(expected) + ' did not match: ' + Test.Unit.inspect(actual) + '"'); }
catch(e) { this.error(e); }
},
assertHidden: function(element) {
var message = arguments[1] || 'assertHidden';
this.assertEqual("none", element.style.display, message);
},
assertNotNull: function(object) {
var message = arguments[1] || 'assertNotNull';
this.assert(object != null, message);
},
assertType: function(expected, actual) {
var message = arguments[2] || 'assertType';
try {
(actual.constructor == expected) ? this.pass() :
this.fail(message + ': expected "' + Test.Unit.inspect(expected) +
'", actual "' + (actual.constructor) + '"'); }
catch(e) { this.error(e); }
},
assertNotOfType: function(expected, actual) {
var message = arguments[2] || 'assertNotOfType';
try {
(actual.constructor != expected) ? this.pass() :
this.fail(message + ': expected "' + Test.Unit.inspect(expected) +
'", actual "' + (actual.constructor) + '"'); }
catch(e) { this.error(e); }
},
assertInstanceOf: function(expected, actual) {
var message = arguments[2] || 'assertInstanceOf';
try {
(actual instanceof expected) ? this.pass() :
this.fail(message + ": object was not an instance of the expected type"); }
catch(e) { this.error(e); }
},
assertNotInstanceOf: function(expected, actual) {
var message = arguments[2] || 'assertNotInstanceOf';
try {
!(actual instanceof expected) ? this.pass() :
this.fail(message + ": object was an instance of the not expected type"); }
catch(e) { this.error(e); }
},
assertRespondsTo: function(method, obj) {
var message = arguments[2] || 'assertRespondsTo';
try {
(obj[method] && typeof obj[method] == 'function') ? this.pass() :
this.fail(message + ": object doesn't respond to [" + method + "]"); }
catch(e) { this.error(e); }
},
assertReturnsTrue: function(method, obj) {
var message = arguments[2] || 'assertReturnsTrue';
try {
var m = obj[method];
if(!m) m = obj['is'+method.charAt(0).toUpperCase()+method.slice(1)];
m() ? this.pass() :
this.fail(message + ": method returned false"); }
catch(e) { this.error(e); }
},
assertReturnsFalse: function(method, obj) {
var message = arguments[2] || 'assertReturnsFalse';
try {
var m = obj[method];
if(!m) m = obj['is'+method.charAt(0).toUpperCase()+method.slice(1)];
!m() ? this.pass() :
this.fail(message + ": method returned true"); }
catch(e) { this.error(e); }
},
assertRaise: function(exceptionName, method) {
var message = arguments[2] || 'assertRaise';
try {
method();
this.fail(message + ": exception expected but none was raised"); }
catch(e) {
((exceptionName == null) || (e.name==exceptionName)) ? this.pass() : this.error(e);
}
},
assertElementsMatch: function() {
var expressions = $A(arguments), elements = $A(expressions.shift());
if (elements.length != expressions.length) {
this.fail('assertElementsMatch: size mismatch: ' + elements.length + ' elements, ' + expressions.length + ' expressions');
return false;
}
elements.zip(expressions).all(function(pair, index) {
var element = $(pair.first()), expression = pair.last();
if (element.match(expression)) return true;
this.fail('assertElementsMatch: (in index ' + index + ') expected ' + expression.inspect() + ' but got ' + element.inspect());
}.bind(this)) && this.pass();
},
assertElementMatches: function(element, expression) {
this.assertElementsMatch([element], expression);
},
benchmark: function(operation, iterations) {
var startAt = new Date();
(iterations || 1).times(operation);
var timeTaken = ((new Date())-startAt);
this.info((arguments[2] || 'Operation') + ' finished ' +
iterations + ' iterations in ' + (timeTaken/1000)+'s' );
return timeTaken;
},
_isVisible: function(element) {
element = $(element);
if(!element.parentNode) return true;
this.assertNotNull(element);
if(element.style && Element.getStyle(element, 'display') == 'none')
return false;
return this._isVisible(element.parentNode);
},
assertNotVisible: function(element) {
this.assert(!this._isVisible(element), Test.Unit.inspect(element) + " was not hidden and didn't have a hidden parent either. " + ("" || arguments[1]));
},
assertVisible: function(element) {
this.assert(this._isVisible(element), Test.Unit.inspect(element) + " was not visible. " + ("" || arguments[1]));
},
benchmark: function(operation, iterations) {
var startAt = new Date();
(iterations || 1).times(operation);
var timeTaken = ((new Date())-startAt);
this.info((arguments[2] || 'Operation') + ' finished ' +
iterations + ' iterations in ' + (timeTaken/1000)+'s' );
return timeTaken;
}
}
Test.Unit.Testcase = Class.create();
Object.extend(Object.extend(Test.Unit.Testcase.prototype, Test.Unit.Assertions.prototype), {
initialize: function(name, test, setup, teardown) {
Test.Unit.Assertions.prototype.initialize.bind(this)();
this.name = name;
if(typeof test == 'string') {
test = test.gsub(/(\.should[^\(]+\()/,'#{0}this,');
test = test.gsub(/(\.should[^\(]+)\(this,\)/,'#{1}(this)');
this.test = function() {
eval('with(this){'+test+'}');
}
} else {
this.test = test || function() {};
}
this.setup = setup || function() {};
this.teardown = teardown || function() {};
this.isWaiting = false;
this.timeToWait = 1000;
},
wait: function(time, nextPart) {
this.isWaiting = true;
this.test = nextPart;
this.timeToWait = time;
},
run: function() {
try {
try {
if (!this.isWaiting) this.setup.bind(this)();
this.isWaiting = false;
this.test.bind(this)();
} finally {
if(!this.isWaiting) {
this.teardown.bind(this)();
}
}
}
catch(e) { this.error(e); }
}
});
// *EXPERIMENTAL* BDD-style testing to please non-technical folk
// This draws many ideas from RSpec http://rspec.rubyforge.org/
Test.setupBDDExtensionMethods = function(){
var METHODMAP = {
shouldEqual: 'assertEqual',
shouldNotEqual: 'assertNotEqual',
shouldEqualEnum: 'assertEnumEqual',
shouldBeA: 'assertType',
shouldNotBeA: 'assertNotOfType',
shouldBeAn: 'assertType',
shouldNotBeAn: 'assertNotOfType',
shouldBeNull: 'assertNull',
shouldNotBeNull: 'assertNotNull',
shouldBe: 'assertReturnsTrue',
shouldNotBe: 'assertReturnsFalse',
shouldRespondTo: 'assertRespondsTo'
};
var makeAssertion = function(assertion, args, object) {
this[assertion].apply(this,(args || []).concat([object]));
}
Test.BDDMethods = {};
$H(METHODMAP).each(function(pair) {
Test.BDDMethods[pair.key] = function() {
var args = $A(arguments);
var scope = args.shift();
makeAssertion.apply(scope, [pair.value, args, this]); };
});
[Array.prototype, String.prototype, Number.prototype, Boolean.prototype].each(
function(p){ Object.extend(p, Test.BDDMethods) }
);
}
Test.context = function(name, spec, log){
Test.setupBDDExtensionMethods();
var compiledSpec = {};
var titles = {};
for(specName in spec) {
switch(specName){
case "setup":
case "teardown":
compiledSpec[specName] = spec[specName];
break;
default:
var testName = 'test'+specName.gsub(/\s+/,'-').camelize();
var body = spec[specName].toString().split('\n').slice(1);
if(/^\{/.test(body[0])) body = body.slice(1);
body.pop();
body = body.map(function(statement){
return statement.strip()
});
compiledSpec[testName] = body.join('\n');
titles[testName] = specName;
}
}
new Test.Unit.Runner(compiledSpec, { titles: titles, testLog: log || 'testlog', context: name });
}; | shanti/olio | webapp/rails/trunk/vendor/plugins/rspec/story_server/prototype/javascripts/unittest.js | JavaScript | apache-2.0 | 21,009 |
export const FILLPATTERN = {
none: '',
crossHatched: 'Crosshatched',
hatched: 'Hatched',
solid: 'Solid'
};
export const STROKEPATTERN = {
none: '',
dashed: 'Dashed',
dotted: 'Dotted',
solid: 'Solid'
};
export const ALTITUDEMODE = {
NONE: '',
ABSOLUTE: 'Absolute',
RELATIVE_TO_GROUND: 'Relative to ground',
CLAMP_TO_GROUND: 'Clamp to ground'
};
export const ICONSIZE = {
none: '',
verySmall: 'Very Small',
small: 'Small',
medium: 'Medium',
large: 'Large',
extraLarge: 'Extra Large'
};
export const ACMATTRIBUTES = {
innerRadius: 'Inner Radius',
leftAzimuth: 'Left Azimuth',
rightAzimuth: 'Right Azimuth',
minAlt: 'Minimum Altitude',
maxAlt: 'Maximum Altitude',
leftWidth: 'Left Width',
rightWidth: 'Right Width',
radius: 'Radius',
turn: 'Turn',
width: 'Width'
};
export const WMSVERSION = {
WMS: 'none',
WMS1_1: '1.0',
WMS1_1_1: '1.1.1',
WMS1_3_0: '1.3.0'
};
export const WMTSVERSION = {
WMTS: 'none',
WMTS1_0_0: '1.0.0'
};
| missioncommand/emp3-web | src/validation/js/constants/PropertyConstants.js | JavaScript | apache-2.0 | 997 |
/*!
* LESS - Leaner CSS v1.7.0
* http://lesscss.org
*
* Copyright (c) 2009-2014, Alexis Sellier <[email protected]>
* Licensed under the Apache v2 License.
*
*/
/** * @license Apache v2
*/
(function (window, undefined) {//
// Stub out `require` in the browser
//
function require(arg) {
return window.less[arg.split('/')[1]];
};
if (typeof(window.less) === 'undefined' || typeof(window.less.nodeType) !== 'undefined') { window.less = {}; }
less = window.less;
tree = window.less.tree = {};
less.mode = 'browser';
var less, tree;
// Node.js does not have a header file added which defines less
if (less === undefined) {
less = exports;
tree = require('./tree');
less.mode = 'node';
}
//
// less.js - parser
//
// A relatively straight-forward predictive parser.
// There is no tokenization/lexing stage, the input is parsed
// in one sweep.
//
// To make the parser fast enough to run in the browser, several
// optimization had to be made:
//
// - Matching and slicing on a huge input is often cause of slowdowns.
// The solution is to chunkify the input into smaller strings.
// The chunks are stored in the `chunks` var,
// `j` holds the current chunk index, and `currentPos` holds
// the index of the current chunk in relation to `input`.
// This gives us an almost 4x speed-up.
//
// - In many cases, we don't need to match individual tokens;
// for example, if a value doesn't hold any variables, operations
// or dynamic references, the parser can effectively 'skip' it,
// treating it as a literal.
// An example would be '1px solid #000' - which evaluates to itself,
// we don't need to know what the individual components are.
// The drawback, of course is that you don't get the benefits of
// syntax-checking on the CSS. This gives us a 50% speed-up in the parser,
// and a smaller speed-up in the code-gen.
//
//
// Token matching is done with the `$` function, which either takes
// a terminal string or regexp, or a non-terminal function to call.
// It also takes care of moving all the indices forwards.
//
//
less.Parser = function Parser(env) {
var input, // LeSS input string
i, // current index in `input`
j, // current chunk
saveStack = [], // holds state for backtracking
furthest, // furthest index the parser has gone to
chunks, // chunkified input
current, // current chunk
currentPos, // index of current chunk, in `input`
parser,
parsers,
rootFilename = env && env.filename;
// Top parser on an import tree must be sure there is one "env"
// which will then be passed around by reference.
if (!(env instanceof tree.parseEnv)) {
env = new tree.parseEnv(env);
}
var imports = this.imports = {
paths: env.paths || [], // Search paths, when importing
queue: [], // Files which haven't been imported yet
files: env.files, // Holds the imported parse trees
contents: env.contents, // Holds the imported file contents
contentsIgnoredChars: env.contentsIgnoredChars, // lines inserted, not in the original less
mime: env.mime, // MIME type of .less files
error: null, // Error in parsing/evaluating an import
push: function (path, currentFileInfo, importOptions, callback) {
var parserImports = this;
this.queue.push(path);
var fileParsedFunc = function (e, root, fullPath) {
parserImports.queue.splice(parserImports.queue.indexOf(path), 1); // Remove the path from the queue
var importedPreviously = fullPath === rootFilename;
parserImports.files[fullPath] = root; // Store the root
if (e && !parserImports.error) { parserImports.error = e; }
callback(e, root, importedPreviously, fullPath);
};
if (less.Parser.importer) {
less.Parser.importer(path, currentFileInfo, fileParsedFunc, env);
} else {
less.Parser.fileLoader(path, currentFileInfo, function(e, contents, fullPath, newFileInfo) {
if (e) {fileParsedFunc(e); return;}
var newEnv = new tree.parseEnv(env);
newEnv.currentFileInfo = newFileInfo;
newEnv.processImports = false;
newEnv.contents[fullPath] = contents;
if (currentFileInfo.reference || importOptions.reference) {
newFileInfo.reference = true;
}
if (importOptions.inline) {
fileParsedFunc(null, contents, fullPath);
} else {
new(less.Parser)(newEnv).parse(contents, function (e, root) {
fileParsedFunc(e, root, fullPath);
});
}
}, env);
}
}
};
function save() { currentPos = i; saveStack.push( { current: current, i: i, j: j }); }
function restore() { var state = saveStack.pop(); current = state.current; currentPos = i = state.i; j = state.j; }
function forget() { saveStack.pop(); }
function sync() {
if (i > currentPos) {
current = current.slice(i - currentPos);
currentPos = i;
}
}
function isWhitespace(str, pos) {
var code = str.charCodeAt(pos | 0);
return (code <= 32) && (code === 32 || code === 10 || code === 9);
}
//
// Parse from a token, regexp or string, and move forward if match
//
function $(tok) {
var tokType = typeof tok,
match, length;
// Either match a single character in the input,
// or match a regexp in the current chunk (`current`).
//
if (tokType === "string") {
if (input.charAt(i) !== tok) {
return null;
}
skipWhitespace(1);
return tok;
}
// regexp
sync ();
if (! (match = tok.exec(current))) {
return null;
}
length = match[0].length;
// The match is confirmed, add the match length to `i`,
// and consume any extra white-space characters (' ' || '\n')
// which come after that. The reason for this is that LeSS's
// grammar is mostly white-space insensitive.
//
skipWhitespace(length);
if(typeof(match) === 'string') {
return match;
} else {
return match.length === 1 ? match[0] : match;
}
}
// Specialization of $(tok)
function $re(tok) {
if (i > currentPos) {
current = current.slice(i - currentPos);
currentPos = i;
}
var m = tok.exec(current);
if (!m) {
return null;
}
skipWhitespace(m[0].length);
if(typeof m === "string") {
return m;
}
return m.length === 1 ? m[0] : m;
}
var _$re = $re;
// Specialization of $(tok)
function $char(tok) {
if (input.charAt(i) !== tok) {
return null;
}
skipWhitespace(1);
return tok;
}
function skipWhitespace(length) {
var oldi = i, oldj = j,
curr = i - currentPos,
endIndex = i + current.length - curr,
mem = (i += length),
inp = input,
c;
for (; i < endIndex; i++) {
c = inp.charCodeAt(i);
if (c > 32) {
break;
}
if ((c !== 32) && (c !== 10) && (c !== 9) && (c !== 13)) {
break;
}
}
current = current.slice(length + i - mem + curr);
currentPos = i;
if (!current.length && (j < chunks.length - 1)) {
current = chunks[++j];
skipWhitespace(0); // skip space at the beginning of a chunk
return true; // things changed
}
return oldi !== i || oldj !== j;
}
function expect(arg, msg) {
// some older browsers return typeof 'function' for RegExp
var result = (Object.prototype.toString.call(arg) === '[object Function]') ? arg.call(parsers) : $(arg);
if (result) {
return result;
}
error(msg || (typeof(arg) === 'string' ? "expected '" + arg + "' got '" + input.charAt(i) + "'"
: "unexpected token"));
}
// Specialization of expect()
function expectChar(arg, msg) {
if (input.charAt(i) === arg) {
skipWhitespace(1);
return arg;
}
error(msg || "expected '" + arg + "' got '" + input.charAt(i) + "'");
}
function error(msg, type) {
var e = new Error(msg);
e.index = i;
e.type = type || 'Syntax';
throw e;
}
// Same as $(), but don't change the state of the parser,
// just return the match.
function peek(tok) {
if (typeof(tok) === 'string') {
return input.charAt(i) === tok;
} else {
return tok.test(current);
}
}
// Specialization of peek()
function peekChar(tok) {
return input.charAt(i) === tok;
}
function getInput(e, env) {
if (e.filename && env.currentFileInfo.filename && (e.filename !== env.currentFileInfo.filename)) {
return parser.imports.contents[e.filename];
} else {
return input;
}
}
function getLocation(index, inputStream) {
var n = index + 1,
line = null,
column = -1;
while (--n >= 0 && inputStream.charAt(n) !== '\n') {
column++;
}
if (typeof index === 'number') {
line = (inputStream.slice(0, index).match(/\n/g) || "").length;
}
return {
line: line,
column: column
};
}
function getDebugInfo(index, inputStream, env) {
var filename = env.currentFileInfo.filename;
if(less.mode !== 'browser' && less.mode !== 'rhino') {
filename = require('path').resolve(filename);
}
return {
lineNumber: getLocation(index, inputStream).line + 1,
fileName: filename
};
}
function LessError(e, env) {
var input = getInput(e, env),
loc = getLocation(e.index, input),
line = loc.line,
col = loc.column,
callLine = e.call && getLocation(e.call, input).line,
lines = input.split('\n');
this.type = e.type || 'Syntax';
this.message = e.message;
this.filename = e.filename || env.currentFileInfo.filename;
this.index = e.index;
this.line = typeof(line) === 'number' ? line + 1 : null;
this.callLine = callLine + 1;
this.callExtract = lines[callLine];
this.stack = e.stack;
this.column = col;
this.extract = [
lines[line - 1],
lines[line],
lines[line + 1]
];
}
LessError.prototype = new Error();
LessError.prototype.constructor = LessError;
this.env = env = env || {};
// The optimization level dictates the thoroughness of the parser,
// the lower the number, the less nodes it will create in the tree.
// This could matter for debugging, or if you want to access
// the individual nodes in the tree.
this.optimization = ('optimization' in this.env) ? this.env.optimization : 1;
//
// The Parser
//
parser = {
imports: imports,
//
// Parse an input string into an abstract syntax tree,
// @param str A string containing 'less' markup
// @param callback call `callback` when done.
// @param [additionalData] An optional map which can contains vars - a map (key, value) of variables to apply
//
parse: function (str, callback, additionalData) {
var root, line, lines, error = null, globalVars, modifyVars, preText = "";
i = j = currentPos = furthest = 0;
globalVars = (additionalData && additionalData.globalVars) ? less.Parser.serializeVars(additionalData.globalVars) + '\n' : '';
modifyVars = (additionalData && additionalData.modifyVars) ? '\n' + less.Parser.serializeVars(additionalData.modifyVars) : '';
if (globalVars || (additionalData && additionalData.banner)) {
preText = ((additionalData && additionalData.banner) ? additionalData.banner : "") + globalVars;
parser.imports.contentsIgnoredChars[env.currentFileInfo.filename] = preText.length;
}
str = str.replace(/\r\n/g, '\n');
// Remove potential UTF Byte Order Mark
input = str = preText + str.replace(/^\uFEFF/, '') + modifyVars;
parser.imports.contents[env.currentFileInfo.filename] = str;
// Split the input into chunks.
chunks = (function (input) {
var len = input.length, level = 0, parenLevel = 0,
lastOpening, lastOpeningParen, lastMultiComment, lastMultiCommentEndBrace,
chunks = [], emitFrom = 0,
parserCurrentIndex, currentChunkStartIndex, cc, cc2, matched;
function fail(msg, index) {
error = new(LessError)({
index: index || parserCurrentIndex,
type: 'Parse',
message: msg,
filename: env.currentFileInfo.filename
}, env);
}
function emitChunk(force) {
var len = parserCurrentIndex - emitFrom;
if (((len < 512) && !force) || !len) {
return;
}
chunks.push(input.slice(emitFrom, parserCurrentIndex + 1));
emitFrom = parserCurrentIndex + 1;
}
for (parserCurrentIndex = 0; parserCurrentIndex < len; parserCurrentIndex++) {
cc = input.charCodeAt(parserCurrentIndex);
if (((cc >= 97) && (cc <= 122)) || (cc < 34)) {
// a-z or whitespace
continue;
}
switch (cc) {
case 40: // (
parenLevel++;
lastOpeningParen = parserCurrentIndex;
continue;
case 41: // )
if (--parenLevel < 0) {
return fail("missing opening `(`");
}
continue;
case 59: // ;
if (!parenLevel) { emitChunk(); }
continue;
case 123: // {
level++;
lastOpening = parserCurrentIndex;
continue;
case 125: // }
if (--level < 0) {
return fail("missing opening `{`");
}
if (!level && !parenLevel) { emitChunk(); }
continue;
case 92: // \
if (parserCurrentIndex < len - 1) { parserCurrentIndex++; continue; }
return fail("unescaped `\\`");
case 34:
case 39:
case 96: // ", ' and `
matched = 0;
currentChunkStartIndex = parserCurrentIndex;
for (parserCurrentIndex = parserCurrentIndex + 1; parserCurrentIndex < len; parserCurrentIndex++) {
cc2 = input.charCodeAt(parserCurrentIndex);
if (cc2 > 96) { continue; }
if (cc2 == cc) { matched = 1; break; }
if (cc2 == 92) { // \
if (parserCurrentIndex == len - 1) {
return fail("unescaped `\\`");
}
parserCurrentIndex++;
}
}
if (matched) { continue; }
return fail("unmatched `" + String.fromCharCode(cc) + "`", currentChunkStartIndex);
case 47: // /, check for comment
if (parenLevel || (parserCurrentIndex == len - 1)) { continue; }
cc2 = input.charCodeAt(parserCurrentIndex + 1);
if (cc2 == 47) {
// //, find lnfeed
for (parserCurrentIndex = parserCurrentIndex + 2; parserCurrentIndex < len; parserCurrentIndex++) {
cc2 = input.charCodeAt(parserCurrentIndex);
if ((cc2 <= 13) && ((cc2 == 10) || (cc2 == 13))) { break; }
}
} else if (cc2 == 42) {
// /*, find */
lastMultiComment = currentChunkStartIndex = parserCurrentIndex;
for (parserCurrentIndex = parserCurrentIndex + 2; parserCurrentIndex < len - 1; parserCurrentIndex++) {
cc2 = input.charCodeAt(parserCurrentIndex);
if (cc2 == 125) { lastMultiCommentEndBrace = parserCurrentIndex; }
if (cc2 != 42) { continue; }
if (input.charCodeAt(parserCurrentIndex + 1) == 47) { break; }
}
if (parserCurrentIndex == len - 1) {
return fail("missing closing `*/`", currentChunkStartIndex);
}
parserCurrentIndex++;
}
continue;
case 42: // *, check for unmatched */
if ((parserCurrentIndex < len - 1) && (input.charCodeAt(parserCurrentIndex + 1) == 47)) {
return fail("unmatched `/*`");
}
continue;
}
}
if (level !== 0) {
if ((lastMultiComment > lastOpening) && (lastMultiCommentEndBrace > lastMultiComment)) {
return fail("missing closing `}` or `*/`", lastOpening);
} else {
return fail("missing closing `}`", lastOpening);
}
} else if (parenLevel !== 0) {
return fail("missing closing `)`", lastOpeningParen);
}
emitChunk(true);
return chunks;
})(str);
if (error) {
return callback(new(LessError)(error, env));
}
current = chunks[0];
// Start with the primary rule.
// The whole syntax tree is held under a Ruleset node,
// with the `root` property set to true, so no `{}` are
// output. The callback is called when the input is parsed.
try {
root = new(tree.Ruleset)(null, this.parsers.primary());
root.root = true;
root.firstRoot = true;
} catch (e) {
return callback(new(LessError)(e, env));
}
root.toCSS = (function (evaluate) {
return function (options, variables) {
options = options || {};
var evaldRoot,
css,
evalEnv = new tree.evalEnv(options);
//
// Allows setting variables with a hash, so:
//
// `{ color: new(tree.Color)('#f01') }` will become:
//
// new(tree.Rule)('@color',
// new(tree.Value)([
// new(tree.Expression)([
// new(tree.Color)('#f01')
// ])
// ])
// )
//
if (typeof(variables) === 'object' && !Array.isArray(variables)) {
variables = Object.keys(variables).map(function (k) {
var value = variables[k];
if (! (value instanceof tree.Value)) {
if (! (value instanceof tree.Expression)) {
value = new(tree.Expression)([value]);
}
value = new(tree.Value)([value]);
}
return new(tree.Rule)('@' + k, value, false, null, 0);
});
evalEnv.frames = [new(tree.Ruleset)(null, variables)];
}
try {
var preEvalVisitors = [],
visitors = [
new(tree.joinSelectorVisitor)(),
new(tree.processExtendsVisitor)(),
new(tree.toCSSVisitor)({compress: Boolean(options.compress)})
], i, root = this;
if (options.plugins) {
for(i =0; i < options.plugins.length; i++) {
if (options.plugins[i].isPreEvalVisitor) {
preEvalVisitors.push(options.plugins[i]);
} else {
if (options.plugins[i].isPreVisitor) {
visitors.splice(0, 0, options.plugins[i]);
} else {
visitors.push(options.plugins[i]);
}
}
}
}
for(i = 0; i < preEvalVisitors.length; i++) {
preEvalVisitors[i].run(root);
}
evaldRoot = evaluate.call(root, evalEnv);
for(i = 0; i < visitors.length; i++) {
visitors[i].run(evaldRoot);
}
if (options.sourceMap) {
evaldRoot = new tree.sourceMapOutput(
{
contentsIgnoredCharsMap: parser.imports.contentsIgnoredChars,
writeSourceMap: options.writeSourceMap,
rootNode: evaldRoot,
contentsMap: parser.imports.contents,
sourceMapFilename: options.sourceMapFilename,
sourceMapURL: options.sourceMapURL,
outputFilename: options.sourceMapOutputFilename,
sourceMapBasepath: options.sourceMapBasepath,
sourceMapRootpath: options.sourceMapRootpath,
outputSourceFiles: options.outputSourceFiles,
sourceMapGenerator: options.sourceMapGenerator
});
}
css = evaldRoot.toCSS({
compress: Boolean(options.compress),
dumpLineNumbers: env.dumpLineNumbers,
strictUnits: Boolean(options.strictUnits),
numPrecision: 8});
} catch (e) {
throw new(LessError)(e, env);
}
if (options.cleancss && less.mode === 'node') {
var CleanCSS = require('clean-css'),
cleancssOptions = options.cleancssOptions || {};
if (cleancssOptions.keepSpecialComments === undefined) {
cleancssOptions.keepSpecialComments = "*";
}
cleancssOptions.processImport = false;
cleancssOptions.noRebase = true;
if (cleancssOptions.noAdvanced === undefined) {
cleancssOptions.noAdvanced = true;
}
return new CleanCSS(cleancssOptions).minify(css);
} else if (options.compress) {
return css.replace(/(^(\s)+)|((\s)+$)/g, "");
} else {
return css;
}
};
})(root.eval);
// If `i` is smaller than the `input.length - 1`,
// it means the parser wasn't able to parse the whole
// string, so we've got a parsing error.
//
// We try to extract a \n delimited string,
// showing the line where the parse error occured.
// We split it up into two parts (the part which parsed,
// and the part which didn't), so we can color them differently.
if (i < input.length - 1) {
i = furthest;
var loc = getLocation(i, input);
lines = input.split('\n');
line = loc.line + 1;
error = {
type: "Parse",
message: "Unrecognised input",
index: i,
filename: env.currentFileInfo.filename,
line: line,
column: loc.column,
extract: [
lines[line - 2],
lines[line - 1],
lines[line]
]
};
}
var finish = function (e) {
e = error || e || parser.imports.error;
if (e) {
if (!(e instanceof LessError)) {
e = new(LessError)(e, env);
}
return callback(e);
}
else {
return callback(null, root);
}
};
if (env.processImports !== false) {
new tree.importVisitor(this.imports, finish)
.run(root);
} else {
return finish();
}
},
//
// Here in, the parsing rules/functions
//
// The basic structure of the syntax tree generated is as follows:
//
// Ruleset -> Rule -> Value -> Expression -> Entity
//
// Here's some LESS code:
//
// .class {
// color: #fff;
// border: 1px solid #000;
// width: @w + 4px;
// > .child {...}
// }
//
// And here's what the parse tree might look like:
//
// Ruleset (Selector '.class', [
// Rule ("color", Value ([Expression [Color #fff]]))
// Rule ("border", Value ([Expression [Dimension 1px][Keyword "solid"][Color #000]]))
// Rule ("width", Value ([Expression [Operation "+" [Variable "@w"][Dimension 4px]]]))
// Ruleset (Selector [Element '>', '.child'], [...])
// ])
//
// In general, most rules will try to parse a token with the `$()` function, and if the return
// value is truly, will return a new node, of the relevant type. Sometimes, we need to check
// first, before parsing, that's when we use `peek()`.
//
parsers: parsers = {
//
// The `primary` rule is the *entry* and *exit* point of the parser.
// The rules here can appear at any level of the parse tree.
//
// The recursive nature of the grammar is an interplay between the `block`
// rule, which represents `{ ... }`, the `ruleset` rule, and this `primary` rule,
// as represented by this simplified grammar:
//
// primary → (ruleset | rule)+
// ruleset → selector+ block
// block → '{' primary '}'
//
// Only at one point is the primary rule not called from the
// block rule: at the root level.
//
primary: function () {
var mixin = this.mixin, $re = _$re, root = [], node;
while (current)
{
node = this.extendRule() || mixin.definition() || this.rule() || this.ruleset() ||
mixin.call() || this.comment() || this.rulesetCall() || this.directive();
if (node) {
root.push(node);
} else {
if (!($re(/^[\s\n]+/) || $re(/^;+/))) {
break;
}
}
if (peekChar('}')) {
break;
}
}
return root;
},
// We create a Comment node for CSS comments `/* */`,
// but keep the LeSS comments `//` silent, by just skipping
// over them.
comment: function () {
var comment;
if (input.charAt(i) !== '/') { return; }
if (input.charAt(i + 1) === '/') {
return new(tree.Comment)($re(/^\/\/.*/), true, i, env.currentFileInfo);
}
comment = $re(/^\/\*(?:[^*]|\*+[^\/*])*\*+\/\n?/);
if (comment) {
return new(tree.Comment)(comment, false, i, env.currentFileInfo);
}
},
comments: function () {
var comment, comments = [];
while(true) {
comment = this.comment();
if (!comment) {
break;
}
comments.push(comment);
}
return comments;
},
//
// Entities are tokens which can be found inside an Expression
//
entities: {
//
// A string, which supports escaping " and '
//
// "milky way" 'he\'s the one!'
//
quoted: function () {
var str, j = i, e, index = i;
if (input.charAt(j) === '~') { j++; e = true; } // Escaped strings
if (input.charAt(j) !== '"' && input.charAt(j) !== "'") { return; }
if (e) { $char('~'); }
str = $re(/^"((?:[^"\\\r\n]|\\.)*)"|'((?:[^'\\\r\n]|\\.)*)'/);
if (str) {
return new(tree.Quoted)(str[0], str[1] || str[2], e, index, env.currentFileInfo);
}
},
//
// A catch-all word, such as:
//
// black border-collapse
//
keyword: function () {
var k;
k = $re(/^%|^[_A-Za-z-][_A-Za-z0-9-]*/);
if (k) {
var color = tree.Color.fromKeyword(k);
if (color) {
return color;
}
return new(tree.Keyword)(k);
}
},
//
// A function call
//
// rgb(255, 0, 255)
//
// We also try to catch IE's `alpha()`, but let the `alpha` parser
// deal with the details.
//
// The arguments are parsed with the `entities.arguments` parser.
//
call: function () {
var name, nameLC, args, alpha_ret, index = i;
name = /^([\w-]+|%|progid:[\w\.]+)\(/.exec(current);
if (!name) { return; }
name = name[1];
nameLC = name.toLowerCase();
if (nameLC === 'url') {
return null;
}
i += name.length;
if (nameLC === 'alpha') {
alpha_ret = parsers.alpha();
if(typeof alpha_ret !== 'undefined') {
return alpha_ret;
}
}
$char('('); // Parse the '(' and consume whitespace.
args = this.arguments();
if (! $char(')')) {
return;
}
if (name) { return new(tree.Call)(name, args, index, env.currentFileInfo); }
},
arguments: function () {
var args = [], arg;
while (true) {
arg = this.assignment() || parsers.expression();
if (!arg) {
break;
}
args.push(arg);
if (! $char(',')) {
break;
}
}
return args;
},
literal: function () {
return this.dimension() ||
this.color() ||
this.quoted() ||
this.unicodeDescriptor();
},
// Assignments are argument entities for calls.
// They are present in ie filter properties as shown below.
//
// filter: progid:DXImageTransform.Microsoft.Alpha( *opacity=50* )
//
assignment: function () {
var key, value;
key = $re(/^\w+(?=\s?=)/i);
if (!key) {
return;
}
if (!$char('=')) {
return;
}
value = parsers.entity();
if (value) {
return new(tree.Assignment)(key, value);
}
},
//
// Parse url() tokens
//
// We use a specific rule for urls, because they don't really behave like
// standard function calls. The difference is that the argument doesn't have
// to be enclosed within a string, so it can't be parsed as an Expression.
//
url: function () {
var value;
if (input.charAt(i) !== 'u' || !$re(/^url\(/)) {
return;
}
value = this.quoted() || this.variable() ||
$re(/^(?:(?:\\[\(\)'"])|[^\(\)'"])+/) || "";
expectChar(')');
return new(tree.URL)((value.value != null || value instanceof tree.Variable)
? value : new(tree.Anonymous)(value), env.currentFileInfo);
},
//
// A Variable entity, such as `@fink`, in
//
// width: @fink + 2px
//
// We use a different parser for variable definitions,
// see `parsers.variable`.
//
variable: function () {
var name, index = i;
if (input.charAt(i) === '@' && (name = $re(/^@@?[\w-]+/))) {
return new(tree.Variable)(name, index, env.currentFileInfo);
}
},
// A variable entity useing the protective {} e.g. @{var}
variableCurly: function () {
var curly, index = i;
if (input.charAt(i) === '@' && (curly = $re(/^@\{([\w-]+)\}/))) {
return new(tree.Variable)("@" + curly[1], index, env.currentFileInfo);
}
},
//
// A Hexadecimal color
//
// #4F3C2F
//
// `rgb` and `hsl` colors are parsed through the `entities.call` parser.
//
color: function () {
var rgb;
if (input.charAt(i) === '#' && (rgb = $re(/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})/))) {
return new(tree.Color)(rgb[1]);
}
},
//
// A Dimension, that is, a number and a unit
//
// 0.5em 95%
//
dimension: function () {
var value, c = input.charCodeAt(i);
//Is the first char of the dimension 0-9, '.', '+' or '-'
if ((c > 57 || c < 43) || c === 47 || c == 44) {
return;
}
value = $re(/^([+-]?\d*\.?\d+)(%|[a-z]+)?/);
if (value) {
return new(tree.Dimension)(value[1], value[2]);
}
},
//
// A unicode descriptor, as is used in unicode-range
//
// U+0?? or U+00A1-00A9
//
unicodeDescriptor: function () {
var ud;
ud = $re(/^U\+[0-9a-fA-F?]+(\-[0-9a-fA-F?]+)?/);
if (ud) {
return new(tree.UnicodeDescriptor)(ud[0]);
}
},
//
// JavaScript code to be evaluated
//
// `window.location.href`
//
javascript: function () {
var str, j = i, e;
if (input.charAt(j) === '~') { j++; e = true; } // Escaped strings
if (input.charAt(j) !== '`') { return; }
if (env.javascriptEnabled !== undefined && !env.javascriptEnabled) {
error("You are using JavaScript, which has been disabled.");
}
if (e) { $char('~'); }
str = $re(/^`([^`]*)`/);
if (str) {
return new(tree.JavaScript)(str[1], i, e);
}
}
},
//
// The variable part of a variable definition. Used in the `rule` parser
//
// @fink:
//
variable: function () {
var name;
if (input.charAt(i) === '@' && (name = $re(/^(@[\w-]+)\s*:/))) { return name[1]; }
},
//
// The variable part of a variable definition. Used in the `rule` parser
//
// @fink();
//
rulesetCall: function () {
var name;
if (input.charAt(i) === '@' && (name = $re(/^(@[\w-]+)\s*\(\s*\)\s*;/))) {
return new tree.RulesetCall(name[1]);
}
},
//
// extend syntax - used to extend selectors
//
extend: function(isRule) {
var elements, e, index = i, option, extendList, extend;
if (!(isRule ? $re(/^&:extend\(/) : $re(/^:extend\(/))) { return; }
do {
option = null;
elements = null;
while (! (option = $re(/^(all)(?=\s*(\)|,))/))) {
e = this.element();
if (!e) { break; }
if (elements) { elements.push(e); } else { elements = [ e ]; }
}
option = option && option[1];
extend = new(tree.Extend)(new(tree.Selector)(elements), option, index);
if (extendList) { extendList.push(extend); } else { extendList = [ extend ]; }
} while($char(","));
expect(/^\)/);
if (isRule) {
expect(/^;/);
}
return extendList;
},
//
// extendRule - used in a rule to extend all the parent selectors
//
extendRule: function() {
return this.extend(true);
},
//
// Mixins
//
mixin: {
//
// A Mixin call, with an optional argument list
//
// #mixins > .square(#fff);
// .rounded(4px, black);
// .button;
//
// The `while` loop is there because mixins can be
// namespaced, but we only support the child and descendant
// selector for now.
//
call: function () {
var s = input.charAt(i), important = false, index = i, elemIndex,
elements, elem, e, c, args;
if (s !== '.' && s !== '#') { return; }
save(); // stop us absorbing part of an invalid selector
while (true) {
elemIndex = i;
e = $re(/^[#.](?:[\w-]|\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+/);
if (!e) {
break;
}
elem = new(tree.Element)(c, e, elemIndex, env.currentFileInfo);
if (elements) { elements.push(elem); } else { elements = [ elem ]; }
c = $char('>');
}
if (elements) {
if ($char('(')) {
args = this.args(true).args;
expectChar(')');
}
if (parsers.important()) {
important = true;
}
if (parsers.end()) {
forget();
return new(tree.mixin.Call)(elements, args, index, env.currentFileInfo, important);
}
}
restore();
},
args: function (isCall) {
var parsers = parser.parsers, entities = parsers.entities,
returner = { args:null, variadic: false },
expressions = [], argsSemiColon = [], argsComma = [],
isSemiColonSeperated, expressionContainsNamed, name, nameLoop, value, arg;
save();
while (true) {
if (isCall) {
arg = parsers.detachedRuleset() || parsers.expression();
} else {
parsers.comments();
if (input.charAt(i) === '.' && $re(/^\.{3}/)) {
returner.variadic = true;
if ($char(";") && !isSemiColonSeperated) {
isSemiColonSeperated = true;
}
(isSemiColonSeperated ? argsSemiColon : argsComma)
.push({ variadic: true });
break;
}
arg = entities.variable() || entities.literal() || entities.keyword();
}
if (!arg) {
break;
}
nameLoop = null;
if (arg.throwAwayComments) {
arg.throwAwayComments();
}
value = arg;
var val = null;
if (isCall) {
// Variable
if (arg.value && arg.value.length == 1) {
val = arg.value[0];
}
} else {
val = arg;
}
if (val && val instanceof tree.Variable) {
if ($char(':')) {
if (expressions.length > 0) {
if (isSemiColonSeperated) {
error("Cannot mix ; and , as delimiter types");
}
expressionContainsNamed = true;
}
// we do not support setting a ruleset as a default variable - it doesn't make sense
// However if we do want to add it, there is nothing blocking it, just don't error
// and remove isCall dependency below
value = (isCall && parsers.detachedRuleset()) || parsers.expression();
if (!value) {
if (isCall) {
error("could not understand value for named argument");
} else {
restore();
returner.args = [];
return returner;
}
}
nameLoop = (name = val.name);
} else if (!isCall && $re(/^\.{3}/)) {
returner.variadic = true;
if ($char(";") && !isSemiColonSeperated) {
isSemiColonSeperated = true;
}
(isSemiColonSeperated ? argsSemiColon : argsComma)
.push({ name: arg.name, variadic: true });
break;
} else if (!isCall) {
name = nameLoop = val.name;
value = null;
}
}
if (value) {
expressions.push(value);
}
argsComma.push({ name:nameLoop, value:value });
if ($char(',')) {
continue;
}
if ($char(';') || isSemiColonSeperated) {
if (expressionContainsNamed) {
error("Cannot mix ; and , as delimiter types");
}
isSemiColonSeperated = true;
if (expressions.length > 1) {
value = new(tree.Value)(expressions);
}
argsSemiColon.push({ name:name, value:value });
name = null;
expressions = [];
expressionContainsNamed = false;
}
}
forget();
returner.args = isSemiColonSeperated ? argsSemiColon : argsComma;
return returner;
},
//
// A Mixin definition, with a list of parameters
//
// .rounded (@radius: 2px, @color) {
// ...
// }
//
// Until we have a finer grained state-machine, we have to
// do a look-ahead, to make sure we don't have a mixin call.
// See the `rule` function for more information.
//
// We start by matching `.rounded (`, and then proceed on to
// the argument list, which has optional default values.
// We store the parameters in `params`, with a `value` key,
// if there is a value, such as in the case of `@radius`.
//
// Once we've got our params list, and a closing `)`, we parse
// the `{...}` block.
//
definition: function () {
var name, params = [], match, ruleset, cond, variadic = false;
if ((input.charAt(i) !== '.' && input.charAt(i) !== '#') ||
peek(/^[^{]*\}/)) {
return;
}
save();
match = $re(/^([#.](?:[\w-]|\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+)\s*\(/);
if (match) {
name = match[1];
var argInfo = this.args(false);
params = argInfo.args;
variadic = argInfo.variadic;
// .mixincall("@{a}");
// looks a bit like a mixin definition..
// also
// .mixincall(@a: {rule: set;});
// so we have to be nice and restore
if (!$char(')')) {
furthest = i;
restore();
return;
}
parsers.comments();
if ($re(/^when/)) { // Guard
cond = expect(parsers.conditions, 'expected condition');
}
ruleset = parsers.block();
if (ruleset) {
forget();
return new(tree.mixin.Definition)(name, params, ruleset, cond, variadic);
} else {
restore();
}
} else {
forget();
}
}
},
//
// Entities are the smallest recognized token,
// and can be found inside a rule's value.
//
entity: function () {
var entities = this.entities;
return entities.literal() || entities.variable() || entities.url() ||
entities.call() || entities.keyword() || entities.javascript() ||
this.comment();
},
//
// A Rule terminator. Note that we use `peek()` to check for '}',
// because the `block` rule will be expecting it, but we still need to make sure
// it's there, if ';' was ommitted.
//
end: function () {
return $char(';') || peekChar('}');
},
//
// IE's alpha function
//
// alpha(opacity=88)
//
alpha: function () {
var value;
if (! $re(/^\(opacity=/i)) { return; }
value = $re(/^\d+/) || this.entities.variable();
if (value) {
expectChar(')');
return new(tree.Alpha)(value);
}
},
//
// A Selector Element
//
// div
// + h1
// #socks
// input[type="text"]
//
// Elements are the building blocks for Selectors,
// they are made out of a `Combinator` (see combinator rule),
// and an element name, such as a tag a class, or `*`.
//
element: function () {
var e, c, v, index = i;
c = this.combinator();
e = $re(/^(?:\d+\.\d+|\d+)%/) || $re(/^(?:[.#]?|:*)(?:[\w-]|[^\x00-\x9f]|\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+/) ||
$char('*') || $char('&') || this.attribute() || $re(/^\([^()@]+\)/) || $re(/^[\.#](?=@)/) ||
this.entities.variableCurly();
if (! e) {
save();
if ($char('(')) {
if ((v = this.selector()) && $char(')')) {
e = new(tree.Paren)(v);
forget();
} else {
restore();
}
} else {
forget();
}
}
if (e) { return new(tree.Element)(c, e, index, env.currentFileInfo); }
},
//
// Combinators combine elements together, in a Selector.
//
// Because our parser isn't white-space sensitive, special care
// has to be taken, when parsing the descendant combinator, ` `,
// as it's an empty space. We have to check the previous character
// in the input, to see if it's a ` ` character. More info on how
// we deal with this in *combinator.js*.
//
combinator: function () {
var c = input.charAt(i);
if (c === '>' || c === '+' || c === '~' || c === '|' || c === '^') {
i++;
if (input.charAt(i) === '^') {
c = '^^';
i++;
}
while (isWhitespace(input, i)) { i++; }
return new(tree.Combinator)(c);
} else if (isWhitespace(input, i - 1)) {
return new(tree.Combinator)(" ");
} else {
return new(tree.Combinator)(null);
}
},
//
// A CSS selector (see selector below)
// with less extensions e.g. the ability to extend and guard
//
lessSelector: function () {
return this.selector(true);
},
//
// A CSS Selector
//
// .class > div + h1
// li a:hover
//
// Selectors are made out of one or more Elements, see above.
//
selector: function (isLess) {
var index = i, $re = _$re, elements, extendList, c, e, extend, when, condition;
while ((isLess && (extend = this.extend())) || (isLess && (when = $re(/^when/))) || (e = this.element())) {
if (when) {
condition = expect(this.conditions, 'expected condition');
} else if (condition) {
error("CSS guard can only be used at the end of selector");
} else if (extend) {
if (extendList) { extendList.push(extend); } else { extendList = [ extend ]; }
} else {
if (extendList) { error("Extend can only be used at the end of selector"); }
c = input.charAt(i);
if (elements) { elements.push(e); } else { elements = [ e ]; }
e = null;
}
if (c === '{' || c === '}' || c === ';' || c === ',' || c === ')') {
break;
}
}
if (elements) { return new(tree.Selector)(elements, extendList, condition, index, env.currentFileInfo); }
if (extendList) { error("Extend must be used to extend a selector, it cannot be used on its own"); }
},
attribute: function () {
if (! $char('[')) { return; }
var entities = this.entities,
key, val, op;
if (!(key = entities.variableCurly())) {
key = expect(/^(?:[_A-Za-z0-9-\*]*\|)?(?:[_A-Za-z0-9-]|\\.)+/);
}
op = $re(/^[|~*$^]?=/);
if (op) {
val = entities.quoted() || $re(/^[0-9]+%/) || $re(/^[\w-]+/) || entities.variableCurly();
}
expectChar(']');
return new(tree.Attribute)(key, op, val);
},
//
// The `block` rule is used by `ruleset` and `mixin.definition`.
// It's a wrapper around the `primary` rule, with added `{}`.
//
block: function () {
var content;
if ($char('{') && (content = this.primary()) && $char('}')) {
return content;
}
},
blockRuleset: function() {
var block = this.block();
if (block) {
block = new tree.Ruleset(null, block);
}
return block;
},
detachedRuleset: function() {
var blockRuleset = this.blockRuleset();
if (blockRuleset) {
return new tree.DetachedRuleset(blockRuleset);
}
},
//
// div, .class, body > p {...}
//
ruleset: function () {
var selectors, s, rules, debugInfo;
save();
if (env.dumpLineNumbers) {
debugInfo = getDebugInfo(i, input, env);
}
while (true) {
s = this.lessSelector();
if (!s) {
break;
}
if (selectors) { selectors.push(s); } else { selectors = [ s ]; }
this.comments();
if (s.condition && selectors.length > 1) {
error("Guards are only currently allowed on a single selector.");
}
if (! $char(',')) { break; }
if (s.condition) {
error("Guards are only currently allowed on a single selector.");
}
this.comments();
}
if (selectors && (rules = this.block())) {
forget();
var ruleset = new(tree.Ruleset)(selectors, rules, env.strictImports);
if (env.dumpLineNumbers) {
ruleset.debugInfo = debugInfo;
}
return ruleset;
} else {
// Backtrack
furthest = i;
restore();
}
},
rule: function (tryAnonymous) {
var name, value, startOfRule = i, c = input.charAt(startOfRule), important, merge, isVariable;
if (c === '.' || c === '#' || c === '&') { return; }
save();
name = this.variable() || this.ruleProperty();
if (name) {
isVariable = typeof name === "string";
if (isVariable) {
value = this.detachedRuleset();
}
if (!value) {
// prefer to try to parse first if its a variable or we are compressing
// but always fallback on the other one
value = !tryAnonymous && (env.compress || isVariable) ?
(this.value() || this.anonymousValue()) :
(this.anonymousValue() || this.value());
important = this.important();
// a name returned by this.ruleProperty() is always an array of the form:
// [string-1, ..., string-n, ""] or [string-1, ..., string-n, "+"]
// where each item is a tree.Keyword or tree.Variable
merge = !isVariable && name.pop().value;
}
if (value && this.end()) {
forget();
return new (tree.Rule)(name, value, important, merge, startOfRule, env.currentFileInfo);
} else {
furthest = i;
restore();
if (value && !tryAnonymous) {
return this.rule(true);
}
}
} else {
forget();
}
},
anonymousValue: function () {
var match;
match = /^([^@+\/'"*`(;{}-]*);/.exec(current);
if (match) {
i += match[0].length - 1;
return new(tree.Anonymous)(match[1]);
}
},
//
// An @import directive
//
// @import "lib";
//
// Depending on our environemnt, importing is done differently:
// In the browser, it's an XHR request, in Node, it would be a
// file-system operation. The function used for importing is
// stored in `import`, which we pass to the Import constructor.
//
"import": function () {
var path, features, index = i;
save();
var dir = $re(/^@import?\s+/);
var options = (dir ? this.importOptions() : null) || {};
if (dir && (path = this.entities.quoted() || this.entities.url())) {
features = this.mediaFeatures();
if ($char(';')) {
forget();
features = features && new(tree.Value)(features);
return new(tree.Import)(path, features, options, index, env.currentFileInfo);
}
}
restore();
},
importOptions: function() {
var o, options = {}, optionName, value;
// list of options, surrounded by parens
if (! $char('(')) { return null; }
do {
o = this.importOption();
if (o) {
optionName = o;
value = true;
switch(optionName) {
case "css":
optionName = "less";
value = false;
break;
case "once":
optionName = "multiple";
value = false;
break;
}
options[optionName] = value;
if (! $char(',')) { break; }
}
} while (o);
expectChar(')');
return options;
},
importOption: function() {
var opt = $re(/^(less|css|multiple|once|inline|reference)/);
if (opt) {
return opt[1];
}
},
mediaFeature: function () {
var entities = this.entities, nodes = [], e, p;
do {
e = entities.keyword() || entities.variable();
if (e) {
nodes.push(e);
} else if ($char('(')) {
p = this.property();
e = this.value();
if ($char(')')) {
if (p && e) {
nodes.push(new(tree.Paren)(new(tree.Rule)(p, e, null, null, i, env.currentFileInfo, true)));
} else if (e) {
nodes.push(new(tree.Paren)(e));
} else {
return null;
}
} else { return null; }
}
} while (e);
if (nodes.length > 0) {
return new(tree.Expression)(nodes);
}
},
mediaFeatures: function () {
var entities = this.entities, features = [], e;
do {
e = this.mediaFeature();
if (e) {
features.push(e);
if (! $char(',')) { break; }
} else {
e = entities.variable();
if (e) {
features.push(e);
if (! $char(',')) { break; }
}
}
} while (e);
return features.length > 0 ? features : null;
},
media: function () {
var features, rules, media, debugInfo;
if (env.dumpLineNumbers) {
debugInfo = getDebugInfo(i, input, env);
}
if ($re(/^@media/)) {
features = this.mediaFeatures();
rules = this.block();
if (rules) {
media = new(tree.Media)(rules, features, i, env.currentFileInfo);
if (env.dumpLineNumbers) {
media.debugInfo = debugInfo;
}
return media;
}
}
},
//
// A CSS Directive
//
// @charset "utf-8";
//
directive: function () {
var index = i, name, value, rules, nonVendorSpecificName,
hasIdentifier, hasExpression, hasUnknown, hasBlock = true;
if (input.charAt(i) !== '@') { return; }
value = this['import']() || this.media();
if (value) {
return value;
}
save();
name = $re(/^@[a-z-]+/);
if (!name) { return; }
nonVendorSpecificName = name;
if (name.charAt(1) == '-' && name.indexOf('-', 2) > 0) {
nonVendorSpecificName = "@" + name.slice(name.indexOf('-', 2) + 1);
}
switch(nonVendorSpecificName) {
/*
case "@font-face":
case "@viewport":
case "@top-left":
case "@top-left-corner":
case "@top-center":
case "@top-right":
case "@top-right-corner":
case "@bottom-left":
case "@bottom-left-corner":
case "@bottom-center":
case "@bottom-right":
case "@bottom-right-corner":
case "@left-top":
case "@left-middle":
case "@left-bottom":
case "@right-top":
case "@right-middle":
case "@right-bottom":
hasBlock = true;
break;
*/
case "@charset":
hasIdentifier = true;
hasBlock = false;
break;
case "@namespace":
hasExpression = true;
hasBlock = false;
break;
case "@keyframes":
hasIdentifier = true;
break;
case "@host":
case "@page":
case "@document":
case "@supports":
hasUnknown = true;
break;
}
if (hasIdentifier) {
value = this.entity();
if (!value) {
error("expected " + name + " identifier");
}
} else if (hasExpression) {
value = this.expression();
if (!value) {
error("expected " + name + " expression");
}
} else if (hasUnknown) {
value = ($re(/^[^{;]+/) || '').trim();
if (value) {
value = new(tree.Anonymous)(value);
}
}
if (hasBlock) {
rules = this.blockRuleset();
}
if (rules || (!hasBlock && value && $char(';'))) {
forget();
return new(tree.Directive)(name, value, rules, index, env.currentFileInfo,
env.dumpLineNumbers ? getDebugInfo(index, input, env) : null);
}
restore();
},
//
// A Value is a comma-delimited list of Expressions
//
// font-family: Baskerville, Georgia, serif;
//
// In a Rule, a Value represents everything after the `:`,
// and before the `;`.
//
value: function () {
var e, expressions = [];
do {
e = this.expression();
if (e) {
expressions.push(e);
if (! $char(',')) { break; }
}
} while(e);
if (expressions.length > 0) {
return new(tree.Value)(expressions);
}
},
important: function () {
if (input.charAt(i) === '!') {
return $re(/^! *important/);
}
},
sub: function () {
var a, e;
if ($char('(')) {
a = this.addition();
if (a) {
e = new(tree.Expression)([a]);
expectChar(')');
e.parens = true;
return e;
}
}
},
multiplication: function () {
var m, a, op, operation, isSpaced;
m = this.operand();
if (m) {
isSpaced = isWhitespace(input, i - 1);
while (true) {
if (peek(/^\/[*\/]/)) {
break;
}
op = $char('/') || $char('*');
if (!op) { break; }
a = this.operand();
if (!a) { break; }
m.parensInOp = true;
a.parensInOp = true;
operation = new(tree.Operation)(op, [operation || m, a], isSpaced);
isSpaced = isWhitespace(input, i - 1);
}
return operation || m;
}
},
addition: function () {
var m, a, op, operation, isSpaced;
m = this.multiplication();
if (m) {
isSpaced = isWhitespace(input, i - 1);
while (true) {
op = $re(/^[-+]\s+/) || (!isSpaced && ($char('+') || $char('-')));
if (!op) {
break;
}
a = this.multiplication();
if (!a) {
break;
}
m.parensInOp = true;
a.parensInOp = true;
operation = new(tree.Operation)(op, [operation || m, a], isSpaced);
isSpaced = isWhitespace(input, i - 1);
}
return operation || m;
}
},
conditions: function () {
var a, b, index = i, condition;
a = this.condition();
if (a) {
while (true) {
if (!peek(/^,\s*(not\s*)?\(/) || !$char(',')) {
break;
}
b = this.condition();
if (!b) {
break;
}
condition = new(tree.Condition)('or', condition || a, b, index);
}
return condition || a;
}
},
condition: function () {
var entities = this.entities, index = i, negate = false,
a, b, c, op;
if ($re(/^not/)) { negate = true; }
expectChar('(');
a = this.addition() || entities.keyword() || entities.quoted();
if (a) {
op = $re(/^(?:>=|<=|=<|[<=>])/);
if (op) {
b = this.addition() || entities.keyword() || entities.quoted();
if (b) {
c = new(tree.Condition)(op, a, b, index, negate);
} else {
error('expected expression');
}
} else {
c = new(tree.Condition)('=', a, new(tree.Keyword)('true'), index, negate);
}
expectChar(')');
return $re(/^and/) ? new(tree.Condition)('and', c, this.condition()) : c;
}
},
//
// An operand is anything that can be part of an operation,
// such as a Color, or a Variable
//
operand: function () {
var entities = this.entities,
p = input.charAt(i + 1), negate;
if (input.charAt(i) === '-' && (p === '@' || p === '(')) { negate = $char('-'); }
var o = this.sub() || entities.dimension() ||
entities.color() || entities.variable() ||
entities.call();
if (negate) {
o.parensInOp = true;
o = new(tree.Negative)(o);
}
return o;
},
//
// Expressions either represent mathematical operations,
// or white-space delimited Entities.
//
// 1px solid black
// @var * 2
//
expression: function () {
var entities = [], e, delim;
do {
e = this.addition() || this.entity();
if (e) {
entities.push(e);
// operations do not allow keyword "/" dimension (e.g. small/20px) so we support that here
if (!peek(/^\/[\/*]/)) {
delim = $char('/');
if (delim) {
entities.push(new(tree.Anonymous)(delim));
}
}
}
} while (e);
if (entities.length > 0) {
return new(tree.Expression)(entities);
}
},
property: function () {
var name = $re(/^(\*?-?[_a-zA-Z0-9-]+)\s*:/);
if (name) {
return name[1];
}
},
ruleProperty: function () {
var c = current, name = [], index = [], length = 0, s, k;
function match(re) {
var a = re.exec(c);
if (a) {
index.push(i + length);
length += a[0].length;
c = c.slice(a[1].length);
return name.push(a[1]);
}
}
match(/^(\*?)/);
while (match(/^((?:[\w-]+)|(?:@\{[\w-]+\}))/)); // !
if ((name.length > 1) && match(/^\s*((?:\+_|\+)?)\s*:/)) {
// at last, we have the complete match now. move forward,
// convert name particles to tree objects and return:
skipWhitespace(length);
if (name[0] === '') {
name.shift();
index.shift();
}
for (k = 0; k < name.length; k++) {
s = name[k];
name[k] = (s.charAt(0) !== '@')
? new(tree.Keyword)(s)
: new(tree.Variable)('@' + s.slice(2, -1),
index[k], env.currentFileInfo);
}
return name;
}
}
}
};
return parser;
};
less.Parser.serializeVars = function(vars) {
var s = '';
for (var name in vars) {
if (Object.hasOwnProperty.call(vars, name)) {
var value = vars[name];
s += ((name[0] === '@') ? '' : '@') + name +': '+ value +
((('' + value).slice(-1) === ';') ? '' : ';');
}
}
return s;
};
(function (tree) {
tree.functions = {
rgb: function (r, g, b) {
return this.rgba(r, g, b, 1.0);
},
rgba: function (r, g, b, a) {
var rgb = [r, g, b].map(function (c) { return scaled(c, 255); });
a = number(a);
return new(tree.Color)(rgb, a);
},
hsl: function (h, s, l) {
return this.hsla(h, s, l, 1.0);
},
hsla: function (h, s, l, a) {
function hue(h) {
h = h < 0 ? h + 1 : (h > 1 ? h - 1 : h);
if (h * 6 < 1) { return m1 + (m2 - m1) * h * 6; }
else if (h * 2 < 1) { return m2; }
else if (h * 3 < 2) { return m1 + (m2 - m1) * (2/3 - h) * 6; }
else { return m1; }
}
h = (number(h) % 360) / 360;
s = clamp(number(s)); l = clamp(number(l)); a = clamp(number(a));
var m2 = l <= 0.5 ? l * (s + 1) : l + s - l * s;
var m1 = l * 2 - m2;
return this.rgba(hue(h + 1/3) * 255,
hue(h) * 255,
hue(h - 1/3) * 255,
a);
},
hsv: function(h, s, v) {
return this.hsva(h, s, v, 1.0);
},
hsva: function(h, s, v, a) {
h = ((number(h) % 360) / 360) * 360;
s = number(s); v = number(v); a = number(a);
var i, f;
i = Math.floor((h / 60) % 6);
f = (h / 60) - i;
var vs = [v,
v * (1 - s),
v * (1 - f * s),
v * (1 - (1 - f) * s)];
var perm = [[0, 3, 1],
[2, 0, 1],
[1, 0, 3],
[1, 2, 0],
[3, 1, 0],
[0, 1, 2]];
return this.rgba(vs[perm[i][0]] * 255,
vs[perm[i][1]] * 255,
vs[perm[i][2]] * 255,
a);
},
hue: function (color) {
return new(tree.Dimension)(Math.round(color.toHSL().h));
},
saturation: function (color) {
return new(tree.Dimension)(Math.round(color.toHSL().s * 100), '%');
},
lightness: function (color) {
return new(tree.Dimension)(Math.round(color.toHSL().l * 100), '%');
},
hsvhue: function(color) {
return new(tree.Dimension)(Math.round(color.toHSV().h));
},
hsvsaturation: function (color) {
return new(tree.Dimension)(Math.round(color.toHSV().s * 100), '%');
},
hsvvalue: function (color) {
return new(tree.Dimension)(Math.round(color.toHSV().v * 100), '%');
},
red: function (color) {
return new(tree.Dimension)(color.rgb[0]);
},
green: function (color) {
return new(tree.Dimension)(color.rgb[1]);
},
blue: function (color) {
return new(tree.Dimension)(color.rgb[2]);
},
alpha: function (color) {
return new(tree.Dimension)(color.toHSL().a);
},
luma: function (color) {
return new(tree.Dimension)(Math.round(color.luma() * color.alpha * 100), '%');
},
luminance: function (color) {
var luminance =
(0.2126 * color.rgb[0] / 255)
+ (0.7152 * color.rgb[1] / 255)
+ (0.0722 * color.rgb[2] / 255);
return new(tree.Dimension)(Math.round(luminance * color.alpha * 100), '%');
},
saturate: function (color, amount) {
// filter: saturate(3.2);
// should be kept as is, so check for color
if (!color.rgb) {
return null;
}
var hsl = color.toHSL();
hsl.s += amount.value / 100;
hsl.s = clamp(hsl.s);
return hsla(hsl);
},
desaturate: function (color, amount) {
var hsl = color.toHSL();
hsl.s -= amount.value / 100;
hsl.s = clamp(hsl.s);
return hsla(hsl);
},
lighten: function (color, amount) {
var hsl = color.toHSL();
hsl.l += amount.value / 100;
hsl.l = clamp(hsl.l);
return hsla(hsl);
},
darken: function (color, amount) {
var hsl = color.toHSL();
hsl.l -= amount.value / 100;
hsl.l = clamp(hsl.l);
return hsla(hsl);
},
fadein: function (color, amount) {
var hsl = color.toHSL();
hsl.a += amount.value / 100;
hsl.a = clamp(hsl.a);
return hsla(hsl);
},
fadeout: function (color, amount) {
var hsl = color.toHSL();
hsl.a -= amount.value / 100;
hsl.a = clamp(hsl.a);
return hsla(hsl);
},
fade: function (color, amount) {
var hsl = color.toHSL();
hsl.a = amount.value / 100;
hsl.a = clamp(hsl.a);
return hsla(hsl);
},
spin: function (color, amount) {
var hsl = color.toHSL();
var hue = (hsl.h + amount.value) % 360;
hsl.h = hue < 0 ? 360 + hue : hue;
return hsla(hsl);
},
//
// Copyright (c) 2006-2009 Hampton Catlin, Nathan Weizenbaum, and Chris Eppstein
// http://sass-lang.com
//
mix: function (color1, color2, weight) {
if (!weight) {
weight = new(tree.Dimension)(50);
}
var p = weight.value / 100.0;
var w = p * 2 - 1;
var a = color1.toHSL().a - color2.toHSL().a;
var w1 = (((w * a == -1) ? w : (w + a) / (1 + w * a)) + 1) / 2.0;
var w2 = 1 - w1;
var rgb = [color1.rgb[0] * w1 + color2.rgb[0] * w2,
color1.rgb[1] * w1 + color2.rgb[1] * w2,
color1.rgb[2] * w1 + color2.rgb[2] * w2];
var alpha = color1.alpha * p + color2.alpha * (1 - p);
return new(tree.Color)(rgb, alpha);
},
greyscale: function (color) {
return this.desaturate(color, new(tree.Dimension)(100));
},
contrast: function (color, dark, light, threshold) {
// filter: contrast(3.2);
// should be kept as is, so check for color
if (!color.rgb) {
return null;
}
if (typeof light === 'undefined') {
light = this.rgba(255, 255, 255, 1.0);
}
if (typeof dark === 'undefined') {
dark = this.rgba(0, 0, 0, 1.0);
}
//Figure out which is actually light and dark!
if (dark.luma() > light.luma()) {
var t = light;
light = dark;
dark = t;
}
if (typeof threshold === 'undefined') {
threshold = 0.43;
} else {
threshold = number(threshold);
}
if (color.luma() < threshold) {
return light;
} else {
return dark;
}
},
e: function (str) {
return new(tree.Anonymous)(str instanceof tree.JavaScript ? str.evaluated : str);
},
escape: function (str) {
return new(tree.Anonymous)(encodeURI(str.value).replace(/=/g, "%3D").replace(/:/g, "%3A").replace(/#/g, "%23").replace(/;/g, "%3B").replace(/\(/g, "%28").replace(/\)/g, "%29"));
},
replace: function (string, pattern, replacement, flags) {
var result = string.value;
result = result.replace(new RegExp(pattern.value, flags ? flags.value : ''), replacement.value);
return new(tree.Quoted)(string.quote || '', result, string.escaped);
},
'%': function (string /* arg, arg, ...*/) {
var args = Array.prototype.slice.call(arguments, 1),
result = string.value;
for (var i = 0; i < args.length; i++) {
/*jshint loopfunc:true */
result = result.replace(/%[sda]/i, function(token) {
var value = token.match(/s/i) ? args[i].value : args[i].toCSS();
return token.match(/[A-Z]$/) ? encodeURIComponent(value) : value;
});
}
result = result.replace(/%%/g, '%');
return new(tree.Quoted)(string.quote || '', result, string.escaped);
},
unit: function (val, unit) {
if(!(val instanceof tree.Dimension)) {
throw { type: "Argument", message: "the first argument to unit must be a number" + (val instanceof tree.Operation ? ". Have you forgotten parenthesis?" : "") };
}
if (unit) {
if (unit instanceof tree.Keyword) {
unit = unit.value;
} else {
unit = unit.toCSS();
}
} else {
unit = "";
}
return new(tree.Dimension)(val.value, unit);
},
convert: function (val, unit) {
return val.convertTo(unit.value);
},
round: function (n, f) {
var fraction = typeof(f) === "undefined" ? 0 : f.value;
return _math(function(num) { return num.toFixed(fraction); }, null, n);
},
pi: function () {
return new(tree.Dimension)(Math.PI);
},
mod: function(a, b) {
return new(tree.Dimension)(a.value % b.value, a.unit);
},
pow: function(x, y) {
if (typeof x === "number" && typeof y === "number") {
x = new(tree.Dimension)(x);
y = new(tree.Dimension)(y);
} else if (!(x instanceof tree.Dimension) || !(y instanceof tree.Dimension)) {
throw { type: "Argument", message: "arguments must be numbers" };
}
return new(tree.Dimension)(Math.pow(x.value, y.value), x.unit);
},
_minmax: function (isMin, args) {
args = Array.prototype.slice.call(args);
switch(args.length) {
case 0: throw { type: "Argument", message: "one or more arguments required" };
}
var i, j, current, currentUnified, referenceUnified, unit, unitStatic, unitClone,
order = [], // elems only contains original argument values.
values = {}; // key is the unit.toString() for unified tree.Dimension values,
// value is the index into the order array.
for (i = 0; i < args.length; i++) {
current = args[i];
if (!(current instanceof tree.Dimension)) {
if(Array.isArray(args[i].value)) {
Array.prototype.push.apply(args, Array.prototype.slice.call(args[i].value));
}
continue;
}
currentUnified = current.unit.toString() === "" && unitClone !== undefined ? new(tree.Dimension)(current.value, unitClone).unify() : current.unify();
unit = currentUnified.unit.toString() === "" && unitStatic !== undefined ? unitStatic : currentUnified.unit.toString();
unitStatic = unit !== "" && unitStatic === undefined || unit !== "" && order[0].unify().unit.toString() === "" ? unit : unitStatic;
unitClone = unit !== "" && unitClone === undefined ? current.unit.toString() : unitClone;
j = values[""] !== undefined && unit !== "" && unit === unitStatic ? values[""] : values[unit];
if (j === undefined) {
if(unitStatic !== undefined && unit !== unitStatic) {
throw{ type: "Argument", message: "incompatible types" };
}
values[unit] = order.length;
order.push(current);
continue;
}
referenceUnified = order[j].unit.toString() === "" && unitClone !== undefined ? new(tree.Dimension)(order[j].value, unitClone).unify() : order[j].unify();
if ( isMin && currentUnified.value < referenceUnified.value ||
!isMin && currentUnified.value > referenceUnified.value) {
order[j] = current;
}
}
if (order.length == 1) {
return order[0];
}
args = order.map(function (a) { return a.toCSS(this.env); }).join(this.env.compress ? "," : ", ");
return new(tree.Anonymous)((isMin ? "min" : "max") + "(" + args + ")");
},
min: function () {
return this._minmax(true, arguments);
},
max: function () {
return this._minmax(false, arguments);
},
"get-unit": function (n) {
return new(tree.Anonymous)(n.unit);
},
argb: function (color) {
return new(tree.Anonymous)(color.toARGB());
},
percentage: function (n) {
return new(tree.Dimension)(n.value * 100, '%');
},
color: function (n) {
if (n instanceof tree.Quoted) {
var colorCandidate = n.value,
returnColor;
returnColor = tree.Color.fromKeyword(colorCandidate);
if (returnColor) {
return returnColor;
}
if (/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})/.test(colorCandidate)) {
return new(tree.Color)(colorCandidate.slice(1));
}
throw { type: "Argument", message: "argument must be a color keyword or 3/6 digit hex e.g. #FFF" };
} else {
throw { type: "Argument", message: "argument must be a string" };
}
},
iscolor: function (n) {
return this._isa(n, tree.Color);
},
isnumber: function (n) {
return this._isa(n, tree.Dimension);
},
isstring: function (n) {
return this._isa(n, tree.Quoted);
},
iskeyword: function (n) {
return this._isa(n, tree.Keyword);
},
isurl: function (n) {
return this._isa(n, tree.URL);
},
ispixel: function (n) {
return this.isunit(n, 'px');
},
ispercentage: function (n) {
return this.isunit(n, '%');
},
isem: function (n) {
return this.isunit(n, 'em');
},
isunit: function (n, unit) {
return (n instanceof tree.Dimension) && n.unit.is(unit.value || unit) ? tree.True : tree.False;
},
_isa: function (n, Type) {
return (n instanceof Type) ? tree.True : tree.False;
},
tint: function(color, amount) {
return this.mix(this.rgb(255,255,255), color, amount);
},
shade: function(color, amount) {
return this.mix(this.rgb(0, 0, 0), color, amount);
},
extract: function(values, index) {
index = index.value - 1; // (1-based index)
// handle non-array values as an array of length 1
// return 'undefined' if index is invalid
return Array.isArray(values.value)
? values.value[index] : Array(values)[index];
},
length: function(values) {
var n = Array.isArray(values.value) ? values.value.length : 1;
return new tree.Dimension(n);
},
"data-uri": function(mimetypeNode, filePathNode) {
if (typeof window !== 'undefined') {
return new tree.URL(filePathNode || mimetypeNode, this.currentFileInfo).eval(this.env);
}
var mimetype = mimetypeNode.value;
var filePath = (filePathNode && filePathNode.value);
var fs = require('fs'),
path = require('path'),
useBase64 = false;
if (arguments.length < 2) {
filePath = mimetype;
}
if (this.env.isPathRelative(filePath)) {
if (this.currentFileInfo.relativeUrls) {
filePath = path.join(this.currentFileInfo.currentDirectory, filePath);
} else {
filePath = path.join(this.currentFileInfo.entryPath, filePath);
}
}
// detect the mimetype if not given
if (arguments.length < 2) {
var mime;
try {
mime = require('mime');
} catch (ex) {
mime = tree._mime;
}
mimetype = mime.lookup(filePath);
// use base 64 unless it's an ASCII or UTF-8 format
var charset = mime.charsets.lookup(mimetype);
useBase64 = ['US-ASCII', 'UTF-8'].indexOf(charset) < 0;
if (useBase64) { mimetype += ';base64'; }
}
else {
useBase64 = /;base64$/.test(mimetype);
}
var buf = fs.readFileSync(filePath);
// IE8 cannot handle a data-uri larger than 32KB. If this is exceeded
// and the --ieCompat flag is enabled, return a normal url() instead.
var DATA_URI_MAX_KB = 32,
fileSizeInKB = parseInt((buf.length / 1024), 10);
if (fileSizeInKB >= DATA_URI_MAX_KB) {
if (this.env.ieCompat !== false) {
if (!this.env.silent) {
console.warn("Skipped data-uri embedding of %s because its size (%dKB) exceeds IE8-safe %dKB!", filePath, fileSizeInKB, DATA_URI_MAX_KB);
}
return new tree.URL(filePathNode || mimetypeNode, this.currentFileInfo).eval(this.env);
}
}
buf = useBase64 ? buf.toString('base64')
: encodeURIComponent(buf);
var uri = "\"data:" + mimetype + ',' + buf + "\"";
return new(tree.URL)(new(tree.Anonymous)(uri));
},
"svg-gradient": function(direction) {
function throwArgumentDescriptor() {
throw { type: "Argument", message: "svg-gradient expects direction, start_color [start_position], [color position,]..., end_color [end_position]" };
}
if (arguments.length < 3) {
throwArgumentDescriptor();
}
var stops = Array.prototype.slice.call(arguments, 1),
gradientDirectionSvg,
gradientType = "linear",
rectangleDimension = 'x="0" y="0" width="1" height="1"',
useBase64 = true,
renderEnv = {compress: false},
returner,
directionValue = direction.toCSS(renderEnv),
i, color, position, positionValue, alpha;
switch (directionValue) {
case "to bottom":
gradientDirectionSvg = 'x1="0%" y1="0%" x2="0%" y2="100%"';
break;
case "to right":
gradientDirectionSvg = 'x1="0%" y1="0%" x2="100%" y2="0%"';
break;
case "to bottom right":
gradientDirectionSvg = 'x1="0%" y1="0%" x2="100%" y2="100%"';
break;
case "to top right":
gradientDirectionSvg = 'x1="0%" y1="100%" x2="100%" y2="0%"';
break;
case "ellipse":
case "ellipse at center":
gradientType = "radial";
gradientDirectionSvg = 'cx="50%" cy="50%" r="75%"';
rectangleDimension = 'x="-50" y="-50" width="101" height="101"';
break;
default:
throw { type: "Argument", message: "svg-gradient direction must be 'to bottom', 'to right', 'to bottom right', 'to top right' or 'ellipse at center'" };
}
returner = '<?xml version="1.0" ?>' +
'<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="100%" height="100%" viewBox="0 0 1 1" preserveAspectRatio="none">' +
'<' + gradientType + 'Gradient id="gradient" gradientUnits="userSpaceOnUse" ' + gradientDirectionSvg + '>';
for (i = 0; i < stops.length; i+= 1) {
if (stops[i].value) {
color = stops[i].value[0];
position = stops[i].value[1];
} else {
color = stops[i];
position = undefined;
}
if (!(color instanceof tree.Color) || (!((i === 0 || i+1 === stops.length) && position === undefined) && !(position instanceof tree.Dimension))) {
throwArgumentDescriptor();
}
positionValue = position ? position.toCSS(renderEnv) : i === 0 ? "0%" : "100%";
alpha = color.alpha;
returner += '<stop offset="' + positionValue + '" stop-color="' + color.toRGB() + '"' + (alpha < 1 ? ' stop-opacity="' + alpha + '"' : '') + '/>';
}
returner += '</' + gradientType + 'Gradient>' +
'<rect ' + rectangleDimension + ' fill="url(#gradient)" /></svg>';
if (useBase64) {
try {
returner = require('./encoder').encodeBase64(returner); // TODO browser implementation
} catch(e) {
useBase64 = false;
}
}
returner = "'data:image/svg+xml" + (useBase64 ? ";base64" : "") + "," + returner + "'";
return new(tree.URL)(new(tree.Anonymous)(returner));
}
};
// these static methods are used as a fallback when the optional 'mime' dependency is missing
tree._mime = {
// this map is intentionally incomplete
// if you want more, install 'mime' dep
_types: {
'.htm' : 'text/html',
'.html': 'text/html',
'.gif' : 'image/gif',
'.jpg' : 'image/jpeg',
'.jpeg': 'image/jpeg',
'.png' : 'image/png'
},
lookup: function (filepath) {
var ext = require('path').extname(filepath),
type = tree._mime._types[ext];
if (type === undefined) {
throw new Error('Optional dependency "mime" is required for ' + ext);
}
return type;
},
charsets: {
lookup: function (type) {
// assumes all text types are UTF-8
return type && (/^text\//).test(type) ? 'UTF-8' : '';
}
}
};
// Math
var mathFunctions = {
// name, unit
ceil: null,
floor: null,
sqrt: null,
abs: null,
tan: "",
sin: "",
cos: "",
atan: "rad",
asin: "rad",
acos: "rad"
};
function _math(fn, unit, n) {
if (!(n instanceof tree.Dimension)) {
throw { type: "Argument", message: "argument must be a number" };
}
if (unit == null) {
unit = n.unit;
} else {
n = n.unify();
}
return new(tree.Dimension)(fn(parseFloat(n.value)), unit);
}
// ~ End of Math
// Color Blending
// ref: http://www.w3.org/TR/compositing-1
function colorBlend(mode, color1, color2) {
var ab = color1.alpha, cb, // backdrop
as = color2.alpha, cs, // source
ar, cr, r = []; // result
ar = as + ab * (1 - as);
for (var i = 0; i < 3; i++) {
cb = color1.rgb[i] / 255;
cs = color2.rgb[i] / 255;
cr = mode(cb, cs);
if (ar) {
cr = (as * cs + ab * (cb
- as * (cb + cs - cr))) / ar;
}
r[i] = cr * 255;
}
return new(tree.Color)(r, ar);
}
var colorBlendMode = {
multiply: function(cb, cs) {
return cb * cs;
},
screen: function(cb, cs) {
return cb + cs - cb * cs;
},
overlay: function(cb, cs) {
cb *= 2;
return (cb <= 1)
? colorBlendMode.multiply(cb, cs)
: colorBlendMode.screen(cb - 1, cs);
},
softlight: function(cb, cs) {
var d = 1, e = cb;
if (cs > 0.5) {
e = 1;
d = (cb > 0.25) ? Math.sqrt(cb)
: ((16 * cb - 12) * cb + 4) * cb;
}
return cb - (1 - 2 * cs) * e * (d - cb);
},
hardlight: function(cb, cs) {
return colorBlendMode.overlay(cs, cb);
},
difference: function(cb, cs) {
return Math.abs(cb - cs);
},
exclusion: function(cb, cs) {
return cb + cs - 2 * cb * cs;
},
// non-w3c functions:
average: function(cb, cs) {
return (cb + cs) / 2;
},
negation: function(cb, cs) {
return 1 - Math.abs(cb + cs - 1);
}
};
// ~ End of Color Blending
tree.defaultFunc = {
eval: function () {
var v = this.value_, e = this.error_;
if (e) {
throw e;
}
if (v != null) {
return v ? tree.True : tree.False;
}
},
value: function (v) {
this.value_ = v;
},
error: function (e) {
this.error_ = e;
},
reset: function () {
this.value_ = this.error_ = null;
}
};
function initFunctions() {
var f, tf = tree.functions;
// math
for (f in mathFunctions) {
if (mathFunctions.hasOwnProperty(f)) {
tf[f] = _math.bind(null, Math[f], mathFunctions[f]);
}
}
// color blending
for (f in colorBlendMode) {
if (colorBlendMode.hasOwnProperty(f)) {
tf[f] = colorBlend.bind(null, colorBlendMode[f]);
}
}
// default
f = tree.defaultFunc;
tf["default"] = f.eval.bind(f);
} initFunctions();
function hsla(color) {
return tree.functions.hsla(color.h, color.s, color.l, color.a);
}
function scaled(n, size) {
if (n instanceof tree.Dimension && n.unit.is('%')) {
return parseFloat(n.value * size / 100);
} else {
return number(n);
}
}
function number(n) {
if (n instanceof tree.Dimension) {
return parseFloat(n.unit.is('%') ? n.value / 100 : n.value);
} else if (typeof(n) === 'number') {
return n;
} else {
throw {
error: "RuntimeError",
message: "color functions take numbers as parameters"
};
}
}
function clamp(val) {
return Math.min(1, Math.max(0, val));
}
tree.fround = function(env, value) {
var p;
if (env && (env.numPrecision != null)) {
p = Math.pow(10, env.numPrecision);
return Math.round(value * p) / p;
} else {
return value;
}
};
tree.functionCall = function(env, currentFileInfo) {
this.env = env;
this.currentFileInfo = currentFileInfo;
};
tree.functionCall.prototype = tree.functions;
})(require('./tree'));
(function (tree) {
tree.colors = {
'aliceblue':'#f0f8ff',
'antiquewhite':'#faebd7',
'aqua':'#00ffff',
'aquamarine':'#7fffd4',
'azure':'#f0ffff',
'beige':'#f5f5dc',
'bisque':'#ffe4c4',
'black':'#000000',
'blanchedalmond':'#ffebcd',
'blue':'#0000ff',
'blueviolet':'#8a2be2',
'brown':'#a52a2a',
'burlywood':'#deb887',
'cadetblue':'#5f9ea0',
'chartreuse':'#7fff00',
'chocolate':'#d2691e',
'coral':'#ff7f50',
'cornflowerblue':'#6495ed',
'cornsilk':'#fff8dc',
'crimson':'#dc143c',
'cyan':'#00ffff',
'darkblue':'#00008b',
'darkcyan':'#008b8b',
'darkgoldenrod':'#b8860b',
'darkgray':'#a9a9a9',
'darkgrey':'#a9a9a9',
'darkgreen':'#006400',
'darkkhaki':'#bdb76b',
'darkmagenta':'#8b008b',
'darkolivegreen':'#556b2f',
'darkorange':'#ff8c00',
'darkorchid':'#9932cc',
'darkred':'#8b0000',
'darksalmon':'#e9967a',
'darkseagreen':'#8fbc8f',
'darkslateblue':'#483d8b',
'darkslategray':'#2f4f4f',
'darkslategrey':'#2f4f4f',
'darkturquoise':'#00ced1',
'darkviolet':'#9400d3',
'deeppink':'#ff1493',
'deepskyblue':'#00bfff',
'dimgray':'#696969',
'dimgrey':'#696969',
'dodgerblue':'#1e90ff',
'firebrick':'#b22222',
'floralwhite':'#fffaf0',
'forestgreen':'#228b22',
'fuchsia':'#ff00ff',
'gainsboro':'#dcdcdc',
'ghostwhite':'#f8f8ff',
'gold':'#ffd700',
'goldenrod':'#daa520',
'gray':'#808080',
'grey':'#808080',
'green':'#008000',
'greenyellow':'#adff2f',
'honeydew':'#f0fff0',
'hotpink':'#ff69b4',
'indianred':'#cd5c5c',
'indigo':'#4b0082',
'ivory':'#fffff0',
'khaki':'#f0e68c',
'lavender':'#e6e6fa',
'lavenderblush':'#fff0f5',
'lawngreen':'#7cfc00',
'lemonchiffon':'#fffacd',
'lightblue':'#add8e6',
'lightcoral':'#f08080',
'lightcyan':'#e0ffff',
'lightgoldenrodyellow':'#fafad2',
'lightgray':'#d3d3d3',
'lightgrey':'#d3d3d3',
'lightgreen':'#90ee90',
'lightpink':'#ffb6c1',
'lightsalmon':'#ffa07a',
'lightseagreen':'#20b2aa',
'lightskyblue':'#87cefa',
'lightslategray':'#778899',
'lightslategrey':'#778899',
'lightsteelblue':'#b0c4de',
'lightyellow':'#ffffe0',
'lime':'#00ff00',
'limegreen':'#32cd32',
'linen':'#faf0e6',
'magenta':'#ff00ff',
'maroon':'#800000',
'mediumaquamarine':'#66cdaa',
'mediumblue':'#0000cd',
'mediumorchid':'#ba55d3',
'mediumpurple':'#9370d8',
'mediumseagreen':'#3cb371',
'mediumslateblue':'#7b68ee',
'mediumspringgreen':'#00fa9a',
'mediumturquoise':'#48d1cc',
'mediumvioletred':'#c71585',
'midnightblue':'#191970',
'mintcream':'#f5fffa',
'mistyrose':'#ffe4e1',
'moccasin':'#ffe4b5',
'navajowhite':'#ffdead',
'navy':'#000080',
'oldlace':'#fdf5e6',
'olive':'#808000',
'olivedrab':'#6b8e23',
'orange':'#ffa500',
'orangered':'#ff4500',
'orchid':'#da70d6',
'palegoldenrod':'#eee8aa',
'palegreen':'#98fb98',
'paleturquoise':'#afeeee',
'palevioletred':'#d87093',
'papayawhip':'#ffefd5',
'peachpuff':'#ffdab9',
'peru':'#cd853f',
'pink':'#ffc0cb',
'plum':'#dda0dd',
'powderblue':'#b0e0e6',
'purple':'#800080',
'red':'#ff0000',
'rosybrown':'#bc8f8f',
'royalblue':'#4169e1',
'saddlebrown':'#8b4513',
'salmon':'#fa8072',
'sandybrown':'#f4a460',
'seagreen':'#2e8b57',
'seashell':'#fff5ee',
'sienna':'#a0522d',
'silver':'#c0c0c0',
'skyblue':'#87ceeb',
'slateblue':'#6a5acd',
'slategray':'#708090',
'slategrey':'#708090',
'snow':'#fffafa',
'springgreen':'#00ff7f',
'steelblue':'#4682b4',
'tan':'#d2b48c',
'teal':'#008080',
'thistle':'#d8bfd8',
'tomato':'#ff6347',
'turquoise':'#40e0d0',
'violet':'#ee82ee',
'wheat':'#f5deb3',
'white':'#ffffff',
'whitesmoke':'#f5f5f5',
'yellow':'#ffff00',
'yellowgreen':'#9acd32'
};
})(require('./tree'));
(function (tree) {
tree.debugInfo = function(env, ctx, lineSeperator) {
var result="";
if (env.dumpLineNumbers && !env.compress) {
switch(env.dumpLineNumbers) {
case 'comments':
result = tree.debugInfo.asComment(ctx);
break;
case 'mediaquery':
result = tree.debugInfo.asMediaQuery(ctx);
break;
case 'all':
result = tree.debugInfo.asComment(ctx) + (lineSeperator || "") + tree.debugInfo.asMediaQuery(ctx);
break;
}
}
return result;
};
tree.debugInfo.asComment = function(ctx) {
return '/* line ' + ctx.debugInfo.lineNumber + ', ' + ctx.debugInfo.fileName + ' */\n';
};
tree.debugInfo.asMediaQuery = function(ctx) {
return '@media -sass-debug-info{filename{font-family:' +
('file://' + ctx.debugInfo.fileName).replace(/([.:\/\\])/g, function (a) {
if (a == '\\') {
a = '\/';
}
return '\\' + a;
}) +
'}line{font-family:\\00003' + ctx.debugInfo.lineNumber + '}}\n';
};
tree.find = function (obj, fun) {
for (var i = 0, r; i < obj.length; i++) {
r = fun.call(obj, obj[i]);
if (r) { return r; }
}
return null;
};
tree.jsify = function (obj) {
if (Array.isArray(obj.value) && (obj.value.length > 1)) {
return '[' + obj.value.map(function (v) { return v.toCSS(false); }).join(', ') + ']';
} else {
return obj.toCSS(false);
}
};
tree.toCSS = function (env) {
var strs = [];
this.genCSS(env, {
add: function(chunk, fileInfo, index) {
strs.push(chunk);
},
isEmpty: function () {
return strs.length === 0;
}
});
return strs.join('');
};
tree.outputRuleset = function (env, output, rules) {
var ruleCnt = rules.length, i;
env.tabLevel = (env.tabLevel | 0) + 1;
// Compressed
if (env.compress) {
output.add('{');
for (i = 0; i < ruleCnt; i++) {
rules[i].genCSS(env, output);
}
output.add('}');
env.tabLevel--;
return;
}
// Non-compressed
var tabSetStr = '\n' + Array(env.tabLevel).join(" "), tabRuleStr = tabSetStr + " ";
if (!ruleCnt) {
output.add(" {" + tabSetStr + '}');
} else {
output.add(" {" + tabRuleStr);
rules[0].genCSS(env, output);
for (i = 1; i < ruleCnt; i++) {
output.add(tabRuleStr);
rules[i].genCSS(env, output);
}
output.add(tabSetStr + '}');
}
env.tabLevel--;
};
})(require('./tree'));
(function (tree) {
tree.Alpha = function (val) {
this.value = val;
};
tree.Alpha.prototype = {
type: "Alpha",
accept: function (visitor) {
this.value = visitor.visit(this.value);
},
eval: function (env) {
if (this.value.eval) { return new tree.Alpha(this.value.eval(env)); }
return this;
},
genCSS: function (env, output) {
output.add("alpha(opacity=");
if (this.value.genCSS) {
this.value.genCSS(env, output);
} else {
output.add(this.value);
}
output.add(")");
},
toCSS: tree.toCSS
};
})(require('../tree'));
(function (tree) {
tree.Anonymous = function (string, index, currentFileInfo, mapLines) {
this.value = string.value || string;
this.index = index;
this.mapLines = mapLines;
this.currentFileInfo = currentFileInfo;
};
tree.Anonymous.prototype = {
type: "Anonymous",
eval: function () {
return new tree.Anonymous(this.value, this.index, this.currentFileInfo, this.mapLines);
},
compare: function (x) {
if (!x.toCSS) {
return -1;
}
var left = this.toCSS(),
right = x.toCSS();
if (left === right) {
return 0;
}
return left < right ? -1 : 1;
},
genCSS: function (env, output) {
output.add(this.value, this.currentFileInfo, this.index, this.mapLines);
},
toCSS: tree.toCSS
};
})(require('../tree'));
(function (tree) {
tree.Assignment = function (key, val) {
this.key = key;
this.value = val;
};
tree.Assignment.prototype = {
type: "Assignment",
accept: function (visitor) {
this.value = visitor.visit(this.value);
},
eval: function (env) {
if (this.value.eval) {
return new(tree.Assignment)(this.key, this.value.eval(env));
}
return this;
},
genCSS: function (env, output) {
output.add(this.key + '=');
if (this.value.genCSS) {
this.value.genCSS(env, output);
} else {
output.add(this.value);
}
},
toCSS: tree.toCSS
};
})(require('../tree'));
(function (tree) {
//
// A function call node.
//
tree.Call = function (name, args, index, currentFileInfo) {
this.name = name;
this.args = args;
this.index = index;
this.currentFileInfo = currentFileInfo;
};
tree.Call.prototype = {
type: "Call",
accept: function (visitor) {
if (this.args) {
this.args = visitor.visitArray(this.args);
}
},
//
// When evaluating a function call,
// we either find the function in `tree.functions` [1],
// in which case we call it, passing the evaluated arguments,
// if this returns null or we cannot find the function, we
// simply print it out as it appeared originally [2].
//
// The *functions.js* file contains the built-in functions.
//
// The reason why we evaluate the arguments, is in the case where
// we try to pass a variable to a function, like: `saturate(@color)`.
// The function should receive the value, not the variable.
//
eval: function (env) {
var args = this.args.map(function (a) { return a.eval(env); }),
nameLC = this.name.toLowerCase(),
result, func;
if (nameLC in tree.functions) { // 1.
try {
func = new tree.functionCall(env, this.currentFileInfo);
result = func[nameLC].apply(func, args);
if (result != null) {
return result;
}
} catch (e) {
throw { type: e.type || "Runtime",
message: "error evaluating function `" + this.name + "`" +
(e.message ? ': ' + e.message : ''),
index: this.index, filename: this.currentFileInfo.filename };
}
}
return new tree.Call(this.name, args, this.index, this.currentFileInfo);
},
genCSS: function (env, output) {
output.add(this.name + "(", this.currentFileInfo, this.index);
for(var i = 0; i < this.args.length; i++) {
this.args[i].genCSS(env, output);
if (i + 1 < this.args.length) {
output.add(", ");
}
}
output.add(")");
},
toCSS: tree.toCSS
};
})(require('../tree'));
(function (tree) {
//
// RGB Colors - #ff0014, #eee
//
tree.Color = function (rgb, a) {
//
// The end goal here, is to parse the arguments
// into an integer triplet, such as `128, 255, 0`
//
// This facilitates operations and conversions.
//
if (Array.isArray(rgb)) {
this.rgb = rgb;
} else if (rgb.length == 6) {
this.rgb = rgb.match(/.{2}/g).map(function (c) {
return parseInt(c, 16);
});
} else {
this.rgb = rgb.split('').map(function (c) {
return parseInt(c + c, 16);
});
}
this.alpha = typeof(a) === 'number' ? a : 1;
};
var transparentKeyword = "transparent";
tree.Color.prototype = {
type: "Color",
eval: function () { return this; },
luma: function () {
var r = this.rgb[0] / 255,
g = this.rgb[1] / 255,
b = this.rgb[2] / 255;
r = (r <= 0.03928) ? r / 12.92 : Math.pow(((r + 0.055) / 1.055), 2.4);
g = (g <= 0.03928) ? g / 12.92 : Math.pow(((g + 0.055) / 1.055), 2.4);
b = (b <= 0.03928) ? b / 12.92 : Math.pow(((b + 0.055) / 1.055), 2.4);
return 0.2126 * r + 0.7152 * g + 0.0722 * b;
},
genCSS: function (env, output) {
output.add(this.toCSS(env));
},
toCSS: function (env, doNotCompress) {
var compress = env && env.compress && !doNotCompress,
alpha = tree.fround(env, this.alpha);
// If we have some transparency, the only way to represent it
// is via `rgba`. Otherwise, we use the hex representation,
// which has better compatibility with older browsers.
// Values are capped between `0` and `255`, rounded and zero-padded.
if (alpha < 1) {
if (alpha === 0 && this.isTransparentKeyword) {
return transparentKeyword;
}
return "rgba(" + this.rgb.map(function (c) {
return clamp(Math.round(c), 255);
}).concat(clamp(alpha, 1))
.join(',' + (compress ? '' : ' ')) + ")";
} else {
var color = this.toRGB();
if (compress) {
var splitcolor = color.split('');
// Convert color to short format
if (splitcolor[1] === splitcolor[2] && splitcolor[3] === splitcolor[4] && splitcolor[5] === splitcolor[6]) {
color = '#' + splitcolor[1] + splitcolor[3] + splitcolor[5];
}
}
return color;
}
},
//
// Operations have to be done per-channel, if not,
// channels will spill onto each other. Once we have
// our result, in the form of an integer triplet,
// we create a new Color node to hold the result.
//
operate: function (env, op, other) {
var rgb = [];
var alpha = this.alpha * (1 - other.alpha) + other.alpha;
for (var c = 0; c < 3; c++) {
rgb[c] = tree.operate(env, op, this.rgb[c], other.rgb[c]);
}
return new(tree.Color)(rgb, alpha);
},
toRGB: function () {
return toHex(this.rgb);
},
toHSL: function () {
var r = this.rgb[0] / 255,
g = this.rgb[1] / 255,
b = this.rgb[2] / 255,
a = this.alpha;
var max = Math.max(r, g, b), min = Math.min(r, g, b);
var h, s, l = (max + min) / 2, d = max - min;
if (max === min) {
h = s = 0;
} else {
s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
switch (max) {
case r: h = (g - b) / d + (g < b ? 6 : 0); break;
case g: h = (b - r) / d + 2; break;
case b: h = (r - g) / d + 4; break;
}
h /= 6;
}
return { h: h * 360, s: s, l: l, a: a };
},
//Adapted from http://mjijackson.com/2008/02/rgb-to-hsl-and-rgb-to-hsv-color-model-conversion-algorithms-in-javascript
toHSV: function () {
var r = this.rgb[0] / 255,
g = this.rgb[1] / 255,
b = this.rgb[2] / 255,
a = this.alpha;
var max = Math.max(r, g, b), min = Math.min(r, g, b);
var h, s, v = max;
var d = max - min;
if (max === 0) {
s = 0;
} else {
s = d / max;
}
if (max === min) {
h = 0;
} else {
switch(max){
case r: h = (g - b) / d + (g < b ? 6 : 0); break;
case g: h = (b - r) / d + 2; break;
case b: h = (r - g) / d + 4; break;
}
h /= 6;
}
return { h: h * 360, s: s, v: v, a: a };
},
toARGB: function () {
return toHex([this.alpha * 255].concat(this.rgb));
},
compare: function (x) {
if (!x.rgb) {
return -1;
}
return (x.rgb[0] === this.rgb[0] &&
x.rgb[1] === this.rgb[1] &&
x.rgb[2] === this.rgb[2] &&
x.alpha === this.alpha) ? 0 : -1;
}
};
tree.Color.fromKeyword = function(keyword) {
keyword = keyword.toLowerCase();
if (tree.colors.hasOwnProperty(keyword)) {
// detect named color
return new(tree.Color)(tree.colors[keyword].slice(1));
}
if (keyword === transparentKeyword) {
var transparent = new(tree.Color)([0, 0, 0], 0);
transparent.isTransparentKeyword = true;
return transparent;
}
};
function toHex(v) {
return '#' + v.map(function (c) {
c = clamp(Math.round(c), 255);
return (c < 16 ? '0' : '') + c.toString(16);
}).join('');
}
function clamp(v, max) {
return Math.min(Math.max(v, 0), max);
}
})(require('../tree'));
(function (tree) {
tree.Comment = function (value, silent, index, currentFileInfo) {
this.value = value;
this.silent = !!silent;
this.currentFileInfo = currentFileInfo;
};
tree.Comment.prototype = {
type: "Comment",
genCSS: function (env, output) {
if (this.debugInfo) {
output.add(tree.debugInfo(env, this), this.currentFileInfo, this.index);
}
output.add(this.value.trim()); //TODO shouldn't need to trim, we shouldn't grab the \n
},
toCSS: tree.toCSS,
isSilent: function(env) {
var isReference = (this.currentFileInfo && this.currentFileInfo.reference && !this.isReferenced),
isCompressed = env.compress && !this.value.match(/^\/\*!/);
return this.silent || isReference || isCompressed;
},
eval: function () { return this; },
markReferenced: function () {
this.isReferenced = true;
}
};
})(require('../tree'));
(function (tree) {
tree.Condition = function (op, l, r, i, negate) {
this.op = op.trim();
this.lvalue = l;
this.rvalue = r;
this.index = i;
this.negate = negate;
};
tree.Condition.prototype = {
type: "Condition",
accept: function (visitor) {
this.lvalue = visitor.visit(this.lvalue);
this.rvalue = visitor.visit(this.rvalue);
},
eval: function (env) {
var a = this.lvalue.eval(env),
b = this.rvalue.eval(env);
var i = this.index, result;
result = (function (op) {
switch (op) {
case 'and':
return a && b;
case 'or':
return a || b;
default:
if (a.compare) {
result = a.compare(b);
} else if (b.compare) {
result = b.compare(a);
} else {
throw { type: "Type",
message: "Unable to perform comparison",
index: i };
}
switch (result) {
case -1: return op === '<' || op === '=<' || op === '<=';
case 0: return op === '=' || op === '>=' || op === '=<' || op === '<=';
case 1: return op === '>' || op === '>=';
}
}
})(this.op);
return this.negate ? !result : result;
}
};
})(require('../tree'));
(function (tree) {
tree.DetachedRuleset = function (ruleset, frames) {
this.ruleset = ruleset;
this.frames = frames;
};
tree.DetachedRuleset.prototype = {
type: "DetachedRuleset",
accept: function (visitor) {
this.ruleset = visitor.visit(this.ruleset);
},
eval: function (env) {
var frames = this.frames || env.frames.slice(0);
return new tree.DetachedRuleset(this.ruleset, frames);
},
callEval: function (env) {
return this.ruleset.eval(this.frames ? new(tree.evalEnv)(env, this.frames.concat(env.frames)) : env);
}
};
})(require('../tree'));
(function (tree) {
//
// A number with a unit
//
tree.Dimension = function (value, unit) {
this.value = parseFloat(value);
this.unit = (unit && unit instanceof tree.Unit) ? unit :
new(tree.Unit)(unit ? [unit] : undefined);
};
tree.Dimension.prototype = {
type: "Dimension",
accept: function (visitor) {
this.unit = visitor.visit(this.unit);
},
eval: function (env) {
return this;
},
toColor: function () {
return new(tree.Color)([this.value, this.value, this.value]);
},
genCSS: function (env, output) {
if ((env && env.strictUnits) && !this.unit.isSingular()) {
throw new Error("Multiple units in dimension. Correct the units or use the unit function. Bad unit: "+this.unit.toString());
}
var value = tree.fround(env, this.value),
strValue = String(value);
if (value !== 0 && value < 0.000001 && value > -0.000001) {
// would be output 1e-6 etc.
strValue = value.toFixed(20).replace(/0+$/, "");
}
if (env && env.compress) {
// Zero values doesn't need a unit
if (value === 0 && this.unit.isLength()) {
output.add(strValue);
return;
}
// Float values doesn't need a leading zero
if (value > 0 && value < 1) {
strValue = (strValue).substr(1);
}
}
output.add(strValue);
this.unit.genCSS(env, output);
},
toCSS: tree.toCSS,
// In an operation between two Dimensions,
// we default to the first Dimension's unit,
// so `1px + 2` will yield `3px`.
operate: function (env, op, other) {
/*jshint noempty:false */
var value = tree.operate(env, op, this.value, other.value),
unit = this.unit.clone();
if (op === '+' || op === '-') {
if (unit.numerator.length === 0 && unit.denominator.length === 0) {
unit.numerator = other.unit.numerator.slice(0);
unit.denominator = other.unit.denominator.slice(0);
} else if (other.unit.numerator.length === 0 && unit.denominator.length === 0) {
// do nothing
} else {
other = other.convertTo(this.unit.usedUnits());
if(env.strictUnits && other.unit.toString() !== unit.toString()) {
throw new Error("Incompatible units. Change the units or use the unit function. Bad units: '" + unit.toString() +
"' and '" + other.unit.toString() + "'.");
}
value = tree.operate(env, op, this.value, other.value);
}
} else if (op === '*') {
unit.numerator = unit.numerator.concat(other.unit.numerator).sort();
unit.denominator = unit.denominator.concat(other.unit.denominator).sort();
unit.cancel();
} else if (op === '/') {
unit.numerator = unit.numerator.concat(other.unit.denominator).sort();
unit.denominator = unit.denominator.concat(other.unit.numerator).sort();
unit.cancel();
}
return new(tree.Dimension)(value, unit);
},
compare: function (other) {
if (other instanceof tree.Dimension) {
var a, b,
aValue, bValue;
if (this.unit.isEmpty() || other.unit.isEmpty()) {
a = this;
b = other;
} else {
a = this.unify();
b = other.unify();
if (a.unit.compare(b.unit) !== 0) {
return -1;
}
}
aValue = a.value;
bValue = b.value;
if (bValue > aValue) {
return -1;
} else if (bValue < aValue) {
return 1;
} else {
return 0;
}
} else {
return -1;
}
},
unify: function () {
return this.convertTo({ length: 'px', duration: 's', angle: 'rad' });
},
convertTo: function (conversions) {
var value = this.value, unit = this.unit.clone(),
i, groupName, group, targetUnit, derivedConversions = {}, applyUnit;
if (typeof conversions === 'string') {
for(i in tree.UnitConversions) {
if (tree.UnitConversions[i].hasOwnProperty(conversions)) {
derivedConversions = {};
derivedConversions[i] = conversions;
}
}
conversions = derivedConversions;
}
applyUnit = function (atomicUnit, denominator) {
/*jshint loopfunc:true */
if (group.hasOwnProperty(atomicUnit)) {
if (denominator) {
value = value / (group[atomicUnit] / group[targetUnit]);
} else {
value = value * (group[atomicUnit] / group[targetUnit]);
}
return targetUnit;
}
return atomicUnit;
};
for (groupName in conversions) {
if (conversions.hasOwnProperty(groupName)) {
targetUnit = conversions[groupName];
group = tree.UnitConversions[groupName];
unit.map(applyUnit);
}
}
unit.cancel();
return new(tree.Dimension)(value, unit);
}
};
// http://www.w3.org/TR/css3-values/#absolute-lengths
tree.UnitConversions = {
length: {
'm': 1,
'cm': 0.01,
'mm': 0.001,
'in': 0.0254,
'px': 0.0254 / 96,
'pt': 0.0254 / 72,
'pc': 0.0254 / 72 * 12
},
duration: {
's': 1,
'ms': 0.001
},
angle: {
'rad': 1/(2*Math.PI),
'deg': 1/360,
'grad': 1/400,
'turn': 1
}
};
tree.Unit = function (numerator, denominator, backupUnit) {
this.numerator = numerator ? numerator.slice(0).sort() : [];
this.denominator = denominator ? denominator.slice(0).sort() : [];
this.backupUnit = backupUnit;
};
tree.Unit.prototype = {
type: "Unit",
clone: function () {
return new tree.Unit(this.numerator.slice(0), this.denominator.slice(0), this.backupUnit);
},
genCSS: function (env, output) {
if (this.numerator.length >= 1) {
output.add(this.numerator[0]);
} else
if (this.denominator.length >= 1) {
output.add(this.denominator[0]);
} else
if ((!env || !env.strictUnits) && this.backupUnit) {
output.add(this.backupUnit);
}
},
toCSS: tree.toCSS,
toString: function () {
var i, returnStr = this.numerator.join("*");
for (i = 0; i < this.denominator.length; i++) {
returnStr += "/" + this.denominator[i];
}
return returnStr;
},
compare: function (other) {
return this.is(other.toString()) ? 0 : -1;
},
is: function (unitString) {
return this.toString() === unitString;
},
isLength: function () {
return Boolean(this.toCSS().match(/px|em|%|in|cm|mm|pc|pt|ex/));
},
isEmpty: function () {
return this.numerator.length === 0 && this.denominator.length === 0;
},
isSingular: function() {
return this.numerator.length <= 1 && this.denominator.length === 0;
},
map: function(callback) {
var i;
for (i = 0; i < this.numerator.length; i++) {
this.numerator[i] = callback(this.numerator[i], false);
}
for (i = 0; i < this.denominator.length; i++) {
this.denominator[i] = callback(this.denominator[i], true);
}
},
usedUnits: function() {
var group, result = {}, mapUnit;
mapUnit = function (atomicUnit) {
/*jshint loopfunc:true */
if (group.hasOwnProperty(atomicUnit) && !result[groupName]) {
result[groupName] = atomicUnit;
}
return atomicUnit;
};
for (var groupName in tree.UnitConversions) {
if (tree.UnitConversions.hasOwnProperty(groupName)) {
group = tree.UnitConversions[groupName];
this.map(mapUnit);
}
}
return result;
},
cancel: function () {
var counter = {}, atomicUnit, i, backup;
for (i = 0; i < this.numerator.length; i++) {
atomicUnit = this.numerator[i];
if (!backup) {
backup = atomicUnit;
}
counter[atomicUnit] = (counter[atomicUnit] || 0) + 1;
}
for (i = 0; i < this.denominator.length; i++) {
atomicUnit = this.denominator[i];
if (!backup) {
backup = atomicUnit;
}
counter[atomicUnit] = (counter[atomicUnit] || 0) - 1;
}
this.numerator = [];
this.denominator = [];
for (atomicUnit in counter) {
if (counter.hasOwnProperty(atomicUnit)) {
var count = counter[atomicUnit];
if (count > 0) {
for (i = 0; i < count; i++) {
this.numerator.push(atomicUnit);
}
} else if (count < 0) {
for (i = 0; i < -count; i++) {
this.denominator.push(atomicUnit);
}
}
}
}
if (this.numerator.length === 0 && this.denominator.length === 0 && backup) {
this.backupUnit = backup;
}
this.numerator.sort();
this.denominator.sort();
}
};
})(require('../tree'));
(function (tree) {
tree.Directive = function (name, value, rules, index, currentFileInfo, debugInfo) {
this.name = name;
this.value = value;
if (rules) {
this.rules = rules;
this.rules.allowImports = true;
}
this.index = index;
this.currentFileInfo = currentFileInfo;
this.debugInfo = debugInfo;
};
tree.Directive.prototype = {
type: "Directive",
accept: function (visitor) {
var value = this.value, rules = this.rules;
if (rules) {
rules = visitor.visit(rules);
}
if (value) {
value = visitor.visit(value);
}
},
genCSS: function (env, output) {
var value = this.value, rules = this.rules;
output.add(this.name, this.currentFileInfo, this.index);
if (value) {
output.add(' ');
value.genCSS(env, output);
}
if (rules) {
tree.outputRuleset(env, output, [rules]);
} else {
output.add(';');
}
},
toCSS: tree.toCSS,
eval: function (env) {
var value = this.value, rules = this.rules;
if (value) {
value = value.eval(env);
}
if (rules) {
rules = rules.eval(env);
rules.root = true;
}
return new(tree.Directive)(this.name, value, rules,
this.index, this.currentFileInfo, this.debugInfo);
},
variable: function (name) { if (this.rules) return tree.Ruleset.prototype.variable.call(this.rules, name); },
find: function () { if (this.rules) return tree.Ruleset.prototype.find.apply(this.rules, arguments); },
rulesets: function () { if (this.rules) return tree.Ruleset.prototype.rulesets.apply(this.rules); },
markReferenced: function () {
var i, rules;
this.isReferenced = true;
if (this.rules) {
rules = this.rules.rules;
for (i = 0; i < rules.length; i++) {
if (rules[i].markReferenced) {
rules[i].markReferenced();
}
}
}
}
};
})(require('../tree'));
(function (tree) {
tree.Element = function (combinator, value, index, currentFileInfo) {
this.combinator = combinator instanceof tree.Combinator ?
combinator : new(tree.Combinator)(combinator);
if (typeof(value) === 'string') {
this.value = value.trim();
} else if (value) {
this.value = value;
} else {
this.value = "";
}
this.index = index;
this.currentFileInfo = currentFileInfo;
};
tree.Element.prototype = {
type: "Element",
accept: function (visitor) {
var value = this.value;
this.combinator = visitor.visit(this.combinator);
if (typeof value === "object") {
this.value = visitor.visit(value);
}
},
eval: function (env) {
return new(tree.Element)(this.combinator,
this.value.eval ? this.value.eval(env) : this.value,
this.index,
this.currentFileInfo);
},
genCSS: function (env, output) {
output.add(this.toCSS(env), this.currentFileInfo, this.index);
},
toCSS: function (env) {
var value = (this.value.toCSS ? this.value.toCSS(env) : this.value);
if (value === '' && this.combinator.value.charAt(0) === '&') {
return '';
} else {
return this.combinator.toCSS(env || {}) + value;
}
}
};
tree.Attribute = function (key, op, value) {
this.key = key;
this.op = op;
this.value = value;
};
tree.Attribute.prototype = {
type: "Attribute",
eval: function (env) {
return new(tree.Attribute)(this.key.eval ? this.key.eval(env) : this.key,
this.op, (this.value && this.value.eval) ? this.value.eval(env) : this.value);
},
genCSS: function (env, output) {
output.add(this.toCSS(env));
},
toCSS: function (env) {
var value = this.key.toCSS ? this.key.toCSS(env) : this.key;
if (this.op) {
value += this.op;
value += (this.value.toCSS ? this.value.toCSS(env) : this.value);
}
return '[' + value + ']';
}
};
tree.Combinator = function (value) {
if (value === ' ') {
this.value = ' ';
} else {
this.value = value ? value.trim() : "";
}
};
tree.Combinator.prototype = {
type: "Combinator",
_outputMap: {
'' : '',
' ' : ' ',
':' : ' :',
'+' : ' + ',
'~' : ' ~ ',
'>' : ' > ',
'|' : '|',
'^' : ' ^ ',
'^^' : ' ^^ '
},
_outputMapCompressed: {
'' : '',
' ' : ' ',
':' : ' :',
'+' : '+',
'~' : '~',
'>' : '>',
'|' : '|',
'^' : '^',
'^^' : '^^'
},
genCSS: function (env, output) {
output.add((env.compress ? this._outputMapCompressed : this._outputMap)[this.value]);
},
toCSS: tree.toCSS
};
})(require('../tree'));
(function (tree) {
tree.Expression = function (value) { this.value = value; };
tree.Expression.prototype = {
type: "Expression",
accept: function (visitor) {
if (this.value) {
this.value = visitor.visitArray(this.value);
}
},
eval: function (env) {
var returnValue,
inParenthesis = this.parens && !this.parensInOp,
doubleParen = false;
if (inParenthesis) {
env.inParenthesis();
}
if (this.value.length > 1) {
returnValue = new(tree.Expression)(this.value.map(function (e) {
return e.eval(env);
}));
} else if (this.value.length === 1) {
if (this.value[0].parens && !this.value[0].parensInOp) {
doubleParen = true;
}
returnValue = this.value[0].eval(env);
} else {
returnValue = this;
}
if (inParenthesis) {
env.outOfParenthesis();
}
if (this.parens && this.parensInOp && !(env.isMathOn()) && !doubleParen) {
returnValue = new(tree.Paren)(returnValue);
}
return returnValue;
},
genCSS: function (env, output) {
for(var i = 0; i < this.value.length; i++) {
this.value[i].genCSS(env, output);
if (i + 1 < this.value.length) {
output.add(" ");
}
}
},
toCSS: tree.toCSS,
throwAwayComments: function () {
this.value = this.value.filter(function(v) {
return !(v instanceof tree.Comment);
});
}
};
})(require('../tree'));
(function (tree) {
tree.Extend = function Extend(selector, option, index) {
this.selector = selector;
this.option = option;
this.index = index;
this.object_id = tree.Extend.next_id++;
this.parent_ids = [this.object_id];
switch(option) {
case "all":
this.allowBefore = true;
this.allowAfter = true;
break;
default:
this.allowBefore = false;
this.allowAfter = false;
break;
}
};
tree.Extend.next_id = 0;
tree.Extend.prototype = {
type: "Extend",
accept: function (visitor) {
this.selector = visitor.visit(this.selector);
},
eval: function (env) {
return new(tree.Extend)(this.selector.eval(env), this.option, this.index);
},
clone: function (env) {
return new(tree.Extend)(this.selector, this.option, this.index);
},
findSelfSelectors: function (selectors) {
var selfElements = [],
i,
selectorElements;
for(i = 0; i < selectors.length; i++) {
selectorElements = selectors[i].elements;
// duplicate the logic in genCSS function inside the selector node.
// future TODO - move both logics into the selector joiner visitor
if (i > 0 && selectorElements.length && selectorElements[0].combinator.value === "") {
selectorElements[0].combinator.value = ' ';
}
selfElements = selfElements.concat(selectors[i].elements);
}
this.selfSelectors = [{ elements: selfElements }];
}
};
})(require('../tree'));
(function (tree) {
//
// CSS @import node
//
// The general strategy here is that we don't want to wait
// for the parsing to be completed, before we start importing
// the file. That's because in the context of a browser,
// most of the time will be spent waiting for the server to respond.
//
// On creation, we push the import path to our import queue, though
// `import,push`, we also pass it a callback, which it'll call once
// the file has been fetched, and parsed.
//
tree.Import = function (path, features, options, index, currentFileInfo) {
this.options = options;
this.index = index;
this.path = path;
this.features = features;
this.currentFileInfo = currentFileInfo;
if (this.options.less !== undefined || this.options.inline) {
this.css = !this.options.less || this.options.inline;
} else {
var pathValue = this.getPath();
if (pathValue && /css([\?;].*)?$/.test(pathValue)) {
this.css = true;
}
}
};
//
// The actual import node doesn't return anything, when converted to CSS.
// The reason is that it's used at the evaluation stage, so that the rules
// it imports can be treated like any other rules.
//
// In `eval`, we make sure all Import nodes get evaluated, recursively, so
// we end up with a flat structure, which can easily be imported in the parent
// ruleset.
//
tree.Import.prototype = {
type: "Import",
accept: function (visitor) {
if (this.features) {
this.features = visitor.visit(this.features);
}
this.path = visitor.visit(this.path);
if (!this.options.inline && this.root) {
this.root = visitor.visit(this.root);
}
},
genCSS: function (env, output) {
if (this.css) {
output.add("@import ", this.currentFileInfo, this.index);
this.path.genCSS(env, output);
if (this.features) {
output.add(" ");
this.features.genCSS(env, output);
}
output.add(';');
}
},
toCSS: tree.toCSS,
getPath: function () {
if (this.path instanceof tree.Quoted) {
var path = this.path.value;
return (this.css !== undefined || /(\.[a-z]*$)|([\?;].*)$/.test(path)) ? path : path + '.less';
} else if (this.path instanceof tree.URL) {
return this.path.value.value;
}
return null;
},
evalForImport: function (env) {
return new(tree.Import)(this.path.eval(env), this.features, this.options, this.index, this.currentFileInfo);
},
evalPath: function (env) {
var path = this.path.eval(env);
var rootpath = this.currentFileInfo && this.currentFileInfo.rootpath;
if (!(path instanceof tree.URL)) {
if (rootpath) {
var pathValue = path.value;
// Add the base path if the import is relative
if (pathValue && env.isPathRelative(pathValue)) {
path.value = rootpath +pathValue;
}
}
path.value = env.normalizePath(path.value);
}
return path;
},
eval: function (env) {
var ruleset, features = this.features && this.features.eval(env);
if (this.skip) {
if (typeof this.skip === "function") {
this.skip = this.skip();
}
if (this.skip) {
return [];
}
}
if (this.options.inline) {
//todo needs to reference css file not import
var contents = new(tree.Anonymous)(this.root, 0, {filename: this.importedFilename}, true);
return this.features ? new(tree.Media)([contents], this.features.value) : [contents];
} else if (this.css) {
var newImport = new(tree.Import)(this.evalPath(env), features, this.options, this.index);
if (!newImport.css && this.error) {
throw this.error;
}
return newImport;
} else {
ruleset = new(tree.Ruleset)(null, this.root.rules.slice(0));
ruleset.evalImports(env);
return this.features ? new(tree.Media)(ruleset.rules, this.features.value) : ruleset.rules;
}
}
};
})(require('../tree'));
(function (tree) {
tree.JavaScript = function (string, index, escaped) {
this.escaped = escaped;
this.expression = string;
this.index = index;
};
tree.JavaScript.prototype = {
type: "JavaScript",
eval: function (env) {
var result,
that = this,
context = {};
var expression = this.expression.replace(/@\{([\w-]+)\}/g, function (_, name) {
return tree.jsify(new(tree.Variable)('@' + name, that.index).eval(env));
});
try {
expression = new(Function)('return (' + expression + ')');
} catch (e) {
throw { message: "JavaScript evaluation error: " + e.message + " from `" + expression + "`" ,
index: this.index };
}
var variables = env.frames[0].variables();
for (var k in variables) {
if (variables.hasOwnProperty(k)) {
/*jshint loopfunc:true */
context[k.slice(1)] = {
value: variables[k].value,
toJS: function () {
return this.value.eval(env).toCSS();
}
};
}
}
try {
result = expression.call(context);
} catch (e) {
throw { message: "JavaScript evaluation error: '" + e.name + ': ' + e.message.replace(/["]/g, "'") + "'" ,
index: this.index };
}
if (typeof(result) === 'number') {
return new(tree.Dimension)(result);
} else if (typeof(result) === 'string') {
return new(tree.Quoted)('"' + result + '"', result, this.escaped, this.index);
} else if (Array.isArray(result)) {
return new(tree.Anonymous)(result.join(', '));
} else {
return new(tree.Anonymous)(result);
}
}
};
})(require('../tree'));
(function (tree) {
tree.Keyword = function (value) { this.value = value; };
tree.Keyword.prototype = {
type: "Keyword",
eval: function () { return this; },
genCSS: function (env, output) {
if (this.value === '%') { throw { type: "Syntax", message: "Invalid % without number" }; }
output.add(this.value);
},
toCSS: tree.toCSS,
compare: function (other) {
if (other instanceof tree.Keyword) {
return other.value === this.value ? 0 : 1;
} else {
return -1;
}
}
};
tree.True = new(tree.Keyword)('true');
tree.False = new(tree.Keyword)('false');
})(require('../tree'));
(function (tree) {
tree.Media = function (value, features, index, currentFileInfo) {
this.index = index;
this.currentFileInfo = currentFileInfo;
var selectors = this.emptySelectors();
this.features = new(tree.Value)(features);
this.rules = [new(tree.Ruleset)(selectors, value)];
this.rules[0].allowImports = true;
};
tree.Media.prototype = {
type: "Media",
accept: function (visitor) {
if (this.features) {
this.features = visitor.visit(this.features);
}
if (this.rules) {
this.rules = visitor.visitArray(this.rules);
}
},
genCSS: function (env, output) {
output.add('@media ', this.currentFileInfo, this.index);
this.features.genCSS(env, output);
tree.outputRuleset(env, output, this.rules);
},
toCSS: tree.toCSS,
eval: function (env) {
if (!env.mediaBlocks) {
env.mediaBlocks = [];
env.mediaPath = [];
}
var media = new(tree.Media)(null, [], this.index, this.currentFileInfo);
if(this.debugInfo) {
this.rules[0].debugInfo = this.debugInfo;
media.debugInfo = this.debugInfo;
}
var strictMathBypass = false;
if (!env.strictMath) {
strictMathBypass = true;
env.strictMath = true;
}
try {
media.features = this.features.eval(env);
}
finally {
if (strictMathBypass) {
env.strictMath = false;
}
}
env.mediaPath.push(media);
env.mediaBlocks.push(media);
env.frames.unshift(this.rules[0]);
media.rules = [this.rules[0].eval(env)];
env.frames.shift();
env.mediaPath.pop();
return env.mediaPath.length === 0 ? media.evalTop(env) :
media.evalNested(env);
},
variable: function (name) { return tree.Ruleset.prototype.variable.call(this.rules[0], name); },
find: function () { return tree.Ruleset.prototype.find.apply(this.rules[0], arguments); },
rulesets: function () { return tree.Ruleset.prototype.rulesets.apply(this.rules[0]); },
emptySelectors: function() {
var el = new(tree.Element)('', '&', this.index, this.currentFileInfo),
sels = [new(tree.Selector)([el], null, null, this.index, this.currentFileInfo)];
sels[0].mediaEmpty = true;
return sels;
},
markReferenced: function () {
var i, rules = this.rules[0].rules;
this.rules[0].markReferenced();
this.isReferenced = true;
for (i = 0; i < rules.length; i++) {
if (rules[i].markReferenced) {
rules[i].markReferenced();
}
}
},
evalTop: function (env) {
var result = this;
// Render all dependent Media blocks.
if (env.mediaBlocks.length > 1) {
var selectors = this.emptySelectors();
result = new(tree.Ruleset)(selectors, env.mediaBlocks);
result.multiMedia = true;
}
delete env.mediaBlocks;
delete env.mediaPath;
return result;
},
evalNested: function (env) {
var i, value,
path = env.mediaPath.concat([this]);
// Extract the media-query conditions separated with `,` (OR).
for (i = 0; i < path.length; i++) {
value = path[i].features instanceof tree.Value ?
path[i].features.value : path[i].features;
path[i] = Array.isArray(value) ? value : [value];
}
// Trace all permutations to generate the resulting media-query.
//
// (a, b and c) with nested (d, e) ->
// a and d
// a and e
// b and c and d
// b and c and e
this.features = new(tree.Value)(this.permute(path).map(function (path) {
path = path.map(function (fragment) {
return fragment.toCSS ? fragment : new(tree.Anonymous)(fragment);
});
for(i = path.length - 1; i > 0; i--) {
path.splice(i, 0, new(tree.Anonymous)("and"));
}
return new(tree.Expression)(path);
}));
// Fake a tree-node that doesn't output anything.
return new(tree.Ruleset)([], []);
},
permute: function (arr) {
if (arr.length === 0) {
return [];
} else if (arr.length === 1) {
return arr[0];
} else {
var result = [];
var rest = this.permute(arr.slice(1));
for (var i = 0; i < rest.length; i++) {
for (var j = 0; j < arr[0].length; j++) {
result.push([arr[0][j]].concat(rest[i]));
}
}
return result;
}
},
bubbleSelectors: function (selectors) {
if (!selectors)
return;
this.rules = [new(tree.Ruleset)(selectors.slice(0), [this.rules[0]])];
}
};
})(require('../tree'));
(function (tree) {
tree.mixin = {};
tree.mixin.Call = function (elements, args, index, currentFileInfo, important) {
this.selector = new(tree.Selector)(elements);
this.arguments = (args && args.length) ? args : null;
this.index = index;
this.currentFileInfo = currentFileInfo;
this.important = important;
};
tree.mixin.Call.prototype = {
type: "MixinCall",
accept: function (visitor) {
if (this.selector) {
this.selector = visitor.visit(this.selector);
}
if (this.arguments) {
this.arguments = visitor.visitArray(this.arguments);
}
},
eval: function (env) {
var mixins, mixin, args, rules = [], match = false, i, m, f, isRecursive, isOneFound, rule,
candidates = [], candidate, conditionResult = [], defaultFunc = tree.defaultFunc,
defaultResult, defNone = 0, defTrue = 1, defFalse = 2, count;
args = this.arguments && this.arguments.map(function (a) {
return { name: a.name, value: a.value.eval(env) };
});
for (i = 0; i < env.frames.length; i++) {
if ((mixins = env.frames[i].find(this.selector)).length > 0) {
isOneFound = true;
// To make `default()` function independent of definition order we have two "subpasses" here.
// At first we evaluate each guard *twice* (with `default() == true` and `default() == false`),
// and build candidate list with corresponding flags. Then, when we know all possible matches,
// we make a final decision.
for (m = 0; m < mixins.length; m++) {
mixin = mixins[m];
isRecursive = false;
for(f = 0; f < env.frames.length; f++) {
if ((!(mixin instanceof tree.mixin.Definition)) && mixin === (env.frames[f].originalRuleset || env.frames[f])) {
isRecursive = true;
break;
}
}
if (isRecursive) {
continue;
}
if (mixin.matchArgs(args, env)) {
candidate = {mixin: mixin, group: defNone};
if (mixin.matchCondition) {
for (f = 0; f < 2; f++) {
defaultFunc.value(f);
conditionResult[f] = mixin.matchCondition(args, env);
}
if (conditionResult[0] || conditionResult[1]) {
if (conditionResult[0] != conditionResult[1]) {
candidate.group = conditionResult[1] ?
defTrue : defFalse;
}
candidates.push(candidate);
}
}
else {
candidates.push(candidate);
}
match = true;
}
}
defaultFunc.reset();
count = [0, 0, 0];
for (m = 0; m < candidates.length; m++) {
count[candidates[m].group]++;
}
if (count[defNone] > 0) {
defaultResult = defFalse;
} else {
defaultResult = defTrue;
if ((count[defTrue] + count[defFalse]) > 1) {
throw { type: 'Runtime',
message: 'Ambiguous use of `default()` found when matching for `'
+ this.format(args) + '`',
index: this.index, filename: this.currentFileInfo.filename };
}
}
for (m = 0; m < candidates.length; m++) {
candidate = candidates[m].group;
if ((candidate === defNone) || (candidate === defaultResult)) {
try {
mixin = candidates[m].mixin;
if (!(mixin instanceof tree.mixin.Definition)) {
mixin = new tree.mixin.Definition("", [], mixin.rules, null, false);
mixin.originalRuleset = mixins[m].originalRuleset || mixins[m];
}
Array.prototype.push.apply(
rules, mixin.evalCall(env, args, this.important).rules);
} catch (e) {
throw { message: e.message, index: this.index, filename: this.currentFileInfo.filename, stack: e.stack };
}
}
}
if (match) {
if (!this.currentFileInfo || !this.currentFileInfo.reference) {
for (i = 0; i < rules.length; i++) {
rule = rules[i];
if (rule.markReferenced) {
rule.markReferenced();
}
}
}
return rules;
}
}
}
if (isOneFound) {
throw { type: 'Runtime',
message: 'No matching definition was found for `' + this.format(args) + '`',
index: this.index, filename: this.currentFileInfo.filename };
} else {
throw { type: 'Name',
message: this.selector.toCSS().trim() + " is undefined",
index: this.index, filename: this.currentFileInfo.filename };
}
},
format: function (args) {
return this.selector.toCSS().trim() + '(' +
(args ? args.map(function (a) {
var argValue = "";
if (a.name) {
argValue += a.name + ":";
}
if (a.value.toCSS) {
argValue += a.value.toCSS();
} else {
argValue += "???";
}
return argValue;
}).join(', ') : "") + ")";
}
};
tree.mixin.Definition = function (name, params, rules, condition, variadic, frames) {
this.name = name;
this.selectors = [new(tree.Selector)([new(tree.Element)(null, name, this.index, this.currentFileInfo)])];
this.params = params;
this.condition = condition;
this.variadic = variadic;
this.arity = params.length;
this.rules = rules;
this._lookups = {};
this.required = params.reduce(function (count, p) {
if (!p.name || (p.name && !p.value)) { return count + 1; }
else { return count; }
}, 0);
this.parent = tree.Ruleset.prototype;
this.frames = frames;
};
tree.mixin.Definition.prototype = {
type: "MixinDefinition",
accept: function (visitor) {
if (this.params && this.params.length) {
this.params = visitor.visitArray(this.params);
}
this.rules = visitor.visitArray(this.rules);
if (this.condition) {
this.condition = visitor.visit(this.condition);
}
},
variable: function (name) { return this.parent.variable.call(this, name); },
variables: function () { return this.parent.variables.call(this); },
find: function () { return this.parent.find.apply(this, arguments); },
rulesets: function () { return this.parent.rulesets.apply(this); },
evalParams: function (env, mixinEnv, args, evaldArguments) {
/*jshint boss:true */
var frame = new(tree.Ruleset)(null, null),
varargs, arg,
params = this.params.slice(0),
i, j, val, name, isNamedFound, argIndex, argsLength = 0;
mixinEnv = new tree.evalEnv(mixinEnv, [frame].concat(mixinEnv.frames));
if (args) {
args = args.slice(0);
argsLength = args.length;
for(i = 0; i < argsLength; i++) {
arg = args[i];
if (name = (arg && arg.name)) {
isNamedFound = false;
for(j = 0; j < params.length; j++) {
if (!evaldArguments[j] && name === params[j].name) {
evaldArguments[j] = arg.value.eval(env);
frame.prependRule(new(tree.Rule)(name, arg.value.eval(env)));
isNamedFound = true;
break;
}
}
if (isNamedFound) {
args.splice(i, 1);
i--;
continue;
} else {
throw { type: 'Runtime', message: "Named argument for " + this.name +
' ' + args[i].name + ' not found' };
}
}
}
}
argIndex = 0;
for (i = 0; i < params.length; i++) {
if (evaldArguments[i]) { continue; }
arg = args && args[argIndex];
if (name = params[i].name) {
if (params[i].variadic) {
varargs = [];
for (j = argIndex; j < argsLength; j++) {
varargs.push(args[j].value.eval(env));
}
frame.prependRule(new(tree.Rule)(name, new(tree.Expression)(varargs).eval(env)));
} else {
val = arg && arg.value;
if (val) {
val = val.eval(env);
} else if (params[i].value) {
val = params[i].value.eval(mixinEnv);
frame.resetCache();
} else {
throw { type: 'Runtime', message: "wrong number of arguments for " + this.name +
' (' + argsLength + ' for ' + this.arity + ')' };
}
frame.prependRule(new(tree.Rule)(name, val));
evaldArguments[i] = val;
}
}
if (params[i].variadic && args) {
for (j = argIndex; j < argsLength; j++) {
evaldArguments[j] = args[j].value.eval(env);
}
}
argIndex++;
}
return frame;
},
eval: function (env) {
return new tree.mixin.Definition(this.name, this.params, this.rules, this.condition, this.variadic, this.frames || env.frames.slice(0));
},
evalCall: function (env, args, important) {
var _arguments = [],
mixinFrames = this.frames ? this.frames.concat(env.frames) : env.frames,
frame = this.evalParams(env, new(tree.evalEnv)(env, mixinFrames), args, _arguments),
rules, ruleset;
frame.prependRule(new(tree.Rule)('@arguments', new(tree.Expression)(_arguments).eval(env)));
rules = this.rules.slice(0);
ruleset = new(tree.Ruleset)(null, rules);
ruleset.originalRuleset = this;
ruleset = ruleset.eval(new(tree.evalEnv)(env, [this, frame].concat(mixinFrames)));
if (important) {
ruleset = this.parent.makeImportant.apply(ruleset);
}
return ruleset;
},
matchCondition: function (args, env) {
if (this.condition && !this.condition.eval(
new(tree.evalEnv)(env,
[this.evalParams(env, new(tree.evalEnv)(env, this.frames.concat(env.frames)), args, [])] // the parameter variables
.concat(this.frames) // the parent namespace/mixin frames
.concat(env.frames)))) { // the current environment frames
return false;
}
return true;
},
matchArgs: function (args, env) {
var argsLength = (args && args.length) || 0, len;
if (! this.variadic) {
if (argsLength < this.required) { return false; }
if (argsLength > this.params.length) { return false; }
} else {
if (argsLength < (this.required - 1)) { return false; }
}
len = Math.min(argsLength, this.arity);
for (var i = 0; i < len; i++) {
if (!this.params[i].name && !this.params[i].variadic) {
if (args[i].value.eval(env).toCSS() != this.params[i].value.eval(env).toCSS()) {
return false;
}
}
}
return true;
}
};
})(require('../tree'));
(function (tree) {
tree.Negative = function (node) {
this.value = node;
};
tree.Negative.prototype = {
type: "Negative",
accept: function (visitor) {
this.value = visitor.visit(this.value);
},
genCSS: function (env, output) {
output.add('-');
this.value.genCSS(env, output);
},
toCSS: tree.toCSS,
eval: function (env) {
if (env.isMathOn()) {
return (new(tree.Operation)('*', [new(tree.Dimension)(-1), this.value])).eval(env);
}
return new(tree.Negative)(this.value.eval(env));
}
};
})(require('../tree'));
(function (tree) {
tree.Operation = function (op, operands, isSpaced) {
this.op = op.trim();
this.operands = operands;
this.isSpaced = isSpaced;
};
tree.Operation.prototype = {
type: "Operation",
accept: function (visitor) {
this.operands = visitor.visit(this.operands);
},
eval: function (env) {
var a = this.operands[0].eval(env),
b = this.operands[1].eval(env);
if (env.isMathOn()) {
if (a instanceof tree.Dimension && b instanceof tree.Color) {
a = a.toColor();
}
if (b instanceof tree.Dimension && a instanceof tree.Color) {
b = b.toColor();
}
if (!a.operate) {
throw { type: "Operation",
message: "Operation on an invalid type" };
}
return a.operate(env, this.op, b);
} else {
return new(tree.Operation)(this.op, [a, b], this.isSpaced);
}
},
genCSS: function (env, output) {
this.operands[0].genCSS(env, output);
if (this.isSpaced) {
output.add(" ");
}
output.add(this.op);
if (this.isSpaced) {
output.add(" ");
}
this.operands[1].genCSS(env, output);
},
toCSS: tree.toCSS
};
tree.operate = function (env, op, a, b) {
switch (op) {
case '+': return a + b;
case '-': return a - b;
case '*': return a * b;
case '/': return a / b;
}
};
})(require('../tree'));
(function (tree) {
tree.Paren = function (node) {
this.value = node;
};
tree.Paren.prototype = {
type: "Paren",
accept: function (visitor) {
this.value = visitor.visit(this.value);
},
genCSS: function (env, output) {
output.add('(');
this.value.genCSS(env, output);
output.add(')');
},
toCSS: tree.toCSS,
eval: function (env) {
return new(tree.Paren)(this.value.eval(env));
}
};
})(require('../tree'));
(function (tree) {
tree.Quoted = function (str, content, escaped, index, currentFileInfo) {
this.escaped = escaped;
this.value = content || '';
this.quote = str.charAt(0);
this.index = index;
this.currentFileInfo = currentFileInfo;
};
tree.Quoted.prototype = {
type: "Quoted",
genCSS: function (env, output) {
if (!this.escaped) {
output.add(this.quote, this.currentFileInfo, this.index);
}
output.add(this.value);
if (!this.escaped) {
output.add(this.quote);
}
},
toCSS: tree.toCSS,
eval: function (env) {
var that = this;
var value = this.value.replace(/`([^`]+)`/g, function (_, exp) {
return new(tree.JavaScript)(exp, that.index, true).eval(env).value;
}).replace(/@\{([\w-]+)\}/g, function (_, name) {
var v = new(tree.Variable)('@' + name, that.index, that.currentFileInfo).eval(env, true);
return (v instanceof tree.Quoted) ? v.value : v.toCSS();
});
return new(tree.Quoted)(this.quote + value + this.quote, value, this.escaped, this.index, this.currentFileInfo);
},
compare: function (x) {
if (!x.toCSS) {
return -1;
}
var left = this.toCSS(),
right = x.toCSS();
if (left === right) {
return 0;
}
return left < right ? -1 : 1;
}
};
})(require('../tree'));
(function (tree) {
tree.Rule = function (name, value, important, merge, index, currentFileInfo, inline) {
this.name = name;
this.value = (value instanceof tree.Value || value instanceof tree.Ruleset) ? value : new(tree.Value)([value]);
this.important = important ? ' ' + important.trim() : '';
this.merge = merge;
this.index = index;
this.currentFileInfo = currentFileInfo;
this.inline = inline || false;
this.variable = name.charAt && (name.charAt(0) === '@');
};
tree.Rule.prototype = {
type: "Rule",
accept: function (visitor) {
this.value = visitor.visit(this.value);
},
genCSS: function (env, output) {
output.add(this.name + (env.compress ? ':' : ': '), this.currentFileInfo, this.index);
try {
this.value.genCSS(env, output);
}
catch(e) {
e.index = this.index;
e.filename = this.currentFileInfo.filename;
throw e;
}
output.add(this.important + ((this.inline || (env.lastRule && env.compress)) ? "" : ";"), this.currentFileInfo, this.index);
},
toCSS: tree.toCSS,
eval: function (env) {
var strictMathBypass = false, name = this.name, evaldValue;
if (typeof name !== "string") {
// expand 'primitive' name directly to get
// things faster (~10% for benchmark.less):
name = (name.length === 1)
&& (name[0] instanceof tree.Keyword)
? name[0].value : evalName(env, name);
}
if (name === "font" && !env.strictMath) {
strictMathBypass = true;
env.strictMath = true;
}
try {
evaldValue = this.value.eval(env);
if (!this.variable && evaldValue.type === "DetachedRuleset") {
throw { message: "Rulesets cannot be evaluated on a property.",
index: this.index, filename: this.currentFileInfo.filename };
}
return new(tree.Rule)(name,
evaldValue,
this.important,
this.merge,
this.index, this.currentFileInfo, this.inline);
}
catch(e) {
if (typeof e.index !== 'number') {
e.index = this.index;
e.filename = this.currentFileInfo.filename;
}
throw e;
}
finally {
if (strictMathBypass) {
env.strictMath = false;
}
}
},
makeImportant: function () {
return new(tree.Rule)(this.name,
this.value,
"!important",
this.merge,
this.index, this.currentFileInfo, this.inline);
}
};
function evalName(env, name) {
var value = "", i, n = name.length,
output = {add: function (s) {value += s;}};
for (i = 0; i < n; i++) {
name[i].eval(env).genCSS(env, output);
}
return value;
}
})(require('../tree'));
(function (tree) {
tree.RulesetCall = function (variable) {
this.variable = variable;
};
tree.RulesetCall.prototype = {
type: "RulesetCall",
accept: function (visitor) {
},
eval: function (env) {
var detachedRuleset = new(tree.Variable)(this.variable).eval(env);
return detachedRuleset.callEval(env);
}
};
})(require('../tree'));
(function (tree) {
tree.Ruleset = function (selectors, rules, strictImports) {
this.selectors = selectors;
this.rules = rules;
this._lookups = {};
this.strictImports = strictImports;
};
tree.Ruleset.prototype = {
type: "Ruleset",
accept: function (visitor) {
if (this.paths) {
visitor.visitArray(this.paths, true);
} else if (this.selectors) {
this.selectors = visitor.visitArray(this.selectors);
}
if (this.rules && this.rules.length) {
this.rules = visitor.visitArray(this.rules);
}
},
eval: function (env) {
var thisSelectors = this.selectors, selectors,
selCnt, selector, i, defaultFunc = tree.defaultFunc, hasOnePassingSelector = false;
if (thisSelectors && (selCnt = thisSelectors.length)) {
selectors = [];
defaultFunc.error({
type: "Syntax",
message: "it is currently only allowed in parametric mixin guards,"
});
for (i = 0; i < selCnt; i++) {
selector = thisSelectors[i].eval(env);
selectors.push(selector);
if (selector.evaldCondition) {
hasOnePassingSelector = true;
}
}
defaultFunc.reset();
} else {
hasOnePassingSelector = true;
}
var rules = this.rules ? this.rules.slice(0) : null,
ruleset = new(tree.Ruleset)(selectors, rules, this.strictImports),
rule, subRule;
ruleset.originalRuleset = this;
ruleset.root = this.root;
ruleset.firstRoot = this.firstRoot;
ruleset.allowImports = this.allowImports;
if(this.debugInfo) {
ruleset.debugInfo = this.debugInfo;
}
if (!hasOnePassingSelector) {
rules.length = 0;
}
// push the current ruleset to the frames stack
var envFrames = env.frames;
envFrames.unshift(ruleset);
// currrent selectors
var envSelectors = env.selectors;
if (!envSelectors) {
env.selectors = envSelectors = [];
}
envSelectors.unshift(this.selectors);
// Evaluate imports
if (ruleset.root || ruleset.allowImports || !ruleset.strictImports) {
ruleset.evalImports(env);
}
// Store the frames around mixin definitions,
// so they can be evaluated like closures when the time comes.
var rsRules = ruleset.rules, rsRuleCnt = rsRules ? rsRules.length : 0;
for (i = 0; i < rsRuleCnt; i++) {
if (rsRules[i] instanceof tree.mixin.Definition || rsRules[i] instanceof tree.DetachedRuleset) {
rsRules[i] = rsRules[i].eval(env);
}
}
var mediaBlockCount = (env.mediaBlocks && env.mediaBlocks.length) || 0;
// Evaluate mixin calls.
for (i = 0; i < rsRuleCnt; i++) {
if (rsRules[i] instanceof tree.mixin.Call) {
/*jshint loopfunc:true */
rules = rsRules[i].eval(env).filter(function(r) {
if ((r instanceof tree.Rule) && r.variable) {
// do not pollute the scope if the variable is
// already there. consider returning false here
// but we need a way to "return" variable from mixins
return !(ruleset.variable(r.name));
}
return true;
});
rsRules.splice.apply(rsRules, [i, 1].concat(rules));
rsRuleCnt += rules.length - 1;
i += rules.length-1;
ruleset.resetCache();
} else if (rsRules[i] instanceof tree.RulesetCall) {
/*jshint loopfunc:true */
rules = rsRules[i].eval(env).rules.filter(function(r) {
if ((r instanceof tree.Rule) && r.variable) {
// do not pollute the scope at all
return false;
}
return true;
});
rsRules.splice.apply(rsRules, [i, 1].concat(rules));
rsRuleCnt += rules.length - 1;
i += rules.length-1;
ruleset.resetCache();
}
}
// Evaluate everything else
for (i = 0; i < rsRules.length; i++) {
rule = rsRules[i];
if (! (rule instanceof tree.mixin.Definition || rule instanceof tree.DetachedRuleset)) {
rsRules[i] = rule = rule.eval ? rule.eval(env) : rule;
}
}
// Evaluate everything else
for (i = 0; i < rsRules.length; i++) {
rule = rsRules[i];
// for rulesets, check if it is a css guard and can be removed
if (rule instanceof tree.Ruleset && rule.selectors && rule.selectors.length === 1) {
// check if it can be folded in (e.g. & where)
if (rule.selectors[0].isJustParentSelector()) {
rsRules.splice(i--, 1);
for(var j = 0; j < rule.rules.length; j++) {
subRule = rule.rules[j];
if (!(subRule instanceof tree.Rule) || !subRule.variable) {
rsRules.splice(++i, 0, subRule);
}
}
}
}
}
// Pop the stack
envFrames.shift();
envSelectors.shift();
if (env.mediaBlocks) {
for (i = mediaBlockCount; i < env.mediaBlocks.length; i++) {
env.mediaBlocks[i].bubbleSelectors(selectors);
}
}
return ruleset;
},
evalImports: function(env) {
var rules = this.rules, i, importRules;
if (!rules) { return; }
for (i = 0; i < rules.length; i++) {
if (rules[i] instanceof tree.Import) {
importRules = rules[i].eval(env);
if (importRules && importRules.length) {
rules.splice.apply(rules, [i, 1].concat(importRules));
i+= importRules.length-1;
} else {
rules.splice(i, 1, importRules);
}
this.resetCache();
}
}
},
makeImportant: function() {
return new tree.Ruleset(this.selectors, this.rules.map(function (r) {
if (r.makeImportant) {
return r.makeImportant();
} else {
return r;
}
}), this.strictImports);
},
matchArgs: function (args) {
return !args || args.length === 0;
},
// lets you call a css selector with a guard
matchCondition: function (args, env) {
var lastSelector = this.selectors[this.selectors.length-1];
if (!lastSelector.evaldCondition) {
return false;
}
if (lastSelector.condition &&
!lastSelector.condition.eval(
new(tree.evalEnv)(env,
env.frames))) {
return false;
}
return true;
},
resetCache: function () {
this._rulesets = null;
this._variables = null;
this._lookups = {};
},
variables: function () {
if (!this._variables) {
this._variables = !this.rules ? {} : this.rules.reduce(function (hash, r) {
if (r instanceof tree.Rule && r.variable === true) {
hash[r.name] = r;
}
return hash;
}, {});
}
return this._variables;
},
variable: function (name) {
return this.variables()[name];
},
rulesets: function () {
if (!this.rules) { return null; }
var _Ruleset = tree.Ruleset, _MixinDefinition = tree.mixin.Definition,
filtRules = [], rules = this.rules, cnt = rules.length,
i, rule;
for (i = 0; i < cnt; i++) {
rule = rules[i];
if ((rule instanceof _Ruleset) || (rule instanceof _MixinDefinition)) {
filtRules.push(rule);
}
}
return filtRules;
},
prependRule: function (rule) {
var rules = this.rules;
if (rules) { rules.unshift(rule); } else { this.rules = [ rule ]; }
},
find: function (selector, self) {
self = self || this;
var rules = [], match,
key = selector.toCSS();
if (key in this._lookups) { return this._lookups[key]; }
this.rulesets().forEach(function (rule) {
if (rule !== self) {
for (var j = 0; j < rule.selectors.length; j++) {
match = selector.match(rule.selectors[j]);
if (match) {
if (selector.elements.length > match) {
Array.prototype.push.apply(rules, rule.find(
new(tree.Selector)(selector.elements.slice(match)), self));
} else {
rules.push(rule);
}
break;
}
}
}
});
this._lookups[key] = rules;
return rules;
},
genCSS: function (env, output) {
var i, j,
ruleNodes = [],
rulesetNodes = [],
rulesetNodeCnt,
debugInfo, // Line number debugging
rule,
path;
env.tabLevel = (env.tabLevel || 0);
if (!this.root) {
env.tabLevel++;
}
var tabRuleStr = env.compress ? '' : Array(env.tabLevel + 1).join(" "),
tabSetStr = env.compress ? '' : Array(env.tabLevel).join(" "),
sep;
for (i = 0; i < this.rules.length; i++) {
rule = this.rules[i];
if (rule.rules || (rule instanceof tree.Media) || rule instanceof tree.Directive || (this.root && rule instanceof tree.Comment)) {
rulesetNodes.push(rule);
} else {
ruleNodes.push(rule);
}
}
// If this is the root node, we don't render
// a selector, or {}.
if (!this.root) {
debugInfo = tree.debugInfo(env, this, tabSetStr);
if (debugInfo) {
output.add(debugInfo);
output.add(tabSetStr);
}
var paths = this.paths, pathCnt = paths.length,
pathSubCnt;
sep = env.compress ? ',' : (',\n' + tabSetStr);
for (i = 0; i < pathCnt; i++) {
path = paths[i];
if (!(pathSubCnt = path.length)) { continue; }
if (i > 0) { output.add(sep); }
env.firstSelector = true;
path[0].genCSS(env, output);
env.firstSelector = false;
for (j = 1; j < pathSubCnt; j++) {
path[j].genCSS(env, output);
}
}
output.add((env.compress ? '{' : ' {\n') + tabRuleStr);
}
// Compile rules and rulesets
for (i = 0; i < ruleNodes.length; i++) {
rule = ruleNodes[i];
// @page{ directive ends up with root elements inside it, a mix of rules and rulesets
// In this instance we do not know whether it is the last property
if (i + 1 === ruleNodes.length && (!this.root || rulesetNodes.length === 0 || this.firstRoot)) {
env.lastRule = true;
}
if (rule.genCSS) {
rule.genCSS(env, output);
} else if (rule.value) {
output.add(rule.value.toString());
}
if (!env.lastRule) {
output.add(env.compress ? '' : ('\n' + tabRuleStr));
} else {
env.lastRule = false;
}
}
if (!this.root) {
output.add((env.compress ? '}' : '\n' + tabSetStr + '}'));
env.tabLevel--;
}
sep = (env.compress ? "" : "\n") + (this.root ? tabRuleStr : tabSetStr);
rulesetNodeCnt = rulesetNodes.length;
if (rulesetNodeCnt) {
if (ruleNodes.length && sep) { output.add(sep); }
rulesetNodes[0].genCSS(env, output);
for (i = 1; i < rulesetNodeCnt; i++) {
if (sep) { output.add(sep); }
rulesetNodes[i].genCSS(env, output);
}
}
if (!output.isEmpty() && !env.compress && this.firstRoot) {
output.add('\n');
}
},
toCSS: tree.toCSS,
markReferenced: function () {
if (!this.selectors) {
return;
}
for (var s = 0; s < this.selectors.length; s++) {
this.selectors[s].markReferenced();
}
},
joinSelectors: function (paths, context, selectors) {
for (var s = 0; s < selectors.length; s++) {
this.joinSelector(paths, context, selectors[s]);
}
},
joinSelector: function (paths, context, selector) {
var i, j, k,
hasParentSelector, newSelectors, el, sel, parentSel,
newSelectorPath, afterParentJoin, newJoinedSelector,
newJoinedSelectorEmpty, lastSelector, currentElements,
selectorsMultiplied;
for (i = 0; i < selector.elements.length; i++) {
el = selector.elements[i];
if (el.value === '&') {
hasParentSelector = true;
}
}
if (!hasParentSelector) {
if (context.length > 0) {
for (i = 0; i < context.length; i++) {
paths.push(context[i].concat(selector));
}
}
else {
paths.push([selector]);
}
return;
}
// The paths are [[Selector]]
// The first list is a list of comma seperated selectors
// The inner list is a list of inheritance seperated selectors
// e.g.
// .a, .b {
// .c {
// }
// }
// == [[.a] [.c]] [[.b] [.c]]
//
// the elements from the current selector so far
currentElements = [];
// the current list of new selectors to add to the path.
// We will build it up. We initiate it with one empty selector as we "multiply" the new selectors
// by the parents
newSelectors = [[]];
for (i = 0; i < selector.elements.length; i++) {
el = selector.elements[i];
// non parent reference elements just get added
if (el.value !== "&") {
currentElements.push(el);
} else {
// the new list of selectors to add
selectorsMultiplied = [];
// merge the current list of non parent selector elements
// on to the current list of selectors to add
if (currentElements.length > 0) {
this.mergeElementsOnToSelectors(currentElements, newSelectors);
}
// loop through our current selectors
for (j = 0; j < newSelectors.length; j++) {
sel = newSelectors[j];
// if we don't have any parent paths, the & might be in a mixin so that it can be used
// whether there are parents or not
if (context.length === 0) {
// the combinator used on el should now be applied to the next element instead so that
// it is not lost
if (sel.length > 0) {
sel[0].elements = sel[0].elements.slice(0);
sel[0].elements.push(new(tree.Element)(el.combinator, '', el.index, el.currentFileInfo));
}
selectorsMultiplied.push(sel);
}
else {
// and the parent selectors
for (k = 0; k < context.length; k++) {
parentSel = context[k];
// We need to put the current selectors
// then join the last selector's elements on to the parents selectors
// our new selector path
newSelectorPath = [];
// selectors from the parent after the join
afterParentJoin = [];
newJoinedSelectorEmpty = true;
//construct the joined selector - if & is the first thing this will be empty,
// if not newJoinedSelector will be the last set of elements in the selector
if (sel.length > 0) {
newSelectorPath = sel.slice(0);
lastSelector = newSelectorPath.pop();
newJoinedSelector = selector.createDerived(lastSelector.elements.slice(0));
newJoinedSelectorEmpty = false;
}
else {
newJoinedSelector = selector.createDerived([]);
}
//put together the parent selectors after the join
if (parentSel.length > 1) {
afterParentJoin = afterParentJoin.concat(parentSel.slice(1));
}
if (parentSel.length > 0) {
newJoinedSelectorEmpty = false;
// join the elements so far with the first part of the parent
newJoinedSelector.elements.push(new(tree.Element)(el.combinator, parentSel[0].elements[0].value, el.index, el.currentFileInfo));
newJoinedSelector.elements = newJoinedSelector.elements.concat(parentSel[0].elements.slice(1));
}
if (!newJoinedSelectorEmpty) {
// now add the joined selector
newSelectorPath.push(newJoinedSelector);
}
// and the rest of the parent
newSelectorPath = newSelectorPath.concat(afterParentJoin);
// add that to our new set of selectors
selectorsMultiplied.push(newSelectorPath);
}
}
}
// our new selectors has been multiplied, so reset the state
newSelectors = selectorsMultiplied;
currentElements = [];
}
}
// if we have any elements left over (e.g. .a& .b == .b)
// add them on to all the current selectors
if (currentElements.length > 0) {
this.mergeElementsOnToSelectors(currentElements, newSelectors);
}
for (i = 0; i < newSelectors.length; i++) {
if (newSelectors[i].length > 0) {
paths.push(newSelectors[i]);
}
}
},
mergeElementsOnToSelectors: function(elements, selectors) {
var i, sel;
if (selectors.length === 0) {
selectors.push([ new(tree.Selector)(elements) ]);
return;
}
for (i = 0; i < selectors.length; i++) {
sel = selectors[i];
// if the previous thing in sel is a parent this needs to join on to it
if (sel.length > 0) {
sel[sel.length - 1] = sel[sel.length - 1].createDerived(sel[sel.length - 1].elements.concat(elements));
}
else {
sel.push(new(tree.Selector)(elements));
}
}
}
};
})(require('../tree'));
(function (tree) {
tree.Selector = function (elements, extendList, condition, index, currentFileInfo, isReferenced) {
this.elements = elements;
this.extendList = extendList;
this.condition = condition;
this.currentFileInfo = currentFileInfo || {};
this.isReferenced = isReferenced;
if (!condition) {
this.evaldCondition = true;
}
};
tree.Selector.prototype = {
type: "Selector",
accept: function (visitor) {
if (this.elements) {
this.elements = visitor.visitArray(this.elements);
}
if (this.extendList) {
this.extendList = visitor.visitArray(this.extendList);
}
if (this.condition) {
this.condition = visitor.visit(this.condition);
}
},
createDerived: function(elements, extendList, evaldCondition) {
evaldCondition = (evaldCondition != null) ? evaldCondition : this.evaldCondition;
var newSelector = new(tree.Selector)(elements, extendList || this.extendList, null, this.index, this.currentFileInfo, this.isReferenced);
newSelector.evaldCondition = evaldCondition;
newSelector.mediaEmpty = this.mediaEmpty;
return newSelector;
},
match: function (other) {
var elements = this.elements,
len = elements.length,
olen, i;
other.CacheElements();
olen = other._elements.length;
if (olen === 0 || len < olen) {
return 0;
} else {
for (i = 0; i < olen; i++) {
if (elements[i].value !== other._elements[i]) {
return 0;
}
}
}
return olen; // return number of matched elements
},
CacheElements: function(){
var css = '', len, v, i;
if( !this._elements ){
len = this.elements.length;
for(i = 0; i < len; i++){
v = this.elements[i];
css += v.combinator.value;
if( !v.value.value ){
css += v.value;
continue;
}
if( typeof v.value.value !== "string" ){
css = '';
break;
}
css += v.value.value;
}
this._elements = css.match(/[,&#\.\w-]([\w-]|(\\.))*/g);
if (this._elements) {
if (this._elements[0] === "&") {
this._elements.shift();
}
} else {
this._elements = [];
}
}
},
isJustParentSelector: function() {
return !this.mediaEmpty &&
this.elements.length === 1 &&
this.elements[0].value === '&' &&
(this.elements[0].combinator.value === ' ' || this.elements[0].combinator.value === '');
},
eval: function (env) {
var evaldCondition = this.condition && this.condition.eval(env),
elements = this.elements, extendList = this.extendList;
elements = elements && elements.map(function (e) { return e.eval(env); });
extendList = extendList && extendList.map(function(extend) { return extend.eval(env); });
return this.createDerived(elements, extendList, evaldCondition);
},
genCSS: function (env, output) {
var i, element;
if ((!env || !env.firstSelector) && this.elements[0].combinator.value === "") {
output.add(' ', this.currentFileInfo, this.index);
}
if (!this._css) {
//TODO caching? speed comparison?
for(i = 0; i < this.elements.length; i++) {
element = this.elements[i];
element.genCSS(env, output);
}
}
},
toCSS: tree.toCSS,
markReferenced: function () {
this.isReferenced = true;
},
getIsReferenced: function() {
return !this.currentFileInfo.reference || this.isReferenced;
},
getIsOutput: function() {
return this.evaldCondition;
}
};
})(require('../tree'));
(function (tree) {
tree.UnicodeDescriptor = function (value) {
this.value = value;
};
tree.UnicodeDescriptor.prototype = {
type: "UnicodeDescriptor",
genCSS: function (env, output) {
output.add(this.value);
},
toCSS: tree.toCSS,
eval: function () { return this; }
};
})(require('../tree'));
(function (tree) {
tree.URL = function (val, currentFileInfo, isEvald) {
this.value = val;
this.currentFileInfo = currentFileInfo;
this.isEvald = isEvald;
};
tree.URL.prototype = {
type: "Url",
accept: function (visitor) {
this.value = visitor.visit(this.value);
},
genCSS: function (env, output) {
output.add("url(");
this.value.genCSS(env, output);
output.add(")");
},
toCSS: tree.toCSS,
eval: function (ctx) {
var val = this.value.eval(ctx),
rootpath;
if (!this.isEvald) {
// Add the base path if the URL is relative
rootpath = this.currentFileInfo && this.currentFileInfo.rootpath;
if (rootpath && typeof val.value === "string" && ctx.isPathRelative(val.value)) {
if (!val.quote) {
rootpath = rootpath.replace(/[\(\)'"\s]/g, function(match) { return "\\"+match; });
}
val.value = rootpath + val.value;
}
val.value = ctx.normalizePath(val.value);
// Add url args if enabled
if (ctx.urlArgs) {
if (!val.value.match(/^\s*data:/)) {
var delimiter = val.value.indexOf('?') === -1 ? '?' : '&';
var urlArgs = delimiter + ctx.urlArgs;
if (val.value.indexOf('#') !== -1) {
val.value = val.value.replace('#', urlArgs + '#');
} else {
val.value += urlArgs;
}
}
}
}
return new(tree.URL)(val, this.currentFileInfo, true);
}
};
})(require('../tree'));
(function (tree) {
tree.Value = function (value) {
this.value = value;
};
tree.Value.prototype = {
type: "Value",
accept: function (visitor) {
if (this.value) {
this.value = visitor.visitArray(this.value);
}
},
eval: function (env) {
if (this.value.length === 1) {
return this.value[0].eval(env);
} else {
return new(tree.Value)(this.value.map(function (v) {
return v.eval(env);
}));
}
},
genCSS: function (env, output) {
var i;
for(i = 0; i < this.value.length; i++) {
this.value[i].genCSS(env, output);
if (i+1 < this.value.length) {
output.add((env && env.compress) ? ',' : ', ');
}
}
},
toCSS: tree.toCSS
};
})(require('../tree'));
(function (tree) {
tree.Variable = function (name, index, currentFileInfo) {
this.name = name;
this.index = index;
this.currentFileInfo = currentFileInfo || {};
};
tree.Variable.prototype = {
type: "Variable",
eval: function (env) {
var variable, name = this.name;
if (name.indexOf('@@') === 0) {
name = '@' + new(tree.Variable)(name.slice(1)).eval(env).value;
}
if (this.evaluating) {
throw { type: 'Name',
message: "Recursive variable definition for " + name,
filename: this.currentFileInfo.file,
index: this.index };
}
this.evaluating = true;
variable = tree.find(env.frames, function (frame) {
var v = frame.variable(name);
if (v) {
return v.value.eval(env);
}
});
if (variable) {
this.evaluating = false;
return variable;
} else {
throw { type: 'Name',
message: "variable " + name + " is undefined",
filename: this.currentFileInfo.filename,
index: this.index };
}
}
};
})(require('../tree'));
(function (tree) {
var parseCopyProperties = [
'paths', // option - unmodified - paths to search for imports on
'optimization', // option - optimization level (for the chunker)
'files', // list of files that have been imported, used for import-once
'contents', // map - filename to contents of all the files
'contentsIgnoredChars', // map - filename to lines at the begining of each file to ignore
'relativeUrls', // option - whether to adjust URL's to be relative
'rootpath', // option - rootpath to append to URL's
'strictImports', // option -
'insecure', // option - whether to allow imports from insecure ssl hosts
'dumpLineNumbers', // option - whether to dump line numbers
'compress', // option - whether to compress
'processImports', // option - whether to process imports. if false then imports will not be imported
'syncImport', // option - whether to import synchronously
'javascriptEnabled',// option - whether JavaScript is enabled. if undefined, defaults to true
'mime', // browser only - mime type for sheet import
'useFileCache', // browser only - whether to use the per file session cache
'currentFileInfo' // information about the current file - for error reporting and importing and making urls relative etc.
];
//currentFileInfo = {
// 'relativeUrls' - option - whether to adjust URL's to be relative
// 'filename' - full resolved filename of current file
// 'rootpath' - path to append to normal URLs for this node
// 'currentDirectory' - path to the current file, absolute
// 'rootFilename' - filename of the base file
// 'entryPath' - absolute path to the entry file
// 'reference' - whether the file should not be output and only output parts that are referenced
tree.parseEnv = function(options) {
copyFromOriginal(options, this, parseCopyProperties);
if (!this.contents) { this.contents = {}; }
if (!this.contentsIgnoredChars) { this.contentsIgnoredChars = {}; }
if (!this.files) { this.files = {}; }
if (!this.currentFileInfo) {
var filename = (options && options.filename) || "input";
var entryPath = filename.replace(/[^\/\\]*$/, "");
if (options) {
options.filename = null;
}
this.currentFileInfo = {
filename: filename,
relativeUrls: this.relativeUrls,
rootpath: (options && options.rootpath) || "",
currentDirectory: entryPath,
entryPath: entryPath,
rootFilename: filename
};
}
};
var evalCopyProperties = [
'silent', // whether to swallow errors and warnings
'verbose', // whether to log more activity
'compress', // whether to compress
'yuicompress', // whether to compress with the outside tool yui compressor
'ieCompat', // whether to enforce IE compatibility (IE8 data-uri)
'strictMath', // whether math has to be within parenthesis
'strictUnits', // whether units need to evaluate correctly
'cleancss', // whether to compress with clean-css
'sourceMap', // whether to output a source map
'importMultiple', // whether we are currently importing multiple copies
'urlArgs' // whether to add args into url tokens
];
tree.evalEnv = function(options, frames) {
copyFromOriginal(options, this, evalCopyProperties);
this.frames = frames || [];
};
tree.evalEnv.prototype.inParenthesis = function () {
if (!this.parensStack) {
this.parensStack = [];
}
this.parensStack.push(true);
};
tree.evalEnv.prototype.outOfParenthesis = function () {
this.parensStack.pop();
};
tree.evalEnv.prototype.isMathOn = function () {
return this.strictMath ? (this.parensStack && this.parensStack.length) : true;
};
tree.evalEnv.prototype.isPathRelative = function (path) {
return !/^(?:[a-z-]+:|\/)/.test(path);
};
tree.evalEnv.prototype.normalizePath = function( path ) {
var
segments = path.split("/").reverse(),
segment;
path = [];
while (segments.length !== 0 ) {
segment = segments.pop();
switch( segment ) {
case ".":
break;
case "..":
if ((path.length === 0) || (path[path.length - 1] === "..")) {
path.push( segment );
} else {
path.pop();
}
break;
default:
path.push( segment );
break;
}
}
return path.join("/");
};
//todo - do the same for the toCSS env
//tree.toCSSEnv = function (options) {
//};
var copyFromOriginal = function(original, destination, propertiesToCopy) {
if (!original) { return; }
for(var i = 0; i < propertiesToCopy.length; i++) {
if (original.hasOwnProperty(propertiesToCopy[i])) {
destination[propertiesToCopy[i]] = original[propertiesToCopy[i]];
}
}
};
})(require('./tree'));
(function (tree) {
var _visitArgs = { visitDeeper: true },
_hasIndexed = false;
function _noop(node) {
return node;
}
function indexNodeTypes(parent, ticker) {
// add .typeIndex to tree node types for lookup table
var key, child;
for (key in parent) {
if (parent.hasOwnProperty(key)) {
child = parent[key];
switch (typeof child) {
case "function":
// ignore bound functions directly on tree which do not have a prototype
// or aren't nodes
if (child.prototype && child.prototype.type) {
child.prototype.typeIndex = ticker++;
}
break;
case "object":
ticker = indexNodeTypes(child, ticker);
break;
}
}
}
return ticker;
}
tree.visitor = function(implementation) {
this._implementation = implementation;
this._visitFnCache = [];
if (!_hasIndexed) {
indexNodeTypes(tree, 1);
_hasIndexed = true;
}
};
tree.visitor.prototype = {
visit: function(node) {
if (!node) {
return node;
}
var nodeTypeIndex = node.typeIndex;
if (!nodeTypeIndex) {
return node;
}
var visitFnCache = this._visitFnCache,
impl = this._implementation,
aryIndx = nodeTypeIndex << 1,
outAryIndex = aryIndx | 1,
func = visitFnCache[aryIndx],
funcOut = visitFnCache[outAryIndex],
visitArgs = _visitArgs,
fnName;
visitArgs.visitDeeper = true;
if (!func) {
fnName = "visit" + node.type;
func = impl[fnName] || _noop;
funcOut = impl[fnName + "Out"] || _noop;
visitFnCache[aryIndx] = func;
visitFnCache[outAryIndex] = funcOut;
}
if (func !== _noop) {
var newNode = func.call(impl, node, visitArgs);
if (impl.isReplacing) {
node = newNode;
}
}
if (visitArgs.visitDeeper && node && node.accept) {
node.accept(this);
}
if (funcOut != _noop) {
funcOut.call(impl, node);
}
return node;
},
visitArray: function(nodes, nonReplacing) {
if (!nodes) {
return nodes;
}
var cnt = nodes.length, i;
// Non-replacing
if (nonReplacing || !this._implementation.isReplacing) {
for (i = 0; i < cnt; i++) {
this.visit(nodes[i]);
}
return nodes;
}
// Replacing
var out = [];
for (i = 0; i < cnt; i++) {
var evald = this.visit(nodes[i]);
if (!evald.splice) {
out.push(evald);
} else if (evald.length) {
this.flatten(evald, out);
}
}
return out;
},
flatten: function(arr, out) {
if (!out) {
out = [];
}
var cnt, i, item,
nestedCnt, j, nestedItem;
for (i = 0, cnt = arr.length; i < cnt; i++) {
item = arr[i];
if (!item.splice) {
out.push(item);
continue;
}
for (j = 0, nestedCnt = item.length; j < nestedCnt; j++) {
nestedItem = item[j];
if (!nestedItem.splice) {
out.push(nestedItem);
} else if (nestedItem.length) {
this.flatten(nestedItem, out);
}
}
}
return out;
}
};
})(require('./tree'));
(function (tree) {
tree.importVisitor = function(importer, finish, evalEnv, onceFileDetectionMap, recursionDetector) {
this._visitor = new tree.visitor(this);
this._importer = importer;
this._finish = finish;
this.env = evalEnv || new tree.evalEnv();
this.importCount = 0;
this.onceFileDetectionMap = onceFileDetectionMap || {};
this.recursionDetector = {};
if (recursionDetector) {
for(var fullFilename in recursionDetector) {
if (recursionDetector.hasOwnProperty(fullFilename)) {
this.recursionDetector[fullFilename] = true;
}
}
}
};
tree.importVisitor.prototype = {
isReplacing: true,
run: function (root) {
var error;
try {
// process the contents
this._visitor.visit(root);
}
catch(e) {
error = e;
}
this.isFinished = true;
if (this.importCount === 0) {
this._finish(error);
}
},
visitImport: function (importNode, visitArgs) {
var importVisitor = this,
evaldImportNode,
inlineCSS = importNode.options.inline;
if (!importNode.css || inlineCSS) {
try {
evaldImportNode = importNode.evalForImport(this.env);
} catch(e){
if (!e.filename) { e.index = importNode.index; e.filename = importNode.currentFileInfo.filename; }
// attempt to eval properly and treat as css
importNode.css = true;
// if that fails, this error will be thrown
importNode.error = e;
}
if (evaldImportNode && (!evaldImportNode.css || inlineCSS)) {
importNode = evaldImportNode;
this.importCount++;
var env = new tree.evalEnv(this.env, this.env.frames.slice(0));
if (importNode.options.multiple) {
env.importMultiple = true;
}
this._importer.push(importNode.getPath(), importNode.currentFileInfo, importNode.options, function (e, root, importedAtRoot, fullPath) {
if (e && !e.filename) { e.index = importNode.index; e.filename = importNode.currentFileInfo.filename; }
if (!env.importMultiple) {
if (importedAtRoot) {
importNode.skip = true;
} else {
importNode.skip = function() {
if (fullPath in importVisitor.onceFileDetectionMap) {
return true;
}
importVisitor.onceFileDetectionMap[fullPath] = true;
return false;
};
}
}
var subFinish = function(e) {
importVisitor.importCount--;
if (importVisitor.importCount === 0 && importVisitor.isFinished) {
importVisitor._finish(e);
}
};
if (root) {
importNode.root = root;
importNode.importedFilename = fullPath;
var duplicateImport = importedAtRoot || fullPath in importVisitor.recursionDetector;
if (!inlineCSS && (env.importMultiple || !duplicateImport)) {
importVisitor.recursionDetector[fullPath] = true;
new(tree.importVisitor)(importVisitor._importer, subFinish, env, importVisitor.onceFileDetectionMap, importVisitor.recursionDetector)
.run(root);
return;
}
}
subFinish();
});
}
}
visitArgs.visitDeeper = false;
return importNode;
},
visitRule: function (ruleNode, visitArgs) {
visitArgs.visitDeeper = false;
return ruleNode;
},
visitDirective: function (directiveNode, visitArgs) {
this.env.frames.unshift(directiveNode);
return directiveNode;
},
visitDirectiveOut: function (directiveNode) {
this.env.frames.shift();
},
visitMixinDefinition: function (mixinDefinitionNode, visitArgs) {
this.env.frames.unshift(mixinDefinitionNode);
return mixinDefinitionNode;
},
visitMixinDefinitionOut: function (mixinDefinitionNode) {
this.env.frames.shift();
},
visitRuleset: function (rulesetNode, visitArgs) {
this.env.frames.unshift(rulesetNode);
return rulesetNode;
},
visitRulesetOut: function (rulesetNode) {
this.env.frames.shift();
},
visitMedia: function (mediaNode, visitArgs) {
this.env.frames.unshift(mediaNode.ruleset);
return mediaNode;
},
visitMediaOut: function (mediaNode) {
this.env.frames.shift();
}
};
})(require('./tree'));
(function (tree) {
tree.joinSelectorVisitor = function() {
this.contexts = [[]];
this._visitor = new tree.visitor(this);
};
tree.joinSelectorVisitor.prototype = {
run: function (root) {
return this._visitor.visit(root);
},
visitRule: function (ruleNode, visitArgs) {
visitArgs.visitDeeper = false;
},
visitMixinDefinition: function (mixinDefinitionNode, visitArgs) {
visitArgs.visitDeeper = false;
},
visitRuleset: function (rulesetNode, visitArgs) {
var context = this.contexts[this.contexts.length - 1],
paths = [], selectors;
this.contexts.push(paths);
if (! rulesetNode.root) {
selectors = rulesetNode.selectors;
if (selectors) {
selectors = selectors.filter(function(selector) { return selector.getIsOutput(); });
rulesetNode.selectors = selectors.length ? selectors : (selectors = null);
if (selectors) { rulesetNode.joinSelectors(paths, context, selectors); }
}
if (!selectors) { rulesetNode.rules = null; }
rulesetNode.paths = paths;
}
},
visitRulesetOut: function (rulesetNode) {
this.contexts.length = this.contexts.length - 1;
},
visitMedia: function (mediaNode, visitArgs) {
var context = this.contexts[this.contexts.length - 1];
mediaNode.rules[0].root = (context.length === 0 || context[0].multiMedia);
}
};
})(require('./tree'));
(function (tree) {
tree.toCSSVisitor = function(env) {
this._visitor = new tree.visitor(this);
this._env = env;
};
tree.toCSSVisitor.prototype = {
isReplacing: true,
run: function (root) {
return this._visitor.visit(root);
},
visitRule: function (ruleNode, visitArgs) {
if (ruleNode.variable) {
return [];
}
return ruleNode;
},
visitMixinDefinition: function (mixinNode, visitArgs) {
// mixin definitions do not get eval'd - this means they keep state
// so we have to clear that state here so it isn't used if toCSS is called twice
mixinNode.frames = [];
return [];
},
visitExtend: function (extendNode, visitArgs) {
return [];
},
visitComment: function (commentNode, visitArgs) {
if (commentNode.isSilent(this._env)) {
return [];
}
return commentNode;
},
visitMedia: function(mediaNode, visitArgs) {
mediaNode.accept(this._visitor);
visitArgs.visitDeeper = false;
if (!mediaNode.rules.length) {
return [];
}
return mediaNode;
},
visitDirective: function(directiveNode, visitArgs) {
if (directiveNode.currentFileInfo.reference && !directiveNode.isReferenced) {
return [];
}
if (directiveNode.name === "@charset") {
// Only output the debug info together with subsequent @charset definitions
// a comment (or @media statement) before the actual @charset directive would
// be considered illegal css as it has to be on the first line
if (this.charset) {
if (directiveNode.debugInfo) {
var comment = new tree.Comment("/* " + directiveNode.toCSS(this._env).replace(/\n/g, "")+" */\n");
comment.debugInfo = directiveNode.debugInfo;
return this._visitor.visit(comment);
}
return [];
}
this.charset = true;
}
return directiveNode;
},
checkPropertiesInRoot: function(rules) {
var ruleNode;
for(var i = 0; i < rules.length; i++) {
ruleNode = rules[i];
if (ruleNode instanceof tree.Rule && !ruleNode.variable) {
throw { message: "properties must be inside selector blocks, they cannot be in the root.",
index: ruleNode.index, filename: ruleNode.currentFileInfo ? ruleNode.currentFileInfo.filename : null};
}
}
},
visitRuleset: function (rulesetNode, visitArgs) {
var rule, rulesets = [];
if (rulesetNode.firstRoot) {
this.checkPropertiesInRoot(rulesetNode.rules);
}
if (! rulesetNode.root) {
if (rulesetNode.paths) {
rulesetNode.paths = rulesetNode.paths
.filter(function(p) {
var i;
if (p[0].elements[0].combinator.value === ' ') {
p[0].elements[0].combinator = new(tree.Combinator)('');
}
for(i = 0; i < p.length; i++) {
if (p[i].getIsReferenced() && p[i].getIsOutput()) {
return true;
}
}
return false;
});
}
// Compile rules and rulesets
var nodeRules = rulesetNode.rules, nodeRuleCnt = nodeRules ? nodeRules.length : 0;
for (var i = 0; i < nodeRuleCnt; ) {
rule = nodeRules[i];
if (rule && rule.rules) {
// visit because we are moving them out from being a child
rulesets.push(this._visitor.visit(rule));
nodeRules.splice(i, 1);
nodeRuleCnt--;
continue;
}
i++;
}
// accept the visitor to remove rules and refactor itself
// then we can decide now whether we want it or not
if (nodeRuleCnt > 0) {
rulesetNode.accept(this._visitor);
} else {
rulesetNode.rules = null;
}
visitArgs.visitDeeper = false;
nodeRules = rulesetNode.rules;
if (nodeRules) {
this._mergeRules(nodeRules);
nodeRules = rulesetNode.rules;
}
if (nodeRules) {
this._removeDuplicateRules(nodeRules);
nodeRules = rulesetNode.rules;
}
// now decide whether we keep the ruleset
if (nodeRules && nodeRules.length > 0 && rulesetNode.paths.length > 0) {
rulesets.splice(0, 0, rulesetNode);
}
} else {
rulesetNode.accept(this._visitor);
visitArgs.visitDeeper = false;
if (rulesetNode.firstRoot || (rulesetNode.rules && rulesetNode.rules.length > 0)) {
rulesets.splice(0, 0, rulesetNode);
}
}
if (rulesets.length === 1) {
return rulesets[0];
}
return rulesets;
},
_removeDuplicateRules: function(rules) {
if (!rules) { return; }
// remove duplicates
var ruleCache = {},
ruleList, rule, i;
for(i = rules.length - 1; i >= 0 ; i--) {
rule = rules[i];
if (rule instanceof tree.Rule) {
if (!ruleCache[rule.name]) {
ruleCache[rule.name] = rule;
} else {
ruleList = ruleCache[rule.name];
if (ruleList instanceof tree.Rule) {
ruleList = ruleCache[rule.name] = [ruleCache[rule.name].toCSS(this._env)];
}
var ruleCSS = rule.toCSS(this._env);
if (ruleList.indexOf(ruleCSS) !== -1) {
rules.splice(i, 1);
} else {
ruleList.push(ruleCSS);
}
}
}
}
},
_mergeRules: function (rules) {
if (!rules) { return; }
var groups = {},
parts,
rule,
key;
for (var i = 0; i < rules.length; i++) {
rule = rules[i];
if ((rule instanceof tree.Rule) && rule.merge) {
key = [rule.name,
rule.important ? "!" : ""].join(",");
if (!groups[key]) {
groups[key] = [];
} else {
rules.splice(i--, 1);
}
groups[key].push(rule);
}
}
Object.keys(groups).map(function (k) {
function toExpression(values) {
return new (tree.Expression)(values.map(function (p) {
return p.value;
}));
}
function toValue(values) {
return new (tree.Value)(values.map(function (p) {
return p;
}));
}
parts = groups[k];
if (parts.length > 1) {
rule = parts[0];
var spacedGroups = [];
var lastSpacedGroup = [];
parts.map(function (p) {
if (p.merge==="+") {
if (lastSpacedGroup.length > 0) {
spacedGroups.push(toExpression(lastSpacedGroup));
}
lastSpacedGroup = [];
}
lastSpacedGroup.push(p);
});
spacedGroups.push(toExpression(lastSpacedGroup));
rule.value = toValue(spacedGroups);
}
});
}
};
})(require('./tree'));
(function (tree) {
/*jshint loopfunc:true */
tree.extendFinderVisitor = function() {
this._visitor = new tree.visitor(this);
this.contexts = [];
this.allExtendsStack = [[]];
};
tree.extendFinderVisitor.prototype = {
run: function (root) {
root = this._visitor.visit(root);
root.allExtends = this.allExtendsStack[0];
return root;
},
visitRule: function (ruleNode, visitArgs) {
visitArgs.visitDeeper = false;
},
visitMixinDefinition: function (mixinDefinitionNode, visitArgs) {
visitArgs.visitDeeper = false;
},
visitRuleset: function (rulesetNode, visitArgs) {
if (rulesetNode.root) {
return;
}
var i, j, extend, allSelectorsExtendList = [], extendList;
// get &:extend(.a); rules which apply to all selectors in this ruleset
var rules = rulesetNode.rules, ruleCnt = rules ? rules.length : 0;
for(i = 0; i < ruleCnt; i++) {
if (rulesetNode.rules[i] instanceof tree.Extend) {
allSelectorsExtendList.push(rules[i]);
rulesetNode.extendOnEveryPath = true;
}
}
// now find every selector and apply the extends that apply to all extends
// and the ones which apply to an individual extend
var paths = rulesetNode.paths;
for(i = 0; i < paths.length; i++) {
var selectorPath = paths[i],
selector = selectorPath[selectorPath.length - 1],
selExtendList = selector.extendList;
extendList = selExtendList ? selExtendList.slice(0).concat(allSelectorsExtendList)
: allSelectorsExtendList;
if (extendList) {
extendList = extendList.map(function(allSelectorsExtend) {
return allSelectorsExtend.clone();
});
}
for(j = 0; j < extendList.length; j++) {
this.foundExtends = true;
extend = extendList[j];
extend.findSelfSelectors(selectorPath);
extend.ruleset = rulesetNode;
if (j === 0) { extend.firstExtendOnThisSelectorPath = true; }
this.allExtendsStack[this.allExtendsStack.length-1].push(extend);
}
}
this.contexts.push(rulesetNode.selectors);
},
visitRulesetOut: function (rulesetNode) {
if (!rulesetNode.root) {
this.contexts.length = this.contexts.length - 1;
}
},
visitMedia: function (mediaNode, visitArgs) {
mediaNode.allExtends = [];
this.allExtendsStack.push(mediaNode.allExtends);
},
visitMediaOut: function (mediaNode) {
this.allExtendsStack.length = this.allExtendsStack.length - 1;
},
visitDirective: function (directiveNode, visitArgs) {
directiveNode.allExtends = [];
this.allExtendsStack.push(directiveNode.allExtends);
},
visitDirectiveOut: function (directiveNode) {
this.allExtendsStack.length = this.allExtendsStack.length - 1;
}
};
tree.processExtendsVisitor = function() {
this._visitor = new tree.visitor(this);
};
tree.processExtendsVisitor.prototype = {
run: function(root) {
var extendFinder = new tree.extendFinderVisitor();
extendFinder.run(root);
if (!extendFinder.foundExtends) { return root; }
root.allExtends = root.allExtends.concat(this.doExtendChaining(root.allExtends, root.allExtends));
this.allExtendsStack = [root.allExtends];
return this._visitor.visit(root);
},
doExtendChaining: function (extendsList, extendsListTarget, iterationCount) {
//
// chaining is different from normal extension.. if we extend an extend then we are not just copying, altering and pasting
// the selector we would do normally, but we are also adding an extend with the same target selector
// this means this new extend can then go and alter other extends
//
// this method deals with all the chaining work - without it, extend is flat and doesn't work on other extend selectors
// this is also the most expensive.. and a match on one selector can cause an extension of a selector we had already processed if
// we look at each selector at a time, as is done in visitRuleset
var extendIndex, targetExtendIndex, matches, extendsToAdd = [], newSelector, extendVisitor = this, selectorPath, extend, targetExtend, newExtend;
iterationCount = iterationCount || 0;
//loop through comparing every extend with every target extend.
// a target extend is the one on the ruleset we are looking at copy/edit/pasting in place
// e.g. .a:extend(.b) {} and .b:extend(.c) {} then the first extend extends the second one
// and the second is the target.
// the seperation into two lists allows us to process a subset of chains with a bigger set, as is the
// case when processing media queries
for(extendIndex = 0; extendIndex < extendsList.length; extendIndex++){
for(targetExtendIndex = 0; targetExtendIndex < extendsListTarget.length; targetExtendIndex++){
extend = extendsList[extendIndex];
targetExtend = extendsListTarget[targetExtendIndex];
// look for circular references
if( extend.parent_ids.indexOf( targetExtend.object_id ) >= 0 ){ continue; }
// find a match in the target extends self selector (the bit before :extend)
selectorPath = [targetExtend.selfSelectors[0]];
matches = extendVisitor.findMatch(extend, selectorPath);
if (matches.length) {
// we found a match, so for each self selector..
extend.selfSelectors.forEach(function(selfSelector) {
// process the extend as usual
newSelector = extendVisitor.extendSelector(matches, selectorPath, selfSelector);
// but now we create a new extend from it
newExtend = new(tree.Extend)(targetExtend.selector, targetExtend.option, 0);
newExtend.selfSelectors = newSelector;
// add the extend onto the list of extends for that selector
newSelector[newSelector.length-1].extendList = [newExtend];
// record that we need to add it.
extendsToAdd.push(newExtend);
newExtend.ruleset = targetExtend.ruleset;
//remember its parents for circular references
newExtend.parent_ids = newExtend.parent_ids.concat(targetExtend.parent_ids, extend.parent_ids);
// only process the selector once.. if we have :extend(.a,.b) then multiple
// extends will look at the same selector path, so when extending
// we know that any others will be duplicates in terms of what is added to the css
if (targetExtend.firstExtendOnThisSelectorPath) {
newExtend.firstExtendOnThisSelectorPath = true;
targetExtend.ruleset.paths.push(newSelector);
}
});
}
}
}
if (extendsToAdd.length) {
// try to detect circular references to stop a stack overflow.
// may no longer be needed.
this.extendChainCount++;
if (iterationCount > 100) {
var selectorOne = "{unable to calculate}";
var selectorTwo = "{unable to calculate}";
try
{
selectorOne = extendsToAdd[0].selfSelectors[0].toCSS();
selectorTwo = extendsToAdd[0].selector.toCSS();
}
catch(e) {}
throw {message: "extend circular reference detected. One of the circular extends is currently:"+selectorOne+":extend(" + selectorTwo+")"};
}
// now process the new extends on the existing rules so that we can handle a extending b extending c ectending d extending e...
return extendsToAdd.concat(extendVisitor.doExtendChaining(extendsToAdd, extendsListTarget, iterationCount+1));
} else {
return extendsToAdd;
}
},
visitRule: function (ruleNode, visitArgs) {
visitArgs.visitDeeper = false;
},
visitMixinDefinition: function (mixinDefinitionNode, visitArgs) {
visitArgs.visitDeeper = false;
},
visitSelector: function (selectorNode, visitArgs) {
visitArgs.visitDeeper = false;
},
visitRuleset: function (rulesetNode, visitArgs) {
if (rulesetNode.root) {
return;
}
var matches, pathIndex, extendIndex, allExtends = this.allExtendsStack[this.allExtendsStack.length-1], selectorsToAdd = [], extendVisitor = this, selectorPath;
// look at each selector path in the ruleset, find any extend matches and then copy, find and replace
for(extendIndex = 0; extendIndex < allExtends.length; extendIndex++) {
for(pathIndex = 0; pathIndex < rulesetNode.paths.length; pathIndex++) {
selectorPath = rulesetNode.paths[pathIndex];
// extending extends happens initially, before the main pass
if (rulesetNode.extendOnEveryPath) { continue; }
var extendList = selectorPath[selectorPath.length-1].extendList;
if (extendList && extendList.length) { continue; }
matches = this.findMatch(allExtends[extendIndex], selectorPath);
if (matches.length) {
allExtends[extendIndex].selfSelectors.forEach(function(selfSelector) {
selectorsToAdd.push(extendVisitor.extendSelector(matches, selectorPath, selfSelector));
});
}
}
}
rulesetNode.paths = rulesetNode.paths.concat(selectorsToAdd);
},
findMatch: function (extend, haystackSelectorPath) {
//
// look through the haystack selector path to try and find the needle - extend.selector
// returns an array of selector matches that can then be replaced
//
var haystackSelectorIndex, hackstackSelector, hackstackElementIndex, haystackElement,
targetCombinator, i,
extendVisitor = this,
needleElements = extend.selector.elements,
potentialMatches = [], potentialMatch, matches = [];
// loop through the haystack elements
for(haystackSelectorIndex = 0; haystackSelectorIndex < haystackSelectorPath.length; haystackSelectorIndex++) {
hackstackSelector = haystackSelectorPath[haystackSelectorIndex];
for(hackstackElementIndex = 0; hackstackElementIndex < hackstackSelector.elements.length; hackstackElementIndex++) {
haystackElement = hackstackSelector.elements[hackstackElementIndex];
// if we allow elements before our match we can add a potential match every time. otherwise only at the first element.
if (extend.allowBefore || (haystackSelectorIndex === 0 && hackstackElementIndex === 0)) {
potentialMatches.push({pathIndex: haystackSelectorIndex, index: hackstackElementIndex, matched: 0, initialCombinator: haystackElement.combinator});
}
for(i = 0; i < potentialMatches.length; i++) {
potentialMatch = potentialMatches[i];
// selectors add " " onto the first element. When we use & it joins the selectors together, but if we don't
// then each selector in haystackSelectorPath has a space before it added in the toCSS phase. so we need to work out
// what the resulting combinator will be
targetCombinator = haystackElement.combinator.value;
if (targetCombinator === '' && hackstackElementIndex === 0) {
targetCombinator = ' ';
}
// if we don't match, null our match to indicate failure
if (!extendVisitor.isElementValuesEqual(needleElements[potentialMatch.matched].value, haystackElement.value) ||
(potentialMatch.matched > 0 && needleElements[potentialMatch.matched].combinator.value !== targetCombinator)) {
potentialMatch = null;
} else {
potentialMatch.matched++;
}
// if we are still valid and have finished, test whether we have elements after and whether these are allowed
if (potentialMatch) {
potentialMatch.finished = potentialMatch.matched === needleElements.length;
if (potentialMatch.finished &&
(!extend.allowAfter && (hackstackElementIndex+1 < hackstackSelector.elements.length || haystackSelectorIndex+1 < haystackSelectorPath.length))) {
potentialMatch = null;
}
}
// if null we remove, if not, we are still valid, so either push as a valid match or continue
if (potentialMatch) {
if (potentialMatch.finished) {
potentialMatch.length = needleElements.length;
potentialMatch.endPathIndex = haystackSelectorIndex;
potentialMatch.endPathElementIndex = hackstackElementIndex + 1; // index after end of match
potentialMatches.length = 0; // we don't allow matches to overlap, so start matching again
matches.push(potentialMatch);
}
} else {
potentialMatches.splice(i, 1);
i--;
}
}
}
}
return matches;
},
isElementValuesEqual: function(elementValue1, elementValue2) {
if (typeof elementValue1 === "string" || typeof elementValue2 === "string") {
return elementValue1 === elementValue2;
}
if (elementValue1 instanceof tree.Attribute) {
if (elementValue1.op !== elementValue2.op || elementValue1.key !== elementValue2.key) {
return false;
}
if (!elementValue1.value || !elementValue2.value) {
if (elementValue1.value || elementValue2.value) {
return false;
}
return true;
}
elementValue1 = elementValue1.value.value || elementValue1.value;
elementValue2 = elementValue2.value.value || elementValue2.value;
return elementValue1 === elementValue2;
}
elementValue1 = elementValue1.value;
elementValue2 = elementValue2.value;
if (elementValue1 instanceof tree.Selector) {
if (!(elementValue2 instanceof tree.Selector) || elementValue1.elements.length !== elementValue2.elements.length) {
return false;
}
for(var i = 0; i <elementValue1.elements.length; i++) {
if (elementValue1.elements[i].combinator.value !== elementValue2.elements[i].combinator.value) {
if (i !== 0 || (elementValue1.elements[i].combinator.value || ' ') !== (elementValue2.elements[i].combinator.value || ' ')) {
return false;
}
}
if (!this.isElementValuesEqual(elementValue1.elements[i].value, elementValue2.elements[i].value)) {
return false;
}
}
return true;
}
return false;
},
extendSelector:function (matches, selectorPath, replacementSelector) {
//for a set of matches, replace each match with the replacement selector
var currentSelectorPathIndex = 0,
currentSelectorPathElementIndex = 0,
path = [],
matchIndex,
selector,
firstElement,
match,
newElements;
for (matchIndex = 0; matchIndex < matches.length; matchIndex++) {
match = matches[matchIndex];
selector = selectorPath[match.pathIndex];
firstElement = new tree.Element(
match.initialCombinator,
replacementSelector.elements[0].value,
replacementSelector.elements[0].index,
replacementSelector.elements[0].currentFileInfo
);
if (match.pathIndex > currentSelectorPathIndex && currentSelectorPathElementIndex > 0) {
path[path.length - 1].elements = path[path.length - 1].elements.concat(selectorPath[currentSelectorPathIndex].elements.slice(currentSelectorPathElementIndex));
currentSelectorPathElementIndex = 0;
currentSelectorPathIndex++;
}
newElements = selector.elements
.slice(currentSelectorPathElementIndex, match.index)
.concat([firstElement])
.concat(replacementSelector.elements.slice(1));
if (currentSelectorPathIndex === match.pathIndex && matchIndex > 0) {
path[path.length - 1].elements =
path[path.length - 1].elements.concat(newElements);
} else {
path = path.concat(selectorPath.slice(currentSelectorPathIndex, match.pathIndex));
path.push(new tree.Selector(
newElements
));
}
currentSelectorPathIndex = match.endPathIndex;
currentSelectorPathElementIndex = match.endPathElementIndex;
if (currentSelectorPathElementIndex >= selectorPath[currentSelectorPathIndex].elements.length) {
currentSelectorPathElementIndex = 0;
currentSelectorPathIndex++;
}
}
if (currentSelectorPathIndex < selectorPath.length && currentSelectorPathElementIndex > 0) {
path[path.length - 1].elements = path[path.length - 1].elements.concat(selectorPath[currentSelectorPathIndex].elements.slice(currentSelectorPathElementIndex));
currentSelectorPathIndex++;
}
path = path.concat(selectorPath.slice(currentSelectorPathIndex, selectorPath.length));
return path;
},
visitRulesetOut: function (rulesetNode) {
},
visitMedia: function (mediaNode, visitArgs) {
var newAllExtends = mediaNode.allExtends.concat(this.allExtendsStack[this.allExtendsStack.length-1]);
newAllExtends = newAllExtends.concat(this.doExtendChaining(newAllExtends, mediaNode.allExtends));
this.allExtendsStack.push(newAllExtends);
},
visitMediaOut: function (mediaNode) {
this.allExtendsStack.length = this.allExtendsStack.length - 1;
},
visitDirective: function (directiveNode, visitArgs) {
var newAllExtends = directiveNode.allExtends.concat(this.allExtendsStack[this.allExtendsStack.length-1]);
newAllExtends = newAllExtends.concat(this.doExtendChaining(newAllExtends, directiveNode.allExtends));
this.allExtendsStack.push(newAllExtends);
},
visitDirectiveOut: function (directiveNode) {
this.allExtendsStack.length = this.allExtendsStack.length - 1;
}
};
})(require('./tree'));
(function (tree) {
tree.sourceMapOutput = function (options) {
this._css = [];
this._rootNode = options.rootNode;
this._writeSourceMap = options.writeSourceMap;
this._contentsMap = options.contentsMap;
this._contentsIgnoredCharsMap = options.contentsIgnoredCharsMap;
this._sourceMapFilename = options.sourceMapFilename;
this._outputFilename = options.outputFilename;
this._sourceMapURL = options.sourceMapURL;
if (options.sourceMapBasepath) {
this._sourceMapBasepath = options.sourceMapBasepath.replace(/\\/g, '/');
}
this._sourceMapRootpath = options.sourceMapRootpath;
this._outputSourceFiles = options.outputSourceFiles;
this._sourceMapGeneratorConstructor = options.sourceMapGenerator || require("source-map").SourceMapGenerator;
if (this._sourceMapRootpath && this._sourceMapRootpath.charAt(this._sourceMapRootpath.length-1) !== '/') {
this._sourceMapRootpath += '/';
}
this._lineNumber = 0;
this._column = 0;
};
tree.sourceMapOutput.prototype.normalizeFilename = function(filename) {
filename = filename.replace(/\\/g, '/');
if (this._sourceMapBasepath && filename.indexOf(this._sourceMapBasepath) === 0) {
filename = filename.substring(this._sourceMapBasepath.length);
if (filename.charAt(0) === '\\' || filename.charAt(0) === '/') {
filename = filename.substring(1);
}
}
return (this._sourceMapRootpath || "") + filename;
};
tree.sourceMapOutput.prototype.add = function(chunk, fileInfo, index, mapLines) {
//ignore adding empty strings
if (!chunk) {
return;
}
var lines,
sourceLines,
columns,
sourceColumns,
i;
if (fileInfo) {
var inputSource = this._contentsMap[fileInfo.filename];
// remove vars/banner added to the top of the file
if (this._contentsIgnoredCharsMap[fileInfo.filename]) {
// adjust the index
index -= this._contentsIgnoredCharsMap[fileInfo.filename];
if (index < 0) { index = 0; }
// adjust the source
inputSource = inputSource.slice(this._contentsIgnoredCharsMap[fileInfo.filename]);
}
inputSource = inputSource.substring(0, index);
sourceLines = inputSource.split("\n");
sourceColumns = sourceLines[sourceLines.length-1];
}
lines = chunk.split("\n");
columns = lines[lines.length-1];
if (fileInfo) {
if (!mapLines) {
this._sourceMapGenerator.addMapping({ generated: { line: this._lineNumber + 1, column: this._column},
original: { line: sourceLines.length, column: sourceColumns.length},
source: this.normalizeFilename(fileInfo.filename)});
} else {
for(i = 0; i < lines.length; i++) {
this._sourceMapGenerator.addMapping({ generated: { line: this._lineNumber + i + 1, column: i === 0 ? this._column : 0},
original: { line: sourceLines.length + i, column: i === 0 ? sourceColumns.length : 0},
source: this.normalizeFilename(fileInfo.filename)});
}
}
}
if (lines.length === 1) {
this._column += columns.length;
} else {
this._lineNumber += lines.length - 1;
this._column = columns.length;
}
this._css.push(chunk);
};
tree.sourceMapOutput.prototype.isEmpty = function() {
return this._css.length === 0;
};
tree.sourceMapOutput.prototype.toCSS = function(env) {
this._sourceMapGenerator = new this._sourceMapGeneratorConstructor({ file: this._outputFilename, sourceRoot: null });
if (this._outputSourceFiles) {
for(var filename in this._contentsMap) {
if (this._contentsMap.hasOwnProperty(filename))
{
var source = this._contentsMap[filename];
if (this._contentsIgnoredCharsMap[filename]) {
source = source.slice(this._contentsIgnoredCharsMap[filename]);
}
this._sourceMapGenerator.setSourceContent(this.normalizeFilename(filename), source);
}
}
}
this._rootNode.genCSS(env, this);
if (this._css.length > 0) {
var sourceMapURL,
sourceMapContent = JSON.stringify(this._sourceMapGenerator.toJSON());
if (this._sourceMapURL) {
sourceMapURL = this._sourceMapURL;
} else if (this._sourceMapFilename) {
sourceMapURL = this.normalizeFilename(this._sourceMapFilename);
}
if (this._writeSourceMap) {
this._writeSourceMap(sourceMapContent);
} else {
sourceMapURL = "data:application/json," + encodeURIComponent(sourceMapContent);
}
if (sourceMapURL) {
this._css.push("/*# sourceMappingURL=" + sourceMapURL + " */");
}
}
return this._css.join('');
};
})(require('./tree'));
//
// browser.js - client-side engine
//
/*global less, window, document, XMLHttpRequest, location */
var isFileProtocol = /^(file|chrome(-extension)?|resource|qrc|app):/.test(location.protocol);
less.env = less.env || (location.hostname == '127.0.0.1' ||
location.hostname == '0.0.0.0' ||
location.hostname == 'localhost' ||
(location.port &&
location.port.length > 0) ||
isFileProtocol ? 'development'
: 'production');
var logLevel = {
debug: 3,
info: 2,
errors: 1,
none: 0
};
// The amount of logging in the javascript console.
// 3 - Debug, information and errors
// 2 - Information and errors
// 1 - Errors
// 0 - None
// Defaults to 2
less.logLevel = typeof(less.logLevel) != 'undefined' ? less.logLevel : (less.env === 'development' ? logLevel.debug : logLevel.errors);
// Load styles asynchronously (default: false)
//
// This is set to `false` by default, so that the body
// doesn't start loading before the stylesheets are parsed.
// Setting this to `true` can result in flickering.
//
less.async = less.async || false;
less.fileAsync = less.fileAsync || false;
// Interval between watch polls
less.poll = less.poll || (isFileProtocol ? 1000 : 1500);
//Setup user functions
if (less.functions) {
for(var func in less.functions) {
if (less.functions.hasOwnProperty(func)) {
less.tree.functions[func] = less.functions[func];
}
}
}
var dumpLineNumbers = /!dumpLineNumbers:(comments|mediaquery|all)/.exec(location.hash);
if (dumpLineNumbers) {
less.dumpLineNumbers = dumpLineNumbers[1];
}
var typePattern = /^text\/(x-)?less$/;
var cache = null;
var fileCache = {};
function log(str, level) {
if (typeof(console) !== 'undefined' && less.logLevel >= level) {
console.log('less: ' + str);
}
}
function extractId(href) {
return href.replace(/^[a-z-]+:\/+?[^\/]+/, '' ) // Remove protocol & domain
.replace(/^\//, '' ) // Remove root /
.replace(/\.[a-zA-Z]+$/, '' ) // Remove simple extension
.replace(/[^\.\w-]+/g, '-') // Replace illegal characters
.replace(/\./g, ':'); // Replace dots with colons(for valid id)
}
function errorConsole(e, rootHref) {
var template = '{line} {content}';
var filename = e.filename || rootHref;
var errors = [];
var content = (e.type || "Syntax") + "Error: " + (e.message || 'There is an error in your .less file') +
" in " + filename + " ";
var errorline = function (e, i, classname) {
if (e.extract[i] !== undefined) {
errors.push(template.replace(/\{line\}/, (parseInt(e.line, 10) || 0) + (i - 1))
.replace(/\{class\}/, classname)
.replace(/\{content\}/, e.extract[i]));
}
};
if (e.extract) {
errorline(e, 0, '');
errorline(e, 1, 'line');
errorline(e, 2, '');
content += 'on line ' + e.line + ', column ' + (e.column + 1) + ':\n' +
errors.join('\n');
} else if (e.stack) {
content += e.stack;
}
log(content, logLevel.errors);
}
function createCSS(styles, sheet, lastModified) {
// Strip the query-string
var href = sheet.href || '';
// If there is no title set, use the filename, minus the extension
var id = 'less:' + (sheet.title || extractId(href));
// If this has already been inserted into the DOM, we may need to replace it
var oldCss = document.getElementById(id);
var keepOldCss = false;
// Create a new stylesheet node for insertion or (if necessary) replacement
var css = document.createElement('style');
css.setAttribute('type', 'text/css');
if (sheet.media) {
css.setAttribute('media', sheet.media);
}
css.id = id;
if (css.styleSheet) { // IE
try {
css.styleSheet.cssText = styles;
} catch (e) {
throw new(Error)("Couldn't reassign styleSheet.cssText.");
}
} else {
css.appendChild(document.createTextNode(styles));
// If new contents match contents of oldCss, don't replace oldCss
keepOldCss = (oldCss !== null && oldCss.childNodes.length > 0 && css.childNodes.length > 0 &&
oldCss.firstChild.nodeValue === css.firstChild.nodeValue);
}
var head = document.getElementsByTagName('head')[0];
// If there is no oldCss, just append; otherwise, only append if we need
// to replace oldCss with an updated stylesheet
if (oldCss === null || keepOldCss === false) {
var nextEl = sheet && sheet.nextSibling || null;
if (nextEl) {
nextEl.parentNode.insertBefore(css, nextEl);
} else {
head.appendChild(css);
}
}
if (oldCss && keepOldCss === false) {
oldCss.parentNode.removeChild(oldCss);
}
// Don't update the local store if the file wasn't modified
if (lastModified && cache) {
log('saving ' + href + ' to cache.', logLevel.info);
try {
cache.setItem(href, styles);
cache.setItem(href + ':timestamp', lastModified);
} catch(e) {
//TODO - could do with adding more robust error handling
log('failed to save', logLevel.errors);
}
}
}
function postProcessCSS(styles) {
if (less.postProcessor && typeof less.postProcessor === 'function') {
styles = less.postProcessor.call(styles, styles) || styles;
}
return styles;
}
function errorHTML(e, rootHref) {
var id = 'less-error-message:' + extractId(rootHref || "");
var template = '<li><label>{line}</label><pre class="{class}">{content}</pre></li>';
var elem = document.createElement('div'), timer, content, errors = [];
var filename = e.filename || rootHref;
var filenameNoPath = filename.match(/([^\/]+(\?.*)?)$/)[1];
elem.id = id;
elem.className = "less-error-message";
content = '<h3>' + (e.type || "Syntax") + "Error: " + (e.message || 'There is an error in your .less file') +
'</h3>' + '<p>in <a href="' + filename + '">' + filenameNoPath + "</a> ";
var errorline = function (e, i, classname) {
if (e.extract[i] !== undefined) {
errors.push(template.replace(/\{line\}/, (parseInt(e.line, 10) || 0) + (i - 1))
.replace(/\{class\}/, classname)
.replace(/\{content\}/, e.extract[i]));
}
};
if (e.extract) {
errorline(e, 0, '');
errorline(e, 1, 'line');
errorline(e, 2, '');
content += 'on line ' + e.line + ', column ' + (e.column + 1) + ':</p>' +
'<ul>' + errors.join('') + '</ul>';
} else if (e.stack) {
content += '<br/>' + e.stack.split('\n').slice(1).join('<br/>');
}
elem.innerHTML = content;
// CSS for error messages
createCSS([
'.less-error-message ul, .less-error-message li {',
'list-style-type: none;',
'margin-right: 15px;',
'padding: 4px 0;',
'margin: 0;',
'}',
'.less-error-message label {',
'font-size: 12px;',
'margin-right: 15px;',
'padding: 4px 0;',
'color: #cc7777;',
'}',
'.less-error-message pre {',
'color: #dd6666;',
'padding: 4px 0;',
'margin: 0;',
'display: inline-block;',
'}',
'.less-error-message pre.line {',
'color: #ff0000;',
'}',
'.less-error-message h3 {',
'font-size: 20px;',
'font-weight: bold;',
'padding: 15px 0 5px 0;',
'margin: 0;',
'}',
'.less-error-message a {',
'color: #10a',
'}',
'.less-error-message .error {',
'color: red;',
'font-weight: bold;',
'padding-bottom: 2px;',
'border-bottom: 1px dashed red;',
'}'
].join('\n'), { title: 'error-message' });
elem.style.cssText = [
"font-family: Arial, sans-serif",
"border: 1px solid #e00",
"background-color: #eee",
"border-radius: 5px",
"-webkit-border-radius: 5px",
"-moz-border-radius: 5px",
"color: #e00",
"padding: 15px",
"margin-bottom: 15px"
].join(';');
if (less.env == 'development') {
timer = setInterval(function () {
if (document.body) {
if (document.getElementById(id)) {
document.body.replaceChild(elem, document.getElementById(id));
} else {
document.body.insertBefore(elem, document.body.firstChild);
}
clearInterval(timer);
}
}, 10);
}
}
function error(e, rootHref) {
if (!less.errorReporting || less.errorReporting === "html") {
errorHTML(e, rootHref);
} else if (less.errorReporting === "console") {
errorConsole(e, rootHref);
} else if (typeof less.errorReporting === 'function') {
less.errorReporting("add", e, rootHref);
}
}
function removeErrorHTML(path) {
var node = document.getElementById('less-error-message:' + extractId(path));
if (node) {
node.parentNode.removeChild(node);
}
}
function removeErrorConsole(path) {
//no action
}
function removeError(path) {
if (!less.errorReporting || less.errorReporting === "html") {
removeErrorHTML(path);
} else if (less.errorReporting === "console") {
removeErrorConsole(path);
} else if (typeof less.errorReporting === 'function') {
less.errorReporting("remove", path);
}
}
function loadStyles(modifyVars) {
var styles = document.getElementsByTagName('style'),
style;
for (var i = 0; i < styles.length; i++) {
style = styles[i];
if (style.type.match(typePattern)) {
var env = new less.tree.parseEnv(less),
lessText = style.innerHTML || '';
env.filename = document.location.href.replace(/#.*$/, '');
if (modifyVars || less.globalVars) {
env.useFileCache = true;
}
/*jshint loopfunc:true */
// use closure to store current value of i
var callback = (function(style) {
return function (e, cssAST) {
if (e) {
return error(e, "inline");
}
var css = cssAST.toCSS(less);
style.type = 'text/css';
if (style.styleSheet) {
style.styleSheet.cssText = css;
} else {
style.innerHTML = css;
}
};
})(style);
new(less.Parser)(env).parse(lessText, callback, {globalVars: less.globalVars, modifyVars: modifyVars});
}
}
}
function extractUrlParts(url, baseUrl) {
// urlParts[1] = protocol&hostname || /
// urlParts[2] = / if path relative to host base
// urlParts[3] = directories
// urlParts[4] = filename
// urlParts[5] = parameters
var urlPartsRegex = /^((?:[a-z-]+:)?\/+?(?:[^\/\?#]*\/)|([\/\\]))?((?:[^\/\\\?#]*[\/\\])*)([^\/\\\?#]*)([#\?].*)?$/i,
urlParts = url.match(urlPartsRegex),
returner = {}, directories = [], i, baseUrlParts;
if (!urlParts) {
throw new Error("Could not parse sheet href - '"+url+"'");
}
// Stylesheets in IE don't always return the full path
if (!urlParts[1] || urlParts[2]) {
baseUrlParts = baseUrl.match(urlPartsRegex);
if (!baseUrlParts) {
throw new Error("Could not parse page url - '"+baseUrl+"'");
}
urlParts[1] = urlParts[1] || baseUrlParts[1] || "";
if (!urlParts[2]) {
urlParts[3] = baseUrlParts[3] + urlParts[3];
}
}
if (urlParts[3]) {
directories = urlParts[3].replace(/\\/g, "/").split("/");
// extract out . before .. so .. doesn't absorb a non-directory
for(i = 0; i < directories.length; i++) {
if (directories[i] === ".") {
directories.splice(i, 1);
i -= 1;
}
}
for(i = 0; i < directories.length; i++) {
if (directories[i] === ".." && i > 0) {
directories.splice(i-1, 2);
i -= 2;
}
}
}
returner.hostPart = urlParts[1];
returner.directories = directories;
returner.path = urlParts[1] + directories.join("/");
returner.fileUrl = returner.path + (urlParts[4] || "");
returner.url = returner.fileUrl + (urlParts[5] || "");
return returner;
}
function pathDiff(url, baseUrl) {
// diff between two paths to create a relative path
var urlParts = extractUrlParts(url),
baseUrlParts = extractUrlParts(baseUrl),
i, max, urlDirectories, baseUrlDirectories, diff = "";
if (urlParts.hostPart !== baseUrlParts.hostPart) {
return "";
}
max = Math.max(baseUrlParts.directories.length, urlParts.directories.length);
for(i = 0; i < max; i++) {
if (baseUrlParts.directories[i] !== urlParts.directories[i]) { break; }
}
baseUrlDirectories = baseUrlParts.directories.slice(i);
urlDirectories = urlParts.directories.slice(i);
for(i = 0; i < baseUrlDirectories.length-1; i++) {
diff += "../";
}
for(i = 0; i < urlDirectories.length-1; i++) {
diff += urlDirectories[i] + "/";
}
return diff;
}
function getXMLHttpRequest() {
if (window.XMLHttpRequest && (window.location.protocol !== "file:" || !window.ActiveXObject)) {
return new XMLHttpRequest();
} else {
try {
/*global ActiveXObject */
return new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
log("browser doesn't support AJAX.", logLevel.errors);
return null;
}
}
}
function doXHR(url, type, callback, errback) {
var xhr = getXMLHttpRequest();
var async = isFileProtocol ? less.fileAsync : less.async;
if (typeof(xhr.overrideMimeType) === 'function') {
xhr.overrideMimeType('text/css');
}
log("XHR: Getting '" + url + "'", logLevel.debug);
xhr.open('GET', url+"?_nocache="+Math.random(), async);
xhr.setRequestHeader('Accept', type || 'text/x-less, text/css; q=0.9, */*; q=0.5');
xhr.send(null);
function handleResponse(xhr, callback, errback) {
if (xhr.status >= 200 && xhr.status < 300) {
callback(xhr.responseText,
xhr.getResponseHeader("Last-Modified"));
} else if (typeof(errback) === 'function') {
errback(xhr.status, url);
}
}
if (isFileProtocol && !less.fileAsync) {
if (xhr.status === 0 || (xhr.status >= 200 && xhr.status < 300)) {
callback(xhr.responseText);
} else {
errback(xhr.status, url);
}
} else if (async) {
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
handleResponse(xhr, callback, errback);
}
};
} else {
handleResponse(xhr, callback, errback);
}
}
function loadFile(originalHref, currentFileInfo, callback, env, modifyVars) {
if (currentFileInfo && currentFileInfo.currentDirectory && !/^([a-z-]+:)?\//.test(originalHref)) {
originalHref = currentFileInfo.currentDirectory + originalHref;
}
// sheet may be set to the stylesheet for the initial load or a collection of properties including
// some env variables for imports
var hrefParts = extractUrlParts(originalHref, window.location.href);
var href = hrefParts.url;
var newFileInfo = {
currentDirectory: hrefParts.path,
filename: href
};
if (currentFileInfo) {
newFileInfo.entryPath = currentFileInfo.entryPath;
newFileInfo.rootpath = currentFileInfo.rootpath;
newFileInfo.rootFilename = currentFileInfo.rootFilename;
newFileInfo.relativeUrls = currentFileInfo.relativeUrls;
} else {
newFileInfo.entryPath = hrefParts.path;
newFileInfo.rootpath = less.rootpath || hrefParts.path;
newFileInfo.rootFilename = href;
newFileInfo.relativeUrls = env.relativeUrls;
}
if (newFileInfo.relativeUrls) {
if (env.rootpath) {
newFileInfo.rootpath = extractUrlParts(env.rootpath + pathDiff(hrefParts.path, newFileInfo.entryPath)).path;
} else {
newFileInfo.rootpath = hrefParts.path;
}
}
if (env.useFileCache && fileCache[href]) {
try {
var lessText = fileCache[href];
callback(null, lessText, href, newFileInfo, { lastModified: new Date() });
} catch (e) {
callback(e, null, href);
}
return;
}
doXHR(href, env.mime, function (data, lastModified) {
// per file cache
fileCache[href] = data;
// Use remote copy (re-parse)
try {
callback(null, data, href, newFileInfo, { lastModified: lastModified });
} catch (e) {
callback(e, null, href);
}
}, function (status, url) {
callback({ type: 'File', message: "'" + url + "' wasn't found (" + status + ")" }, null, href);
});
}
function loadStyleSheet(sheet, callback, reload, remaining, modifyVars) {
var env = new less.tree.parseEnv(less);
env.mime = sheet.type;
if (modifyVars || less.globalVars) {
env.useFileCache = true;
}
loadFile(sheet.href, null, function(e, data, path, newFileInfo, webInfo) {
if (webInfo) {
webInfo.remaining = remaining;
var css = cache && cache.getItem(path),
timestamp = cache && cache.getItem(path + ':timestamp');
if (!reload && timestamp && webInfo.lastModified &&
(new(Date)(webInfo.lastModified).valueOf() ===
new(Date)(timestamp).valueOf())) {
// Use local copy
createCSS(css, sheet);
webInfo.local = true;
callback(null, null, data, sheet, webInfo, path);
return;
}
}
//TODO add tests around how this behaves when reloading
removeError(path);
if (data) {
env.currentFileInfo = newFileInfo;
new(less.Parser)(env).parse(data, function (e, root) {
if (e) { return callback(e, null, null, sheet); }
try {
callback(e, root, data, sheet, webInfo, path);
} catch (e) {
callback(e, null, null, sheet);
}
}, {modifyVars: modifyVars, globalVars: less.globalVars});
} else {
callback(e, null, null, sheet, webInfo, path);
}
}, env, modifyVars);
}
function loadStyleSheets(callback, reload, modifyVars) {
for (var i = 0; i < less.sheets.length; i++) {
loadStyleSheet(less.sheets[i], callback, reload, less.sheets.length - (i + 1), modifyVars);
}
}
function initRunningMode(){
if (less.env === 'development') {
less.optimization = 0;
less.watchTimer = setInterval(function () {
if (less.watchMode) {
loadStyleSheets(function (e, root, _, sheet, env) {
if (e) {
error(e, sheet.href);
} else if (root) {
var styles = root.toCSS(less);
styles = postProcessCSS(styles);
createCSS(styles, sheet, env.lastModified);
}
});
}
}, less.poll);
} else {
less.optimization = 3;
}
}
//
// Watch mode
//
less.watch = function () {
if (!less.watchMode ){
less.env = 'development';
initRunningMode();
}
this.watchMode = true;
return true;
};
less.unwatch = function () {clearInterval(less.watchTimer); this.watchMode = false; return false; };
if (/!watch/.test(location.hash)) {
less.watch();
}
if (less.env != 'development') {
try {
cache = (typeof(window.localStorage) === 'undefined') ? null : window.localStorage;
} catch (_) {}
}
//
// Get all <link> tags with the 'rel' attribute set to "stylesheet/less"
//
var links = document.getElementsByTagName('link');
less.sheets = [];
for (var i = 0; i < links.length; i++) {
if (links[i].rel === 'stylesheet/less' || (links[i].rel.match(/stylesheet/) &&
(links[i].type.match(typePattern)))) {
less.sheets.push(links[i]);
}
}
//
// With this function, it's possible to alter variables and re-render
// CSS without reloading less-files
//
less.modifyVars = function(record) {
less.refresh(false, record);
};
less.refresh = function (reload, modifyVars) {
var startTime, endTime;
startTime = endTime = new Date();
loadStyleSheets(function (e, root, _, sheet, env) {
if (e) {
return error(e, sheet.href);
}
if (env.local) {
log("loading " + sheet.href + " from cache.", logLevel.info);
} else {
log("parsed " + sheet.href + " successfully.", logLevel.debug);
var styles = root.toCSS(less);
styles = postProcessCSS(styles);
createCSS(styles, sheet, env.lastModified);
}
log("css for " + sheet.href + " generated in " + (new Date() - endTime) + 'ms', logLevel.info);
if (env.remaining === 0) {
log("less has finished. css generated in " + (new Date() - startTime) + 'ms', logLevel.info);
}
endTime = new Date();
}, reload, modifyVars);
loadStyles(modifyVars);
};
less.refreshStyles = loadStyles;
less.Parser.fileLoader = loadFile;
less.refresh(less.env === 'development');
// amd.js
//
// Define Less as an AMD module.
if (typeof define === "function" && define.amd) {
define(function () { return less; } );
}
})(window); | lnc2014/sxg | ace-v1.3/build/lib/less.js | JavaScript | apache-2.0 | 280,205 |
/*! @license
* Shaka Player
* Copyright 2016 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
goog.provide('shaka.ui.FastForwardButton');
goog.require('shaka.ui.Controls');
goog.require('shaka.ui.Element');
goog.require('shaka.ui.Enums');
goog.require('shaka.ui.Locales');
goog.require('shaka.ui.Localization');
goog.require('shaka.util.Dom');
/**
* @extends {shaka.ui.Element}
* @final
* @export
*/
shaka.ui.FastForwardButton = class extends shaka.ui.Element {
/**
* @param {!HTMLElement} parent
* @param {!shaka.ui.Controls} controls
*/
constructor(parent, controls) {
super(parent, controls);
/** @private {!HTMLButtonElement} */
this.button_ = shaka.util.Dom.createButton();
this.button_.classList.add('material-icons-round');
this.button_.classList.add('shaka-fast-forward-button');
this.button_.classList.add('shaka-tooltip-status');
this.button_.setAttribute('shaka-status', '1x');
this.button_.textContent =
shaka.ui.Enums.MaterialDesignIcons.FAST_FORWARD;
this.parent.appendChild(this.button_);
this.updateAriaLabel_();
/** @private {!Array.<number>} */
this.fastForwardRates_ = this.controls.getConfig().fastForwardRates;
this.eventManager.listen(
this.localization, shaka.ui.Localization.LOCALE_UPDATED, () => {
this.updateAriaLabel_();
});
this.eventManager.listen(
this.localization, shaka.ui.Localization.LOCALE_CHANGED, () => {
this.updateAriaLabel_();
});
this.eventManager.listen(this.button_, 'click', () => {
this.fastForward_();
});
}
/**
* @private
*/
updateAriaLabel_() {
this.button_.ariaLabel =
this.localization.resolve(shaka.ui.Locales.Ids.FAST_FORWARD);
}
/**
* Cycles trick play rate between the selected fast forward rates.
* @private
*/
fastForward_() {
if (!this.video.duration) {
return;
}
const trickPlayRate = this.player.getPlaybackRate();
const newRateIndex = this.fastForwardRates_.indexOf(trickPlayRate) + 1;
// When the button is clicked, the next rate in this.fastForwardRates_ is
// selected. If no more rates are available, the first one is set.
const newRate = (newRateIndex != this.fastForwardRates_.length) ?
this.fastForwardRates_[newRateIndex] : this.fastForwardRates_[0];
this.player.trickPlay(newRate);
this.button_.setAttribute('shaka-status', newRate + 'x');
}
};
/**
* @implements {shaka.extern.IUIElement.Factory}
* @final
*/
shaka.ui.FastForwardButton.Factory = class {
/** @override */
create(rootElement, controls) {
return new shaka.ui.FastForwardButton(rootElement, controls);
}
};
shaka.ui.Controls.registerElement(
'fast_forward', new shaka.ui.FastForwardButton.Factory());
| tvoli/shaka-player | ui/fast_forward_button.js | JavaScript | apache-2.0 | 2,812 |
'use strict';
var nconf = require('nconf');
var path = require('path');
/**
* Handle the configuration management.
*
* @constructor
*/
function Config() {
nconf.argv().env("_");
var environment = nconf.get("NODE:ENV") || "development";
nconf.file(environment, {file: path.resolve(__dirname, '../config/' + environment + '.json')});
nconf.file('default', {file: path.resolve(__dirname, '../config/default.json')});
}
/**
* Return the value of the provided key from the configuration object.
*
* @param {string} key - Key from the configuration object.
*/
Config.prototype.get = function (key) {
return nconf.get(key);
};
module.exports = new Config();
| mxr576/webpage-content-extractor-api | lib/config.js | JavaScript | apache-2.0 | 676 |
let hookTypes;
const callStyles = {
sync: 'applyPlugins',
syncWaterfall: 'applyPluginsWaterfall',
syncBail: 'applyPluginsBailResult',
sync_map: 'applyPlugins',
asyncWaterfall: 'applyPluginsAsyncWaterfall',
asyncParallel: 'applyPluginsParallel',
asyncSerial: 'applyPluginsAsync',
};
const camelToDash = camel =>
camel.replace(/_/g, '--').replace(/[A-Z]/g, c => `-${c.toLowerCase()}`);
const knownPluginRegistrations = {
Compilation: {
needAdditionalPass: ['sync', []],
succeedModule: ['sync', ['module']],
buildModule: ['sync', ['module']],
seal: ['sync', []],
},
Compiler: {
afterCompile: ['asyncSerial', ['compilation']],
afterEnvironment: ['sync', []],
afterPlugins: ['sync', []],
afterResolvers: ['sync', []],
compilation: ['sync', ['compilation', 'params']],
emit: ['asyncSerial', ['compilation']],
make: ['asyncParallel', ['compilation']],
watchRun: ['asyncSerial', ['watcher']],
run: ['asyncSerial', ['compiler']],
},
NormalModuleFactory: {
createModule: ['syncBail', ['data']],
parser: ['sync_map', ['parser', 'parserOptions']],
resolver: ['syncWaterfall', ['nextResolver']],
},
ContextModuleFactory: {
afterResolve: ['asyncWaterfall', ['data']],
},
};
exports.register = (tapable, name, style, args) => {
if (tapable.hooks) {
if (!hookTypes) {
const Tapable = require('tapable');
hookTypes = {
sync: Tapable.SyncHook,
syncWaterfall: Tapable.SyncWaterfallHook,
syncBail: Tapable.SyncBailHook,
asyncWaterfall: Tapable.AsyncWaterfallHook,
asyncParallel: Tapable.AsyncParallelHook,
asyncSerial: Tapable.AsyncSeriesHook,
asyncSeries: Tapable.AsyncSeriesHook,
};
}
if (!tapable.hooks[name]) {
tapable.hooks[name] = new hookTypes[style](args);
}
} else {
if (!tapable.__hardSource_hooks) {
tapable.__hardSource_hooks = {};
}
if (!tapable.__hardSource_hooks[name]) {
tapable.__hardSource_hooks[name] = {
name,
dashName: camelToDash(name),
style,
args,
async: style.startsWith('async'),
map: style.endsWith('_map'),
};
}
if (!tapable.__hardSource_proxy) {
tapable.__hardSource_proxy = {};
}
if (!tapable.__hardSource_proxy[name]) {
if (tapable.__hardSource_hooks[name].map) {
const _forCache = {};
tapable.__hardSource_proxy[name] = {
_forCache,
for: key => {
let hook = _forCache[key];
if (hook) {
return hook;
}
_forCache[key] = {
tap: (...args) => exports.tapFor(tapable, name, key, ...args),
tapPromise: (...args) =>
exports.tapPromiseFor(tapable, name, key, ...args),
call: (...args) => exports.callFor(tapable, name, key, ...args),
promise: (...args) =>
exports.promiseFor(tapable, name, key, ...args),
};
return _forCache[key];
},
tap: (...args) => exports.tapFor(tapable, name, ...args),
tapPromise: (...args) =>
exports.tapPromiseFor(tapable, name, ...args),
call: (...args) => exports.callFor(tapable, name, ...args),
promise: (...args) => exports.promiseFor(tapable, name, ...args),
};
} else {
tapable.__hardSource_proxy[name] = {
tap: (...args) => exports.tap(tapable, name, ...args),
tapPromise: (...args) => exports.tapPromise(tapable, name, ...args),
call: (...args) => exports.call(tapable, name, args),
promise: (...args) => exports.promise(tapable, name, args),
};
}
}
}
};
exports.tap = (tapable, name, reason, callback) => {
if (tapable.hooks) {
tapable.hooks[name].tap(reason, callback);
} else {
if (!tapable.__hardSource_hooks || !tapable.__hardSource_hooks[name]) {
const registration =
knownPluginRegistrations[tapable.constructor.name][name];
exports.register(tapable, name, registration[0], registration[1]);
}
const dashName = tapable.__hardSource_hooks[name].dashName;
if (tapable.__hardSource_hooks[name].async) {
tapable.plugin(dashName, (...args) => {
const cb = args.pop();
cb(null, callback(...args));
});
} else {
tapable.plugin(dashName, callback);
}
}
};
exports.tapPromise = (tapable, name, reason, callback) => {
if (tapable.hooks) {
tapable.hooks[name].tapPromise(reason, callback);
} else {
if (!tapable.__hardSource_hooks || !tapable.__hardSource_hooks[name]) {
const registration =
knownPluginRegistrations[tapable.constructor.name][name];
exports.register(tapable, name, registration[0], registration[1]);
}
const dashName = tapable.__hardSource_hooks[name].dashName;
tapable.plugin(dashName, (...args) => {
const cb = args.pop();
return callback(...args).then(value => cb(null, value), cb);
});
}
};
exports.tapAsync = (tapable, name, reason, callback) => {
if (tapable.hooks) {
tapable.hooks[name].tapAsync(reason, callback);
} else {
if (!tapable.__hardSource_hooks || !tapable.__hardSource_hooks[name]) {
const registration =
knownPluginRegistrations[tapable.constructor.name][name];
exports.register(tapable, name, registration[0], registration[1]);
}
const dashName = tapable.__hardSource_hooks[name].dashName;
tapable.plugin(dashName, callback);
}
};
exports.call = (tapable, name, args) => {
if (tapable.hooks) {
const hook = tapable.hooks[name];
return hook.call(...args);
} else {
const dashName = tapable.__hardSource_hooks[name].dashName;
const style = tapable.__hardSource_hooks[name].style;
return tapable[callStyles[style]](...[dashName].concat(args));
}
};
exports.promise = (tapable, name, args) => {
if (tapable.hooks) {
const hook = tapable.hooks[name];
return hook.promise(...args);
} else {
const dashName = tapable.__hardSource_hooks[name].dashName;
const style = tapable.__hardSource_hooks[name].style;
return new Promise((resolve, reject) => {
tapable[callStyles[style]](
...[dashName].concat(args, (err, value) => {
if (err) {
reject(err);
} else {
resolve(value);
}
}),
);
});
}
};
exports.tapFor = (tapable, name, key, reason, callback) => {
if (tapable.hooks) {
tapable.hooks[name].for(key).tap(reason, callback);
} else {
exports.tap(tapable, name, reason, callback);
}
};
exports.tapPromiseFor = (tapable, name, key, reason, callback) => {
if (tapable.hooks) {
tapable.hooks[name].for(key).tapPromise(reason, callback);
} else {
exports.tapPromise(tapable, name, reason, callback);
}
};
exports.callFor = (tapable, name, key, args) => {
if (tapable.hooks) {
tapable.hooks[name].for(key).call(...args);
} else {
exports.call(tapable, name, args);
}
};
exports.promiseFor = (tapable, name, key, args) => {
if (tapable.hooks) {
tapable.hooks[name].for(key).promise(...args);
} else {
exports.promise(tapable, name, args);
}
};
exports.hooks = tapable => {
if (tapable.hooks) {
return tapable.hooks;
}
if (!tapable.__hardSource_proxy) {
tapable.__hardSource_proxy = {};
}
const registrations = knownPluginRegistrations[tapable.constructor.name];
if (registrations) {
for (const name in registrations) {
const registration = registrations[name];
exports.register(tapable, name, registration[0], registration[1]);
}
}
return tapable.__hardSource_proxy;
};
| BigBoss424/portfolio | v6/node_modules/hard-source-webpack-plugin/lib/util/plugin-compat.js | JavaScript | apache-2.0 | 7,732 |
/**
* Wraps the
*
* @param text
* {string} haystack to search through
* @param search
* {string} needle to search for
* @param [caseSensitive]
* {boolean} optional boolean to use case-sensitive searching
*/
angular.module('ui.highlight', []).filter('highlight', function(highlight) {
return function(text, search, caseSensitive) {
if (search || angular.isNumber(search)) {
var ltext = text.toString();
var lsearch = search.toString();
if (caseSensitive) {
return ltext.split(lsearch).join('<span class="ui-match">' + lsearch + '</span>');
} else {
return ltext.replace(new RegExp(lsearch, 'gi'), '<span class="ui-match">$&</span>');
}
} else {
return text;
}
};
});
| WestCoastInformatics/OTF-Mapping-Service | webapp/src/main/webapp/js/highlight.js | JavaScript | apache-2.0 | 771 |
module.exports = {
"env": {
"es6": true,
"node": true
},
"globals": {
"expect": true,
"it": true,
"describe": true,
},
"extends": "eslint:recommended",
"parser": "babel-eslint",
"parserOptions": {
"ecmaFeatures": {
"experimentalObjectRestSpread": true,
"jsx": true
},
"sourceType": "module"
},
"plugins": [
"react"
],
"rules": {
"no-unused-vars": 2,
"react/jsx-uses-vars": 2,
"react/jsx-uses-react": 2,
"indent": [
"error",
2
],
"linebreak-style": [
"error",
"unix"
],
"quotes": [
"error",
"single"
],
"semi": [
"error",
"always"
]
}
};
| airingursb/two-life | src/components/react-native-calendars/.eslintrc.js | JavaScript | apache-2.0 | 859 |
(function(window) {
var DEFAULT_ERROR_ID = 'error-default';
/**
* Very simple base class for views.
* Provides functionality for active/inactive.
*
* The first time the view is activated
* the onactive function/event will fire.
*
* The .seen property is added to each object
* with view in its prototype. .seen can be used
* to detect if the view has ever been activated.
*
* @param {String|Object} options options or a selector for element.
*/
function View(options) {
if (typeof(options) === 'undefined') {
options = {};
}
if (typeof(options) === 'string') {
this.selectors = { element: options };
} else {
var key;
if (typeof(options) === 'undefined') {
options = {};
}
for (key in options) {
if (options.hasOwnProperty(key)) {
this[key] = options[key];
}
}
}
this.hideErrors = this.hideErrors.bind(this);
}
const INVALID_CSS = /([^a-zA-Z\-\_0-9])/g;
View.ACTIVE = 'active';
View.prototype = {
seen: false,
activeClass: View.ACTIVE,
errorVisible: false,
get element() {
return this._findElement('element');
},
get status() {
return this._findElement('status');
},
get errors() {
return this._findElement('errors');
},
/**
* Creates a string id for a given model.
*
* view.idForModel('foo-', { _id: 1 }); // => foo-1
* view.idForModel('foo-', '2'); // => foo-2
*
* @param {String} prefix of string.
* @param {Object|String|Numeric} objectOrString representation of model.
*/
idForModel: function(prefix, objectOrString) {
prefix += (typeof(objectOrString) === 'object') ?
objectOrString._id :
objectOrString;
return prefix;
},
calendarId: function(input) {
if (typeof(input) !== 'string') {
input = input.calendarId;
}
input = this.cssClean(input);
return 'calendar-id-' + input;
},
/**
* Delegate pattern event listener.
*
* @param {HTMLElement} element parent element.
* @param {String} type type of dom event.
* @param {String} selector css selector element should match
* _note_ there is no magic here this
* is determined from the root of the document.
* @param {Function|Object} handler event handler.
* first argument is the raw
* event second is the element
* matching the pattern.
*/
delegate: function(element, type, selector, handler) {
if (typeof(handler) === 'object') {
var context = handler;
handler = function() {
context.handleEvent.apply(context, arguments);
};
}
element.addEventListener(type, function(e) {
var target = e.target;
while (target !== element) {
if ('mozMatchesSelector' in target &&
target.mozMatchesSelector(selector)) {
return handler(e, target);
}
target = target.parentNode;
}
});
},
/**
* Clean a string for use with css.
* Converts illegal chars to legal ones.
*/
cssClean: function(string) {
if (typeof(string) !== 'string')
return string;
//TODO: I am worried about the performance
//of using this all over the place =/
//consider sanitizing all keys to ensure
//they don't blow up when used as a selector?
return string.replace(INVALID_CSS, '-');
},
/**
* Finds a caches a element defined
* by selectors
*
* @param {String} selector name as defined in selectors.
* @param {Boolean} all true when to find all elements. (default false).
*/
_findElement: function(name, all, element) {
if (typeof(all) === 'object') {
element = all;
all = false;
}
element = element || document;
var cacheName;
var selector;
if (typeof(all) === 'undefined') {
all = false;
}
if (name in this.selectors) {
cacheName = '_' + name + 'Element';
selector = this.selectors[name];
if (!this[cacheName]) {
if (all) {
this[cacheName] = element.querySelectorAll(selector);
} else {
this[cacheName] = element.querySelector(selector);
}
}
return this[cacheName];
}
return null;
},
/**
* Displays a list of errors
*
* @param {Array} list error list
* (see Event.validaitonErrors) or Error object.
*/
showErrors: function(list) {
var _ = navigator.mozL10n.get;
var errors = '';
// We can pass Error objects or
// Array of {name: foo} objects
if (!Array.isArray(list)) {
list = [list];
}
var i = 0;
var len = list.length;
for (; i < len; i++) {
var name = list[i].l10nID || list[i].name;
errors += _('error-' + name) || _(DEFAULT_ERROR_ID);
}
// populate error and display it.
this.errors.textContent = errors;
this.errorVisible = true;
this.status.classList.add(this.activeClass);
this.status.addEventListener('animationend', this.hideErrors);
},
hideErrors: function() {
this.status.classList.remove(this.activeClass);
this.status.removeEventListener('animationend', this.hideErrors);
this.errorVisible = false;
},
onactive: function() {
if (this.errorVisible) {
this.hideErrors();
}
//seen can be set to anything other
//then false to override this behaviour
if (this.seen === false) {
this.onfirstseen();
}
// intentionally using 'in'
if ('dispatch' in this) {
this.dispatch.apply(this, arguments);
}
this.seen = true;
if (this.element) {
this.element.classList.add(this.activeClass);
}
},
oninactive: function() {
if (this.element) {
this.element.classList.remove(this.activeClass);
}
},
onfirstseen: function() {}
};
Calendar.View = View;
}(this));
| wilebeast/FireFox-OS | B2G/gaia/apps/calendar/js/view.js | JavaScript | apache-2.0 | 6,314 |
// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/**
* Extension ID of Files.app.
* @type {string}
* @const
*/
var FILE_MANAGER_EXTENSIONS_ID = 'hhaomjibdihmijegdhdafkllkbggdgoj';
/**
* Calls a remote test util in Files.app's extension. See: test_util.js.
*
* @param {string} func Function name.
* @param {?string} appId Target window's App ID or null for functions
* not requiring a window.
* @param {Array.<*>} args Array of arguments.
* @param {function(*)} callback Callback handling the function's result.
*/
function callRemoteTestUtil(func, appId, args, callback) {
chrome.runtime.sendMessage(
FILE_MANAGER_EXTENSIONS_ID, {
func: func,
appId: appId,
args: args
},
callback);
}
chrome.test.runTests([
// Waits for the C++ code to send a string identifying a test, then runs that
// test.
function testRunner() {
var command = chrome.extension.inIncognitoContext ? 'which test guest' :
'which test non-guest';
chrome.test.sendMessage(command, function(testCaseName) {
// Run one of the test cases defined in the testcase namespace, in
// test_cases.js. The test case name is passed via StartTest call in
// file_manager_browsertest.cc.
if (testcase[testCaseName])
testcase[testCaseName]();
else
chrome.test.fail('Bogus test name passed to testRunner()');
});
}
]);
| plxaye/chromium | src/chrome/test/data/extensions/api_test/file_manager_browsertest/background.js | JavaScript | apache-2.0 | 1,527 |
import { Type } from 'angular2/src/facade/lang';
import { CanActivate } from './lifecycle_annotations_impl';
import { reflector } from 'angular2/src/core/reflection/reflection';
export function hasLifecycleHook(e, type) {
if (!(type instanceof Type))
return false;
return e.name in type.prototype;
}
export function getCanActivateHook(type) {
var annotations = reflector.annotations(type);
for (let i = 0; i < annotations.length; i += 1) {
let annotation = annotations[i];
if (annotation instanceof CanActivate) {
return annotation.fn;
}
}
return null;
}
//# sourceMappingURL=route_lifecycle_reflector.js.map
| aayushkapoor206/whatshot | node_modules/angular2/es6/prod/src/router/route_lifecycle_reflector.js | JavaScript | apache-2.0 | 677 |
var msg = require('./locale');
var api = require('./apiJavascript.js');
var paramLists = require('./paramLists.js');
module.exports.blocks = [
{func: 'setDroid', parent: api, category: '', params: ['"R2-D2"'], dropdown: { 0: ['"random"', '"R2-D2"', '"C-3PO"'] } },
{func: 'setDroidSpeed', parent: api, category: '', params: ['"fast"'], dropdown: { 0: ['"random"', '"slow"', '"normal"', '"fast"'] } },
{func: 'setBackground', parent: api, category: '', params: ['"Hoth"'], dropdown: { 0: ['"random"', '"Endor"', '"Hoth"', '"Starship"'] } },
{func: 'setMap', parent: api, category: '', params: ['"blank"'], dropdown: { 0: ['"random"', '"blank"', '"circle"', '"horizontal"', '"grid"', '"blobs"'] } },
{func: 'moveRight', parent: api, category: '', },
{func: 'moveLeft', parent: api, category: '', },
{func: 'moveUp', parent: api, category: '', },
{func: 'moveDown', parent: api, category: '', },
{func: 'goRight', parent: api, category: '', },
{func: 'goLeft', parent: api, category: '', },
{func: 'goUp', parent: api, category: '', },
{func: 'goDown', parent: api, category: '', },
{func: 'playSound', parent: api, category: '', params: ['"R2-D2sound1"'], dropdown: { 0: paramLists.playSoundDropdown } },
{func: 'endGame', parent: api, category: '', params: ['"win"'], dropdown: { 0: ['"win"', '"lose"'] } },
{func: 'addPoints', parent: api, category: '', params: ["100"] },
{func: 'removePoints', parent: api, category: '', params: ["100"] },
{func: 'addCharacter', parent: api, category: '', params: ['"PufferPig"'], dropdown: { 0: ['"random"', '"Stormtrooper"', '"RebelPilot"', '"PufferPig"', '"Mynock"', '"MouseDroid"', '"Tauntaun"', '"Probot"'] } },
{func: 'moveFast', parent: api, category: '', params: ['"PufferPig"'], dropdown: { 0: ['"random"', '"Stormtrooper"', '"RebelPilot"', '"PufferPig"', '"Mynock"', '"MouseDroid"', '"Tauntaun"', '"Probot"'] } },
{func: 'moveNormal', parent: api, category: '', params: ['"PufferPig"'], dropdown: { 0: ['"random"', '"Stormtrooper"', '"RebelPilot"', '"PufferPig"', '"Mynock"', '"MouseDroid"', '"Tauntaun"', '"Probot"'] } },
{func: 'moveSlow', parent: api, category: '', params: ['"PufferPig"'], dropdown: { 0: ['"random"', '"Stormtrooper"', '"RebelPilot"', '"PufferPig"', '"Mynock"', '"MouseDroid"', '"Tauntaun"', '"Probot"'] } },
{func: 'whenLeft', block: 'function whenLeft() {}', expansion: 'function whenLeft() {\n __;\n}', category: '' },
{func: 'whenRight', block: 'function whenRight() {}', expansion: 'function whenRight() {\n __;\n}', category: '' },
{func: 'whenUp', block: 'function whenUp() {}', expansion: 'function whenUp() {\n __;\n}', category: '' },
{func: 'whenDown', block: 'function whenDown() {}', expansion: 'function whenDown() {\n __;\n}', category: '' },
{func: 'whenTouchObstacle', block: 'function whenTouchObstacle() {}', expansion: 'function whenTouchObstacle() {\n __;\n}', category: '' },
{func: 'whenGetCharacter', block: 'function whenGetCharacter() {}', expansion: 'function whenGetCharacter() {\n __;\n}', category: '' },
{func: 'whenGetStormtrooper', block: 'function whenGetStormtrooper() {}', expansion: 'function whenGetStormtrooper() {\n __;\n}', category: '' },
{func: 'whenGetRebelPilot', block: 'function whenGetRebelPilot() {}', expansion: 'function whenGetRebelPilot() {\n __;\n}', category: '' },
{func: 'whenGetPufferPig', block: 'function whenGetPufferPig() {}', expansion: 'function whenGetPufferPig() {\n __;\n}', category: '' },
{func: 'whenGetMynock', block: 'function whenGetMynock() {}', expansion: 'function whenGetMynock() {\n __;\n}', category: '' },
{func: 'whenGetMouseDroid', block: 'function whenGetMouseDroid() {}', expansion: 'function whenGetMouseDroid() {\n __;\n}', category: '' },
{func: 'whenGetTauntaun', block: 'function whenGetTauntaun() {}', expansion: 'function whenGetTauntaun() {\n __;\n}', category: '' },
{func: 'whenGetProbot', block: 'function whenGetProbot() {}', expansion: 'function whenGetProbot() {\n __;\n}', category: '' },
{func: 'whenGetAllCharacters', block: 'function whenGetAllCharacters() {}', expansion: 'function whenGetAllCharacters() {\n __;\n}', category: '' },
{func: 'whenGetAllStormtroopers', block: 'function whenGetAllStormtroopers() {}', expansion: 'function whenGetAllStormtroopers() {\n __;\n}', category: '' },
{func: 'whenGetAllRebelPilots', block: 'function whenGetAllRebelPilots() {}', expansion: 'function whenGetAllRebelPilots() {\n __;\n}', category: '' },
{func: 'whenGetAllPufferPigs', block: 'function whenGetAllPufferPigs() {}', expansion: 'function whenGetAllPufferPigs() {\n __;\n}', category: '' },
{func: 'whenGetAllMynocks', block: 'function whenGetAllMynocks() {}', expansion: 'function whenGetAllMynocks() {\n __;\n}', category: '' },
{func: 'whenGetAllMouseDroids', block: 'function whenGetAllMouseDroids() {}', expansion: 'function whenGetAllMouseDroids() {\n __;\n}', category: '' },
{func: 'whenGetAllTauntauns', block: 'function whenGetAllTauntauns() {}', expansion: 'function whenGetAllTauntauns() {\n __;\n}', category: '' },
{func: 'whenGetAllProbots', block: 'function whenGetAllProbots() {}', expansion: 'function whenGetAllProbots() {\n __;\n}', category: '' },
// Functions hidden from autocomplete - not used in hoc2015:
{func: 'whenTouchStormtrooper', block: 'function whenTouchStormtrooper() {}', expansion: 'function whenTouchStormtrooper() {\n __;\n}', category: '', noAutocomplete: true },
{func: 'whenTouchRebelPilot', block: 'function whenTouchRebelPilot() {}', expansion: 'function whenTouchRebelPilot() {\n __;\n}', category: '', noAutocomplete: true },
{func: 'whenTouchPufferPig', block: 'function whenTouchPufferPig() {}', expansion: 'function whenTouchPufferPig() {\n __;\n}', category: '', noAutocomplete: true },
{func: 'whenTouchMynock', block: 'function whenTouchMynock() {}', expansion: 'function whenTouchMynock() {\n __;\n}', category: '', noAutocomplete: true },
{func: 'whenTouchMouseDroid', block: 'function whenTouchMouseDroid() {}', expansion: 'function whenTouchMouseDroid() {\n __;\n}', category: '', noAutocomplete: true },
{func: 'whenTouchTauntaun', block: 'function whenTouchTauntaun() {}', expansion: 'function whenTouchTauntaun() {\n __;\n}', category: '', noAutocomplete: true },
{func: 'whenTouchProbot', block: 'function whenTouchProbot() {}', expansion: 'function whenTouchProbot() {\n __;\n}', category: '', noAutocomplete: true },
{func: 'whenTouchCharacter', block: 'function whenTouchCharacter() {}', expansion: 'function whenTouchCharacter() {\n __;\n}', category: '', noAutocomplete: true },
{func: 'changeScore', parent: api, category: '', params: ["1"], noAutocomplete: true },
{func: 'whenTouchGoal', block: 'function whenTouchGoal() {}', expansion: 'function whenTouchGoal() {\n __;\n}', category: '', noAutocomplete: true },
{func: 'whenTouchAllGoals', block: 'function whenTouchAllGoals() {}', expansion: 'function whenTouchAllGoals() {\n __;\n}', category: '', noAutocomplete: true },
{func: 'whenScore1000', block: 'function whenScore1000() {}', expansion: 'function whenScore1000() {\n __;\n}', category: '', noAutocomplete: true },
{func: 'setToChase', parent: api, category: '', params: ['"PufferPig"'], dropdown: { 0: ['"random"', '"Stormtrooper"', '"RebelPilot"', '"PufferPig"', '"Mynock"', '"MouseDroid"', '"Tauntaun"', '"Probot"'] }, noAutocomplete: true },
{func: 'setToFlee', parent: api, category: '', params: ['"PufferPig"'], dropdown: { 0: ['"random"', '"Stormtrooper"', '"RebelPilot"', '"PufferPig"', '"Mynock"', '"MouseDroid"', '"Tauntaun"', '"Probot"'] }, noAutocomplete: true },
{func: 'setToRoam', parent: api, category: '', params: ['"PufferPig"'], dropdown: { 0: ['"random"', '"Stormtrooper"', '"RebelPilot"', '"PufferPig"', '"Mynock"', '"MouseDroid"', '"Tauntaun"', '"Probot"'] }, noAutocomplete: true },
{func: 'setToStop', parent: api, category: '', params: ['"PufferPig"'], dropdown: { 0: ['"random"', '"Stormtrooper"', '"RebelPilot"', '"PufferPig"', '"Mynock"', '"MouseDroid"', '"Tauntaun"', '"Probot"'] }, noAutocomplete: true },
{func: 'setSprite', parent: api, category: '', params: ['0', '"R2-D2"'], dropdown: { 1: ['"random"', '"R2-D2"', '"C-3PO"'] }, noAutocomplete: true },
{func: 'setSpritePosition', parent: api, category: '', params: ["0", "7"], noAutocomplete: true },
{func: 'setSpriteSpeed', parent: api, category: '', params: ["0", "8"], noAutocomplete: true },
{func: 'setSpriteEmotion', parent: api, category: '', params: ["0", "1"], noAutocomplete: true },
{func: 'setSpriteSize', parent: api, category: '', params: ["0", "1.0"], noAutocomplete: true },
{func: 'throwProjectile', parent: api, category: '', params: ["0", "1", '"blue_fireball"'], noAutocomplete: true },
{func: 'vanish', parent: api, category: '', params: ["0"], noAutocomplete: true },
{func: 'move', parent: api, category: '', params: ["0", "1"], noAutocomplete: true },
{func: 'showDebugInfo', parent: api, category: '', params: ["false"], noAutocomplete: true },
{func: 'onEvent', parent: api, category: '', params: ["'when-left'", "function() {\n \n}"], noAutocomplete: true },
];
module.exports.categories = {
'': {
color: 'red',
blocks: []
},
'Play Lab': {
color: 'red',
blocks: []
},
Commands: {
color: 'red',
blocks: []
},
Events: {
color: 'green',
blocks: []
},
};
module.exports.autocompleteFunctionsWithParens = true;
module.exports.showParamDropdowns = true;
| pickettd/code-dot-org | apps/src/studio/dropletConfig.js | JavaScript | apache-2.0 | 9,539 |
/**
* libjass
*
* https://github.com/Arnavion/libjass
*
* Copyright 2013 Arnav Singh
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
define(["intern!tdd", "require", "tests/support/test-page"], function (tdd, require, TestPage) {
tdd.suite("Outlines", function () {
tdd.test("Basic", function () {
var testPage = new TestPage(this.remote, require.toUrl("tests/support/browser-test-page.html"), "/tests/functional/outlines/outlines.ass", 1280, 720);
return testPage
.prepare()
.then(function (testPage) { return testPage.seekAndCompareScreenshot(0.5, require.toUrl("./outlines-1.png")); })
.then(function (testPage) { return testPage.seekAndCompareScreenshot(1.5, require.toUrl("./outlines-2.png")); })
.then(function (testPage) { return testPage.seekAndCompareScreenshot(2.5, require.toUrl("./outlines-3.png")); })
.then(function (testPage) { return testPage.seekAndCompareScreenshot(3.5, require.toUrl("./outlines-4.png")); })
.then(function (testPage) { return testPage.done(); });
});
});
});
| joshuabrown-ellation/libjass | tests/functional/outlines/outlines.js | JavaScript | apache-2.0 | 1,551 |
/*
* Copyright (c) 2001-2007, TIBCO Software Inc.
* Use, modification, and distribution subject to terms of license.
*/
jsx3.require("jsx3.chart.Axis");jsx3.Class.defineClass("jsx3.chart.CategoryAxis",jsx3.chart.Axis,null,function(c,p){var
ub={d:"h6",a:"aligned",c:"av",f:"gn",b:"between",e:"tickAlignment"};c.TICKS_ALIGNED=ub.a;c.TICKS_BETWEEN=ub.b;c.MAX_TICKS=200;c.BG={aligned:1,between:1};p.init=function(i,r,q){this.jsxsuper(i,r,q);this.tickAlignment=ub.b;this.categoryField=null;this.paddingLow=null;this.paddingHigh=null;this.Ho(ub.c,0);this.Ho(ub.d,0);};p.getTickAlignment=function(){return this.tickAlignment;};p.setTickAlignment=function(l){if(c.BG[l]){this.tickAlignment=l;}else throw new
jsx3.IllegalArgumentException(ub.e,l);};p.getCategoryField=function(){return this.categoryField;};p.setCategoryField=function(m){this.categoryField=m;};p.getPaddingLow=function(){return this.paddingLow!=null?this.paddingLow:0;};p.setPaddingLow=function(h){this.paddingLow=h;};p.getPaddingHigh=function(){return this.paddingHigh!=null?this.paddingHigh:0;};p.setPaddingHigh=function(r){this.paddingHigh=r;};p.fl=function(){this.Ll(ub.f);var
da=this.getChart();if(da==null){this.Ho(ub.c,0);this.Ho(ub.d,0);}else{var
tb=da.pe(this,true);var
ib=da.bh();this.Ho(ub.d,tb.length);this.Ho(ub.c,ib!=null?ib.length:0);}};p.Hf=function(){var
nb=this.pj(ub.f);if(nb!=null)return nb;var
B=this.pj(ub.c);nb=[];if(B<1)return nb;var
ga=this.getPaddingLow();var
Va=this.getPaddingHigh();var
x=this.tickAlignment==ub.b?B+1:B;var
La=x-1;var
fb=La+ga+Va;var
pb=this.length/fb;var
C=ga*pb;for(var
Qa=0;Qa<x&&Qa<c.MAX_TICKS;Qa++)nb.push(Math.round(C+Qa*pb));this.Ho(ub.f,nb);return nb;};p.se=function(){var
B=this.pj(ub.c);if(this.tickAlignment==ub.b){var
Ab=this.Hf();var
Xa=[];for(var
va=0;va<B;va++)Xa[va]=Math.round((Ab[va]+Ab[va+1])/2);return Xa;}else return this.Hf();};p.Xj=function(b){var
Pa=b;var
z=this.getChart();if(this.categoryField&&z!=null){var
ab=z.bh();if(ab!=null){var
ga=ab[b];if(ga!=null)Pa=ga.getAttribute([this.categoryField]);}}return Pa;};p.mo=function(){return false;};p.getRangeForCategory=function(j){var
_=this.Hf();if(this.tickAlignment==ub.b){if(j<0||j>=_.length-1)return null;else return [_[j],_[j+1]];}else{if(j<0||j>=_.length||_.length<2)return null;var
Xa=j==0?_[1]-_[0]:_[j]-_[j-1];return [Math.round(_[j]-Xa/2),Math.round(_[j]+Xa/2)];}};p.getPointForCategory=function(n){var
Aa=this.Hf();if(this.tickAlignment==ub.b){if(n<0||n>=Aa.length-1)return null;else return Math.round((Aa[n]+Aa[n+1])/2);}else return Aa[n];};c.getVersion=function(){return jsx3.chart.si;};});
| burris/dwr | ui/gi/demo/web/gi/JSX/addins/charting/classes/jsx3/chart/CategoryAxis.js | JavaScript | apache-2.0 | 2,582 |
/*
* Kendo UI Web v2014.1.318 (http://kendoui.com)
* Copyright 2014 Telerik AD. All rights reserved.
*
* Kendo UI Web commercial licenses may be obtained at
* http://www.telerik.com/purchase/license-agreement/kendo-ui-web
* If you do not own a commercial license, this file shall be governed by the
* GNU General Public License (GPL) version 3.
* For GPL requirements, please review: http://www.gnu.org/copyleft/gpl.html
*/
(function(f, define){
define([], f);
})(function(){
(function( window, undefined ) {
var kendo = window.kendo || (window.kendo = { cultures: {} });
kendo.cultures["nn"] = {
name: "nn",
numberFormat: {
pattern: ["-n"],
decimals: 2,
",": " ",
".": ",",
groupSize: [3],
percent: {
pattern: ["-n %","n %"],
decimals: 2,
",": " ",
".": ",",
groupSize: [3],
symbol: "%"
},
currency: {
pattern: ["$ -n","$ n"],
decimals: 2,
",": " ",
".": ",",
groupSize: [3],
symbol: "kr"
}
},
calendars: {
standard: {
days: {
names: ["søndag","måndag","tysdag","onsdag","torsdag","fredag","laurdag"],
namesAbbr: ["sø","må","ty","on","to","fr","la"],
namesShort: ["sø","må","ty","on","to","fr","la"]
},
months: {
names: ["januar","februar","mars","april","mai","juni","juli","august","september","oktober","november","desember",""],
namesAbbr: ["jan","feb","mar","apr","mai","jun","jul","aug","sep","okt","nov","des",""]
},
AM: [""],
PM: [""],
patterns: {
d: "dd.MM.yyyy",
D: "d. MMMM yyyy",
F: "d. MMMM yyyy HH:mm:ss",
g: "dd.MM.yyyy HH:mm",
G: "dd.MM.yyyy HH:mm:ss",
m: "d. MMMM",
M: "d. MMMM",
s: "yyyy'-'MM'-'dd'T'HH':'mm':'ss",
t: "HH:mm",
T: "HH:mm:ss",
u: "yyyy'-'MM'-'dd HH':'mm':'ss'Z'",
y: "MMMM yyyy",
Y: "MMMM yyyy"
},
"/": ".",
":": ":",
firstDay: 1
}
}
}
})(this);
return window.kendo;
}, typeof define == 'function' && define.amd ? define : function(_, f){ f(); }); | facundolucas/eCuentas | src/main/webapp/resources/kendoui/src/js/cultures/kendo.culture.nn.js | JavaScript | apache-2.0 | 2,710 |
// Copyright 2017, Dell EMC, Inc.
/* jshint node:true */
'use strict';
describe(require('path').basename(__filename), function () {
var base = require('./base-task-data-spec');
base.before(function (context) {
context.taskdefinition = helper.require(
'/lib/task-data/base-tasks/dell-wsman-reset-components.js'
);
});
describe('task-data', function () {
base.examples();
});
});
| AlaricChan/on-tasks | spec/lib/task-data/base-tasks/dell-wsman-reset-components-spec.js | JavaScript | apache-2.0 | 439 |
/*
* Kendo UI Web v2014.1.318 (http://kendoui.com)
* Copyright 2014 Telerik AD. All rights reserved.
*
* Kendo UI Web commercial licenses may be obtained at
* http://www.telerik.com/purchase/license-agreement/kendo-ui-web
* If you do not own a commercial license, this file shall be governed by the
* GNU General Public License (GPL) version 3.
* For GPL requirements, please review: http://www.gnu.org/copyleft/gpl.html
*/
(function(f, define){
define([], f);
})(function(){
(function( window, undefined ) {
var kendo = window.kendo || (window.kendo = { cultures: {} });
kendo.cultures["he"] = {
name: "he",
numberFormat: {
pattern: ["-n"],
decimals: 2,
",": ",",
".": ".",
groupSize: [3],
percent: {
pattern: ["-n%","n%"],
decimals: 2,
",": ",",
".": ".",
groupSize: [3],
symbol: "%"
},
currency: {
pattern: ["$-n","$ n"],
decimals: 2,
",": ",",
".": ".",
groupSize: [3],
symbol: "₪"
}
},
calendars: {
standard: {
days: {
names: ["יום ראשון","יום שני","יום שלישי","יום רביעי","יום חמישי","יום שישי","שבת"],
namesAbbr: ["יום א","יום ב","יום ג","יום ד","יום ה","יום ו","שבת"],
namesShort: ["א","ב","ג","ד","ה","ו","ש"]
},
months: {
names: ["ינואר","פברואר","מרץ","אפריל","מאי","יוני","יולי","אוגוסט","ספטמבר","אוקטובר","נובמבר","דצמבר",""],
namesAbbr: ["ינו","פבר","מרץ","אפר","מאי","יונ","יול","אוג","ספט","אוק","נוב","דצמ",""]
},
AM: ["AM","am","AM"],
PM: ["PM","pm","PM"],
patterns: {
d: "dd/MM/yyyy",
D: "dddd dd MMMM yyyy",
F: "dddd dd MMMM yyyy HH:mm:ss",
g: "dd/MM/yyyy HH:mm",
G: "dd/MM/yyyy HH:mm:ss",
m: "dd MMMM",
M: "dd MMMM",
s: "yyyy'-'MM'-'dd'T'HH':'mm':'ss",
t: "HH:mm",
T: "HH:mm:ss",
u: "yyyy'-'MM'-'dd HH':'mm':'ss'Z'",
y: "MMMM yyyy",
Y: "MMMM yyyy"
},
"/": "/",
":": ":",
firstDay: 0
}
}
}
})(this);
return window.kendo;
}, typeof define == 'function' && define.amd ? define : function(_, f){ f(); }); | facundolucas/eCuentas | src/main/webapp/resources/kendoui/src/js/cultures/kendo.culture.he.js | JavaScript | apache-2.0 | 2,934 |
var express = require( 'express' ),
router = require( './router' );
var app = express();
app.set('port', (process.env.PORT || 3000));
router.define( app );
// Set up port
// ========================================================
app.listen(app.get('port'), function() {
console.log("Node app is running at localhost:" + app.get('port'));
});
| OnWhoseBehalf/on-behalf-api | src/server.js | JavaScript | apache-2.0 | 353 |
import backgroundImages from '@const/background-images';
import * as actions from './actions.js';
import Background from './class.js';
// const getObj = (indexString) => {
/*
const [type, index] = indexString.split('-')
if (typeof index === 'undefined') return {}
return store.getState().bgimgState.list[type][index]
*/
// }
const getListInitial = (type) => {
let list = [];
if (type === 'default') {
list = backgroundImages.map(
(filename, index) => new Background(filename, type + '-' + index)
);
}
/*
const dir = type == 'custom' ? thePath.bgimgs_custom : thePath.bgimgs
const parseData = (name) => {
return {
name: name
}
}
if (self.nw) {
const fs = require('fs')
const path = require('path')
const getList = (dir) => {
return fs.readdirSync(dir)
.filter(function (file) {
return !fs.lstatSync(path.join(dir, file)).isDirectory()
})
.map(function (filename) {
return {
name: filename,
time: fs.statSync(path.join(dir, filename)).mtime.getTime()
};
})
.sort(function (a, b) { return b.time - a.time; })
.map(function (o) { return o.name; })
}
getList(dir)
.forEach(function (name) {
list.push(parseData(
name,
type === 'default'
))
})
} else {
}
*/
return list;
};
export const initList = (currentIndex = 'default-0') => {
const listDefault = getListInitial('default');
const listCustom = getListInitial('custom');
const [type, index] = currentIndex.split('-');
const current = eval(
'list' + type.substr(0, 1).toUpperCase() + type.substr(1)
)[index];
// const currentPath = current ? {
// original: current.getPath(),
// blured: current.getPath('blured')
// } : {}
return (dispatch) => {
dispatch(
actions.init({
list: {
default: listDefault,
custom: listCustom,
},
current, //,
// currentIndex,
// currentPath
})
);
};
};
export const add = (/*filename*/) => {};
export const remove = (/*indexCustom*/) => {};
export const change = (obj) => {
return (dispatch) => {
dispatch(actions.change(obj));
};
};
export const mainImgLoaded = () => (dispatch) => dispatch(actions.mainLoaded());
| Diablohu/WhoCallsTheFleet-React | src/api/bgimg/api.js | JavaScript | apache-2.0 | 2,700 |
cordova.define('cordova/plugin_list', function(require, exports, module) {
module.exports = [
{
"file": "plugins/cordova-plugin-whitelist/whitelist.js",
"id": "cordova-plugin-whitelist.whitelist",
"pluginId": "cordova-plugin-whitelist",
"runs": true
},
{
"file": "plugins/cordova-plugin-file/www/DirectoryEntry.js",
"id": "cordova-plugin-file.DirectoryEntry",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.DirectoryEntry"
]
},
{
"file": "plugins/cordova-plugin-file/www/DirectoryReader.js",
"id": "cordova-plugin-file.DirectoryReader",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.DirectoryReader"
]
},
{
"file": "plugins/cordova-plugin-file/www/Entry.js",
"id": "cordova-plugin-file.Entry",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.Entry"
]
},
{
"file": "plugins/cordova-plugin-file/www/File.js",
"id": "cordova-plugin-file.File",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.File"
]
},
{
"file": "plugins/cordova-plugin-file/www/FileEntry.js",
"id": "cordova-plugin-file.FileEntry",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.FileEntry"
]
},
{
"file": "plugins/cordova-plugin-file/www/FileError.js",
"id": "cordova-plugin-file.FileError",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.FileError"
]
},
{
"file": "plugins/cordova-plugin-file/www/FileReader.js",
"id": "cordova-plugin-file.FileReader",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.FileReader"
]
},
{
"file": "plugins/cordova-plugin-file/www/FileSystem.js",
"id": "cordova-plugin-file.FileSystem",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.FileSystem"
]
},
{
"file": "plugins/cordova-plugin-file/www/FileUploadOptions.js",
"id": "cordova-plugin-file.FileUploadOptions",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.FileUploadOptions"
]
},
{
"file": "plugins/cordova-plugin-file/www/FileUploadResult.js",
"id": "cordova-plugin-file.FileUploadResult",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.FileUploadResult"
]
},
{
"file": "plugins/cordova-plugin-file/www/FileWriter.js",
"id": "cordova-plugin-file.FileWriter",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.FileWriter"
]
},
{
"file": "plugins/cordova-plugin-file/www/Flags.js",
"id": "cordova-plugin-file.Flags",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.Flags"
]
},
{
"file": "plugins/cordova-plugin-file/www/LocalFileSystem.js",
"id": "cordova-plugin-file.LocalFileSystem",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.LocalFileSystem"
],
"merges": [
"window"
]
},
{
"file": "plugins/cordova-plugin-file/www/Metadata.js",
"id": "cordova-plugin-file.Metadata",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.Metadata"
]
},
{
"file": "plugins/cordova-plugin-file/www/ProgressEvent.js",
"id": "cordova-plugin-file.ProgressEvent",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.ProgressEvent"
]
},
{
"file": "plugins/cordova-plugin-file/www/fileSystems.js",
"id": "cordova-plugin-file.fileSystems",
"pluginId": "cordova-plugin-file"
},
{
"file": "plugins/cordova-plugin-file/www/requestFileSystem.js",
"id": "cordova-plugin-file.requestFileSystem",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.requestFileSystem"
]
},
{
"file": "plugins/cordova-plugin-file/www/resolveLocalFileSystemURI.js",
"id": "cordova-plugin-file.resolveLocalFileSystemURI",
"pluginId": "cordova-plugin-file",
"merges": [
"window"
]
},
{
"file": "plugins/cordova-plugin-file/www/android/FileSystem.js",
"id": "cordova-plugin-file.androidFileSystem",
"pluginId": "cordova-plugin-file",
"merges": [
"FileSystem"
]
},
{
"file": "plugins/cordova-plugin-file/www/fileSystems-roots.js",
"id": "cordova-plugin-file.fileSystems-roots",
"pluginId": "cordova-plugin-file",
"runs": true
},
{
"file": "plugins/cordova-plugin-file/www/fileSystemPaths.js",
"id": "cordova-plugin-file.fileSystemPaths",
"pluginId": "cordova-plugin-file",
"merges": [
"cordova"
],
"runs": true
},
{
"file": "plugins/cordova-plugin-file-transfer/www/FileTransferError.js",
"id": "cordova-plugin-file-transfer.FileTransferError",
"pluginId": "cordova-plugin-file-transfer",
"clobbers": [
"window.FileTransferError"
]
},
{
"file": "plugins/cordova-plugin-file-transfer/www/FileTransfer.js",
"id": "cordova-plugin-file-transfer.FileTransfer",
"pluginId": "cordova-plugin-file-transfer",
"clobbers": [
"window.FileTransfer"
]
},
{
"file": "plugins/cordova-plugin-device/www/device.js",
"id": "cordova-plugin-device.device",
"pluginId": "cordova-plugin-device",
"clobbers": [
"device"
]
},
{
"file": "plugins/de.appplant.cordova.plugin.email-composer/www/email_composer.js",
"id": "de.appplant.cordova.plugin.email-composer.EmailComposer",
"pluginId": "de.appplant.cordova.plugin.email-composer",
"clobbers": [
"cordova.plugins.email",
"plugin.email"
]
}
];
module.exports.metadata =
// TOP OF METADATA
{}
// BOTTOM OF METADATA
}); | sergiolucas/Projects | Guellcom/calculadora/platforms/android/platform_www/cordova_plugins.js | JavaScript | apache-2.0 | 6,421 |
function CredentialTypesStrings (BaseString) {
BaseString.call(this, 'credential_types');
let t = this.t;
let ns = this.credential_types;
ns.deleteCredentialType = {
CREDENTIAL_TYPE_IN_USE: t.s('This credential type is currently being used by one or more credentials. Credentials that use this credential type must be deleted before the credential type can be deleted.')
};
}
CredentialTypesStrings.$inject = ['BaseStringService'];
export default CredentialTypesStrings;
| GoogleCloudPlatform/sap-deployment-automation | third_party/github.com/ansible/awx/awx/ui/client/src/credential-types/credential-types.strings.js | JavaScript | apache-2.0 | 504 |
const ng = require('angular');
ng.module('porybox.static', ['ngRoute']).config(['$routeProvider', $routeProvider => {
[
'about',
'donate',
'extracting-pokemon-files',
'faq',
'how-to-pk6-1-bvs',
'how-to-pk6-2-homebrew',
'how-to-pk6-3-4-save-files',
'how-to-pk6-6-decrypted-powersaves',
'how-to-pk7-1-bvs',
'how-to-pk7-2-homebrew',
'how-to-pk7-3-digital-save-files',
'how-to-pk7-4-tea',
'markdown',
'privacy-policy',
'tos'
].forEach(pageName => {
$routeProvider.when(`/${pageName}`, {templateUrl: `/static/${pageName}.html`});
});
$routeProvider.when('/extracting-pk6-files', {redirectTo: '/extracting-pokemon-files'});
}]);
| porybox/porybox | client/static/static.module.js | JavaScript | apache-2.0 | 696 |
/*
AngularJS v1.2.10
(c) 2010-2014 Google, Inc. http://angularjs.org
License: MIT
*/
(function(Z,Q,r){'use strict';function F(b){return function(){var a=arguments[0],c,a="["+(b?b+":":"")+a+"] http://errors.angularjs.org/1.2.10/"+(b?b+"/":"")+a;for(c=1;c<arguments.length;c++)a=a+(1==c?"?":"&")+"p"+(c-1)+"="+encodeURIComponent("function"==typeof arguments[c]?arguments[c].toString().replace(/ \{[\s\S]*$/,""):"undefined"==typeof arguments[c]?"undefined":"string"!=typeof arguments[c]?JSON.stringify(arguments[c]):arguments[c]);return Error(a)}}function rb(b){if(null==b||Aa(b))return!1;
var a=b.length;return 1===b.nodeType&&a?!0:D(b)||K(b)||0===a||"number"===typeof a&&0<a&&a-1 in b}function q(b,a,c){var d;if(b)if(L(b))for(d in b)"prototype"==d||("length"==d||"name"==d||b.hasOwnProperty&&!b.hasOwnProperty(d))||a.call(c,b[d],d);else if(b.forEach&&b.forEach!==q)b.forEach(a,c);else if(rb(b))for(d=0;d<b.length;d++)a.call(c,b[d],d);else for(d in b)b.hasOwnProperty(d)&&a.call(c,b[d],d);return b}function Pb(b){var a=[],c;for(c in b)b.hasOwnProperty(c)&&a.push(c);return a.sort()}function Pc(b,
a,c){for(var d=Pb(b),e=0;e<d.length;e++)a.call(c,b[d[e]],d[e]);return d}function Qb(b){return function(a,c){b(c,a)}}function $a(){for(var b=ka.length,a;b;){b--;a=ka[b].charCodeAt(0);if(57==a)return ka[b]="A",ka.join("");if(90==a)ka[b]="0";else return ka[b]=String.fromCharCode(a+1),ka.join("")}ka.unshift("0");return ka.join("")}function Rb(b,a){a?b.$$hashKey=a:delete b.$$hashKey}function t(b){var a=b.$$hashKey;q(arguments,function(a){a!==b&&q(a,function(a,c){b[c]=a})});Rb(b,a);return b}function S(b){return parseInt(b,
10)}function Sb(b,a){return t(new (t(function(){},{prototype:b})),a)}function w(){}function Ba(b){return b}function $(b){return function(){return b}}function z(b){return"undefined"===typeof b}function B(b){return"undefined"!==typeof b}function X(b){return null!=b&&"object"===typeof b}function D(b){return"string"===typeof b}function sb(b){return"number"===typeof b}function La(b){return"[object Date]"===Ma.call(b)}function K(b){return"[object Array]"===Ma.call(b)}function L(b){return"function"===typeof b}
function ab(b){return"[object RegExp]"===Ma.call(b)}function Aa(b){return b&&b.document&&b.location&&b.alert&&b.setInterval}function Qc(b){return!(!b||!(b.nodeName||b.on&&b.find))}function Rc(b,a,c){var d=[];q(b,function(b,g,f){d.push(a.call(c,b,g,f))});return d}function bb(b,a){if(b.indexOf)return b.indexOf(a);for(var c=0;c<b.length;c++)if(a===b[c])return c;return-1}function Na(b,a){var c=bb(b,a);0<=c&&b.splice(c,1);return a}function aa(b,a){if(Aa(b)||b&&b.$evalAsync&&b.$watch)throw Oa("cpws");if(a){if(b===
a)throw Oa("cpi");if(K(b))for(var c=a.length=0;c<b.length;c++)a.push(aa(b[c]));else{c=a.$$hashKey;q(a,function(b,c){delete a[c]});for(var d in b)a[d]=aa(b[d]);Rb(a,c)}}else(a=b)&&(K(b)?a=aa(b,[]):La(b)?a=new Date(b.getTime()):ab(b)?a=RegExp(b.source):X(b)&&(a=aa(b,{})));return a}function Tb(b,a){a=a||{};for(var c in b)b.hasOwnProperty(c)&&("$"!==c.charAt(0)&&"$"!==c.charAt(1))&&(a[c]=b[c]);return a}function ua(b,a){if(b===a)return!0;if(null===b||null===a)return!1;if(b!==b&&a!==a)return!0;var c=typeof b,
d;if(c==typeof a&&"object"==c)if(K(b)){if(!K(a))return!1;if((c=b.length)==a.length){for(d=0;d<c;d++)if(!ua(b[d],a[d]))return!1;return!0}}else{if(La(b))return La(a)&&b.getTime()==a.getTime();if(ab(b)&&ab(a))return b.toString()==a.toString();if(b&&b.$evalAsync&&b.$watch||a&&a.$evalAsync&&a.$watch||Aa(b)||Aa(a)||K(a))return!1;c={};for(d in b)if("$"!==d.charAt(0)&&!L(b[d])){if(!ua(b[d],a[d]))return!1;c[d]=!0}for(d in a)if(!c.hasOwnProperty(d)&&"$"!==d.charAt(0)&&a[d]!==r&&!L(a[d]))return!1;return!0}return!1}
function Ub(){return Q.securityPolicy&&Q.securityPolicy.isActive||Q.querySelector&&!(!Q.querySelector("[ng-csp]")&&!Q.querySelector("[data-ng-csp]"))}function cb(b,a){var c=2<arguments.length?va.call(arguments,2):[];return!L(a)||a instanceof RegExp?a:c.length?function(){return arguments.length?a.apply(b,c.concat(va.call(arguments,0))):a.apply(b,c)}:function(){return arguments.length?a.apply(b,arguments):a.call(b)}}function Sc(b,a){var c=a;"string"===typeof b&&"$"===b.charAt(0)?c=r:Aa(a)?c="$WINDOW":
a&&Q===a?c="$DOCUMENT":a&&(a.$evalAsync&&a.$watch)&&(c="$SCOPE");return c}function qa(b,a){return"undefined"===typeof b?r:JSON.stringify(b,Sc,a?" ":null)}function Vb(b){return D(b)?JSON.parse(b):b}function Pa(b){"function"===typeof b?b=!0:b&&0!==b.length?(b=x(""+b),b=!("f"==b||"0"==b||"false"==b||"no"==b||"n"==b||"[]"==b)):b=!1;return b}function ga(b){b=A(b).clone();try{b.empty()}catch(a){}var c=A("<div>").append(b).html();try{return 3===b[0].nodeType?x(c):c.match(/^(<[^>]+>)/)[1].replace(/^<([\w\-]+)/,
function(a,b){return"<"+x(b)})}catch(d){return x(c)}}function Wb(b){try{return decodeURIComponent(b)}catch(a){}}function Xb(b){var a={},c,d;q((b||"").split("&"),function(b){b&&(c=b.split("="),d=Wb(c[0]),B(d)&&(b=B(c[1])?Wb(c[1]):!0,a[d]?K(a[d])?a[d].push(b):a[d]=[a[d],b]:a[d]=b))});return a}function Yb(b){var a=[];q(b,function(b,d){K(b)?q(b,function(b){a.push(wa(d,!0)+(!0===b?"":"="+wa(b,!0)))}):a.push(wa(d,!0)+(!0===b?"":"="+wa(b,!0)))});return a.length?a.join("&"):""}function tb(b){return wa(b,
!0).replace(/%26/gi,"&").replace(/%3D/gi,"=").replace(/%2B/gi,"+")}function wa(b,a){return encodeURIComponent(b).replace(/%40/gi,"@").replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,a?"%20":"+")}function Tc(b,a){function c(a){a&&d.push(a)}var d=[b],e,g,f=["ng:app","ng-app","x-ng-app","data-ng-app"],h=/\sng[:\-]app(:\s*([\w\d_]+);?)?\s/;q(f,function(a){f[a]=!0;c(Q.getElementById(a));a=a.replace(":","\\:");b.querySelectorAll&&(q(b.querySelectorAll("."+a),c),q(b.querySelectorAll("."+
a+"\\:"),c),q(b.querySelectorAll("["+a+"]"),c))});q(d,function(a){if(!e){var b=h.exec(" "+a.className+" ");b?(e=a,g=(b[2]||"").replace(/\s+/g,",")):q(a.attributes,function(b){!e&&f[b.name]&&(e=a,g=b.value)})}});e&&a(e,g?[g]:[])}function Zb(b,a){var c=function(){b=A(b);if(b.injector()){var c=b[0]===Q?"document":ga(b);throw Oa("btstrpd",c);}a=a||[];a.unshift(["$provide",function(a){a.value("$rootElement",b)}]);a.unshift("ng");c=$b(a);c.invoke(["$rootScope","$rootElement","$compile","$injector","$animate",
function(a,b,c,d,e){a.$apply(function(){b.data("$injector",d);c(b)(a)})}]);return c},d=/^NG_DEFER_BOOTSTRAP!/;if(Z&&!d.test(Z.name))return c();Z.name=Z.name.replace(d,"");Ca.resumeBootstrap=function(b){q(b,function(b){a.push(b)});c()}}function db(b,a){a=a||"_";return b.replace(Uc,function(b,d){return(d?a:"")+b.toLowerCase()})}function ub(b,a,c){if(!b)throw Oa("areq",a||"?",c||"required");return b}function Qa(b,a,c){c&&K(b)&&(b=b[b.length-1]);ub(L(b),a,"not a function, got "+(b&&"object"==typeof b?
b.constructor.name||"Object":typeof b));return b}function xa(b,a){if("hasOwnProperty"===b)throw Oa("badname",a);}function vb(b,a,c){if(!a)return b;a=a.split(".");for(var d,e=b,g=a.length,f=0;f<g;f++)d=a[f],b&&(b=(e=b)[d]);return!c&&L(b)?cb(e,b):b}function wb(b){var a=b[0];b=b[b.length-1];if(a===b)return A(a);var c=[a];do{a=a.nextSibling;if(!a)break;c.push(a)}while(a!==b);return A(c)}function Vc(b){var a=F("$injector"),c=F("ng");b=b.angular||(b.angular={});b.$$minErr=b.$$minErr||F;return b.module||
(b.module=function(){var b={};return function(e,g,f){if("hasOwnProperty"===e)throw c("badname","module");g&&b.hasOwnProperty(e)&&(b[e]=null);return b[e]||(b[e]=function(){function b(a,d,e){return function(){c[e||"push"]([a,d,arguments]);return n}}if(!g)throw a("nomod",e);var c=[],d=[],l=b("$injector","invoke"),n={_invokeQueue:c,_runBlocks:d,requires:g,name:e,provider:b("$provide","provider"),factory:b("$provide","factory"),service:b("$provide","service"),value:b("$provide","value"),constant:b("$provide",
"constant","unshift"),animation:b("$animateProvider","register"),filter:b("$filterProvider","register"),controller:b("$controllerProvider","register"),directive:b("$compileProvider","directive"),config:l,run:function(a){d.push(a);return this}};f&&l(f);return n}())}}())}function Ra(b){return b.replace(Wc,function(a,b,d,e){return e?d.toUpperCase():d}).replace(Xc,"Moz$1")}function xb(b,a,c,d){function e(b){var e=c&&b?[this.filter(b)]:[this],m=a,k,l,n,p,s,C;if(!d||null!=b)for(;e.length;)for(k=e.shift(),
l=0,n=k.length;l<n;l++)for(p=A(k[l]),m?p.triggerHandler("$destroy"):m=!m,s=0,p=(C=p.children()).length;s<p;s++)e.push(Da(C[s]));return g.apply(this,arguments)}var g=Da.fn[b],g=g.$original||g;e.$original=g;Da.fn[b]=e}function O(b){if(b instanceof O)return b;if(!(this instanceof O)){if(D(b)&&"<"!=b.charAt(0))throw yb("nosel");return new O(b)}if(D(b)){var a=Q.createElement("div");a.innerHTML="<div> </div>"+b;a.removeChild(a.firstChild);zb(this,a.childNodes);A(Q.createDocumentFragment()).append(this)}else zb(this,
b)}function Ab(b){return b.cloneNode(!0)}function Ea(b){ac(b);var a=0;for(b=b.childNodes||[];a<b.length;a++)Ea(b[a])}function bc(b,a,c,d){if(B(d))throw yb("offargs");var e=la(b,"events");la(b,"handle")&&(z(a)?q(e,function(a,c){Bb(b,c,a);delete e[c]}):q(a.split(" "),function(a){z(c)?(Bb(b,a,e[a]),delete e[a]):Na(e[a]||[],c)}))}function ac(b,a){var c=b[eb],d=Sa[c];d&&(a?delete Sa[c].data[a]:(d.handle&&(d.events.$destroy&&d.handle({},"$destroy"),bc(b)),delete Sa[c],b[eb]=r))}function la(b,a,c){var d=
b[eb],d=Sa[d||-1];if(B(c))d||(b[eb]=d=++Yc,d=Sa[d]={}),d[a]=c;else return d&&d[a]}function cc(b,a,c){var d=la(b,"data"),e=B(c),g=!e&&B(a),f=g&&!X(a);d||f||la(b,"data",d={});if(e)d[a]=c;else if(g){if(f)return d&&d[a];t(d,a)}else return d}function Cb(b,a){return b.getAttribute?-1<(" "+(b.getAttribute("class")||"")+" ").replace(/[\n\t]/g," ").indexOf(" "+a+" "):!1}function Db(b,a){a&&b.setAttribute&&q(a.split(" "),function(a){b.setAttribute("class",ba((" "+(b.getAttribute("class")||"")+" ").replace(/[\n\t]/g,
" ").replace(" "+ba(a)+" "," ")))})}function Eb(b,a){if(a&&b.setAttribute){var c=(" "+(b.getAttribute("class")||"")+" ").replace(/[\n\t]/g," ");q(a.split(" "),function(a){a=ba(a);-1===c.indexOf(" "+a+" ")&&(c+=a+" ")});b.setAttribute("class",ba(c))}}function zb(b,a){if(a){a=a.nodeName||!B(a.length)||Aa(a)?[a]:a;for(var c=0;c<a.length;c++)b.push(a[c])}}function dc(b,a){return fb(b,"$"+(a||"ngController")+"Controller")}function fb(b,a,c){b=A(b);9==b[0].nodeType&&(b=b.find("html"));for(a=K(a)?a:[a];b.length;){for(var d=
0,e=a.length;d<e;d++)if((c=b.data(a[d]))!==r)return c;b=b.parent()}}function ec(b){for(var a=0,c=b.childNodes;a<c.length;a++)Ea(c[a]);for(;b.firstChild;)b.removeChild(b.firstChild)}function fc(b,a){var c=gb[a.toLowerCase()];return c&&gc[b.nodeName]&&c}function Zc(b,a){var c=function(c,e){c.preventDefault||(c.preventDefault=function(){c.returnValue=!1});c.stopPropagation||(c.stopPropagation=function(){c.cancelBubble=!0});c.target||(c.target=c.srcElement||Q);if(z(c.defaultPrevented)){var g=c.preventDefault;
c.preventDefault=function(){c.defaultPrevented=!0;g.call(c)};c.defaultPrevented=!1}c.isDefaultPrevented=function(){return c.defaultPrevented||!1===c.returnValue};var f=Tb(a[e||c.type]||[]);q(f,function(a){a.call(b,c)});8>=M?(c.preventDefault=null,c.stopPropagation=null,c.isDefaultPrevented=null):(delete c.preventDefault,delete c.stopPropagation,delete c.isDefaultPrevented)};c.elem=b;return c}function Fa(b){var a=typeof b,c;"object"==a&&null!==b?"function"==typeof(c=b.$$hashKey)?c=b.$$hashKey():c===
r&&(c=b.$$hashKey=$a()):c=b;return a+":"+c}function Ta(b){q(b,this.put,this)}function hc(b){var a,c;"function"==typeof b?(a=b.$inject)||(a=[],b.length&&(c=b.toString().replace($c,""),c=c.match(ad),q(c[1].split(bd),function(b){b.replace(cd,function(b,c,d){a.push(d)})})),b.$inject=a):K(b)?(c=b.length-1,Qa(b[c],"fn"),a=b.slice(0,c)):Qa(b,"fn",!0);return a}function $b(b){function a(a){return function(b,c){if(X(b))q(b,Qb(a));else return a(b,c)}}function c(a,b){xa(a,"service");if(L(b)||K(b))b=n.instantiate(b);
if(!b.$get)throw Ua("pget",a);return l[a+h]=b}function d(a,b){return c(a,{$get:b})}function e(a){var b=[],c,d,g,h;q(a,function(a){if(!k.get(a)){k.put(a,!0);try{if(D(a))for(c=Va(a),b=b.concat(e(c.requires)).concat(c._runBlocks),d=c._invokeQueue,g=0,h=d.length;g<h;g++){var f=d[g],m=n.get(f[0]);m[f[1]].apply(m,f[2])}else L(a)?b.push(n.invoke(a)):K(a)?b.push(n.invoke(a)):Qa(a,"module")}catch(s){throw K(a)&&(a=a[a.length-1]),s.message&&(s.stack&&-1==s.stack.indexOf(s.message))&&(s=s.message+"\n"+s.stack),
Ua("modulerr",a,s.stack||s.message||s);}}});return b}function g(a,b){function c(d){if(a.hasOwnProperty(d)){if(a[d]===f)throw Ua("cdep",m.join(" <- "));return a[d]}try{return m.unshift(d),a[d]=f,a[d]=b(d)}catch(e){throw a[d]===f&&delete a[d],e;}finally{m.shift()}}function d(a,b,e){var g=[],h=hc(a),f,k,m;k=0;for(f=h.length;k<f;k++){m=h[k];if("string"!==typeof m)throw Ua("itkn",m);g.push(e&&e.hasOwnProperty(m)?e[m]:c(m))}a.$inject||(a=a[f]);return a.apply(b,g)}return{invoke:d,instantiate:function(a,
b){var c=function(){},e;c.prototype=(K(a)?a[a.length-1]:a).prototype;c=new c;e=d(a,c,b);return X(e)||L(e)?e:c},get:c,annotate:hc,has:function(b){return l.hasOwnProperty(b+h)||a.hasOwnProperty(b)}}}var f={},h="Provider",m=[],k=new Ta,l={$provide:{provider:a(c),factory:a(d),service:a(function(a,b){return d(a,["$injector",function(a){return a.instantiate(b)}])}),value:a(function(a,b){return d(a,$(b))}),constant:a(function(a,b){xa(a,"constant");l[a]=b;p[a]=b}),decorator:function(a,b){var c=n.get(a+h),
d=c.$get;c.$get=function(){var a=s.invoke(d,c);return s.invoke(b,null,{$delegate:a})}}}},n=l.$injector=g(l,function(){throw Ua("unpr",m.join(" <- "));}),p={},s=p.$injector=g(p,function(a){a=n.get(a+h);return s.invoke(a.$get,a)});q(e(b),function(a){s.invoke(a||w)});return s}function dd(){var b=!0;this.disableAutoScrolling=function(){b=!1};this.$get=["$window","$location","$rootScope",function(a,c,d){function e(a){var b=null;q(a,function(a){b||"a"!==x(a.nodeName)||(b=a)});return b}function g(){var b=
c.hash(),d;b?(d=f.getElementById(b))?d.scrollIntoView():(d=e(f.getElementsByName(b)))?d.scrollIntoView():"top"===b&&a.scrollTo(0,0):a.scrollTo(0,0)}var f=a.document;b&&d.$watch(function(){return c.hash()},function(){d.$evalAsync(g)});return g}]}function ed(b,a,c,d){function e(a){try{a.apply(null,va.call(arguments,1))}finally{if(C--,0===C)for(;y.length;)try{y.pop()()}catch(b){c.error(b)}}}function g(a,b){(function T(){q(E,function(a){a()});u=b(T,a)})()}function f(){v=null;R!=h.url()&&(R=h.url(),q(ha,
function(a){a(h.url())}))}var h=this,m=a[0],k=b.location,l=b.history,n=b.setTimeout,p=b.clearTimeout,s={};h.isMock=!1;var C=0,y=[];h.$$completeOutstandingRequest=e;h.$$incOutstandingRequestCount=function(){C++};h.notifyWhenNoOutstandingRequests=function(a){q(E,function(a){a()});0===C?a():y.push(a)};var E=[],u;h.addPollFn=function(a){z(u)&&g(100,n);E.push(a);return a};var R=k.href,H=a.find("base"),v=null;h.url=function(a,c){k!==b.location&&(k=b.location);l!==b.history&&(l=b.history);if(a){if(R!=a)return R=
a,d.history?c?l.replaceState(null,"",a):(l.pushState(null,"",a),H.attr("href",H.attr("href"))):(v=a,c?k.replace(a):k.href=a),h}else return v||k.href.replace(/%27/g,"'")};var ha=[],N=!1;h.onUrlChange=function(a){if(!N){if(d.history)A(b).on("popstate",f);if(d.hashchange)A(b).on("hashchange",f);else h.addPollFn(f);N=!0}ha.push(a);return a};h.baseHref=function(){var a=H.attr("href");return a?a.replace(/^(https?\:)?\/\/[^\/]*/,""):""};var V={},J="",ca=h.baseHref();h.cookies=function(a,b){var d,e,g,h;if(a)b===
r?m.cookie=escape(a)+"=;path="+ca+";expires=Thu, 01 Jan 1970 00:00:00 GMT":D(b)&&(d=(m.cookie=escape(a)+"="+escape(b)+";path="+ca).length+1,4096<d&&c.warn("Cookie '"+a+"' possibly not set or overflowed because it was too large ("+d+" > 4096 bytes)!"));else{if(m.cookie!==J)for(J=m.cookie,d=J.split("; "),V={},g=0;g<d.length;g++)e=d[g],h=e.indexOf("="),0<h&&(a=unescape(e.substring(0,h)),V[a]===r&&(V[a]=unescape(e.substring(h+1))));return V}};h.defer=function(a,b){var c;C++;c=n(function(){delete s[c];
e(a)},b||0);s[c]=!0;return c};h.defer.cancel=function(a){return s[a]?(delete s[a],p(a),e(w),!0):!1}}function fd(){this.$get=["$window","$log","$sniffer","$document",function(b,a,c,d){return new ed(b,d,a,c)}]}function gd(){this.$get=function(){function b(b,d){function e(a){a!=n&&(p?p==a&&(p=a.n):p=a,g(a.n,a.p),g(a,n),n=a,n.n=null)}function g(a,b){a!=b&&(a&&(a.p=b),b&&(b.n=a))}if(b in a)throw F("$cacheFactory")("iid",b);var f=0,h=t({},d,{id:b}),m={},k=d&&d.capacity||Number.MAX_VALUE,l={},n=null,p=null;
return a[b]={put:function(a,b){var c=l[a]||(l[a]={key:a});e(c);if(!z(b))return a in m||f++,m[a]=b,f>k&&this.remove(p.key),b},get:function(a){var b=l[a];if(b)return e(b),m[a]},remove:function(a){var b=l[a];b&&(b==n&&(n=b.p),b==p&&(p=b.n),g(b.n,b.p),delete l[a],delete m[a],f--)},removeAll:function(){m={};f=0;l={};n=p=null},destroy:function(){l=h=m=null;delete a[b]},info:function(){return t({},h,{size:f})}}}var a={};b.info=function(){var b={};q(a,function(a,e){b[e]=a.info()});return b};b.get=function(b){return a[b]};
return b}}function hd(){this.$get=["$cacheFactory",function(b){return b("templates")}]}function jc(b,a){var c={},d="Directive",e=/^\s*directive\:\s*([\d\w\-_]+)\s+(.*)$/,g=/(([\d\w\-_]+)(?:\:([^;]+))?;?)/,f=/^(on[a-z]+|formaction)$/;this.directive=function m(a,e){xa(a,"directive");D(a)?(ub(e,"directiveFactory"),c.hasOwnProperty(a)||(c[a]=[],b.factory(a+d,["$injector","$exceptionHandler",function(b,d){var e=[];q(c[a],function(c,g){try{var f=b.invoke(c);L(f)?f={compile:$(f)}:!f.compile&&f.link&&(f.compile=
$(f.link));f.priority=f.priority||0;f.index=g;f.name=f.name||a;f.require=f.require||f.controller&&f.name;f.restrict=f.restrict||"A";e.push(f)}catch(m){d(m)}});return e}])),c[a].push(e)):q(a,Qb(m));return this};this.aHrefSanitizationWhitelist=function(b){return B(b)?(a.aHrefSanitizationWhitelist(b),this):a.aHrefSanitizationWhitelist()};this.imgSrcSanitizationWhitelist=function(b){return B(b)?(a.imgSrcSanitizationWhitelist(b),this):a.imgSrcSanitizationWhitelist()};this.$get=["$injector","$interpolate",
"$exceptionHandler","$http","$templateCache","$parse","$controller","$rootScope","$document","$sce","$animate","$$sanitizeUri",function(a,b,l,n,p,s,C,y,E,u,R,H){function v(a,b,c,d,e){a instanceof A||(a=A(a));q(a,function(b,c){3==b.nodeType&&b.nodeValue.match(/\S+/)&&(a[c]=A(b).wrap("<span></span>").parent()[0])});var g=N(a,b,a,c,d,e);ha(a,"ng-scope");return function(b,c,d){ub(b,"scope");var e=c?Ga.clone.call(a):a;q(d,function(a,b){e.data("$"+b+"Controller",a)});d=0;for(var f=e.length;d<f;d++){var m=
e[d].nodeType;1!==m&&9!==m||e.eq(d).data("$scope",b)}c&&c(e,b);g&&g(b,e,e);return e}}function ha(a,b){try{a.addClass(b)}catch(c){}}function N(a,b,c,d,e,g){function f(a,c,d,e){var g,k,s,l,n,p,I;g=c.length;var C=Array(g);for(n=0;n<g;n++)C[n]=c[n];I=n=0;for(p=m.length;n<p;I++)k=C[I],c=m[n++],g=m[n++],s=A(k),c?(c.scope?(l=a.$new(),s.data("$scope",l)):l=a,(s=c.transclude)||!e&&b?c(g,l,k,d,V(a,s||b)):c(g,l,k,d,e)):g&&g(a,k.childNodes,r,e)}for(var m=[],k,s,l,n,p=0;p<a.length;p++)k=new Fb,s=J(a[p],[],k,0===
p?d:r,e),(g=s.length?ia(s,a[p],k,b,c,null,[],[],g):null)&&g.scope&&ha(A(a[p]),"ng-scope"),k=g&&g.terminal||!(l=a[p].childNodes)||!l.length?null:N(l,g?g.transclude:b),m.push(g,k),n=n||g||k,g=null;return n?f:null}function V(a,b){return function(c,d,e){var g=!1;c||(c=a.$new(),g=c.$$transcluded=!0);d=b(c,d,e);if(g)d.on("$destroy",cb(c,c.$destroy));return d}}function J(a,b,c,d,f){var k=c.$attr,m;switch(a.nodeType){case 1:T(b,ma(Ha(a).toLowerCase()),"E",d,f);var s,l,n;m=a.attributes;for(var p=0,C=m&&m.length;p<
C;p++){var y=!1,R=!1;s=m[p];if(!M||8<=M||s.specified){l=s.name;n=ma(l);W.test(n)&&(l=db(n.substr(6),"-"));var v=n.replace(/(Start|End)$/,"");n===v+"Start"&&(y=l,R=l.substr(0,l.length-5)+"end",l=l.substr(0,l.length-6));n=ma(l.toLowerCase());k[n]=l;c[n]=s=ba(s.value);fc(a,n)&&(c[n]=!0);S(a,b,s,n);T(b,n,"A",d,f,y,R)}}a=a.className;if(D(a)&&""!==a)for(;m=g.exec(a);)n=ma(m[2]),T(b,n,"C",d,f)&&(c[n]=ba(m[3])),a=a.substr(m.index+m[0].length);break;case 3:F(b,a.nodeValue);break;case 8:try{if(m=e.exec(a.nodeValue))n=
ma(m[1]),T(b,n,"M",d,f)&&(c[n]=ba(m[2]))}catch(E){}}b.sort(z);return b}function ca(a,b,c){var d=[],e=0;if(b&&a.hasAttribute&&a.hasAttribute(b)){do{if(!a)throw ja("uterdir",b,c);1==a.nodeType&&(a.hasAttribute(b)&&e++,a.hasAttribute(c)&&e--);d.push(a);a=a.nextSibling}while(0<e)}else d.push(a);return A(d)}function P(a,b,c){return function(d,e,g,f,m){e=ca(e[0],b,c);return a(d,e,g,f,m)}}function ia(a,c,d,e,g,f,m,n,p){function y(a,b,c,d){if(a){c&&(a=P(a,c,d));a.require=G.require;if(H===G||G.$$isolateScope)a=
kc(a,{isolateScope:!0});m.push(a)}if(b){c&&(b=P(b,c,d));b.require=G.require;if(H===G||G.$$isolateScope)b=kc(b,{isolateScope:!0});n.push(b)}}function R(a,b,c){var d,e="data",g=!1;if(D(a)){for(;"^"==(d=a.charAt(0))||"?"==d;)a=a.substr(1),"^"==d&&(e="inheritedData"),g=g||"?"==d;d=null;c&&"data"===e&&(d=c[a]);d=d||b[e]("$"+a+"Controller");if(!d&&!g)throw ja("ctreq",a,da);}else K(a)&&(d=[],q(a,function(a){d.push(R(a,b,c))}));return d}function E(a,e,g,f,p){function y(a,b){var c;2>arguments.length&&(b=a,
a=r);z&&(c=ca);return p(a,b,c)}var I,v,N,u,P,J,ca={},hb;I=c===g?d:Tb(d,new Fb(A(g),d.$attr));v=I.$$element;if(H){var T=/^\s*([@=&])(\??)\s*(\w*)\s*$/;f=A(g);J=e.$new(!0);ia&&ia===H.$$originalDirective?f.data("$isolateScope",J):f.data("$isolateScopeNoTemplate",J);ha(f,"ng-isolate-scope");q(H.scope,function(a,c){var d=a.match(T)||[],g=d[3]||c,f="?"==d[2],d=d[1],m,l,n,p;J.$$isolateBindings[c]=d+g;switch(d){case "@":I.$observe(g,function(a){J[c]=a});I.$$observers[g].$$scope=e;I[g]&&(J[c]=b(I[g])(e));
break;case "=":if(f&&!I[g])break;l=s(I[g]);p=l.literal?ua:function(a,b){return a===b};n=l.assign||function(){m=J[c]=l(e);throw ja("nonassign",I[g],H.name);};m=J[c]=l(e);J.$watch(function(){var a=l(e);p(a,J[c])||(p(a,m)?n(e,a=J[c]):J[c]=a);return m=a},null,l.literal);break;case "&":l=s(I[g]);J[c]=function(a){return l(e,a)};break;default:throw ja("iscp",H.name,c,a);}})}hb=p&&y;V&&q(V,function(a){var b={$scope:a===H||a.$$isolateScope?J:e,$element:v,$attrs:I,$transclude:hb},c;P=a.controller;"@"==P&&(P=
I[a.name]);c=C(P,b);ca[a.name]=c;z||v.data("$"+a.name+"Controller",c);a.controllerAs&&(b.$scope[a.controllerAs]=c)});f=0;for(N=m.length;f<N;f++)try{u=m[f],u(u.isolateScope?J:e,v,I,u.require&&R(u.require,v,ca),hb)}catch(G){l(G,ga(v))}f=e;H&&(H.template||null===H.templateUrl)&&(f=J);a&&a(f,g.childNodes,r,p);for(f=n.length-1;0<=f;f--)try{u=n[f],u(u.isolateScope?J:e,v,I,u.require&&R(u.require,v,ca),hb)}catch(B){l(B,ga(v))}}p=p||{};var N=-Number.MAX_VALUE,u,V=p.controllerDirectives,H=p.newIsolateScopeDirective,
ia=p.templateDirective;p=p.nonTlbTranscludeDirective;for(var T=!1,z=!1,t=d.$$element=A(c),G,da,U,F=e,O,M=0,na=a.length;M<na;M++){G=a[M];var Wa=G.$$start,S=G.$$end;Wa&&(t=ca(c,Wa,S));U=r;if(N>G.priority)break;if(U=G.scope)u=u||G,G.templateUrl||(x("new/isolated scope",H,G,t),X(U)&&(H=G));da=G.name;!G.templateUrl&&G.controller&&(U=G.controller,V=V||{},x("'"+da+"' controller",V[da],G,t),V[da]=G);if(U=G.transclude)T=!0,G.$$tlb||(x("transclusion",p,G,t),p=G),"element"==U?(z=!0,N=G.priority,U=ca(c,Wa,S),
t=d.$$element=A(Q.createComment(" "+da+": "+d[da]+" ")),c=t[0],ib(g,A(va.call(U,0)),c),F=v(U,e,N,f&&f.name,{nonTlbTranscludeDirective:p})):(U=A(Ab(c)).contents(),t.empty(),F=v(U,e));if(G.template)if(x("template",ia,G,t),ia=G,U=L(G.template)?G.template(t,d):G.template,U=Y(U),G.replace){f=G;U=A("<div>"+ba(U)+"</div>").contents();c=U[0];if(1!=U.length||1!==c.nodeType)throw ja("tplrt",da,"");ib(g,t,c);na={$attr:{}};U=J(c,[],na);var W=a.splice(M+1,a.length-(M+1));H&&ic(U);a=a.concat(U).concat(W);B(d,na);
na=a.length}else t.html(U);if(G.templateUrl)x("template",ia,G,t),ia=G,G.replace&&(f=G),E=w(a.splice(M,a.length-M),t,d,g,F,m,n,{controllerDirectives:V,newIsolateScopeDirective:H,templateDirective:ia,nonTlbTranscludeDirective:p}),na=a.length;else if(G.compile)try{O=G.compile(t,d,F),L(O)?y(null,O,Wa,S):O&&y(O.pre,O.post,Wa,S)}catch(Z){l(Z,ga(t))}G.terminal&&(E.terminal=!0,N=Math.max(N,G.priority))}E.scope=u&&!0===u.scope;E.transclude=T&&F;return E}function ic(a){for(var b=0,c=a.length;b<c;b++)a[b]=Sb(a[b],
{$$isolateScope:!0})}function T(b,e,g,f,k,s,n){if(e===k)return null;k=null;if(c.hasOwnProperty(e)){var p;e=a.get(e+d);for(var C=0,y=e.length;C<y;C++)try{p=e[C],(f===r||f>p.priority)&&-1!=p.restrict.indexOf(g)&&(s&&(p=Sb(p,{$$start:s,$$end:n})),b.push(p),k=p)}catch(v){l(v)}}return k}function B(a,b){var c=b.$attr,d=a.$attr,e=a.$$element;q(a,function(d,e){"$"!=e.charAt(0)&&(b[e]&&(d+=("style"===e?";":" ")+b[e]),a.$set(e,d,!0,c[e]))});q(b,function(b,g){"class"==g?(ha(e,b),a["class"]=(a["class"]?a["class"]+
" ":"")+b):"style"==g?(e.attr("style",e.attr("style")+";"+b),a.style=(a.style?a.style+";":"")+b):"$"==g.charAt(0)||a.hasOwnProperty(g)||(a[g]=b,d[g]=c[g])})}function w(a,b,c,d,e,g,f,m){var k=[],s,l,C=b[0],y=a.shift(),v=t({},y,{templateUrl:null,transclude:null,replace:null,$$originalDirective:y}),R=L(y.templateUrl)?y.templateUrl(b,c):y.templateUrl;b.empty();n.get(u.getTrustedResourceUrl(R),{cache:p}).success(function(n){var p,E;n=Y(n);if(y.replace){n=A("<div>"+ba(n)+"</div>").contents();p=n[0];if(1!=
n.length||1!==p.nodeType)throw ja("tplrt",y.name,R);n={$attr:{}};ib(d,b,p);var u=J(p,[],n);X(y.scope)&&ic(u);a=u.concat(a);B(c,n)}else p=C,b.html(n);a.unshift(v);s=ia(a,p,c,e,b,y,g,f,m);q(d,function(a,c){a==p&&(d[c]=b[0])});for(l=N(b[0].childNodes,e);k.length;){n=k.shift();E=k.shift();var H=k.shift(),ha=k.shift(),u=b[0];E!==C&&(u=Ab(p),ib(H,A(E),u));E=s.transclude?V(n,s.transclude):ha;s(l,n,u,d,E)}k=null}).error(function(a,b,c,d){throw ja("tpload",d.url);});return function(a,b,c,d,e){k?(k.push(b),
k.push(c),k.push(d),k.push(e)):s(l,b,c,d,e)}}function z(a,b){var c=b.priority-a.priority;return 0!==c?c:a.name!==b.name?a.name<b.name?-1:1:a.index-b.index}function x(a,b,c,d){if(b)throw ja("multidir",b.name,c.name,a,ga(d));}function F(a,c){var d=b(c,!0);d&&a.push({priority:0,compile:$(function(a,b){var c=b.parent(),e=c.data("$binding")||[];e.push(d);ha(c.data("$binding",e),"ng-binding");a.$watch(d,function(a){b[0].nodeValue=a})})})}function O(a,b){if("srcdoc"==b)return u.HTML;var c=Ha(a);if("xlinkHref"==
b||"FORM"==c&&"action"==b||"IMG"!=c&&("src"==b||"ngSrc"==b))return u.RESOURCE_URL}function S(a,c,d,e){var g=b(d,!0);if(g){if("multiple"===e&&"SELECT"===Ha(a))throw ja("selmulti",ga(a));c.push({priority:100,compile:function(){return{pre:function(c,d,m){d=m.$$observers||(m.$$observers={});if(f.test(e))throw ja("nodomevents");if(g=b(m[e],!0,O(a,e)))m[e]=g(c),(d[e]||(d[e]=[])).$$inter=!0,(m.$$observers&&m.$$observers[e].$$scope||c).$watch(g,function(a,b){"class"===e&&a!=b?m.$updateClass(a,b):m.$set(e,
a)})}}}})}}function ib(a,b,c){var d=b[0],e=b.length,g=d.parentNode,f,m;if(a)for(f=0,m=a.length;f<m;f++)if(a[f]==d){a[f++]=c;m=f+e-1;for(var k=a.length;f<k;f++,m++)m<k?a[f]=a[m]:delete a[f];a.length-=e-1;break}g&&g.replaceChild(c,d);a=Q.createDocumentFragment();a.appendChild(d);c[A.expando]=d[A.expando];d=1;for(e=b.length;d<e;d++)g=b[d],A(g).remove(),a.appendChild(g),delete b[d];b[0]=c;b.length=1}function kc(a,b){return t(function(){return a.apply(null,arguments)},a,b)}var Fb=function(a,b){this.$$element=
a;this.$attr=b||{}};Fb.prototype={$normalize:ma,$addClass:function(a){a&&0<a.length&&R.addClass(this.$$element,a)},$removeClass:function(a){a&&0<a.length&&R.removeClass(this.$$element,a)},$updateClass:function(a,b){this.$removeClass(lc(b,a));this.$addClass(lc(a,b))},$set:function(a,b,c,d){var e=fc(this.$$element[0],a);e&&(this.$$element.prop(a,b),d=e);this[a]=b;d?this.$attr[a]=d:(d=this.$attr[a])||(this.$attr[a]=d=db(a,"-"));e=Ha(this.$$element);if("A"===e&&"href"===a||"IMG"===e&&"src"===a)this[a]=
b=H(b,"src"===a);!1!==c&&(null===b||b===r?this.$$element.removeAttr(d):this.$$element.attr(d,b));(c=this.$$observers)&&q(c[a],function(a){try{a(b)}catch(c){l(c)}})},$observe:function(a,b){var c=this,d=c.$$observers||(c.$$observers={}),e=d[a]||(d[a]=[]);e.push(b);y.$evalAsync(function(){e.$$inter||b(c[a])});return b}};var da=b.startSymbol(),na=b.endSymbol(),Y="{{"==da||"}}"==na?Ba:function(a){return a.replace(/\{\{/g,da).replace(/}}/g,na)},W=/^ngAttr[A-Z]/;return v}]}function ma(b){return Ra(b.replace(id,
""))}function lc(b,a){var c="",d=b.split(/\s+/),e=a.split(/\s+/),g=0;a:for(;g<d.length;g++){for(var f=d[g],h=0;h<e.length;h++)if(f==e[h])continue a;c+=(0<c.length?" ":"")+f}return c}function jd(){var b={},a=/^(\S+)(\s+as\s+(\w+))?$/;this.register=function(a,d){xa(a,"controller");X(a)?t(b,a):b[a]=d};this.$get=["$injector","$window",function(c,d){return function(e,g){var f,h,m;D(e)&&(f=e.match(a),h=f[1],m=f[3],e=b.hasOwnProperty(h)?b[h]:vb(g.$scope,h,!0)||vb(d,h,!0),Qa(e,h,!0));f=c.instantiate(e,g);
if(m){if(!g||"object"!=typeof g.$scope)throw F("$controller")("noscp",h||e.name,m);g.$scope[m]=f}return f}}]}function kd(){this.$get=["$window",function(b){return A(b.document)}]}function ld(){this.$get=["$log",function(b){return function(a,c){b.error.apply(b,arguments)}}]}function mc(b){var a={},c,d,e;if(!b)return a;q(b.split("\n"),function(b){e=b.indexOf(":");c=x(ba(b.substr(0,e)));d=ba(b.substr(e+1));c&&(a[c]=a[c]?a[c]+(", "+d):d)});return a}function nc(b){var a=X(b)?b:r;return function(c){a||
(a=mc(b));return c?a[x(c)]||null:a}}function oc(b,a,c){if(L(c))return c(b,a);q(c,function(c){b=c(b,a)});return b}function md(){var b=/^\s*(\[|\{[^\{])/,a=/[\}\]]\s*$/,c=/^\)\]\}',?\n/,d={"Content-Type":"application/json;charset=utf-8"},e=this.defaults={transformResponse:[function(d){D(d)&&(d=d.replace(c,""),b.test(d)&&a.test(d)&&(d=Vb(d)));return d}],transformRequest:[function(a){return X(a)&&"[object File]"!==Ma.call(a)?qa(a):a}],headers:{common:{Accept:"application/json, text/plain, */*"},post:aa(d),
put:aa(d),patch:aa(d)},xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN"},g=this.interceptors=[],f=this.responseInterceptors=[];this.$get=["$httpBackend","$browser","$cacheFactory","$rootScope","$q","$injector",function(a,b,c,d,n,p){function s(a){function c(a){var b=t({},a,{data:oc(a.data,a.headers,d.transformResponse)});return 200<=a.status&&300>a.status?b:n.reject(b)}var d={transformRequest:e.transformRequest,transformResponse:e.transformResponse},g=function(a){function b(a){var c;q(a,function(b,
d){L(b)&&(c=b(),null!=c?a[d]=c:delete a[d])})}var c=e.headers,d=t({},a.headers),g,f,c=t({},c.common,c[x(a.method)]);b(c);b(d);a:for(g in c){a=x(g);for(f in d)if(x(f)===a)continue a;d[g]=c[g]}return d}(a);t(d,a);d.headers=g;d.method=Ia(d.method);(a=Gb(d.url)?b.cookies()[d.xsrfCookieName||e.xsrfCookieName]:r)&&(g[d.xsrfHeaderName||e.xsrfHeaderName]=a);var f=[function(a){g=a.headers;var b=oc(a.data,nc(g),a.transformRequest);z(a.data)&&q(g,function(a,b){"content-type"===x(b)&&delete g[b]});z(a.withCredentials)&&
!z(e.withCredentials)&&(a.withCredentials=e.withCredentials);return C(a,b,g).then(c,c)},r],h=n.when(d);for(q(u,function(a){(a.request||a.requestError)&&f.unshift(a.request,a.requestError);(a.response||a.responseError)&&f.push(a.response,a.responseError)});f.length;){a=f.shift();var k=f.shift(),h=h.then(a,k)}h.success=function(a){h.then(function(b){a(b.data,b.status,b.headers,d)});return h};h.error=function(a){h.then(null,function(b){a(b.data,b.status,b.headers,d)});return h};return h}function C(b,
c,g){function f(a,b,c){u&&(200<=a&&300>a?u.put(r,[a,b,mc(c)]):u.remove(r));m(b,a,c);d.$$phase||d.$apply()}function m(a,c,d){c=Math.max(c,0);(200<=c&&300>c?p.resolve:p.reject)({data:a,status:c,headers:nc(d),config:b})}function k(){var a=bb(s.pendingRequests,b);-1!==a&&s.pendingRequests.splice(a,1)}var p=n.defer(),C=p.promise,u,q,r=y(b.url,b.params);s.pendingRequests.push(b);C.then(k,k);(b.cache||e.cache)&&(!1!==b.cache&&"GET"==b.method)&&(u=X(b.cache)?b.cache:X(e.cache)?e.cache:E);if(u)if(q=u.get(r),
B(q)){if(q.then)return q.then(k,k),q;K(q)?m(q[1],q[0],aa(q[2])):m(q,200,{})}else u.put(r,C);z(q)&&a(b.method,r,c,f,g,b.timeout,b.withCredentials,b.responseType);return C}function y(a,b){if(!b)return a;var c=[];Pc(b,function(a,b){null===a||z(a)||(K(a)||(a=[a]),q(a,function(a){X(a)&&(a=qa(a));c.push(wa(b)+"="+wa(a))}))});return a+(-1==a.indexOf("?")?"?":"&")+c.join("&")}var E=c("$http"),u=[];q(g,function(a){u.unshift(D(a)?p.get(a):p.invoke(a))});q(f,function(a,b){var c=D(a)?p.get(a):p.invoke(a);u.splice(b,
0,{response:function(a){return c(n.when(a))},responseError:function(a){return c(n.reject(a))}})});s.pendingRequests=[];(function(a){q(arguments,function(a){s[a]=function(b,c){return s(t(c||{},{method:a,url:b}))}})})("get","delete","head","jsonp");(function(a){q(arguments,function(a){s[a]=function(b,c,d){return s(t(d||{},{method:a,url:b,data:c}))}})})("post","put");s.defaults=e;return s}]}function nd(b){return 8>=M&&"patch"===x(b)?new ActiveXObject("Microsoft.XMLHTTP"):new Z.XMLHttpRequest}function od(){this.$get=
["$browser","$window","$document",function(b,a,c){return pd(b,nd,b.defer,a.angular.callbacks,c[0])}]}function pd(b,a,c,d,e){function g(a,b){var c=e.createElement("script"),d=function(){c.onreadystatechange=c.onload=c.onerror=null;e.body.removeChild(c);b&&b()};c.type="text/javascript";c.src=a;M&&8>=M?c.onreadystatechange=function(){/loaded|complete/.test(c.readyState)&&d()}:c.onload=c.onerror=function(){d()};e.body.appendChild(c);return d}var f=-1;return function(e,m,k,l,n,p,s,C){function y(){u=f;
H&&H();v&&v.abort()}function E(a,d,e,g){r&&c.cancel(r);H=v=null;d=0===d?e?200:404:d;a(1223==d?204:d,e,g);b.$$completeOutstandingRequest(w)}var u;b.$$incOutstandingRequestCount();m=m||b.url();if("jsonp"==x(e)){var R="_"+(d.counter++).toString(36);d[R]=function(a){d[R].data=a};var H=g(m.replace("JSON_CALLBACK","angular.callbacks."+R),function(){d[R].data?E(l,200,d[R].data):E(l,u||-2);d[R]=Ca.noop})}else{var v=a(e);v.open(e,m,!0);q(n,function(a,b){B(a)&&v.setRequestHeader(b,a)});v.onreadystatechange=
function(){if(v&&4==v.readyState){var a=null,b=null;u!==f&&(a=v.getAllResponseHeaders(),b="response"in v?v.response:v.responseText);E(l,u||v.status,b,a)}};s&&(v.withCredentials=!0);C&&(v.responseType=C);v.send(k||null)}if(0<p)var r=c(y,p);else p&&p.then&&p.then(y)}}function qd(){var b="{{",a="}}";this.startSymbol=function(a){return a?(b=a,this):b};this.endSymbol=function(b){return b?(a=b,this):a};this.$get=["$parse","$exceptionHandler","$sce",function(c,d,e){function g(g,k,l){for(var n,p,s=0,C=[],
y=g.length,E=!1,u=[];s<y;)-1!=(n=g.indexOf(b,s))&&-1!=(p=g.indexOf(a,n+f))?(s!=n&&C.push(g.substring(s,n)),C.push(s=c(E=g.substring(n+f,p))),s.exp=E,s=p+h,E=!0):(s!=y&&C.push(g.substring(s)),s=y);(y=C.length)||(C.push(""),y=1);if(l&&1<C.length)throw pc("noconcat",g);if(!k||E)return u.length=y,s=function(a){try{for(var b=0,c=y,f;b<c;b++)"function"==typeof(f=C[b])&&(f=f(a),f=l?e.getTrusted(l,f):e.valueOf(f),null===f||z(f)?f="":"string"!=typeof f&&(f=qa(f))),u[b]=f;return u.join("")}catch(h){a=pc("interr",
g,h.toString()),d(a)}},s.exp=g,s.parts=C,s}var f=b.length,h=a.length;g.startSymbol=function(){return b};g.endSymbol=function(){return a};return g}]}function rd(){this.$get=["$rootScope","$window","$q",function(b,a,c){function d(d,f,h,m){var k=a.setInterval,l=a.clearInterval,n=c.defer(),p=n.promise,s=0,C=B(m)&&!m;h=B(h)?h:0;p.then(null,null,d);p.$$intervalId=k(function(){n.notify(s++);0<h&&s>=h&&(n.resolve(s),l(p.$$intervalId),delete e[p.$$intervalId]);C||b.$apply()},f);e[p.$$intervalId]=n;return p}
var e={};d.cancel=function(a){return a&&a.$$intervalId in e?(e[a.$$intervalId].reject("canceled"),clearInterval(a.$$intervalId),delete e[a.$$intervalId],!0):!1};return d}]}function sd(){this.$get=function(){return{id:"en-us",NUMBER_FORMATS:{DECIMAL_SEP:".",GROUP_SEP:",",PATTERNS:[{minInt:1,minFrac:0,maxFrac:3,posPre:"",posSuf:"",negPre:"-",negSuf:"",gSize:3,lgSize:3},{minInt:1,minFrac:2,maxFrac:2,posPre:"\u00a4",posSuf:"",negPre:"(\u00a4",negSuf:")",gSize:3,lgSize:3}],CURRENCY_SYM:"$"},DATETIME_FORMATS:{MONTH:"January February March April May June July August September October November December".split(" "),
SHORTMONTH:"Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec".split(" "),DAY:"Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),SHORTDAY:"Sun Mon Tue Wed Thu Fri Sat".split(" "),AMPMS:["AM","PM"],medium:"MMM d, y h:mm:ss a","short":"M/d/yy h:mm a",fullDate:"EEEE, MMMM d, y",longDate:"MMMM d, y",mediumDate:"MMM d, y",shortDate:"M/d/yy",mediumTime:"h:mm:ss a",shortTime:"h:mm a"},pluralCat:function(b){return 1===b?"one":"other"}}}}function qc(b){b=b.split("/");for(var a=b.length;a--;)b[a]=
tb(b[a]);return b.join("/")}function rc(b,a,c){b=ya(b,c);a.$$protocol=b.protocol;a.$$host=b.hostname;a.$$port=S(b.port)||td[b.protocol]||null}function sc(b,a,c){var d="/"!==b.charAt(0);d&&(b="/"+b);b=ya(b,c);a.$$path=decodeURIComponent(d&&"/"===b.pathname.charAt(0)?b.pathname.substring(1):b.pathname);a.$$search=Xb(b.search);a.$$hash=decodeURIComponent(b.hash);a.$$path&&"/"!=a.$$path.charAt(0)&&(a.$$path="/"+a.$$path)}function oa(b,a){if(0===a.indexOf(b))return a.substr(b.length)}function Xa(b){var a=
b.indexOf("#");return-1==a?b:b.substr(0,a)}function Hb(b){return b.substr(0,Xa(b).lastIndexOf("/")+1)}function tc(b,a){this.$$html5=!0;a=a||"";var c=Hb(b);rc(b,this,b);this.$$parse=function(a){var e=oa(c,a);if(!D(e))throw Ib("ipthprfx",a,c);sc(e,this,b);this.$$path||(this.$$path="/");this.$$compose()};this.$$compose=function(){var a=Yb(this.$$search),b=this.$$hash?"#"+tb(this.$$hash):"";this.$$url=qc(this.$$path)+(a?"?"+a:"")+b;this.$$absUrl=c+this.$$url.substr(1)};this.$$rewrite=function(d){var e;
if((e=oa(b,d))!==r)return d=e,(e=oa(a,e))!==r?c+(oa("/",e)||e):b+d;if((e=oa(c,d))!==r)return c+e;if(c==d+"/")return c}}function Jb(b,a){var c=Hb(b);rc(b,this,b);this.$$parse=function(d){var e=oa(b,d)||oa(c,d),e="#"==e.charAt(0)?oa(a,e):this.$$html5?e:"";if(!D(e))throw Ib("ihshprfx",d,a);sc(e,this,b);d=this.$$path;var g=/^\/?.*?:(\/.*)/;0===e.indexOf(b)&&(e=e.replace(b,""));g.exec(e)||(d=(e=g.exec(d))?e[1]:d);this.$$path=d;this.$$compose()};this.$$compose=function(){var c=Yb(this.$$search),e=this.$$hash?
"#"+tb(this.$$hash):"";this.$$url=qc(this.$$path)+(c?"?"+c:"")+e;this.$$absUrl=b+(this.$$url?a+this.$$url:"")};this.$$rewrite=function(a){if(Xa(b)==Xa(a))return a}}function uc(b,a){this.$$html5=!0;Jb.apply(this,arguments);var c=Hb(b);this.$$rewrite=function(d){var e;if(b==Xa(d))return d;if(e=oa(c,d))return b+a+e;if(c===d+"/")return c}}function jb(b){return function(){return this[b]}}function vc(b,a){return function(c){if(z(c))return this[b];this[b]=a(c);this.$$compose();return this}}function ud(){var b=
"",a=!1;this.hashPrefix=function(a){return B(a)?(b=a,this):b};this.html5Mode=function(b){return B(b)?(a=b,this):a};this.$get=["$rootScope","$browser","$sniffer","$rootElement",function(c,d,e,g){function f(a){c.$broadcast("$locationChangeSuccess",h.absUrl(),a)}var h,m=d.baseHref(),k=d.url();a?(m=k.substring(0,k.indexOf("/",k.indexOf("//")+2))+(m||"/"),e=e.history?tc:uc):(m=Xa(k),e=Jb);h=new e(m,"#"+b);h.$$parse(h.$$rewrite(k));g.on("click",function(a){if(!a.ctrlKey&&!a.metaKey&&2!=a.which){for(var b=
A(a.target);"a"!==x(b[0].nodeName);)if(b[0]===g[0]||!(b=b.parent())[0])return;var e=b.prop("href");X(e)&&"[object SVGAnimatedString]"===e.toString()&&(e=ya(e.animVal).href);var f=h.$$rewrite(e);e&&(!b.attr("target")&&f&&!a.isDefaultPrevented())&&(a.preventDefault(),f!=d.url()&&(h.$$parse(f),c.$apply(),Z.angular["ff-684208-preventDefault"]=!0))}});h.absUrl()!=k&&d.url(h.absUrl(),!0);d.onUrlChange(function(a){h.absUrl()!=a&&(c.$evalAsync(function(){var b=h.absUrl();h.$$parse(a);c.$broadcast("$locationChangeStart",
a,b).defaultPrevented?(h.$$parse(b),d.url(b)):f(b)}),c.$$phase||c.$digest())});var l=0;c.$watch(function(){var a=d.url(),b=h.$$replace;l&&a==h.absUrl()||(l++,c.$evalAsync(function(){c.$broadcast("$locationChangeStart",h.absUrl(),a).defaultPrevented?h.$$parse(a):(d.url(h.absUrl(),b),f(a))}));h.$$replace=!1;return l});return h}]}function vd(){var b=!0,a=this;this.debugEnabled=function(a){return B(a)?(b=a,this):b};this.$get=["$window",function(c){function d(a){a instanceof Error&&(a.stack?a=a.message&&
-1===a.stack.indexOf(a.message)?"Error: "+a.message+"\n"+a.stack:a.stack:a.sourceURL&&(a=a.message+"\n"+a.sourceURL+":"+a.line));return a}function e(a){var b=c.console||{},e=b[a]||b.log||w;a=!1;try{a=!!e.apply}catch(m){}return a?function(){var a=[];q(arguments,function(b){a.push(d(b))});return e.apply(b,a)}:function(a,b){e(a,null==b?"":b)}}return{log:e("log"),info:e("info"),warn:e("warn"),error:e("error"),debug:function(){var c=e("debug");return function(){b&&c.apply(a,arguments)}}()}}]}function ea(b,
a){if("constructor"===b)throw za("isecfld",a);return b}function Ya(b,a){if(b){if(b.constructor===b)throw za("isecfn",a);if(b.document&&b.location&&b.alert&&b.setInterval)throw za("isecwindow",a);if(b.children&&(b.nodeName||b.on&&b.find))throw za("isecdom",a);}return b}function kb(b,a,c,d,e){e=e||{};a=a.split(".");for(var g,f=0;1<a.length;f++){g=ea(a.shift(),d);var h=b[g];h||(h={},b[g]=h);b=h;b.then&&e.unwrapPromises&&(ra(d),"$$v"in b||function(a){a.then(function(b){a.$$v=b})}(b),b.$$v===r&&(b.$$v=
{}),b=b.$$v)}g=ea(a.shift(),d);return b[g]=c}function wc(b,a,c,d,e,g,f){ea(b,g);ea(a,g);ea(c,g);ea(d,g);ea(e,g);return f.unwrapPromises?function(f,m){var k=m&&m.hasOwnProperty(b)?m:f,l;if(null==k)return k;(k=k[b])&&k.then&&(ra(g),"$$v"in k||(l=k,l.$$v=r,l.then(function(a){l.$$v=a})),k=k.$$v);if(!a)return k;if(null==k)return r;(k=k[a])&&k.then&&(ra(g),"$$v"in k||(l=k,l.$$v=r,l.then(function(a){l.$$v=a})),k=k.$$v);if(!c)return k;if(null==k)return r;(k=k[c])&&k.then&&(ra(g),"$$v"in k||(l=k,l.$$v=r,l.then(function(a){l.$$v=
a})),k=k.$$v);if(!d)return k;if(null==k)return r;(k=k[d])&&k.then&&(ra(g),"$$v"in k||(l=k,l.$$v=r,l.then(function(a){l.$$v=a})),k=k.$$v);if(!e)return k;if(null==k)return r;(k=k[e])&&k.then&&(ra(g),"$$v"in k||(l=k,l.$$v=r,l.then(function(a){l.$$v=a})),k=k.$$v);return k}:function(g,f){var k=f&&f.hasOwnProperty(b)?f:g;if(null==k)return k;k=k[b];if(!a)return k;if(null==k)return r;k=k[a];if(!c)return k;if(null==k)return r;k=k[c];if(!d)return k;if(null==k)return r;k=k[d];return e?null==k?r:k=k[e]:k}}function wd(b,
a){ea(b,a);return function(a,d){return null==a?r:(d&&d.hasOwnProperty(b)?d:a)[b]}}function xd(b,a,c){ea(b,c);ea(a,c);return function(c,e){if(null==c)return r;c=(e&&e.hasOwnProperty(b)?e:c)[b];return null==c?r:c[a]}}function xc(b,a,c){if(Kb.hasOwnProperty(b))return Kb[b];var d=b.split("."),e=d.length,g;if(a.unwrapPromises||1!==e)if(a.unwrapPromises||2!==e)if(a.csp)g=6>e?wc(d[0],d[1],d[2],d[3],d[4],c,a):function(b,g){var f=0,h;do h=wc(d[f++],d[f++],d[f++],d[f++],d[f++],c,a)(b,g),g=r,b=h;while(f<e);
return h};else{var f="var p;\n";q(d,function(b,d){ea(b,c);f+="if(s == null) return undefined;\ns="+(d?"s":'((k&&k.hasOwnProperty("'+b+'"))?k:s)')+'["'+b+'"];\n'+(a.unwrapPromises?'if (s && s.then) {\n pw("'+c.replace(/(["\r\n])/g,"\\$1")+'");\n if (!("$$v" in s)) {\n p=s;\n p.$$v = undefined;\n p.then(function(v) {p.$$v=v;});\n}\n s=s.$$v\n}\n':"")});var f=f+"return s;",h=new Function("s","k","pw",f);h.toString=$(f);g=a.unwrapPromises?function(a,b){return h(a,b,ra)}:h}else g=xd(d[0],d[1],c);else g=
wd(d[0],c);"hasOwnProperty"!==b&&(Kb[b]=g);return g}function yd(){var b={},a={csp:!1,unwrapPromises:!1,logPromiseWarnings:!0};this.unwrapPromises=function(b){return B(b)?(a.unwrapPromises=!!b,this):a.unwrapPromises};this.logPromiseWarnings=function(b){return B(b)?(a.logPromiseWarnings=b,this):a.logPromiseWarnings};this.$get=["$filter","$sniffer","$log",function(c,d,e){a.csp=d.csp;ra=function(b){a.logPromiseWarnings&&!yc.hasOwnProperty(b)&&(yc[b]=!0,e.warn("[$parse] Promise found in the expression `"+
b+"`. Automatic unwrapping of promises in Angular expressions is deprecated."))};return function(d){var e;switch(typeof d){case "string":if(b.hasOwnProperty(d))return b[d];e=new Lb(a);e=(new Za(e,c,a)).parse(d,!1);"hasOwnProperty"!==d&&(b[d]=e);return e;case "function":return d;default:return w}}}]}function zd(){this.$get=["$rootScope","$exceptionHandler",function(b,a){return Ad(function(a){b.$evalAsync(a)},a)}]}function Ad(b,a){function c(a){return a}function d(a){return f(a)}var e=function(){var h=
[],m,k;return k={resolve:function(a){if(h){var c=h;h=r;m=g(a);c.length&&b(function(){for(var a,b=0,d=c.length;b<d;b++)a=c[b],m.then(a[0],a[1],a[2])})}},reject:function(a){k.resolve(f(a))},notify:function(a){if(h){var c=h;h.length&&b(function(){for(var b,d=0,e=c.length;d<e;d++)b=c[d],b[2](a)})}},promise:{then:function(b,g,f){var k=e(),C=function(d){try{k.resolve((L(b)?b:c)(d))}catch(e){k.reject(e),a(e)}},y=function(b){try{k.resolve((L(g)?g:d)(b))}catch(c){k.reject(c),a(c)}},E=function(b){try{k.notify((L(f)?
f:c)(b))}catch(d){a(d)}};h?h.push([C,y,E]):m.then(C,y,E);return k.promise},"catch":function(a){return this.then(null,a)},"finally":function(a){function b(a,c){var d=e();c?d.resolve(a):d.reject(a);return d.promise}function d(e,g){var f=null;try{f=(a||c)()}catch(h){return b(h,!1)}return f&&L(f.then)?f.then(function(){return b(e,g)},function(a){return b(a,!1)}):b(e,g)}return this.then(function(a){return d(a,!0)},function(a){return d(a,!1)})}}}},g=function(a){return a&&L(a.then)?a:{then:function(c){var d=
e();b(function(){d.resolve(c(a))});return d.promise}}},f=function(c){return{then:function(g,f){var l=e();b(function(){try{l.resolve((L(f)?f:d)(c))}catch(b){l.reject(b),a(b)}});return l.promise}}};return{defer:e,reject:f,when:function(h,m,k,l){var n=e(),p,s=function(b){try{return(L(m)?m:c)(b)}catch(d){return a(d),f(d)}},C=function(b){try{return(L(k)?k:d)(b)}catch(c){return a(c),f(c)}},y=function(b){try{return(L(l)?l:c)(b)}catch(d){a(d)}};b(function(){g(h).then(function(a){p||(p=!0,n.resolve(g(a).then(s,
C,y)))},function(a){p||(p=!0,n.resolve(C(a)))},function(a){p||n.notify(y(a))})});return n.promise},all:function(a){var b=e(),c=0,d=K(a)?[]:{};q(a,function(a,e){c++;g(a).then(function(a){d.hasOwnProperty(e)||(d[e]=a,--c||b.resolve(d))},function(a){d.hasOwnProperty(e)||b.reject(a)})});0===c&&b.resolve(d);return b.promise}}}function Bd(){var b=10,a=F("$rootScope"),c=null;this.digestTtl=function(a){arguments.length&&(b=a);return b};this.$get=["$injector","$exceptionHandler","$parse","$browser",function(d,
e,g,f){function h(){this.$id=$a();this.$$phase=this.$parent=this.$$watchers=this.$$nextSibling=this.$$prevSibling=this.$$childHead=this.$$childTail=null;this["this"]=this.$root=this;this.$$destroyed=!1;this.$$asyncQueue=[];this.$$postDigestQueue=[];this.$$listeners={};this.$$listenerCount={};this.$$isolateBindings={}}function m(b){if(p.$$phase)throw a("inprog",p.$$phase);p.$$phase=b}function k(a,b){var c=g(a);Qa(c,b);return c}function l(a,b,c){do a.$$listenerCount[c]-=b,0===a.$$listenerCount[c]&&
delete a.$$listenerCount[c];while(a=a.$parent)}function n(){}h.prototype={constructor:h,$new:function(a){a?(a=new h,a.$root=this.$root,a.$$asyncQueue=this.$$asyncQueue,a.$$postDigestQueue=this.$$postDigestQueue):(a=function(){},a.prototype=this,a=new a,a.$id=$a());a["this"]=a;a.$$listeners={};a.$$listenerCount={};a.$parent=this;a.$$watchers=a.$$nextSibling=a.$$childHead=a.$$childTail=null;a.$$prevSibling=this.$$childTail;this.$$childHead?this.$$childTail=this.$$childTail.$$nextSibling=a:this.$$childHead=
this.$$childTail=a;return a},$watch:function(a,b,d){var e=k(a,"watch"),g=this.$$watchers,f={fn:b,last:n,get:e,exp:a,eq:!!d};c=null;if(!L(b)){var h=k(b||w,"listener");f.fn=function(a,b,c){h(c)}}if("string"==typeof a&&e.constant){var m=f.fn;f.fn=function(a,b,c){m.call(this,a,b,c);Na(g,f)}}g||(g=this.$$watchers=[]);g.unshift(f);return function(){Na(g,f);c=null}},$watchCollection:function(a,b){var c=this,d,e,f=0,h=g(a),m=[],k={},l=0;return this.$watch(function(){e=h(c);var a,b;if(X(e))if(rb(e))for(d!==
m&&(d=m,l=d.length=0,f++),a=e.length,l!==a&&(f++,d.length=l=a),b=0;b<a;b++)d[b]!==e[b]&&(f++,d[b]=e[b]);else{d!==k&&(d=k={},l=0,f++);a=0;for(b in e)e.hasOwnProperty(b)&&(a++,d.hasOwnProperty(b)?d[b]!==e[b]&&(f++,d[b]=e[b]):(l++,d[b]=e[b],f++));if(l>a)for(b in f++,d)d.hasOwnProperty(b)&&!e.hasOwnProperty(b)&&(l--,delete d[b])}else d!==e&&(d=e,f++);return f},function(){b(e,d,c)})},$digest:function(){var d,f,g,h,k=this.$$asyncQueue,l=this.$$postDigestQueue,q,v,r=b,N,V=[],J,A,P;m("$digest");c=null;do{v=
!1;for(N=this;k.length;){try{P=k.shift(),P.scope.$eval(P.expression)}catch(B){p.$$phase=null,e(B)}c=null}a:do{if(h=N.$$watchers)for(q=h.length;q--;)try{if(d=h[q])if((f=d.get(N))!==(g=d.last)&&!(d.eq?ua(f,g):"number"==typeof f&&"number"==typeof g&&isNaN(f)&&isNaN(g)))v=!0,c=d,d.last=d.eq?aa(f):f,d.fn(f,g===n?f:g,N),5>r&&(J=4-r,V[J]||(V[J]=[]),A=L(d.exp)?"fn: "+(d.exp.name||d.exp.toString()):d.exp,A+="; newVal: "+qa(f)+"; oldVal: "+qa(g),V[J].push(A));else if(d===c){v=!1;break a}}catch(t){p.$$phase=
null,e(t)}if(!(h=N.$$childHead||N!==this&&N.$$nextSibling))for(;N!==this&&!(h=N.$$nextSibling);)N=N.$parent}while(N=h);if((v||k.length)&&!r--)throw p.$$phase=null,a("infdig",b,qa(V));}while(v||k.length);for(p.$$phase=null;l.length;)try{l.shift()()}catch(z){e(z)}},$destroy:function(){if(!this.$$destroyed){var a=this.$parent;this.$broadcast("$destroy");this.$$destroyed=!0;this!==p&&(q(this.$$listenerCount,cb(null,l,this)),a.$$childHead==this&&(a.$$childHead=this.$$nextSibling),a.$$childTail==this&&
(a.$$childTail=this.$$prevSibling),this.$$prevSibling&&(this.$$prevSibling.$$nextSibling=this.$$nextSibling),this.$$nextSibling&&(this.$$nextSibling.$$prevSibling=this.$$prevSibling),this.$parent=this.$$nextSibling=this.$$prevSibling=this.$$childHead=this.$$childTail=null)}},$eval:function(a,b){return g(a)(this,b)},$evalAsync:function(a){p.$$phase||p.$$asyncQueue.length||f.defer(function(){p.$$asyncQueue.length&&p.$digest()});this.$$asyncQueue.push({scope:this,expression:a})},$$postDigest:function(a){this.$$postDigestQueue.push(a)},
$apply:function(a){try{return m("$apply"),this.$eval(a)}catch(b){e(b)}finally{p.$$phase=null;try{p.$digest()}catch(c){throw e(c),c;}}},$on:function(a,b){var c=this.$$listeners[a];c||(this.$$listeners[a]=c=[]);c.push(b);var d=this;do d.$$listenerCount[a]||(d.$$listenerCount[a]=0),d.$$listenerCount[a]++;while(d=d.$parent);var e=this;return function(){c[bb(c,b)]=null;l(e,1,a)}},$emit:function(a,b){var c=[],d,f=this,g=!1,h={name:a,targetScope:f,stopPropagation:function(){g=!0},preventDefault:function(){h.defaultPrevented=
!0},defaultPrevented:!1},m=[h].concat(va.call(arguments,1)),k,l;do{d=f.$$listeners[a]||c;h.currentScope=f;k=0;for(l=d.length;k<l;k++)if(d[k])try{d[k].apply(null,m)}catch(p){e(p)}else d.splice(k,1),k--,l--;if(g)break;f=f.$parent}while(f);return h},$broadcast:function(a,b){for(var c=this,d=this,f={name:a,targetScope:this,preventDefault:function(){f.defaultPrevented=!0},defaultPrevented:!1},g=[f].concat(va.call(arguments,1)),h,k;c=d;){f.currentScope=c;d=c.$$listeners[a]||[];h=0;for(k=d.length;h<k;h++)if(d[h])try{d[h].apply(null,
g)}catch(m){e(m)}else d.splice(h,1),h--,k--;if(!(d=c.$$listenerCount[a]&&c.$$childHead||c!==this&&c.$$nextSibling))for(;c!==this&&!(d=c.$$nextSibling);)c=c.$parent}return f}};var p=new h;return p}]}function Cd(){var b=/^\s*(https?|ftp|mailto|tel|file):/,a=/^\s*(https?|ftp|file):|data:image\//;this.aHrefSanitizationWhitelist=function(a){return B(a)?(b=a,this):b};this.imgSrcSanitizationWhitelist=function(b){return B(b)?(a=b,this):a};this.$get=function(){return function(c,d){var e=d?a:b,g;if(!M||8<=
M)if(g=ya(c).href,""!==g&&!g.match(e))return"unsafe:"+g;return c}}}function Dd(b){if("self"===b)return b;if(D(b)){if(-1<b.indexOf("***"))throw sa("iwcard",b);b=b.replace(/([-()\[\]{}+?*.$\^|,:#<!\\])/g,"\\$1").replace(/\x08/g,"\\x08").replace("\\*\\*",".*").replace("\\*","[^:/.?&;]*");return RegExp("^"+b+"$")}if(ab(b))return RegExp("^"+b.source+"$");throw sa("imatcher");}function zc(b){var a=[];B(b)&&q(b,function(b){a.push(Dd(b))});return a}function Ed(){this.SCE_CONTEXTS=fa;var b=["self"],a=[];this.resourceUrlWhitelist=
function(a){arguments.length&&(b=zc(a));return b};this.resourceUrlBlacklist=function(b){arguments.length&&(a=zc(b));return a};this.$get=["$injector",function(c){function d(a){var b=function(a){this.$$unwrapTrustedValue=function(){return a}};a&&(b.prototype=new a);b.prototype.valueOf=function(){return this.$$unwrapTrustedValue()};b.prototype.toString=function(){return this.$$unwrapTrustedValue().toString()};return b}var e=function(a){throw sa("unsafe");};c.has("$sanitize")&&(e=c.get("$sanitize"));
var g=d(),f={};f[fa.HTML]=d(g);f[fa.CSS]=d(g);f[fa.URL]=d(g);f[fa.JS]=d(g);f[fa.RESOURCE_URL]=d(f[fa.URL]);return{trustAs:function(a,b){var c=f.hasOwnProperty(a)?f[a]:null;if(!c)throw sa("icontext",a,b);if(null===b||b===r||""===b)return b;if("string"!==typeof b)throw sa("itype",a);return new c(b)},getTrusted:function(c,d){if(null===d||d===r||""===d)return d;var g=f.hasOwnProperty(c)?f[c]:null;if(g&&d instanceof g)return d.$$unwrapTrustedValue();if(c===fa.RESOURCE_URL){var g=ya(d.toString()),l,n,p=
!1;l=0;for(n=b.length;l<n;l++)if("self"===b[l]?Gb(g):b[l].exec(g.href)){p=!0;break}if(p)for(l=0,n=a.length;l<n;l++)if("self"===a[l]?Gb(g):a[l].exec(g.href)){p=!1;break}if(p)return d;throw sa("insecurl",d.toString());}if(c===fa.HTML)return e(d);throw sa("unsafe");},valueOf:function(a){return a instanceof g?a.$$unwrapTrustedValue():a}}}]}function Fd(){var b=!0;this.enabled=function(a){arguments.length&&(b=!!a);return b};this.$get=["$parse","$sniffer","$sceDelegate",function(a,c,d){if(b&&c.msie&&8>c.msieDocumentMode)throw sa("iequirks");
var e=aa(fa);e.isEnabled=function(){return b};e.trustAs=d.trustAs;e.getTrusted=d.getTrusted;e.valueOf=d.valueOf;b||(e.trustAs=e.getTrusted=function(a,b){return b},e.valueOf=Ba);e.parseAs=function(b,c){var d=a(c);return d.literal&&d.constant?d:function(a,c){return e.getTrusted(b,d(a,c))}};var g=e.parseAs,f=e.getTrusted,h=e.trustAs;q(fa,function(a,b){var c=x(b);e[Ra("parse_as_"+c)]=function(b){return g(a,b)};e[Ra("get_trusted_"+c)]=function(b){return f(a,b)};e[Ra("trust_as_"+c)]=function(b){return h(a,
b)}});return e}]}function Gd(){this.$get=["$window","$document",function(b,a){var c={},d=S((/android (\d+)/.exec(x((b.navigator||{}).userAgent))||[])[1]),e=/Boxee/i.test((b.navigator||{}).userAgent),g=a[0]||{},f=g.documentMode,h,m=/^(Moz|webkit|O|ms)(?=[A-Z])/,k=g.body&&g.body.style,l=!1,n=!1;if(k){for(var p in k)if(l=m.exec(p)){h=l[0];h=h.substr(0,1).toUpperCase()+h.substr(1);break}h||(h="WebkitOpacity"in k&&"webkit");l=!!("transition"in k||h+"Transition"in k);n=!!("animation"in k||h+"Animation"in
k);!d||l&&n||(l=D(g.body.style.webkitTransition),n=D(g.body.style.webkitAnimation))}return{history:!(!b.history||!b.history.pushState||4>d||e),hashchange:"onhashchange"in b&&(!f||7<f),hasEvent:function(a){if("input"==a&&9==M)return!1;if(z(c[a])){var b=g.createElement("div");c[a]="on"+a in b}return c[a]},csp:Ub(),vendorPrefix:h,transitions:l,animations:n,android:d,msie:M,msieDocumentMode:f}}]}function Hd(){this.$get=["$rootScope","$browser","$q","$exceptionHandler",function(b,a,c,d){function e(e,h,
m){var k=c.defer(),l=k.promise,n=B(m)&&!m;h=a.defer(function(){try{k.resolve(e())}catch(a){k.reject(a),d(a)}finally{delete g[l.$$timeoutId]}n||b.$apply()},h);l.$$timeoutId=h;g[h]=k;return l}var g={};e.cancel=function(b){return b&&b.$$timeoutId in g?(g[b.$$timeoutId].reject("canceled"),delete g[b.$$timeoutId],a.defer.cancel(b.$$timeoutId)):!1};return e}]}function ya(b,a){var c=b;M&&(Y.setAttribute("href",c),c=Y.href);Y.setAttribute("href",c);return{href:Y.href,protocol:Y.protocol?Y.protocol.replace(/:$/,
""):"",host:Y.host,search:Y.search?Y.search.replace(/^\?/,""):"",hash:Y.hash?Y.hash.replace(/^#/,""):"",hostname:Y.hostname,port:Y.port,pathname:"/"===Y.pathname.charAt(0)?Y.pathname:"/"+Y.pathname}}function Gb(b){b=D(b)?ya(b):b;return b.protocol===Ac.protocol&&b.host===Ac.host}function Id(){this.$get=$(Z)}function Bc(b){function a(d,e){if(X(d)){var g={};q(d,function(b,c){g[c]=a(c,b)});return g}return b.factory(d+c,e)}var c="Filter";this.register=a;this.$get=["$injector",function(a){return function(b){return a.get(b+
c)}}];a("currency",Cc);a("date",Dc);a("filter",Jd);a("json",Kd);a("limitTo",Ld);a("lowercase",Md);a("number",Ec);a("orderBy",Fc);a("uppercase",Nd)}function Jd(){return function(b,a,c){if(!K(b))return b;var d=typeof c,e=[];e.check=function(a){for(var b=0;b<e.length;b++)if(!e[b](a))return!1;return!0};"function"!==d&&(c="boolean"===d&&c?function(a,b){return Ca.equals(a,b)}:function(a,b){b=(""+b).toLowerCase();return-1<(""+a).toLowerCase().indexOf(b)});var g=function(a,b){if("string"==typeof b&&"!"===
b.charAt(0))return!g(a,b.substr(1));switch(typeof a){case "boolean":case "number":case "string":return c(a,b);case "object":switch(typeof b){case "object":return c(a,b);default:for(var d in a)if("$"!==d.charAt(0)&&g(a[d],b))return!0}return!1;case "array":for(d=0;d<a.length;d++)if(g(a[d],b))return!0;return!1;default:return!1}};switch(typeof a){case "boolean":case "number":case "string":a={$:a};case "object":for(var f in a)(function(b){"undefined"!=typeof a[b]&&e.push(function(c){return g("$"==b?c:
vb(c,b),a[b])})})(f);break;case "function":e.push(a);break;default:return b}d=[];for(f=0;f<b.length;f++){var h=b[f];e.check(h)&&d.push(h)}return d}}function Cc(b){var a=b.NUMBER_FORMATS;return function(b,d){z(d)&&(d=a.CURRENCY_SYM);return Gc(b,a.PATTERNS[1],a.GROUP_SEP,a.DECIMAL_SEP,2).replace(/\u00A4/g,d)}}function Ec(b){var a=b.NUMBER_FORMATS;return function(b,d){return Gc(b,a.PATTERNS[0],a.GROUP_SEP,a.DECIMAL_SEP,d)}}function Gc(b,a,c,d,e){if(isNaN(b)||!isFinite(b))return"";var g=0>b;b=Math.abs(b);
var f=b+"",h="",m=[],k=!1;if(-1!==f.indexOf("e")){var l=f.match(/([\d\.]+)e(-?)(\d+)/);l&&"-"==l[2]&&l[3]>e+1?f="0":(h=f,k=!0)}if(k)0<e&&(-1<b&&1>b)&&(h=b.toFixed(e));else{f=(f.split(Hc)[1]||"").length;z(e)&&(e=Math.min(Math.max(a.minFrac,f),a.maxFrac));f=Math.pow(10,e);b=Math.round(b*f)/f;b=(""+b).split(Hc);f=b[0];b=b[1]||"";var l=0,n=a.lgSize,p=a.gSize;if(f.length>=n+p)for(l=f.length-n,k=0;k<l;k++)0===(l-k)%p&&0!==k&&(h+=c),h+=f.charAt(k);for(k=l;k<f.length;k++)0===(f.length-k)%n&&0!==k&&(h+=c),
h+=f.charAt(k);for(;b.length<e;)b+="0";e&&"0"!==e&&(h+=d+b.substr(0,e))}m.push(g?a.negPre:a.posPre);m.push(h);m.push(g?a.negSuf:a.posSuf);return m.join("")}function Mb(b,a,c){var d="";0>b&&(d="-",b=-b);for(b=""+b;b.length<a;)b="0"+b;c&&(b=b.substr(b.length-a));return d+b}function W(b,a,c,d){c=c||0;return function(e){e=e["get"+b]();if(0<c||e>-c)e+=c;0===e&&-12==c&&(e=12);return Mb(e,a,d)}}function lb(b,a){return function(c,d){var e=c["get"+b](),g=Ia(a?"SHORT"+b:b);return d[g][e]}}function Dc(b){function a(a){var b;
if(b=a.match(c)){a=new Date(0);var g=0,f=0,h=b[8]?a.setUTCFullYear:a.setFullYear,m=b[8]?a.setUTCHours:a.setHours;b[9]&&(g=S(b[9]+b[10]),f=S(b[9]+b[11]));h.call(a,S(b[1]),S(b[2])-1,S(b[3]));g=S(b[4]||0)-g;f=S(b[5]||0)-f;h=S(b[6]||0);b=Math.round(1E3*parseFloat("0."+(b[7]||0)));m.call(a,g,f,h,b)}return a}var c=/^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(Z|([+-])(\d\d):?(\d\d))?)?$/;return function(c,e){var g="",f=[],h,m;e=e||"mediumDate";e=b.DATETIME_FORMATS[e]||e;D(c)&&
(c=Od.test(c)?S(c):a(c));sb(c)&&(c=new Date(c));if(!La(c))return c;for(;e;)(m=Pd.exec(e))?(f=f.concat(va.call(m,1)),e=f.pop()):(f.push(e),e=null);q(f,function(a){h=Qd[a];g+=h?h(c,b.DATETIME_FORMATS):a.replace(/(^'|'$)/g,"").replace(/''/g,"'")});return g}}function Kd(){return function(b){return qa(b,!0)}}function Ld(){return function(b,a){if(!K(b)&&!D(b))return b;a=S(a);if(D(b))return a?0<=a?b.slice(0,a):b.slice(a,b.length):"";var c=[],d,e;a>b.length?a=b.length:a<-b.length&&(a=-b.length);0<a?(d=0,
e=a):(d=b.length+a,e=b.length);for(;d<e;d++)c.push(b[d]);return c}}function Fc(b){return function(a,c,d){function e(a,b){return Pa(b)?function(b,c){return a(c,b)}:a}if(!K(a)||!c)return a;c=K(c)?c:[c];c=Rc(c,function(a){var c=!1,d=a||Ba;if(D(a)){if("+"==a.charAt(0)||"-"==a.charAt(0))c="-"==a.charAt(0),a=a.substring(1);d=b(a)}return e(function(a,b){var c;c=d(a);var e=d(b),g=typeof c,f=typeof e;g==f?("string"==g&&(c=c.toLowerCase(),e=e.toLowerCase()),c=c===e?0:c<e?-1:1):c=g<f?-1:1;return c},c)});for(var g=
[],f=0;f<a.length;f++)g.push(a[f]);return g.sort(e(function(a,b){for(var d=0;d<c.length;d++){var e=c[d](a,b);if(0!==e)return e}return 0},d))}}function ta(b){L(b)&&(b={link:b});b.restrict=b.restrict||"AC";return $(b)}function Ic(b,a){function c(a,c){c=c?"-"+db(c,"-"):"";b.removeClass((a?mb:nb)+c).addClass((a?nb:mb)+c)}var d=this,e=b.parent().controller("form")||ob,g=0,f=d.$error={},h=[];d.$name=a.name||a.ngForm;d.$dirty=!1;d.$pristine=!0;d.$valid=!0;d.$invalid=!1;e.$addControl(d);b.addClass(Ja);c(!0);
d.$addControl=function(a){xa(a.$name,"input");h.push(a);a.$name&&(d[a.$name]=a)};d.$removeControl=function(a){a.$name&&d[a.$name]===a&&delete d[a.$name];q(f,function(b,c){d.$setValidity(c,!0,a)});Na(h,a)};d.$setValidity=function(a,b,h){var n=f[a];if(b)n&&(Na(n,h),n.length||(g--,g||(c(b),d.$valid=!0,d.$invalid=!1),f[a]=!1,c(!0,a),e.$setValidity(a,!0,d)));else{g||c(b);if(n){if(-1!=bb(n,h))return}else f[a]=n=[],g++,c(!1,a),e.$setValidity(a,!1,d);n.push(h);d.$valid=!1;d.$invalid=!0}};d.$setDirty=function(){b.removeClass(Ja).addClass(pb);
d.$dirty=!0;d.$pristine=!1;e.$setDirty()};d.$setPristine=function(){b.removeClass(pb).addClass(Ja);d.$dirty=!1;d.$pristine=!0;q(h,function(a){a.$setPristine()})}}function pa(b,a,c,d){b.$setValidity(a,c);return c?d:r}function qb(b,a,c,d,e,g){if(!e.android){var f=!1;a.on("compositionstart",function(a){f=!0});a.on("compositionend",function(){f=!1})}var h=function(){if(!f){var e=a.val();Pa(c.ngTrim||"T")&&(e=ba(e));d.$viewValue!==e&&(b.$$phase?d.$setViewValue(e):b.$apply(function(){d.$setViewValue(e)}))}};
if(e.hasEvent("input"))a.on("input",h);else{var m,k=function(){m||(m=g.defer(function(){h();m=null}))};a.on("keydown",function(a){a=a.keyCode;91===a||(15<a&&19>a||37<=a&&40>=a)||k()});if(e.hasEvent("paste"))a.on("paste cut",k)}a.on("change",h);d.$render=function(){a.val(d.$isEmpty(d.$viewValue)?"":d.$viewValue)};var l=c.ngPattern;l&&((e=l.match(/^\/(.*)\/([gim]*)$/))?(l=RegExp(e[1],e[2]),e=function(a){return pa(d,"pattern",d.$isEmpty(a)||l.test(a),a)}):e=function(c){var e=b.$eval(l);if(!e||!e.test)throw F("ngPattern")("noregexp",
l,e,ga(a));return pa(d,"pattern",d.$isEmpty(c)||e.test(c),c)},d.$formatters.push(e),d.$parsers.push(e));if(c.ngMinlength){var n=S(c.ngMinlength);e=function(a){return pa(d,"minlength",d.$isEmpty(a)||a.length>=n,a)};d.$parsers.push(e);d.$formatters.push(e)}if(c.ngMaxlength){var p=S(c.ngMaxlength);e=function(a){return pa(d,"maxlength",d.$isEmpty(a)||a.length<=p,a)};d.$parsers.push(e);d.$formatters.push(e)}}function Nb(b,a){b="ngClass"+b;return function(){return{restrict:"AC",link:function(c,d,e){function g(b){if(!0===
a||c.$index%2===a){var d=f(b||"");h?ua(b,h)||e.$updateClass(d,f(h)):e.$addClass(d)}h=aa(b)}function f(a){if(K(a))return a.join(" ");if(X(a)){var b=[];q(a,function(a,c){a&&b.push(c)});return b.join(" ")}return a}var h;c.$watch(e[b],g,!0);e.$observe("class",function(a){g(c.$eval(e[b]))});"ngClass"!==b&&c.$watch("$index",function(d,g){var h=d&1;if(h!==g&1){var n=f(c.$eval(e[b]));h===a?e.$addClass(n):e.$removeClass(n)}})}}}}var x=function(b){return D(b)?b.toLowerCase():b},Ia=function(b){return D(b)?b.toUpperCase():
b},M,A,Da,va=[].slice,Rd=[].push,Ma=Object.prototype.toString,Oa=F("ng"),Ca=Z.angular||(Z.angular={}),Va,Ha,ka=["0","0","0"];M=S((/msie (\d+)/.exec(x(navigator.userAgent))||[])[1]);isNaN(M)&&(M=S((/trident\/.*; rv:(\d+)/.exec(x(navigator.userAgent))||[])[1]));w.$inject=[];Ba.$inject=[];var ba=function(){return String.prototype.trim?function(b){return D(b)?b.trim():b}:function(b){return D(b)?b.replace(/^\s\s*/,"").replace(/\s\s*$/,""):b}}();Ha=9>M?function(b){b=b.nodeName?b:b[0];return b.scopeName&&
"HTML"!=b.scopeName?Ia(b.scopeName+":"+b.nodeName):b.nodeName}:function(b){return b.nodeName?b.nodeName:b[0].nodeName};var Uc=/[A-Z]/g,Sd={full:"1.2.10",major:1,minor:2,dot:10,codeName:"augmented-serendipity"},Sa=O.cache={},eb=O.expando="ng-"+(new Date).getTime(),Yc=1,Jc=Z.document.addEventListener?function(b,a,c){b.addEventListener(a,c,!1)}:function(b,a,c){b.attachEvent("on"+a,c)},Bb=Z.document.removeEventListener?function(b,a,c){b.removeEventListener(a,c,!1)}:function(b,a,c){b.detachEvent("on"+
a,c)},Wc=/([\:\-\_]+(.))/g,Xc=/^moz([A-Z])/,yb=F("jqLite"),Ga=O.prototype={ready:function(b){function a(){c||(c=!0,b())}var c=!1;"complete"===Q.readyState?setTimeout(a):(this.on("DOMContentLoaded",a),O(Z).on("load",a))},toString:function(){var b=[];q(this,function(a){b.push(""+a)});return"["+b.join(", ")+"]"},eq:function(b){return 0<=b?A(this[b]):A(this[this.length+b])},length:0,push:Rd,sort:[].sort,splice:[].splice},gb={};q("multiple selected checked disabled readOnly required open".split(" "),function(b){gb[x(b)]=
b});var gc={};q("input select option textarea button form details".split(" "),function(b){gc[Ia(b)]=!0});q({data:cc,inheritedData:fb,scope:function(b){return A(b).data("$scope")||fb(b.parentNode||b,["$isolateScope","$scope"])},isolateScope:function(b){return A(b).data("$isolateScope")||A(b).data("$isolateScopeNoTemplate")},controller:dc,injector:function(b){return fb(b,"$injector")},removeAttr:function(b,a){b.removeAttribute(a)},hasClass:Cb,css:function(b,a,c){a=Ra(a);if(B(c))b.style[a]=c;else{var d;
8>=M&&(d=b.currentStyle&&b.currentStyle[a],""===d&&(d="auto"));d=d||b.style[a];8>=M&&(d=""===d?r:d);return d}},attr:function(b,a,c){var d=x(a);if(gb[d])if(B(c))c?(b[a]=!0,b.setAttribute(a,d)):(b[a]=!1,b.removeAttribute(d));else return b[a]||(b.attributes.getNamedItem(a)||w).specified?d:r;else if(B(c))b.setAttribute(a,c);else if(b.getAttribute)return b=b.getAttribute(a,2),null===b?r:b},prop:function(b,a,c){if(B(c))b[a]=c;else return b[a]},text:function(){function b(b,d){var e=a[b.nodeType];if(z(d))return e?
b[e]:"";b[e]=d}var a=[];9>M?(a[1]="innerText",a[3]="nodeValue"):a[1]=a[3]="textContent";b.$dv="";return b}(),val:function(b,a){if(z(a)){if("SELECT"===Ha(b)&&b.multiple){var c=[];q(b.options,function(a){a.selected&&c.push(a.value||a.text)});return 0===c.length?null:c}return b.value}b.value=a},html:function(b,a){if(z(a))return b.innerHTML;for(var c=0,d=b.childNodes;c<d.length;c++)Ea(d[c]);b.innerHTML=a},empty:ec},function(b,a){O.prototype[a]=function(a,d){var e,g;if(b!==ec&&(2==b.length&&b!==Cb&&b!==
dc?a:d)===r){if(X(a)){for(e=0;e<this.length;e++)if(b===cc)b(this[e],a);else for(g in a)b(this[e],g,a[g]);return this}e=b.$dv;g=e===r?Math.min(this.length,1):this.length;for(var f=0;f<g;f++){var h=b(this[f],a,d);e=e?e+h:h}return e}for(e=0;e<this.length;e++)b(this[e],a,d);return this}});q({removeData:ac,dealoc:Ea,on:function a(c,d,e,g){if(B(g))throw yb("onargs");var f=la(c,"events"),h=la(c,"handle");f||la(c,"events",f={});h||la(c,"handle",h=Zc(c,f));q(d.split(" "),function(d){var g=f[d];if(!g){if("mouseenter"==
d||"mouseleave"==d){var l=Q.body.contains||Q.body.compareDocumentPosition?function(a,c){var d=9===a.nodeType?a.documentElement:a,e=c&&c.parentNode;return a===e||!!(e&&1===e.nodeType&&(d.contains?d.contains(e):a.compareDocumentPosition&&a.compareDocumentPosition(e)&16))}:function(a,c){if(c)for(;c=c.parentNode;)if(c===a)return!0;return!1};f[d]=[];a(c,{mouseleave:"mouseout",mouseenter:"mouseover"}[d],function(a){var c=a.relatedTarget;c&&(c===this||l(this,c))||h(a,d)})}else Jc(c,d,h),f[d]=[];g=f[d]}g.push(e)})},
off:bc,one:function(a,c,d){a=A(a);a.on(c,function g(){a.off(c,d);a.off(c,g)});a.on(c,d)},replaceWith:function(a,c){var d,e=a.parentNode;Ea(a);q(new O(c),function(c){d?e.insertBefore(c,d.nextSibling):e.replaceChild(c,a);d=c})},children:function(a){var c=[];q(a.childNodes,function(a){1===a.nodeType&&c.push(a)});return c},contents:function(a){return a.childNodes||[]},append:function(a,c){q(new O(c),function(c){1!==a.nodeType&&11!==a.nodeType||a.appendChild(c)})},prepend:function(a,c){if(1===a.nodeType){var d=
a.firstChild;q(new O(c),function(c){a.insertBefore(c,d)})}},wrap:function(a,c){c=A(c)[0];var d=a.parentNode;d&&d.replaceChild(c,a);c.appendChild(a)},remove:function(a){Ea(a);var c=a.parentNode;c&&c.removeChild(a)},after:function(a,c){var d=a,e=a.parentNode;q(new O(c),function(a){e.insertBefore(a,d.nextSibling);d=a})},addClass:Eb,removeClass:Db,toggleClass:function(a,c,d){z(d)&&(d=!Cb(a,c));(d?Eb:Db)(a,c)},parent:function(a){return(a=a.parentNode)&&11!==a.nodeType?a:null},next:function(a){if(a.nextElementSibling)return a.nextElementSibling;
for(a=a.nextSibling;null!=a&&1!==a.nodeType;)a=a.nextSibling;return a},find:function(a,c){return a.getElementsByTagName?a.getElementsByTagName(c):[]},clone:Ab,triggerHandler:function(a,c,d){c=(la(a,"events")||{})[c];d=d||[];var e=[{preventDefault:w,stopPropagation:w}];q(c,function(c){c.apply(a,e.concat(d))})}},function(a,c){O.prototype[c]=function(c,e,g){for(var f,h=0;h<this.length;h++)z(f)?(f=a(this[h],c,e,g),B(f)&&(f=A(f))):zb(f,a(this[h],c,e,g));return B(f)?f:this};O.prototype.bind=O.prototype.on;
O.prototype.unbind=O.prototype.off});Ta.prototype={put:function(a,c){this[Fa(a)]=c},get:function(a){return this[Fa(a)]},remove:function(a){var c=this[a=Fa(a)];delete this[a];return c}};var ad=/^function\s*[^\(]*\(\s*([^\)]*)\)/m,bd=/,/,cd=/^\s*(_?)(\S+?)\1\s*$/,$c=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg,Ua=F("$injector"),Td=F("$animate"),Ud=["$provide",function(a){this.$$selectors={};this.register=function(c,d){var e=c+"-animation";if(c&&"."!=c.charAt(0))throw Td("notcsel",c);this.$$selectors[c.substr(1)]=
e;a.factory(e,d)};this.classNameFilter=function(a){1===arguments.length&&(this.$$classNameFilter=a instanceof RegExp?a:null);return this.$$classNameFilter};this.$get=["$timeout",function(a){return{enter:function(d,e,g,f){g?g.after(d):(e&&e[0]||(e=g.parent()),e.append(d));f&&a(f,0,!1)},leave:function(d,e){d.remove();e&&a(e,0,!1)},move:function(a,c,g,f){this.enter(a,c,g,f)},addClass:function(d,e,g){e=D(e)?e:K(e)?e.join(" "):"";q(d,function(a){Eb(a,e)});g&&a(g,0,!1)},removeClass:function(d,e,g){e=D(e)?
e:K(e)?e.join(" "):"";q(d,function(a){Db(a,e)});g&&a(g,0,!1)},enabled:w}}]}],ja=F("$compile");jc.$inject=["$provide","$$sanitizeUriProvider"];var id=/^(x[\:\-_]|data[\:\-_])/i,pc=F("$interpolate"),Vd=/^([^\?#]*)(\?([^#]*))?(#(.*))?$/,td={http:80,https:443,ftp:21},Ib=F("$location");uc.prototype=Jb.prototype=tc.prototype={$$html5:!1,$$replace:!1,absUrl:jb("$$absUrl"),url:function(a,c){if(z(a))return this.$$url;var d=Vd.exec(a);d[1]&&this.path(decodeURIComponent(d[1]));(d[2]||d[1])&&this.search(d[3]||
"");this.hash(d[5]||"",c);return this},protocol:jb("$$protocol"),host:jb("$$host"),port:jb("$$port"),path:vc("$$path",function(a){return"/"==a.charAt(0)?a:"/"+a}),search:function(a,c){switch(arguments.length){case 0:return this.$$search;case 1:if(D(a))this.$$search=Xb(a);else if(X(a))this.$$search=a;else throw Ib("isrcharg");break;default:z(c)||null===c?delete this.$$search[a]:this.$$search[a]=c}this.$$compose();return this},hash:vc("$$hash",Ba),replace:function(){this.$$replace=!0;return this}};
var za=F("$parse"),yc={},ra,Ka={"null":function(){return null},"true":function(){return!0},"false":function(){return!1},undefined:w,"+":function(a,c,d,e){d=d(a,c);e=e(a,c);return B(d)?B(e)?d+e:d:B(e)?e:r},"-":function(a,c,d,e){d=d(a,c);e=e(a,c);return(B(d)?d:0)-(B(e)?e:0)},"*":function(a,c,d,e){return d(a,c)*e(a,c)},"/":function(a,c,d,e){return d(a,c)/e(a,c)},"%":function(a,c,d,e){return d(a,c)%e(a,c)},"^":function(a,c,d,e){return d(a,c)^e(a,c)},"=":w,"===":function(a,c,d,e){return d(a,c)===e(a,c)},
"!==":function(a,c,d,e){return d(a,c)!==e(a,c)},"==":function(a,c,d,e){return d(a,c)==e(a,c)},"!=":function(a,c,d,e){return d(a,c)!=e(a,c)},"<":function(a,c,d,e){return d(a,c)<e(a,c)},">":function(a,c,d,e){return d(a,c)>e(a,c)},"<=":function(a,c,d,e){return d(a,c)<=e(a,c)},">=":function(a,c,d,e){return d(a,c)>=e(a,c)},"&&":function(a,c,d,e){return d(a,c)&&e(a,c)},"||":function(a,c,d,e){return d(a,c)||e(a,c)},"&":function(a,c,d,e){return d(a,c)&e(a,c)},"|":function(a,c,d,e){return e(a,c)(a,c,d(a,c))},
"!":function(a,c,d){return!d(a,c)}},Wd={n:"\n",f:"\f",r:"\r",t:"\t",v:"\v","'":"'",'"':'"'},Lb=function(a){this.options=a};Lb.prototype={constructor:Lb,lex:function(a){this.text=a;this.index=0;this.ch=r;this.lastCh=":";this.tokens=[];var c;for(a=[];this.index<this.text.length;){this.ch=this.text.charAt(this.index);if(this.is("\"'"))this.readString(this.ch);else if(this.isNumber(this.ch)||this.is(".")&&this.isNumber(this.peek()))this.readNumber();else if(this.isIdent(this.ch))this.readIdent(),this.was("{,")&&
("{"===a[0]&&(c=this.tokens[this.tokens.length-1]))&&(c.json=-1===c.text.indexOf("."));else if(this.is("(){}[].,;:?"))this.tokens.push({index:this.index,text:this.ch,json:this.was(":[,")&&this.is("{[")||this.is("}]:,")}),this.is("{[")&&a.unshift(this.ch),this.is("}]")&&a.shift(),this.index++;else if(this.isWhitespace(this.ch)){this.index++;continue}else{var d=this.ch+this.peek(),e=d+this.peek(2),g=Ka[this.ch],f=Ka[d],h=Ka[e];h?(this.tokens.push({index:this.index,text:e,fn:h}),this.index+=3):f?(this.tokens.push({index:this.index,
text:d,fn:f}),this.index+=2):g?(this.tokens.push({index:this.index,text:this.ch,fn:g,json:this.was("[,:")&&this.is("+-")}),this.index+=1):this.throwError("Unexpected next character ",this.index,this.index+1)}this.lastCh=this.ch}return this.tokens},is:function(a){return-1!==a.indexOf(this.ch)},was:function(a){return-1!==a.indexOf(this.lastCh)},peek:function(a){a=a||1;return this.index+a<this.text.length?this.text.charAt(this.index+a):!1},isNumber:function(a){return"0"<=a&&"9">=a},isWhitespace:function(a){return" "===
a||"\r"===a||"\t"===a||"\n"===a||"\v"===a||"\u00a0"===a},isIdent:function(a){return"a"<=a&&"z">=a||"A"<=a&&"Z">=a||"_"===a||"$"===a},isExpOperator:function(a){return"-"===a||"+"===a||this.isNumber(a)},throwError:function(a,c,d){d=d||this.index;c=B(c)?"s "+c+"-"+this.index+" ["+this.text.substring(c,d)+"]":" "+d;throw za("lexerr",a,c,this.text);},readNumber:function(){for(var a="",c=this.index;this.index<this.text.length;){var d=x(this.text.charAt(this.index));if("."==d||this.isNumber(d))a+=d;else{var e=
this.peek();if("e"==d&&this.isExpOperator(e))a+=d;else if(this.isExpOperator(d)&&e&&this.isNumber(e)&&"e"==a.charAt(a.length-1))a+=d;else if(!this.isExpOperator(d)||e&&this.isNumber(e)||"e"!=a.charAt(a.length-1))break;else this.throwError("Invalid exponent")}this.index++}a*=1;this.tokens.push({index:c,text:a,json:!0,fn:function(){return a}})},readIdent:function(){for(var a=this,c="",d=this.index,e,g,f,h;this.index<this.text.length;){h=this.text.charAt(this.index);if("."===h||this.isIdent(h)||this.isNumber(h))"."===
h&&(e=this.index),c+=h;else break;this.index++}if(e)for(g=this.index;g<this.text.length;){h=this.text.charAt(g);if("("===h){f=c.substr(e-d+1);c=c.substr(0,e-d);this.index=g;break}if(this.isWhitespace(h))g++;else break}d={index:d,text:c};if(Ka.hasOwnProperty(c))d.fn=Ka[c],d.json=Ka[c];else{var m=xc(c,this.options,this.text);d.fn=t(function(a,c){return m(a,c)},{assign:function(d,e){return kb(d,c,e,a.text,a.options)}})}this.tokens.push(d);f&&(this.tokens.push({index:e,text:".",json:!1}),this.tokens.push({index:e+
1,text:f,json:!1}))},readString:function(a){var c=this.index;this.index++;for(var d="",e=a,g=!1;this.index<this.text.length;){var f=this.text.charAt(this.index),e=e+f;if(g)"u"===f?(f=this.text.substring(this.index+1,this.index+5),f.match(/[\da-f]{4}/i)||this.throwError("Invalid unicode escape [\\u"+f+"]"),this.index+=4,d+=String.fromCharCode(parseInt(f,16))):d=(g=Wd[f])?d+g:d+f,g=!1;else if("\\"===f)g=!0;else{if(f===a){this.index++;this.tokens.push({index:c,text:e,string:d,json:!0,fn:function(){return d}});
return}d+=f}this.index++}this.throwError("Unterminated quote",c)}};var Za=function(a,c,d){this.lexer=a;this.$filter=c;this.options=d};Za.ZERO=function(){return 0};Za.prototype={constructor:Za,parse:function(a,c){this.text=a;this.json=c;this.tokens=this.lexer.lex(a);c&&(this.assignment=this.logicalOR,this.functionCall=this.fieldAccess=this.objectIndex=this.filterChain=function(){this.throwError("is not valid json",{text:a,index:0})});var d=c?this.primary():this.statements();0!==this.tokens.length&&
this.throwError("is an unexpected token",this.tokens[0]);d.literal=!!d.literal;d.constant=!!d.constant;return d},primary:function(){var a;if(this.expect("("))a=this.filterChain(),this.consume(")");else if(this.expect("["))a=this.arrayDeclaration();else if(this.expect("{"))a=this.object();else{var c=this.expect();(a=c.fn)||this.throwError("not a primary expression",c);c.json&&(a.constant=!0,a.literal=!0)}for(var d;c=this.expect("(","[",".");)"("===c.text?(a=this.functionCall(a,d),d=null):"["===c.text?
(d=a,a=this.objectIndex(a)):"."===c.text?(d=a,a=this.fieldAccess(a)):this.throwError("IMPOSSIBLE");return a},throwError:function(a,c){throw za("syntax",c.text,a,c.index+1,this.text,this.text.substring(c.index));},peekToken:function(){if(0===this.tokens.length)throw za("ueoe",this.text);return this.tokens[0]},peek:function(a,c,d,e){if(0<this.tokens.length){var g=this.tokens[0],f=g.text;if(f===a||f===c||f===d||f===e||!(a||c||d||e))return g}return!1},expect:function(a,c,d,e){return(a=this.peek(a,c,d,
e))?(this.json&&!a.json&&this.throwError("is not valid json",a),this.tokens.shift(),a):!1},consume:function(a){this.expect(a)||this.throwError("is unexpected, expecting ["+a+"]",this.peek())},unaryFn:function(a,c){return t(function(d,e){return a(d,e,c)},{constant:c.constant})},ternaryFn:function(a,c,d){return t(function(e,g){return a(e,g)?c(e,g):d(e,g)},{constant:a.constant&&c.constant&&d.constant})},binaryFn:function(a,c,d){return t(function(e,g){return c(e,g,a,d)},{constant:a.constant&&d.constant})},
statements:function(){for(var a=[];;)if(0<this.tokens.length&&!this.peek("}",")",";","]")&&a.push(this.filterChain()),!this.expect(";"))return 1===a.length?a[0]:function(c,d){for(var e,g=0;g<a.length;g++){var f=a[g];f&&(e=f(c,d))}return e}},filterChain:function(){for(var a=this.expression(),c;;)if(c=this.expect("|"))a=this.binaryFn(a,c.fn,this.filter());else return a},filter:function(){for(var a=this.expect(),c=this.$filter(a.text),d=[];;)if(a=this.expect(":"))d.push(this.expression());else{var e=
function(a,e,h){h=[h];for(var m=0;m<d.length;m++)h.push(d[m](a,e));return c.apply(a,h)};return function(){return e}}},expression:function(){return this.assignment()},assignment:function(){var a=this.ternary(),c,d;return(d=this.expect("="))?(a.assign||this.throwError("implies assignment but ["+this.text.substring(0,d.index)+"] can not be assigned to",d),c=this.ternary(),function(d,g){return a.assign(d,c(d,g),g)}):a},ternary:function(){var a=this.logicalOR(),c,d;if(this.expect("?")){c=this.ternary();
if(d=this.expect(":"))return this.ternaryFn(a,c,this.ternary());this.throwError("expected :",d)}else return a},logicalOR:function(){for(var a=this.logicalAND(),c;;)if(c=this.expect("||"))a=this.binaryFn(a,c.fn,this.logicalAND());else return a},logicalAND:function(){var a=this.equality(),c;if(c=this.expect("&&"))a=this.binaryFn(a,c.fn,this.logicalAND());return a},equality:function(){var a=this.relational(),c;if(c=this.expect("==","!=","===","!=="))a=this.binaryFn(a,c.fn,this.equality());return a},
relational:function(){var a=this.additive(),c;if(c=this.expect("<",">","<=",">="))a=this.binaryFn(a,c.fn,this.relational());return a},additive:function(){for(var a=this.multiplicative(),c;c=this.expect("+","-");)a=this.binaryFn(a,c.fn,this.multiplicative());return a},multiplicative:function(){for(var a=this.unary(),c;c=this.expect("*","/","%");)a=this.binaryFn(a,c.fn,this.unary());return a},unary:function(){var a;return this.expect("+")?this.primary():(a=this.expect("-"))?this.binaryFn(Za.ZERO,a.fn,
this.unary()):(a=this.expect("!"))?this.unaryFn(a.fn,this.unary()):this.primary()},fieldAccess:function(a){var c=this,d=this.expect().text,e=xc(d,this.options,this.text);return t(function(c,d,h){return e(h||a(c,d))},{assign:function(e,f,h){return kb(a(e,h),d,f,c.text,c.options)}})},objectIndex:function(a){var c=this,d=this.expression();this.consume("]");return t(function(e,g){var f=a(e,g),h=d(e,g),m;if(!f)return r;(f=Ya(f[h],c.text))&&(f.then&&c.options.unwrapPromises)&&(m=f,"$$v"in f||(m.$$v=r,m.then(function(a){m.$$v=
a})),f=f.$$v);return f},{assign:function(e,g,f){var h=d(e,f);return Ya(a(e,f),c.text)[h]=g}})},functionCall:function(a,c){var d=[];if(")"!==this.peekToken().text){do d.push(this.expression());while(this.expect(","))}this.consume(")");var e=this;return function(g,f){for(var h=[],m=c?c(g,f):g,k=0;k<d.length;k++)h.push(d[k](g,f));k=a(g,f,m)||w;Ya(m,e.text);Ya(k,e.text);h=k.apply?k.apply(m,h):k(h[0],h[1],h[2],h[3],h[4]);return Ya(h,e.text)}},arrayDeclaration:function(){var a=[],c=!0;if("]"!==this.peekToken().text){do{var d=
this.expression();a.push(d);d.constant||(c=!1)}while(this.expect(","))}this.consume("]");return t(function(c,d){for(var f=[],h=0;h<a.length;h++)f.push(a[h](c,d));return f},{literal:!0,constant:c})},object:function(){var a=[],c=!0;if("}"!==this.peekToken().text){do{var d=this.expect(),d=d.string||d.text;this.consume(":");var e=this.expression();a.push({key:d,value:e});e.constant||(c=!1)}while(this.expect(","))}this.consume("}");return t(function(c,d){for(var e={},m=0;m<a.length;m++){var k=a[m];e[k.key]=
k.value(c,d)}return e},{literal:!0,constant:c})}};var Kb={},sa=F("$sce"),fa={HTML:"html",CSS:"css",URL:"url",RESOURCE_URL:"resourceUrl",JS:"js"},Y=Q.createElement("a"),Ac=ya(Z.location.href,!0);Bc.$inject=["$provide"];Cc.$inject=["$locale"];Ec.$inject=["$locale"];var Hc=".",Qd={yyyy:W("FullYear",4),yy:W("FullYear",2,0,!0),y:W("FullYear",1),MMMM:lb("Month"),MMM:lb("Month",!0),MM:W("Month",2,1),M:W("Month",1,1),dd:W("Date",2),d:W("Date",1),HH:W("Hours",2),H:W("Hours",1),hh:W("Hours",2,-12),h:W("Hours",
1,-12),mm:W("Minutes",2),m:W("Minutes",1),ss:W("Seconds",2),s:W("Seconds",1),sss:W("Milliseconds",3),EEEE:lb("Day"),EEE:lb("Day",!0),a:function(a,c){return 12>a.getHours()?c.AMPMS[0]:c.AMPMS[1]},Z:function(a){a=-1*a.getTimezoneOffset();return a=(0<=a?"+":"")+(Mb(Math[0<a?"floor":"ceil"](a/60),2)+Mb(Math.abs(a%60),2))}},Pd=/((?:[^yMdHhmsaZE']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d+|H+|h+|m+|s+|a|Z))(.*)/,Od=/^\-?\d+$/;Dc.$inject=["$locale"];var Md=$(x),Nd=$(Ia);Fc.$inject=["$parse"];var Xd=$({restrict:"E",
compile:function(a,c){8>=M&&(c.href||c.name||c.$set("href",""),a.append(Q.createComment("IE fix")));if(!c.href&&!c.xlinkHref&&!c.name)return function(a,c){var g="[object SVGAnimatedString]"===Ma.call(c.prop("href"))?"xlink:href":"href";c.on("click",function(a){c.attr(g)||a.preventDefault()})}}}),Ob={};q(gb,function(a,c){if("multiple"!=a){var d=ma("ng-"+c);Ob[d]=function(){return{priority:100,link:function(a,g,f){a.$watch(f[d],function(a){f.$set(c,!!a)})}}}}});q(["src","srcset","href"],function(a){var c=
ma("ng-"+a);Ob[c]=function(){return{priority:99,link:function(d,e,g){g.$observe(c,function(c){c&&(g.$set(a,c),M&&e.prop(a,g[a]))})}}}});var ob={$addControl:w,$removeControl:w,$setValidity:w,$setDirty:w,$setPristine:w};Ic.$inject=["$element","$attrs","$scope"];var Kc=function(a){return["$timeout",function(c){return{name:"form",restrict:a?"EAC":"E",controller:Ic,compile:function(){return{pre:function(a,e,g,f){if(!g.action){var h=function(a){a.preventDefault?a.preventDefault():a.returnValue=!1};Jc(e[0],
"submit",h);e.on("$destroy",function(){c(function(){Bb(e[0],"submit",h)},0,!1)})}var m=e.parent().controller("form"),k=g.name||g.ngForm;k&&kb(a,k,f,k);if(m)e.on("$destroy",function(){m.$removeControl(f);k&&kb(a,k,r,k);t(f,ob)})}}}}}]},Yd=Kc(),Zd=Kc(!0),$d=/^(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/,ae=/^[a-z0-9!#$%&'*+/=?^_`{|}~.-]+@[a-z0-9-]+(\.[a-z0-9-]+)*$/i,be=/^\s*(\-|\+)?(\d+|(\d*(\.\d*)))\s*$/,Lc={text:qb,number:function(a,c,d,e,g,f){qb(a,c,d,e,g,f);
e.$parsers.push(function(a){var c=e.$isEmpty(a);if(c||be.test(a))return e.$setValidity("number",!0),""===a?null:c?a:parseFloat(a);e.$setValidity("number",!1);return r});e.$formatters.push(function(a){return e.$isEmpty(a)?"":""+a});d.min&&(a=function(a){var c=parseFloat(d.min);return pa(e,"min",e.$isEmpty(a)||a>=c,a)},e.$parsers.push(a),e.$formatters.push(a));d.max&&(a=function(a){var c=parseFloat(d.max);return pa(e,"max",e.$isEmpty(a)||a<=c,a)},e.$parsers.push(a),e.$formatters.push(a));e.$formatters.push(function(a){return pa(e,
"number",e.$isEmpty(a)||sb(a),a)})},url:function(a,c,d,e,g,f){qb(a,c,d,e,g,f);a=function(a){return pa(e,"url",e.$isEmpty(a)||$d.test(a),a)};e.$formatters.push(a);e.$parsers.push(a)},email:function(a,c,d,e,g,f){qb(a,c,d,e,g,f);a=function(a){return pa(e,"email",e.$isEmpty(a)||ae.test(a),a)};e.$formatters.push(a);e.$parsers.push(a)},radio:function(a,c,d,e){z(d.name)&&c.attr("name",$a());c.on("click",function(){c[0].checked&&a.$apply(function(){e.$setViewValue(d.value)})});e.$render=function(){c[0].checked=
d.value==e.$viewValue};d.$observe("value",e.$render)},checkbox:function(a,c,d,e){var g=d.ngTrueValue,f=d.ngFalseValue;D(g)||(g=!0);D(f)||(f=!1);c.on("click",function(){a.$apply(function(){e.$setViewValue(c[0].checked)})});e.$render=function(){c[0].checked=e.$viewValue};e.$isEmpty=function(a){return a!==g};e.$formatters.push(function(a){return a===g});e.$parsers.push(function(a){return a?g:f})},hidden:w,button:w,submit:w,reset:w},Mc=["$browser","$sniffer",function(a,c){return{restrict:"E",require:"?ngModel",
link:function(d,e,g,f){f&&(Lc[x(g.type)]||Lc.text)(d,e,g,f,c,a)}}}],nb="ng-valid",mb="ng-invalid",Ja="ng-pristine",pb="ng-dirty",ce=["$scope","$exceptionHandler","$attrs","$element","$parse",function(a,c,d,e,g){function f(a,c){c=c?"-"+db(c,"-"):"";e.removeClass((a?mb:nb)+c).addClass((a?nb:mb)+c)}this.$modelValue=this.$viewValue=Number.NaN;this.$parsers=[];this.$formatters=[];this.$viewChangeListeners=[];this.$pristine=!0;this.$dirty=!1;this.$valid=!0;this.$invalid=!1;this.$name=d.name;var h=g(d.ngModel),
m=h.assign;if(!m)throw F("ngModel")("nonassign",d.ngModel,ga(e));this.$render=w;this.$isEmpty=function(a){return z(a)||""===a||null===a||a!==a};var k=e.inheritedData("$formController")||ob,l=0,n=this.$error={};e.addClass(Ja);f(!0);this.$setValidity=function(a,c){n[a]!==!c&&(c?(n[a]&&l--,l||(f(!0),this.$valid=!0,this.$invalid=!1)):(f(!1),this.$invalid=!0,this.$valid=!1,l++),n[a]=!c,f(c,a),k.$setValidity(a,c,this))};this.$setPristine=function(){this.$dirty=!1;this.$pristine=!0;e.removeClass(pb).addClass(Ja)};
this.$setViewValue=function(d){this.$viewValue=d;this.$pristine&&(this.$dirty=!0,this.$pristine=!1,e.removeClass(Ja).addClass(pb),k.$setDirty());q(this.$parsers,function(a){d=a(d)});this.$modelValue!==d&&(this.$modelValue=d,m(a,d),q(this.$viewChangeListeners,function(a){try{a()}catch(d){c(d)}}))};var p=this;a.$watch(function(){var c=h(a);if(p.$modelValue!==c){var d=p.$formatters,e=d.length;for(p.$modelValue=c;e--;)c=d[e](c);p.$viewValue!==c&&(p.$viewValue=c,p.$render())}return c})}],de=function(){return{require:["ngModel",
"^?form"],controller:ce,link:function(a,c,d,e){var g=e[0],f=e[1]||ob;f.$addControl(g);a.$on("$destroy",function(){f.$removeControl(g)})}}},ee=$({require:"ngModel",link:function(a,c,d,e){e.$viewChangeListeners.push(function(){a.$eval(d.ngChange)})}}),Nc=function(){return{require:"?ngModel",link:function(a,c,d,e){if(e){d.required=!0;var g=function(a){if(d.required&&e.$isEmpty(a))e.$setValidity("required",!1);else return e.$setValidity("required",!0),a};e.$formatters.push(g);e.$parsers.unshift(g);d.$observe("required",
function(){g(e.$viewValue)})}}}},fe=function(){return{require:"ngModel",link:function(a,c,d,e){var g=(a=/\/(.*)\//.exec(d.ngList))&&RegExp(a[1])||d.ngList||",";e.$parsers.push(function(a){if(!z(a)){var c=[];a&&q(a.split(g),function(a){a&&c.push(ba(a))});return c}});e.$formatters.push(function(a){return K(a)?a.join(", "):r});e.$isEmpty=function(a){return!a||!a.length}}}},ge=/^(true|false|\d+)$/,he=function(){return{priority:100,compile:function(a,c){return ge.test(c.ngValue)?function(a,c,g){g.$set("value",
a.$eval(g.ngValue))}:function(a,c,g){a.$watch(g.ngValue,function(a){g.$set("value",a)})}}}},ie=ta(function(a,c,d){c.addClass("ng-binding").data("$binding",d.ngBind);a.$watch(d.ngBind,function(a){c.text(a==r?"":a)})}),je=["$interpolate",function(a){return function(c,d,e){c=a(d.attr(e.$attr.ngBindTemplate));d.addClass("ng-binding").data("$binding",c);e.$observe("ngBindTemplate",function(a){d.text(a)})}}],ke=["$sce","$parse",function(a,c){return function(d,e,g){e.addClass("ng-binding").data("$binding",
g.ngBindHtml);var f=c(g.ngBindHtml);d.$watch(function(){return(f(d)||"").toString()},function(c){e.html(a.getTrustedHtml(f(d))||"")})}}],le=Nb("",!0),me=Nb("Odd",0),ne=Nb("Even",1),oe=ta({compile:function(a,c){c.$set("ngCloak",r);a.removeClass("ng-cloak")}}),pe=[function(){return{scope:!0,controller:"@",priority:500}}],Oc={};q("click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress submit focus blur copy cut paste".split(" "),function(a){var c=ma("ng-"+
a);Oc[c]=["$parse",function(d){return{compile:function(e,g){var f=d(g[c]);return function(c,d,e){d.on(x(a),function(a){c.$apply(function(){f(c,{$event:a})})})}}}}]});var qe=["$animate",function(a){return{transclude:"element",priority:600,terminal:!0,restrict:"A",$$tlb:!0,link:function(c,d,e,g,f){var h,m;c.$watch(e.ngIf,function(g){Pa(g)?m||(m=c.$new(),f(m,function(c){c[c.length++]=Q.createComment(" end ngIf: "+e.ngIf+" ");h={clone:c};a.enter(c,d.parent(),d)})):(m&&(m.$destroy(),m=null),h&&(a.leave(wb(h.clone)),
h=null))})}}}],re=["$http","$templateCache","$anchorScroll","$animate","$sce",function(a,c,d,e,g){return{restrict:"ECA",priority:400,terminal:!0,transclude:"element",controller:Ca.noop,compile:function(f,h){var m=h.ngInclude||h.src,k=h.onload||"",l=h.autoscroll;return function(f,h,q,r,y){var A=0,u,t,H=function(){u&&(u.$destroy(),u=null);t&&(e.leave(t),t=null)};f.$watch(g.parseAsResourceUrl(m),function(g){var m=function(){!B(l)||l&&!f.$eval(l)||d()},q=++A;g?(a.get(g,{cache:c}).success(function(a){if(q===
A){var c=f.$new();r.template=a;a=y(c,function(a){H();e.enter(a,null,h,m)});u=c;t=a;u.$emit("$includeContentLoaded");f.$eval(k)}}).error(function(){q===A&&H()}),f.$emit("$includeContentRequested")):(H(),r.template=null)})}}}}],se=["$compile",function(a){return{restrict:"ECA",priority:-400,require:"ngInclude",link:function(c,d,e,g){d.html(g.template);a(d.contents())(c)}}}],te=ta({priority:450,compile:function(){return{pre:function(a,c,d){a.$eval(d.ngInit)}}}}),ue=ta({terminal:!0,priority:1E3}),ve=["$locale",
"$interpolate",function(a,c){var d=/{}/g;return{restrict:"EA",link:function(e,g,f){var h=f.count,m=f.$attr.when&&g.attr(f.$attr.when),k=f.offset||0,l=e.$eval(m)||{},n={},p=c.startSymbol(),s=c.endSymbol(),r=/^when(Minus)?(.+)$/;q(f,function(a,c){r.test(c)&&(l[x(c.replace("when","").replace("Minus","-"))]=g.attr(f.$attr[c]))});q(l,function(a,e){n[e]=c(a.replace(d,p+h+"-"+k+s))});e.$watch(function(){var c=parseFloat(e.$eval(h));if(isNaN(c))return"";c in l||(c=a.pluralCat(c-k));return n[c](e,g,!0)},function(a){g.text(a)})}}}],
we=["$parse","$animate",function(a,c){var d=F("ngRepeat");return{transclude:"element",priority:1E3,terminal:!0,$$tlb:!0,link:function(e,g,f,h,m){var k=f.ngRepeat,l=k.match(/^\s*([\s\S]+?)\s+in\s+([\s\S]+?)(?:\s+track\s+by\s+([\s\S]+?))?\s*$/),n,p,s,r,y,t,u={$id:Fa};if(!l)throw d("iexp",k);f=l[1];h=l[2];(l=l[3])?(n=a(l),p=function(a,c,d){t&&(u[t]=a);u[y]=c;u.$index=d;return n(e,u)}):(s=function(a,c){return Fa(c)},r=function(a){return a});l=f.match(/^(?:([\$\w]+)|\(([\$\w]+)\s*,\s*([\$\w]+)\))$/);if(!l)throw d("iidexp",
f);y=l[3]||l[1];t=l[2];var B={};e.$watchCollection(h,function(a){var f,h,l=g[0],n,u={},z,P,D,x,T,w,F=[];if(rb(a))T=a,n=p||s;else{n=p||r;T=[];for(D in a)a.hasOwnProperty(D)&&"$"!=D.charAt(0)&&T.push(D);T.sort()}z=T.length;h=F.length=T.length;for(f=0;f<h;f++)if(D=a===T?f:T[f],x=a[D],x=n(D,x,f),xa(x,"`track by` id"),B.hasOwnProperty(x))w=B[x],delete B[x],u[x]=w,F[f]=w;else{if(u.hasOwnProperty(x))throw q(F,function(a){a&&a.scope&&(B[a.id]=a)}),d("dupes",k,x);F[f]={id:x};u[x]=!1}for(D in B)B.hasOwnProperty(D)&&
(w=B[D],f=wb(w.clone),c.leave(f),q(f,function(a){a.$$NG_REMOVED=!0}),w.scope.$destroy());f=0;for(h=T.length;f<h;f++){D=a===T?f:T[f];x=a[D];w=F[f];F[f-1]&&(l=F[f-1].clone[F[f-1].clone.length-1]);if(w.scope){P=w.scope;n=l;do n=n.nextSibling;while(n&&n.$$NG_REMOVED);w.clone[0]!=n&&c.move(wb(w.clone),null,A(l));l=w.clone[w.clone.length-1]}else P=e.$new();P[y]=x;t&&(P[t]=D);P.$index=f;P.$first=0===f;P.$last=f===z-1;P.$middle=!(P.$first||P.$last);P.$odd=!(P.$even=0===(f&1));w.scope||m(P,function(a){a[a.length++]=
Q.createComment(" end ngRepeat: "+k+" ");c.enter(a,null,A(l));l=a;w.scope=P;w.clone=a;u[w.id]=w})}B=u})}}}],xe=["$animate",function(a){return function(c,d,e){c.$watch(e.ngShow,function(c){a[Pa(c)?"removeClass":"addClass"](d,"ng-hide")})}}],ye=["$animate",function(a){return function(c,d,e){c.$watch(e.ngHide,function(c){a[Pa(c)?"addClass":"removeClass"](d,"ng-hide")})}}],ze=ta(function(a,c,d){a.$watch(d.ngStyle,function(a,d){d&&a!==d&&q(d,function(a,d){c.css(d,"")});a&&c.css(a)},!0)}),Ae=["$animate",
function(a){return{restrict:"EA",require:"ngSwitch",controller:["$scope",function(){this.cases={}}],link:function(c,d,e,g){var f,h,m=[];c.$watch(e.ngSwitch||e.on,function(d){for(var l=0,n=m.length;l<n;l++)m[l].$destroy(),a.leave(h[l]);h=[];m=[];if(f=g.cases["!"+d]||g.cases["?"])c.$eval(e.change),q(f,function(d){var e=c.$new();m.push(e);d.transclude(e,function(c){var e=d.element;h.push(c);a.enter(c,e.parent(),e)})})})}}}],Be=ta({transclude:"element",priority:800,require:"^ngSwitch",link:function(a,
c,d,e,g){e.cases["!"+d.ngSwitchWhen]=e.cases["!"+d.ngSwitchWhen]||[];e.cases["!"+d.ngSwitchWhen].push({transclude:g,element:c})}}),Ce=ta({transclude:"element",priority:800,require:"^ngSwitch",link:function(a,c,d,e,g){e.cases["?"]=e.cases["?"]||[];e.cases["?"].push({transclude:g,element:c})}}),De=ta({controller:["$element","$transclude",function(a,c){if(!c)throw F("ngTransclude")("orphan",ga(a));this.$transclude=c}],link:function(a,c,d,e){e.$transclude(function(a){c.empty();c.append(a)})}}),Ee=["$templateCache",
function(a){return{restrict:"E",terminal:!0,compile:function(c,d){"text/ng-template"==d.type&&a.put(d.id,c[0].text)}}}],Fe=F("ngOptions"),Ge=$({terminal:!0}),He=["$compile","$parse",function(a,c){var d=/^\s*([\s\S]+?)(?:\s+as\s+([\s\S]+?))?(?:\s+group\s+by\s+([\s\S]+?))?\s+for\s+(?:([\$\w][\$\w]*)|(?:\(\s*([\$\w][\$\w]*)\s*,\s*([\$\w][\$\w]*)\s*\)))\s+in\s+([\s\S]+?)(?:\s+track\s+by\s+([\s\S]+?))?$/,e={$setViewValue:w};return{restrict:"E",require:["select","?ngModel"],controller:["$element","$scope",
"$attrs",function(a,c,d){var m=this,k={},l=e,n;m.databound=d.ngModel;m.init=function(a,c,d){l=a;n=d};m.addOption=function(c){xa(c,'"option value"');k[c]=!0;l.$viewValue==c&&(a.val(c),n.parent()&&n.remove())};m.removeOption=function(a){this.hasOption(a)&&(delete k[a],l.$viewValue==a&&this.renderUnknownOption(a))};m.renderUnknownOption=function(c){c="? "+Fa(c)+" ?";n.val(c);a.prepend(n);a.val(c);n.prop("selected",!0)};m.hasOption=function(a){return k.hasOwnProperty(a)};c.$on("$destroy",function(){m.renderUnknownOption=
w})}],link:function(e,f,h,m){function k(a,c,d,e){d.$render=function(){var a=d.$viewValue;e.hasOption(a)?(x.parent()&&x.remove(),c.val(a),""===a&&w.prop("selected",!0)):z(a)&&w?c.val(""):e.renderUnknownOption(a)};c.on("change",function(){a.$apply(function(){x.parent()&&x.remove();d.$setViewValue(c.val())})})}function l(a,c,d){var e;d.$render=function(){var a=new Ta(d.$viewValue);q(c.find("option"),function(c){c.selected=B(a.get(c.value))})};a.$watch(function(){ua(e,d.$viewValue)||(e=aa(d.$viewValue),
d.$render())});c.on("change",function(){a.$apply(function(){var a=[];q(c.find("option"),function(c){c.selected&&a.push(c.value)});d.$setViewValue(a)})})}function n(e,f,g){function h(){var a={"":[]},c=[""],d,k,r,t,v;t=g.$modelValue;v=A(e)||[];var C=n?Pb(v):v,F,I,z;I={};r=!1;var E,H;if(s)if(w&&K(t))for(r=new Ta([]),z=0;z<t.length;z++)I[m]=t[z],r.put(w(e,I),t[z]);else r=new Ta(t);for(z=0;F=C.length,z<F;z++){k=z;if(n){k=C[z];if("$"===k.charAt(0))continue;I[n]=k}I[m]=v[k];d=p(e,I)||"";(k=a[d])||(k=a[d]=
[],c.push(d));s?d=B(r.remove(w?w(e,I):q(e,I))):(w?(d={},d[m]=t,d=w(e,d)===w(e,I)):d=t===q(e,I),r=r||d);E=l(e,I);E=B(E)?E:"";k.push({id:w?w(e,I):n?C[z]:z,label:E,selected:d})}s||(y||null===t?a[""].unshift({id:"",label:"",selected:!r}):r||a[""].unshift({id:"?",label:"",selected:!0}));I=0;for(C=c.length;I<C;I++){d=c[I];k=a[d];x.length<=I?(t={element:D.clone().attr("label",d),label:k.label},v=[t],x.push(v),f.append(t.element)):(v=x[I],t=v[0],t.label!=d&&t.element.attr("label",t.label=d));E=null;z=0;for(F=
k.length;z<F;z++)r=k[z],(d=v[z+1])?(E=d.element,d.label!==r.label&&E.text(d.label=r.label),d.id!==r.id&&E.val(d.id=r.id),E[0].selected!==r.selected&&E.prop("selected",d.selected=r.selected)):(""===r.id&&y?H=y:(H=u.clone()).val(r.id).attr("selected",r.selected).text(r.label),v.push({element:H,label:r.label,id:r.id,selected:r.selected}),E?E.after(H):t.element.append(H),E=H);for(z++;v.length>z;)v.pop().element.remove()}for(;x.length>I;)x.pop()[0].element.remove()}var k;if(!(k=t.match(d)))throw Fe("iexp",
t,ga(f));var l=c(k[2]||k[1]),m=k[4]||k[6],n=k[5],p=c(k[3]||""),q=c(k[2]?k[1]:m),A=c(k[7]),w=k[8]?c(k[8]):null,x=[[{element:f,label:""}]];y&&(a(y)(e),y.removeClass("ng-scope"),y.remove());f.empty();f.on("change",function(){e.$apply(function(){var a,c=A(e)||[],d={},h,k,l,p,t,u,v;if(s)for(k=[],p=0,u=x.length;p<u;p++)for(a=x[p],l=1,t=a.length;l<t;l++){if((h=a[l].element)[0].selected){h=h.val();n&&(d[n]=h);if(w)for(v=0;v<c.length&&(d[m]=c[v],w(e,d)!=h);v++);else d[m]=c[h];k.push(q(e,d))}}else if(h=f.val(),
"?"==h)k=r;else if(""===h)k=null;else if(w)for(v=0;v<c.length;v++){if(d[m]=c[v],w(e,d)==h){k=q(e,d);break}}else d[m]=c[h],n&&(d[n]=h),k=q(e,d);g.$setViewValue(k)})});g.$render=h;e.$watch(h)}if(m[1]){var p=m[0];m=m[1];var s=h.multiple,t=h.ngOptions,y=!1,w,u=A(Q.createElement("option")),D=A(Q.createElement("optgroup")),x=u.clone();h=0;for(var v=f.children(),F=v.length;h<F;h++)if(""===v[h].value){w=y=v.eq(h);break}p.init(m,y,x);s&&(m.$isEmpty=function(a){return!a||0===a.length});t?n(e,f,m):s?l(e,f,m):
k(e,f,m,p)}}}}],Ie=["$interpolate",function(a){var c={addOption:w,removeOption:w};return{restrict:"E",priority:100,compile:function(d,e){if(z(e.value)){var g=a(d.text(),!0);g||e.$set("value",d.text())}return function(a,d,e){var k=d.parent(),l=k.data("$selectController")||k.parent().data("$selectController");l&&l.databound?d.prop("selected",!1):l=c;g?a.$watch(g,function(a,c){e.$set("value",a);a!==c&&l.removeOption(c);l.addOption(a)}):l.addOption(e.value);d.on("$destroy",function(){l.removeOption(e.value)})}}}}],
Je=$({restrict:"E",terminal:!0});(Da=Z.jQuery)?(A=Da,t(Da.fn,{scope:Ga.scope,isolateScope:Ga.isolateScope,controller:Ga.controller,injector:Ga.injector,inheritedData:Ga.inheritedData}),xb("remove",!0,!0,!1),xb("empty",!1,!1,!1),xb("html",!1,!1,!0)):A=O;Ca.element=A;(function(a){t(a,{bootstrap:Zb,copy:aa,extend:t,equals:ua,element:A,forEach:q,injector:$b,noop:w,bind:cb,toJson:qa,fromJson:Vb,identity:Ba,isUndefined:z,isDefined:B,isString:D,isFunction:L,isObject:X,isNumber:sb,isElement:Qc,isArray:K,
version:Sd,isDate:La,lowercase:x,uppercase:Ia,callbacks:{counter:0},$$minErr:F,$$csp:Ub});Va=Vc(Z);try{Va("ngLocale")}catch(c){Va("ngLocale",[]).provider("$locale",sd)}Va("ng",["ngLocale"],["$provide",function(a){a.provider({$$sanitizeUri:Cd});a.provider("$compile",jc).directive({a:Xd,input:Mc,textarea:Mc,form:Yd,script:Ee,select:He,style:Je,option:Ie,ngBind:ie,ngBindHtml:ke,ngBindTemplate:je,ngClass:le,ngClassEven:ne,ngClassOdd:me,ngCloak:oe,ngController:pe,ngForm:Zd,ngHide:ye,ngIf:qe,ngInclude:re,
ngInit:te,ngNonBindable:ue,ngPluralize:ve,ngRepeat:we,ngShow:xe,ngStyle:ze,ngSwitch:Ae,ngSwitchWhen:Be,ngSwitchDefault:Ce,ngOptions:Ge,ngTransclude:De,ngModel:de,ngList:fe,ngChange:ee,required:Nc,ngRequired:Nc,ngValue:he}).directive({ngInclude:se}).directive(Ob).directive(Oc);a.provider({$anchorScroll:dd,$animate:Ud,$browser:fd,$cacheFactory:gd,$controller:jd,$document:kd,$exceptionHandler:ld,$filter:Bc,$interpolate:qd,$interval:rd,$http:md,$httpBackend:od,$location:ud,$log:vd,$parse:yd,$rootScope:Bd,
$q:zd,$sce:Fd,$sceDelegate:Ed,$sniffer:Gd,$templateCache:hd,$timeout:Hd,$window:Id})}])})(Ca);A(Q).ready(function(){Tc(Q,Zb)})})(window,document);!angular.$$csp()&&angular.element(document).find("head").prepend('<style type="text/css">@charset "UTF-8";[ng\\:cloak],[ng-cloak],[data-ng-cloak],[x-ng-cloak],.ng-cloak,.x-ng-cloak,.ng-hide{display:none !important;}ng\\:form{display:block;}</style>');
//# sourceMappingURL=angular.min.js.map | TurpIF/data-gouv | web/js/lib/angular.min.js | JavaScript | artistic-2.0 | 100,084 |
function(modal) {
function ajaxifyLinks (context) {
$('a.address-choice', context).click(function() {
modal.loadUrl(this.href);
return false;
});
$('.pagination a', context).click(function() {
var page = this.getAttribute("data-page");
setPage(page);
return false;
});
};
var searchUrl = $('form.address-search', modal.body).attr('action')
function search() {
$.ajax({
url: searchUrl,
data: {q: $('#id_q').val()},
success: function(data, status) {
$('#search-results').html(data);
ajaxifyLinks($('#search-results'));
}
});
return false;
};
function setPage(page) {
if($('#id_q').val().length){
dataObj = {q: $('#id_q').val(), p: page};
}
else {
dataObj = {p: page};
}
$.ajax({
url: searchUrl,
data: dataObj,
success: function(data, status) {
$('#search-results').html(data);
ajaxifyLinks($('#search-results'));
}
});
return false;
}
ajaxifyLinks(modal.body);
function submitForm() {
var formdata = new FormData(this);
$.ajax({
url: this.action,
data: formdata,
processData: false,
contentType: false,
type: 'POST',
dataType: 'text',
success: function(response){
modal.loadResponseText(response);
}
});
return false;
}
$('form.address-create', modal.body).submit(submitForm);
$('form.address-edit', modal.body).submit(submitForm);
$('form.address-search', modal.body).submit(search);
$('#id_q').on('input', function() {
clearTimeout($.data(this, 'timer'));
var wait = setTimeout(search, 50);
$(this).data('timer', wait);
});
{% url 'wagtailadmin_tag_autocomplete' as autocomplete_url %}
$('#id_tags', modal.body).tagit({
autocomplete: {source: "{{ autocomplete_url|addslashes }}"}
});
function detectErrors() {
var errorSections = {};
// First count up all the errors
$('form.address-create .error-message').each(function(){
var parentSection = $(this).closest('section');
if(!errorSections[parentSection.attr('id')]){
errorSections[parentSection.attr('id')] = 0;
}
errorSections[parentSection.attr('id')] = errorSections[parentSection.attr('id')]+1;
});
// Now identify them on each tab
for(var index in errorSections) {
$('.tab-nav a[href=#'+ index +']').addClass('errors').attr('data-count', errorSections[index]);
}
}
detectErrors();
} | MechanisM/wagtailplus | wagtailplus/wagtailaddresses/templates/wagtailaddresses/component-chooser/chooser.js | JavaScript | bsd-2-clause | 3,032 |
import React from 'react';
import { shallow } from 'enzyme';
import sinon from 'sinon';
import AddComment from './AddComment';
const USER = {
user: {
user: 'RSwanson',
username: 'Ron_Swanson',
imageURL: '',
users: [
{
name: 'April Ludwig',
url: '[email protected]',
display: 'April',
},
],
},
};
describe('<AddComment>', () => {
it('calls submitComment function', () => {
const submitCommentFn = sinon.spy();
const wrapper = shallow(
<AddComment {...USER} submitComment={submitCommentFn} />,
);
const event = {
preventDefault: sinon.spy(),
};
wrapper.find('button').simulate('onClick', event);
expect(submitCommentFn.calledOnce).toBeTruthy;
});
});
| mathjazz/pontoon | translate/src/core/comments/components/AddComment.test.js | JavaScript | bsd-3-clause | 761 |
'use strict';
angular.module('shopnxApp')
.config(function ($stateProvider) {
$stateProvider
.state('checkout', {
title: 'Checkout with the items you selected',
url: '/checkout',
templateUrl: 'app/checkout/checkout.html',
controller: 'CheckoutCtrl',
authenticate: true
});
});
| kinddevil/shop | client/app/checkout/checkout.js | JavaScript | bsd-3-clause | 338 |
import PromiseRouter from '../PromiseRouter';
import * as middleware from "../middlewares";
import { Parse } from "parse/node";
export class PushRouter extends PromiseRouter {
mountRoutes() {
this.route("POST", "/push", middleware.promiseEnforceMasterKeyAccess, PushRouter.handlePOST);
}
static handlePOST(req) {
const pushController = req.config.pushController;
if (!pushController) {
throw new Parse.Error(Parse.Error.PUSH_MISCONFIGURED, 'Push controller is not set');
}
let where = PushRouter.getQueryCondition(req);
pushController.sendPush(req.body, where, req.config, req.auth);
return Promise.resolve({
response: {
'result': true
}
});
}
/**
* Get query condition from the request body.
* @param {Object} req A request object
* @returns {Object} The query condition, the where field in a query api call
*/
static getQueryCondition(req) {
let body = req.body || {};
let hasWhere = typeof body.where !== 'undefined';
let hasChannels = typeof body.channels !== 'undefined';
let where;
if (hasWhere && hasChannels) {
throw new Parse.Error(Parse.Error.PUSH_MISCONFIGURED,
'Channels and query can not be set at the same time.');
} else if (hasWhere) {
where = body.where;
} else if (hasChannels) {
where = {
"channels": {
"$in": body.channels
}
}
} else {
throw new Parse.Error(Parse.Error.PUSH_MISCONFIGURED,
'Channels and query should be set at least one.');
}
return where;
}
}
export default PushRouter;
| lucianmat/parse-server | src/Routers/PushRouter.js | JavaScript | bsd-3-clause | 1,611 |
/* ***** BEGIN LICENSE BLOCK *****
* Distributed under the BSD license:
*
* Copyright (c) 2010, Ajax.org B.V.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Ajax.org B.V. nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* ***** END LICENSE BLOCK ***** */
define(function(require, exports, module) {
"use strict";
var keys = require("./keys");
var useragent = require("./useragent");
exports.addListener = function(elem, type, callback) {
if (elem.addEventListener) {
return elem.addEventListener(type, callback, false);
}
if (elem.attachEvent) {
var wrapper = function() {
callback.call(elem, window.event);
};
callback._wrapper = wrapper;
elem.attachEvent("on" + type, wrapper);
}
};
exports.removeListener = function(elem, type, callback) {
if (elem.removeEventListener) {
return elem.removeEventListener(type, callback, false);
}
if (elem.detachEvent) {
elem.detachEvent("on" + type, callback._wrapper || callback);
}
};
/*
* Prevents propagation and clobbers the default action of the passed event
*/
exports.stopEvent = function(e) {
exports.stopPropagation(e);
exports.preventDefault(e);
return false;
};
exports.stopPropagation = function(e) {
if (e.stopPropagation)
e.stopPropagation();
else
e.cancelBubble = true;
};
exports.preventDefault = function(e) {
if (e.preventDefault)
e.preventDefault();
else
e.returnValue = false;
};
/*
* @return {Number} 0 for left button, 1 for middle button, 2 for right button
*/
exports.getButton = function(e) {
if (e.type == "dblclick")
return 0;
if (e.type == "contextmenu" || (useragent.isMac && (e.ctrlKey && !e.altKey && !e.shiftKey)))
return 2;
// DOM Event
if (e.preventDefault) {
return e.button;
}
// old IE
else {
return {1:0, 2:2, 4:1}[e.button];
}
};
exports.capture = function(el, eventHandler, releaseCaptureHandler) {
function onMouseUp(e) {
eventHandler && eventHandler(e);
releaseCaptureHandler && releaseCaptureHandler(e);
exports.removeListener(document, "mousemove", eventHandler, true);
exports.removeListener(document, "mouseup", onMouseUp, true);
exports.removeListener(document, "dragstart", onMouseUp, true);
}
exports.addListener(document, "mousemove", eventHandler, true);
exports.addListener(document, "mouseup", onMouseUp, true);
exports.addListener(document, "dragstart", onMouseUp, true);
return onMouseUp;
};
exports.addMouseWheelListener = function(el, callback) {
if ("onmousewheel" in el) {
exports.addListener(el, "mousewheel", function(e) {
var factor = 8;
if (e.wheelDeltaX !== undefined) {
e.wheelX = -e.wheelDeltaX / factor;
e.wheelY = -e.wheelDeltaY / factor;
} else {
e.wheelX = 0;
e.wheelY = -e.wheelDelta / factor;
}
callback(e);
});
} else if ("onwheel" in el) {
exports.addListener(el, "wheel", function(e) {
var factor = 0.35;
switch (e.deltaMode) {
case e.DOM_DELTA_PIXEL:
e.wheelX = e.deltaX * factor || 0;
e.wheelY = e.deltaY * factor || 0;
break;
case e.DOM_DELTA_LINE:
case e.DOM_DELTA_PAGE:
e.wheelX = (e.deltaX || 0) * 5;
e.wheelY = (e.deltaY || 0) * 5;
break;
}
callback(e);
});
} else {
exports.addListener(el, "DOMMouseScroll", function(e) {
if (e.axis && e.axis == e.HORIZONTAL_AXIS) {
e.wheelX = (e.detail || 0) * 5;
e.wheelY = 0;
} else {
e.wheelX = 0;
e.wheelY = (e.detail || 0) * 5;
}
callback(e);
});
}
};
exports.addMultiMouseDownListener = function(el, timeouts, eventHandler, callbackName) {
var clicks = 0;
var startX, startY, timer;
var eventNames = {
2: "dblclick",
3: "tripleclick",
4: "quadclick"
};
exports.addListener(el, "mousedown", function(e) {
if (exports.getButton(e) !== 0) {
clicks = 0;
} else if (e.detail > 1) {
clicks++;
if (clicks > 4)
clicks = 1;
} else {
clicks = 1;
}
if (useragent.isIE) {
var isNewClick = Math.abs(e.clientX - startX) > 5 || Math.abs(e.clientY - startY) > 5;
if (!timer || isNewClick)
clicks = 1;
if (timer)
clearTimeout(timer);
timer = setTimeout(function() {timer = null}, timeouts[clicks - 1] || 600);
if (clicks == 1) {
startX = e.clientX;
startY = e.clientY;
}
}
e._clicks = clicks;
eventHandler[callbackName]("mousedown", e);
if (clicks > 4)
clicks = 0;
else if (clicks > 1)
return eventHandler[callbackName](eventNames[clicks], e);
});
if (useragent.isOldIE) {
exports.addListener(el, "dblclick", function(e) {
clicks = 2;
if (timer)
clearTimeout(timer);
timer = setTimeout(function() {timer = null}, timeouts[clicks - 1] || 600);
eventHandler[callbackName]("mousedown", e);
eventHandler[callbackName](eventNames[clicks], e);
});
}
};
var getModifierHash = useragent.isMac && useragent.isOpera && !("KeyboardEvent" in window)
? function(e) {
return 0 | (e.metaKey ? 1 : 0) | (e.altKey ? 2 : 0) | (e.shiftKey ? 4 : 0) | (e.ctrlKey ? 8 : 0);
}
: function(e) {
return 0 | (e.ctrlKey ? 1 : 0) | (e.altKey ? 2 : 0) | (e.shiftKey ? 4 : 0) | (e.metaKey ? 8 : 0);
};
exports.getModifierString = function(e) {
return keys.KEY_MODS[getModifierHash(e)];
};
function normalizeCommandKeys(callback, e, keyCode) {
var hashId = getModifierHash(e);
if (!useragent.isMac && pressedKeys) {
if (pressedKeys[91] || pressedKeys[92])
hashId |= 8;
if (pressedKeys.altGr) {
if ((3 & hashId) != 3)
pressedKeys.altGr = 0;
else
return;
}
if (keyCode === 18 || keyCode === 17) {
var location = "location" in e ? e.location : e.keyLocation;
if (keyCode === 17 && location === 1) {
if (pressedKeys[keyCode] == 1)
ts = e.timeStamp;
} else if (keyCode === 18 && hashId === 3 && location === 2) {
var dt = e.timeStamp - ts;
if (dt < 50)
pressedKeys.altGr = true;
}
}
}
if (keyCode in keys.MODIFIER_KEYS) {
keyCode = -1;
}
if (hashId & 8 && (keyCode === 91 || keyCode === 93)) {
keyCode = -1;
}
if (!hashId && keyCode === 13) {
var location = "location" in e ? e.location : e.keyLocation;
if (location === 3) {
callback(e, hashId, -keyCode);
if (e.defaultPrevented)
return;
}
}
if (useragent.isChromeOS && hashId & 8) {
callback(e, hashId, keyCode);
if (e.defaultPrevented)
return;
else
hashId &= ~8;
}
// If there is no hashId and the keyCode is not a function key, then
// we don't call the callback as we don't handle a command key here
// (it's a normal key/character input).
if (!hashId && !(keyCode in keys.FUNCTION_KEYS) && !(keyCode in keys.PRINTABLE_KEYS)) {
return false;
}
return callback(e, hashId, keyCode);
}
var pressedKeys = null;
var ts = 0;
exports.addCommandKeyListener = function(el, callback) {
var addListener = exports.addListener;
if (useragent.isOldGecko || (useragent.isOpera && !("KeyboardEvent" in window))) {
// Old versions of Gecko aka. Firefox < 4.0 didn't repeat the keydown
// event if the user pressed the key for a longer time. Instead, the
// keydown event was fired once and later on only the keypress event.
// To emulate the 'right' keydown behavior, the keyCode of the initial
// keyDown event is stored and in the following keypress events the
// stores keyCode is used to emulate a keyDown event.
var lastKeyDownKeyCode = null;
addListener(el, "keydown", function(e) {
lastKeyDownKeyCode = e.keyCode;
});
addListener(el, "keypress", function(e) {
return normalizeCommandKeys(callback, e, lastKeyDownKeyCode);
});
} else {
var lastDefaultPrevented = null;
addListener(el, "keydown", function(e) {
pressedKeys[e.keyCode] = (pressedKeys[e.keyCode] || 0) + 1;
var result = normalizeCommandKeys(callback, e, e.keyCode);
lastDefaultPrevented = e.defaultPrevented;
return result;
});
addListener(el, "keypress", function(e) {
if (lastDefaultPrevented && (e.ctrlKey || e.altKey || e.shiftKey || e.metaKey)) {
exports.stopEvent(e);
lastDefaultPrevented = null;
}
});
addListener(el, "keyup", function(e) {
pressedKeys[e.keyCode] = null;
});
if (!pressedKeys) {
pressedKeys = Object.create(null);
addListener(window, "focus", function(e) {
pressedKeys = Object.create(null);
});
}
}
};
if (window.postMessage && !useragent.isOldIE) {
var postMessageId = 1;
exports.nextTick = function(callback, win) {
win = win || window;
var messageName = "zero-timeout-message-" + postMessageId;
exports.addListener(win, "message", function listener(e) {
if (e.data == messageName) {
exports.stopPropagation(e);
exports.removeListener(win, "message", listener);
callback();
}
});
win.postMessage(messageName, "*");
};
}
exports.nextFrame = window.requestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.msRequestAnimationFrame ||
window.oRequestAnimationFrame;
if (exports.nextFrame)
exports.nextFrame = exports.nextFrame.bind(window);
else
exports.nextFrame = function(callback) {
setTimeout(callback, 17);
};
});
| louis-tru/touch_code | client/third_party/ace/lib/ace/lib/event.js | JavaScript | bsd-3-clause | 12,179 |
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @emails oncall+jsinfra
*/
'use strict';
jest.unmock('everyObject');
var everyObject = require('everyObject');
describe('everyObject', function() {
var mockObject;
var mockCallback;
beforeEach(() => {
mockObject = {foo: 1, bar: 2, baz: 3};
mockCallback = jest.fn();
});
it('handles null', () => {
everyObject(null, mockCallback);
expect(mockCallback).not.toBeCalled();
});
it('returns true if all properties pass the test', () => {
mockCallback.mockImplementation(() => true);
var result = everyObject(mockObject, mockCallback);
expect(result).toBeTruthy();
expect(mockCallback.mock.calls).toEqual([
[1, 'foo', mockObject],
[2, 'bar', mockObject],
[3, 'baz', mockObject]
]);
});
it('returns false if any of the properties fail the test', () => {
mockCallback.mockImplementation(() => false);
var result = everyObject(mockObject, mockCallback);
expect(result).toBeFalsy();
expect(mockCallback).toBeCalled();
});
it('returns immediately upon finding a property that fails the test', () => {
mockCallback.mockImplementation(() => false);
var result = everyObject(mockObject, mockCallback);
expect(result).toBeFalsy();
expect(mockCallback.mock.calls.length).toEqual(1);
});
});
| chicoxyzzy/fbjs | packages/fbjs/src/functional/__tests__/everyObject-test.js | JavaScript | bsd-3-clause | 1,608 |
Ext.define('Ozone.data.Dashboard', {
extend: 'Ext.data.Model',
idProperty: 'guid',
fields:[
'alteredByAdmin',
'guid',
{name:'id', mapping: 'guid'},
{ name: 'isdefault', type: 'boolean', defaultValue: false },
{ name: 'dashboardPosition', type: 'int' },
'EDashboardLayoutList',
'name',
{ name: 'state', defaultValue: [] },
'removed',
'groups',
'isGroupDashboard',
'description',
'createdDate',
'prettyCreatedDate',
'editedDate',
'prettyEditedDate',
{ name: 'stack', defaultValue: null },
{ name: 'locked', type: 'boolean', defaultValue: false },
{ name: 'layoutConfig', defaultValue: null },
{ name: 'createdBy', model: 'User'},
{ name: 'user', model: 'User'}
],
constructor: function(data, id, raw) {
if(data.layoutConfig && typeof data.layoutConfig === 'string' && data.layoutConfig !== Object.prototype.toString()) {
data.layoutConfig = Ext.JSON.decode(data.layoutConfig);
}
//todo see if we still need this
if(data.layoutConfig === Object.prototype.toString()) {
data.layoutConfig = "";
}
if(!data.guid) {
data.guid = guid.util.guid();
}
this.callParent(arguments);
}
});
Ext.define('Ozone.data.stores.AdminDashboardStore', {
extend:'Ozone.data.OWFStore',
model: 'Ozone.data.Dashboard',
alias: 'store.admindashboardstore',
remoteSort: true,
totalProperty:'results',
sorters: [
{
property : 'dashboardPosition',
direction: 'ASC'
}
],
constructor: function(config) {
Ext.applyIf(config, {
api: {
read: "/dashboard",
create: "/dashboard",
update: "/dashboard",
destroy: "/dashboard"
},
reader: {
root: 'data'
},
writer: {
root: 'data'
}
});
this.callParent(arguments);
},
reorder: function() {
if (this.getCount() > 0) {
for (var i = 0; i < this.getCount(); i++) {
var dashboard = this.getAt(i);
dashboard.set('dashboardPosition', i + 1);
}
}
}
});
Ext.define('Ozone.components.admin.grid.DashboardGroupsGrid', {
extend: 'Ext.grid.Panel',
alias: ['widget.dashboardgroupsgrid'],
quickSearchFields: ['name'],
plugins: new Ozone.components.focusable.FocusableGridPanel(),
cls: 'grid-dashboard',
defaultPageSize: 50,
multiSelect: true,
forceFit: true,
baseParams: null,
initComponent: function() {
//create new store
if (this.store == null) {
this.store = Ext.StoreMgr.lookup({
type: 'admindashboardstore',
pageSize: this.defaultPageSize
});
}
if (this.baseParams) { this.setBaseParams(this.baseParams); }
Ext.apply(this, {
columnLines:true,
columns: [
{
itemId: 'guid',
header: 'GUID',
dataIndex: 'guid',
flex: 1,
width: 210,
minWidth: 210,
sortable: true,
hidden: true,
renderer: function(value, metaData, record, rowIndex, columnIndex, store, view) {
return '<div class="grid-text">' + value +'</div>';
}
},{
itemId: 'name',
header: 'Dashboard Title',
dataIndex: 'name',
flex: 3,
minWidth: 200,
sortable: true,
renderer: function(value, metaData, record, rowIndex, columnIndex, store, view) {
var title = value;
var dashboardLayoutList = record.get('EDashboardLayoutList'); //List of valid ENUM Dashboard Layout Strings
var dashboardLayout = record.get('layout'); //current dashboard layout string
var iconClass = "grid-dashboard-default-icon-layout";
// if(dashboardLayout && dashboardLayoutList){
// if(dashboardLayoutList.indexOf(dashboardLayout) != -1){
// iconClass = "grid-dashboard-icon-layout-" + dashboardLayout;
// }
// }
// var retVal = '<div class="grid-dashboard-title-box"><div class="grid-dashboard-icon ' + iconClass +'"></div>';
// retVal += '<div class="grid-dashboard-title">' + title + '</div>';
// retVal += '</div>';
return '<p class="grid-dashboard-title '+ iconClass + '">' + Ext.htmlEncode(title) + '</p>';
}
},
{
itemId: 'groups',
header: 'Groups',
dataIndex: 'groups',
flex: 1,
sortable: false,
renderer: function(value, metaData, record, rowIndex, columnIndex, store, view) {
return '<div class="grid-text grid-dashboard-group-count">' + value.length +'</div>';
}
},
{
itemId: 'widgets',
header: 'Widgets',
dataIndex: 'layoutConfig',
flex: 1,
sortable: false,
renderer: function(value, metaData, record, rowIndex, columnIndex, store, view) {
var widgetCount = 0;
if (value) {
var countWidgets = function(cfg) {
if(!cfg || !cfg.items)
return;
if(cfg.items.length === 0) {
if(cfg.widgets && cfg.widgets.length > 0) {
widgetCount += cfg.widgets.length;
}
}
else {
for(var i = 0, len = cfg.items.length; i < len; i++) {
countWidgets(cfg.items[i]);
}
}
return widgetCount;
};
widgetCount = countWidgets(value);
}
return '<div class="grid-text grid-dashboard-widget-count">' + widgetCount +'</div>';
}
}
]
});
Ext.apply(this, {
multiSelect: true,
dockedItems: [Ext.create('Ext.toolbar.Paging', {
dock: 'bottom',
store: this.store,
displayInfo: true,
hidden: this.hidePagingToolbar,
itemId: 'dashboard-groups-grid-paging'
})]
});
this.callParent(arguments);
},
getSelectedDashboards: function(){
return this.getSelectionModel().getSelection();
},
load: function() {
this.store.loadPage(1);
},
refresh: function() {
this.store.loadPage(this.store.currentPage);
},
getTopToolbar: function() {
return this.getDockedItems('toolbar[dock="top"]')[0];
},
getBottomToolbar: function() {
return this.getDockedItems('toolbar[dock="bottom"]')[0];
},
applyFilter: function(filterText, fields) {
this.store.proxy.extraParams = undefined;
if (filterText) {
var filters = [];
for (var i = 0; i < fields.length; i++) {
filters.push({
filterField: fields[i],
filterValue: filterText
});
}
this.store.proxy.extraParams = {
filters: Ext.JSON.encode(filters),
filterOperator: 'OR'
};
}
if (this.baseParams) { this.setBaseParams(this.baseParams); }
this.store.loadPage(1,{
params: {
offset: 0,
max: this.store.pageSize
}
});
},
clearFilters: function() {
this.store.proxy.extraParams = undefined;
if (this.baseParams) { this.setBaseParams(this.baseParams); }
this.store.load({
params: {
start: 0,
max: this.store.pageSize
}
});
},
setBaseParams: function(params) {
this.baseParams = params;
if (this.store.proxy.extraParams) {
Ext.apply(this.store.proxy.extraParams, params);
} else {
this.store.proxy.extraParams = params;
}
},
setStore: function(store, cols) {
this.reconfigure(store, cols);
var pgtb = this.getBottomToolbar();
if (pgtb) { pgtb.bindStore(store); }
}
});
Ext.define('Ozone.components.admin.dashboard.DashboardDetailPanel', {
extend: 'Ext.panel.Panel',
alias: ['widget.dashboarddetailpanel', 'widget.dashboarddetail'],
viewDashboard: null,
loadedRecord: null,
initComponent: function() {
//init quicktips
Ext.tip.QuickTipManager.init(true,{
dismissDelay: 60000,
showDelay: 2000
});
this.viewDashboard = Ext.create('Ext.view.View', {
store: Ext.create('Ext.data.Store', {
storeId: 'storeDashboardItem',
fields: [
{ name: 'name', type: 'string' },
{ name: 'layout', type: 'string' },
{ name: 'EDashboardLayoutList', type: 'string' },
{ name: 'isGroupDashboard', type: 'boolean'},
{ name: 'groups', model: 'Group'},
{ name: 'description', type: 'string' },
{ name: 'createdDate', type: 'string' },
{ name: 'prettyCreatedDate', type: 'string' },
{ name: 'editedDate', type: 'string' },
{ name: 'prettyEditedDate', type: 'string' },
{ name: 'createdBy', model: 'User' },
{ name: 'stack', model: 'Stack'}
]
}),
deferEmptyText: false,
tpl: new Ext.XTemplate(
'<tpl for=".">',
'<div class="selector">',
'<div id="detail-info" class="detail-info">',
'<div class="dashboard-detail-icon-block">',
'{[this.renderIconBlock(values)]}',
'</div>',
'<div class="dashboard-detail-info-block">',
'<div class="detail-header-block">',
'{[this.renderDetailHeaderBlock(values)]}',
'</div>',
'<div class="detail-block">',
'<div><span class="detail-label">Description:</span> {description:htmlEncode}</span></div><br>',
'<div><span class="detail-label">Groups:</span> {[this.renderGroups(values)]}</div>',
'<div><span class="detail-label">Created:</span> <span {createdDate:this.renderToolTip}>{prettyCreatedDate:this.renderDate}</span></div>',
'<div><span class="detail-label">Author:</span> {[this.renderUserRealName(values)]}</div>',
'<div><span class="detail-label">Last Modified:</span> <span {editedDate:this.renderToolTip}>{prettyEditedDate:this.renderDate}</span></div>',
'</div>',
'</div>',
'</div>',
'</div>',
'</tpl>',
{
compiled: true,
renderDate: function(value) {
return value ? value : '';
},
renderToolTip: function (value) {
var str = 'data-qtip="' + value + '"';
return str;
},
renderUserRealName: function(values) {
var createdBy = values.createdBy;
return (createdBy.userRealName ? Ext.htmlEncode(createdBy.userRealName) : '')
},
renderGroups: function(values) {
var groups = values.groups;
var stack = values.stack;
var retVal = '';
if (!stack && groups && groups.length > 0) {
for (var i = -1; ++i < groups.length;) {
retVal += Ext.htmlEncode(groups[i].name) + ', ';
}
retVal = retVal.substring(0, retVal.length - 2);
}
return retVal;
},
renderIconBlock: function(values) {
var iconClass = "dashboard-default-icon-layout";
var retVal = '<div class="dashboard-icon ' + iconClass + '"></div>';
return retVal;
},
renderDetailHeaderBlock: function(values){
var isGroupDashboard = values.isGroupDashboard;
var title = values.name;
var retVal = '<div class="dashboard-title-block">';
retVal += '<div class="dashboard-title detail-title">' + Ext.htmlEncode(title) + '</div>';
retVal += (isGroupDashboard) ? '<div>This is a group dashboard.</div>' : '';
retVal += '</div>';
return retVal;
}
}
),
emptyText: 'No dashboard selected',
itemSelector: 'div.selector',
autoScroll: 'true'
});
this.items = [this.viewDashboard];
this.callParent(arguments);
},
loadData: function(record) {
this.viewDashboard.store.loadData([record], false);
this.loadedRecord = record;
},
removeData: function() {
this.viewDashboard.store.removeAll(false);
this.loadedRecord = null;
}
});
Ext.define('Ozone.components.admin.dashboard.GroupDashboardManagementPanel', {
extend: 'Ozone.components.admin.ManagementPanel',
alias: ['widget.groupdashboardmanagement','widget.groupdashboardmanagementpanel','widget.Ozone.components.admin.GroupDashboardManagementPanel'],
layout: 'fit',
cls: 'groupdashboardmanagementpanel',
gridDashboards: null,
pnlDashboardDetail: null,
txtHeading: null,
lastAction: null,
guid_EditCopyWidget: null,
widgetStateHandler: null,
dragAndDrop: true,
launchesWidgets: true,
channel: 'AdminChannel',
defaultTitle: 'Group Dashboards',
minButtonWidth: 80,
detailsAutoOpen: true,
initComponent: function() {
var me = this;
OWF.Preferences.getUserPreference({
namespace: 'owf.admin.DashboardEditCopy',
name: 'guid_to_launch',
onSuccess: function(result) {
me.guid_EditCopyWidget = result.value;
},
onFailure: function(err){ /* No op */
me.showAlert('Preferences Error', 'Error looking up Dashboard Editor: ' + err);
}
});
this.gridDashboards = Ext.create('Ozone.components.admin.grid.DashboardGroupsGrid', {
preventHeader: true,
region: 'center',
border: false
});
this.gridDashboards.setBaseParams({
adminEnabled: true,
isGroupDashboard: true,
isStackDashboard: false
});
this.gridDashboards.store.load({
params: {
offset: 0,
max: this.pageSize
}
});
this.relayEvents(this.gridDashboards, ['datachanged', 'select', 'deselect', 'itemdblclick']);
this.pnlDashboardDetail = Ext.create('Ozone.components.admin.dashboard.DashboardDetailPanel', {
layout: {
type: 'fit',
align: 'stretch'
},
region: 'east',
preventHeader: true,
collapseMode: 'mini',
collapsible: true,
collapsed: true,
split: true,
border: false,
width: 266
});
this.txtHeading = Ext.create('Ext.toolbar.TextItem', {
text: '<span class="heading-bold">'+this.defaultTitle+'</span>'
});
this.searchBox = Ext.widget('searchbox');
this.items = [{
xtype: 'panel',
layout: 'border',
border: false,
items: [
this.gridDashboards,
this.pnlDashboardDetail
]
}];
this.dockedItems = [{
xtype: 'toolbar',
dock: 'top',
layout: {
type: 'hbox',
align: 'stretchmax'
},
items: [
this.txtHeading,
{
xtype: 'tbfill'
},
this.searchBox
]
}, {
xtype: 'toolbar',
dock: 'bottom',
ui: 'footer',
defaults: {
minWidth: this.minButtonWidth
},
items: [{
xtype: 'button',
text: 'Create',
handler: function(button, evt) {
evt.stopPropagation();
me.doCreate();
}
}, {
xtype: 'button',
text: 'Edit',
handler: function() {
me.doEdit();
}
}, {
xtype: 'button',
text: 'Delete',
handler: function(button) {
me.doDelete();
}
}]
}];
this.gridDashboards.store.on(
'load',
function(thisStore, records, options){
if ((this.pnlDashboardDetail != null ) &&
(!this.pnlDashboardDetail.collapsed) &&
(this.pnlDashboardDetail.loadedRecord != null)){
for(var idx=0; idx < records.length; idx++){
if(records[idx].id == this.pnlDashboardDetail.loadedRecord.id){
this.pnlDashboardDetail.loadData(records[idx]);
break;
}
}
}
},
this
);
this.on(
'datachanged',
function(store, opts) {
//collapse and clear detail panel if the store is refreshed
if (this.pnlDashboardDetail != null ) {
this.pnlDashboardDetail.collapse();
this.pnlDashboardDetail.removeData();
}
//refresh launch menu
if (!this.disableLaunchMenuRefresh) {
this.refreshWidgetLaunchMenu();
}
},
this
);
this.on(
'select',
function(rowModel, record, index, opts) {
this.pnlDashboardDetail.loadData(record);
if (this.pnlDashboardDetail.collapsed && this.detailsAutoOpen) {this.pnlDashboardDetail.expand();}
},
this
);
this.searchBox.on(
'searchChanged',
function(searchbox, value) {
var grid = this.gridDashboards;
if (grid) {
if (!value)
this.gridDashboards.clearFilters();
else
this.gridDashboards.applyFilter(value, ['name', 'description']);
}
},
this
);
this.on({
'itemdblclick': {
scope: this,
fn: this.doEdit
}
});
this.gridDashboards.getView().on({
itemkeydown: {
scope: this,
fn: function(view, record, dom, index, evt) {
switch(evt.getKey()) {
case evt.SPACE:
case evt.ENTER:
this.doEdit();
}
}
}
});
this.callParent(arguments);
OWF.Eventing.subscribe('AdminChannel', owfdojo.hitch(this, function(sender, msg, channel) {
if(msg.domain === 'Dashboard') {
this.gridDashboards.getBottomToolbar().doRefresh();
}
}));
this.on(
'afterrender',
function() {
var splitterEl = this.el.down(".x-collapse-el");
splitterEl.on('click', function() {
var collapsed = this.el.down(".x-splitter-collapsed");
if(collapsed) {
this.detailsAutoOpen = true;
}
else {
this.detailsAutoOpen = false;
}
}, this);
},
this
);
},
onLaunchFailed: function(response) {
if (response.error) {
this.showAlert('Launch Error', 'Dashboard Editor Launch Failed: ' + response.message);
}
},
doCreate: function() {
var dataString = Ozone.util.toString({
copyFlag: false,
isCreate: true,
isGroupDashboard: true
});
OWF.Launcher.launch({
guid: this.guid_EditCopyWidget,
launchOnlyIfClosed: false,
data: dataString
}, this.onLaunchFailed);
},
doEdit: function() {
var records = this.gridDashboards.getSelectedDashboards();
if (records && records.length > 0) {
for (var i = 0; i < records.length; i++) {
var id = records[i].getId();//From Id property of Dashboard Model
var dataString = Ozone.util.toString({
id: id,
copyFlag: false,
isCreate: false,
isGroupDashboard: true
});
OWF.Launcher.launch({
title: '$1 - ' + records[i].get('name'),
titleRegex: /(.*)/,
guid: this.guid_EditCopyWidget,
launchOnlyIfClosed: false,
data: dataString
}, this.onLaunchFailed);
}
} else {
this.showAlert("Error", "You must select at least one dashboard to edit");
}
},
doDelete: function() {
var records = this.gridDashboards.getSelectionModel().getSelection();
if (records && records.length > 0) {
var msg = 'This action will permanently delete ';
if (records.length == 1) {
msg += '<span class="heading-bold">' + Ext.htmlEncode(records[0].data.name) + '</span>.';
}
else {
msg += 'the selected <span class="heading-bold">' + records.length + ' dashboards</span>.';
}
this.showConfirmation('Warning', msg, function(btn, text, opts) {
if(btn == 'ok') {
var store = this.gridDashboards.getStore();
store.remove(records);
var remainingRecords = store.getTotalCount() - records.length;
store.on({
write: {
fn: function() {
if(store.data.items.length == 0 && store.currentPage > 1) {
var lastPage = store.getPageFromRecordIndex(remainingRecords - 1);
var pageToLoad = (lastPage >= store.currentPage) ? store.currentPage : lastPage;
store.loadPage(pageToLoad);
}
this.gridDashboards.getBottomToolbar().doRefresh();
this.pnlDashboardDetail.removeData();
if(!this.pnlDashboardDetail.collapsed) {
this.pnlDashboardDetail.collapse();}
this.refreshWidgetLaunchMenu();
},
scope: this,
single: true
}
});
store.save();
}
});
} else {
this.showAlert("Error", "You must select at least one dashboard to delete");
}
}
});
| Nanonid/tcsolrsvc | webapps/owf/js/owf-group-dashboard-management-widget.js | JavaScript | bsd-3-clause | 24,987 |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/**
* @fileoverview A command is an abstraction of an action a user can do in the
* UI.
*
* When the focus changes in the document for each command a canExecute event
* is dispatched on the active element. By listening to this event you can
* enable and disable the command by setting the event.canExecute property.
*
* When a command is executed a command event is dispatched on the active
* element. Note that you should stop the propagation after you have handled the
* command if there might be other command listeners higher up in the DOM tree.
*/
cr.define('cr.ui', function() {
/**
* This is used to identify keyboard shortcuts.
* @param {string} shortcut The text used to describe the keys for this
* keyboard shortcut.
* @constructor
*/
function KeyboardShortcut(shortcut) {
var mods = {};
var ident = '';
shortcut.split('-').forEach(function(part) {
var partLc = part.toLowerCase();
switch (partLc) {
case 'alt':
case 'ctrl':
case 'meta':
case 'shift':
mods[partLc + 'Key'] = true;
break;
default:
if (ident)
throw Error('Invalid shortcut');
ident = part;
}
});
this.ident_ = ident;
this.mods_ = mods;
}
KeyboardShortcut.prototype = {
/**
* Whether the keyboard shortcut object matches a keyboard event.
* @param {!Event} e The keyboard event object.
* @return {boolean} Whether we found a match or not.
*/
matchesEvent: function(e) {
if (e.keyIdentifier == this.ident_) {
// All keyboard modifiers needs to match.
var mods = this.mods_;
return ['altKey', 'ctrlKey', 'metaKey', 'shiftKey'].every(function(k) {
return e[k] == !!mods[k];
});
}
return false;
}
};
/**
* Creates a new command element.
* @constructor
* @extends {HTMLElement}
*/
var Command = cr.ui.define('command');
Command.prototype = {
__proto__: HTMLElement.prototype,
/**
* Initializes the command.
*/
decorate: function() {
CommandManager.init(this.ownerDocument);
if (this.hasAttribute('shortcut'))
this.shortcut = this.getAttribute('shortcut');
},
/**
* Executes the command by dispatching a command event on the given element.
* If |element| isn't given, the active element is used instead.
* If the command is {@code disabled} this does nothing.
* @param {HTMLElement=} opt_element Optional element to dispatch event on.
*/
execute: function(opt_element) {
if (this.disabled)
return;
var doc = this.ownerDocument;
if (doc.activeElement) {
var e = new cr.Event('command', true, false);
e.command = this;
(opt_element || doc.activeElement).dispatchEvent(e);
}
},
/**
* Call this when there have been changes that might change whether the
* command can be executed or not.
* @param {Node=} opt_node Node for which to actuate command state.
*/
canExecuteChange: function(opt_node) {
dispatchCanExecuteEvent(this,
opt_node || this.ownerDocument.activeElement);
},
/**
* The keyboard shortcut that triggers the command. This is a string
* consisting of a keyIdentifier (as reported by WebKit in keydown) as
* well as optional key modifiers joinded with a '-'.
*
* Multiple keyboard shortcuts can be provided by separating them by
* whitespace.
*
* For example:
* "F1"
* "U+0008-Meta" for Apple command backspace.
* "U+0041-Ctrl" for Control A
* "U+007F U+0008-Meta" for Delete and Command Backspace
*
* @type {string}
*/
shortcut_: '',
get shortcut() {
return this.shortcut_;
},
set shortcut(shortcut) {
var oldShortcut = this.shortcut_;
if (shortcut !== oldShortcut) {
this.keyboardShortcuts_ = shortcut.split(/\s+/).map(function(shortcut) {
return new KeyboardShortcut(shortcut);
});
// Set this after the keyboardShortcuts_ since that might throw.
this.shortcut_ = shortcut;
cr.dispatchPropertyChange(this, 'shortcut', this.shortcut_,
oldShortcut);
}
},
/**
* Whether the event object matches the shortcut for this command.
* @param {!Event} e The key event object.
* @return {boolean} Whether it matched or not.
*/
matchesEvent: function(e) {
if (!this.keyboardShortcuts_)
return false;
return this.keyboardShortcuts_.some(function(keyboardShortcut) {
return keyboardShortcut.matchesEvent(e);
});
}
};
/**
* The label of the command.
* @type {string}
*/
cr.defineProperty(Command, 'label', cr.PropertyKind.ATTR);
/**
* Whether the command is disabled or not.
* @type {boolean}
*/
cr.defineProperty(Command, 'disabled', cr.PropertyKind.BOOL_ATTR);
/**
* Whether the command is hidden or not.
* @type {boolean}
*/
cr.defineProperty(Command, 'hidden', cr.PropertyKind.BOOL_ATTR);
/**
* Whether the command is checked or not.
* @type {boolean}
*/
cr.defineProperty(Command, 'checked', cr.PropertyKind.BOOL_ATTR);
/**
* Dispatches a canExecute event on the target.
* @param {cr.ui.Command} command The command that we are testing for.
* @param {Element} target The target element to dispatch the event on.
*/
function dispatchCanExecuteEvent(command, target) {
var e = new CanExecuteEvent(command, true);
target.dispatchEvent(e);
command.disabled = !e.canExecute;
}
/**
* The command managers for different documents.
*/
var commandManagers = {};
/**
* Keeps track of the focused element and updates the commands when the focus
* changes.
* @param {!Document} doc The document that we are managing the commands for.
* @constructor
*/
function CommandManager(doc) {
doc.addEventListener('focus', this.handleFocus_.bind(this), true);
// Make sure we add the listener to the bubbling phase so that elements can
// prevent the command.
doc.addEventListener('keydown', this.handleKeyDown_.bind(this), false);
}
/**
* Initializes a command manager for the document as needed.
* @param {!Document} doc The document to manage the commands for.
*/
CommandManager.init = function(doc) {
var uid = cr.getUid(doc);
if (!(uid in commandManagers)) {
commandManagers[uid] = new CommandManager(doc);
}
};
CommandManager.prototype = {
/**
* Handles focus changes on the document.
* @param {Event} e The focus event object.
* @private
*/
handleFocus_: function(e) {
var target = e.target;
// Ignore focus on a menu button or command item
if (target.menu || target.command)
return;
var commands = Array.prototype.slice.call(
target.ownerDocument.querySelectorAll('command'));
commands.forEach(function(command) {
dispatchCanExecuteEvent(command, target);
});
},
/**
* Handles the keydown event and routes it to the right command.
* @param {!Event} e The keydown event.
*/
handleKeyDown_: function(e) {
var target = e.target;
var commands = Array.prototype.slice.call(
target.ownerDocument.querySelectorAll('command'));
for (var i = 0, command; command = commands[i]; i++) {
if (!command.disabled && command.matchesEvent(e)) {
e.preventDefault();
// We do not want any other element to handle this.
e.stopPropagation();
command.execute();
return;
}
}
}
};
/**
* The event type used for canExecute events.
* @param {!cr.ui.Command} command The command that we are evaluating.
* @extends {Event}
* @constructor
* @class
*/
function CanExecuteEvent(command) {
var e = command.ownerDocument.createEvent('Event');
e.initEvent('canExecute', true, false);
e.__proto__ = CanExecuteEvent.prototype;
e.command = command;
return e;
}
CanExecuteEvent.prototype = {
__proto__: Event.prototype,
/**
* The current command
* @type {cr.ui.Command}
*/
command: null,
/**
* Whether the target can execute the command. Setting this also stops the
* propagation.
* @type {boolean}
*/
canExecute_: false,
get canExecute() {
return this.canExecute_;
},
set canExecute(canExecute) {
this.canExecute_ = !!canExecute;
this.stopPropagation();
}
};
// Export
return {
Command: Command,
CanExecuteEvent: CanExecuteEvent
};
});
| timopulkkinen/BubbleFish | ui/webui/resources/js/cr/ui/command.js | JavaScript | bsd-3-clause | 8,976 |
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
jest.disableAutomock();
const React = require('React');
const ReactTestRenderer = require('react-test-renderer');
const VirtualizedList = require('VirtualizedList');
describe('VirtualizedList', () => {
it('renders simple list', () => {
const component = ReactTestRenderer.create(
<VirtualizedList
data={[{key: 'i1'}, {key: 'i2'}, {key: 'i3'}]}
renderItem={({item}) => <item value={item.key} />}
/>
);
expect(component).toMatchSnapshot();
});
it('renders empty list', () => {
const component = ReactTestRenderer.create(
<VirtualizedList
data={[]}
renderItem={({item}) => <item value={item.key} />}
/>
);
expect(component).toMatchSnapshot();
});
it('renders null list', () => {
const component = ReactTestRenderer.create(
<VirtualizedList
data={undefined}
renderItem={({item}) => <item value={item.key} />}
/>
);
expect(component).toMatchSnapshot();
});
it('renders all the bells and whistles', () => {
const component = ReactTestRenderer.create(
<VirtualizedList
ItemSeparatorComponent={() => <separator />}
ListFooterComponent={() => <footer />}
ListHeaderComponent={() => <header />}
data={new Array(5).fill().map((_, ii) => ({id: String(ii)}))}
keyExtractor={(item, index) => item.id}
getItemLayout={({index}) => ({length: 50, offset: index * 50})}
numColumns={2}
refreshing={false}
onRefresh={jest.fn()}
renderItem={({item}) => <item value={item.id} />}
/>
);
expect(component).toMatchSnapshot();
});
it('test getItem functionality where data is not an Array', () => {
const component = ReactTestRenderer.create(
<VirtualizedList
data={new Map([['id_0', {key: 'item_0'}]])}
getItem={(data, index) => data.get('id_' + index)}
getItemCount={(data: Map) => data.size}
renderItem={({item}) => <item value={item.key} />}
/>
);
expect(component).toMatchSnapshot();
});
});
| Maxwell2022/react-native | Libraries/Lists/__tests__/VirtualizedList-test.js | JavaScript | bsd-3-clause | 2,405 |
define(["require"], function (require) {
function boot(ev) {
ev.target.removeEventListener("click", boot);
require(["demos/water/water"]);
}
const start = document.querySelector(".code-demo.water [data-trigger='water.start']");
start.addEventListener("click", boot);
start.disabled = false;
});
| canena/canena.github.io | src/_resources/js/demos/water/boot.js | JavaScript | bsd-3-clause | 333 |
'use strict';
angular.module("ngLocale", [], ["$provide", function ($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
function getDecimals(n) {
n = n + '';
var i = n.indexOf('.');
return (i == -1) ? 0 : n.length - i - 1;
}
function getVF(n, opt_precision) {
var v = opt_precision;
if (undefined === v) {
v = Math.min(getDecimals(n), 3);
}
var base = Math.pow(10, v);
var f = ((n * base) | 0) % base;
return {v: v, f: f};
}
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"AM",
"PM"
],
"DAY": [
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday"
],
"ERANAMES": [
"Before Christ",
"Anno Domini"
],
"ERAS": [
"BC",
"AD"
],
"FIRSTDAYOFWEEK": 6,
"MONTH": [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
],
"SHORTDAY": [
"Sun",
"Mon",
"Tue",
"Wed",
"Thu",
"Fri",
"Sat"
],
"SHORTMONTH": [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec"
],
"STANDALONEMONTH": [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
],
"WEEKENDRANGE": [
5,
6
],
"fullDate": "EEEE, d MMMM y",
"longDate": "d MMMM y",
"medium": "d MMM y h:mm:ss a",
"mediumDate": "d MMM y",
"mediumTime": "h:mm:ss a",
"short": "d/M/yy h:mm a",
"shortDate": "d/M/yy",
"shortTime": "h:mm a"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "$",
"DECIMAL_SEP": ".",
"GROUP_SEP": ",",
"PATTERNS": [
{
"gSize": 3,
"lgSize": 3,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
{
"gSize": 3,
"lgSize": 3,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "-\u00a4",
"negSuf": "",
"posPre": "\u00a4",
"posSuf": ""
}
]
},
"id": "en-jm",
"localeID": "en_JM",
"pluralCat": function (n, opt_precision) {
var i = n | 0;
var vf = getVF(n, opt_precision);
if (i == 1 && vf.v == 0) {
return PLURAL_CATEGORY.ONE;
}
return PLURAL_CATEGORY.OTHER;
}
});
}]);
| mudunuriRaju/tlr-live | tollbackend/web/js/angular-1.5.5/i18n/angular-locale_en-jm.js | JavaScript | bsd-3-clause | 4,012 |
define(["pat-autoscale", "jquery"], function(pattern, jQuery) {
describe("pat-autoscale", function() {
beforeEach(function() {
$("<div/>", {id: "lab"}).appendTo(document.body);
$(window).off(".autoscale");
});
afterEach(function() {
$("#lab").remove();
});
describe("setup", function() {
var force_method, mozilla, msie, version;
beforeEach(function() {
force_method=pattern.force_method;
mozilla=jQuery.browser.mozilla;
msie=jQuery.browser.msie;
version=jQuery.browser.version;
pattern.force_method=null;
jQuery.browser.mozilla=false;
jQuery.browser.msie=false;
});
afterEach(function() {
pattern.force_method=force_method;
jQuery.browser.mozilla=mozilla;
jQuery.browser.msie=msie;
jQuery.browser.version=version;
});
it("Force zoom on old IE versions", function() {
jQuery.browser.msie=true;
jQuery.browser.version="8.192.921";
pattern._setup();
expect(pattern.force_method).toBe("zoom");
});
it("Force nothing on recent IE versions", function() {
jQuery.browser.msie=true;
jQuery.browser.version="9.0.19A";
pattern._setup();
expect(pattern.force_method).toBe(null);
});
it("Force scale on gecko", function() {
// See https://bugzilla.mozilla.org/show_bug.cgi?id=390936
jQuery.browser.mozilla=true;
pattern._setup();
expect(pattern.force_method).toBe("scale");
});
it("Force nothing on other browsers", function() {
pattern._setup();
expect(pattern.force_method).toBe(null);
});
});
describe("init", function() {
var force_method;
beforeEach(function() {
force_method=pattern.force_method;
});
afterEach(function() {
pattern.force_method=force_method;
});
it("Return jQuery object", function() {
var jq = jasmine.createSpyObj("jQuery", ["each"]);
jq.each.andReturn(jq);
expect(pattern.init(jq)).toBe(jq);
});
it("Perform initial scaling", function() {
$("<div/>", {id: "parent"}).css({width: "200px"})
.append($("<div/>", {id: "child", "data-pat-auto-scale": "scale"})
.css({width: "50px"}))
.appendTo("#lab");
var $child = $("#child");
spyOn(pattern, "scale");
pattern.init($child);
expect(pattern.scale).toHaveBeenCalled();
});
it("Honour method override", function() {
$("<div/>", {id: "parent"}).css({width: "200px"})
.append($("<div/>", {id: "child", "data-pat-auto-scale": "scale"})
.css({width: "50px"}))
.appendTo("#lab");
var $child = $("#child");
pattern.force_method = "forced";
pattern.init($child);
expect($child.data("patterns.auto-scale").method).toBe("forced");
});
});
describe("scale", function() {
it("Scale element", function() {
$("<div/>", {id: "parent"}).css({width: "200px"})
.append($("<div/>", {id: "child"}).css({width: "50px"}))
.appendTo("#lab");
var child = document.getElementById("child");
$(child).data("patterns.auto-scale", {method: "scale", minWidth: 0, maxWidth: 1000});
pattern.scale.apply(child, []);
expect(child.getAttribute("style")).toMatch(/transform: scale\(4\);/);
});
it("Zoom element", function() {
$("<div/>", {id: "parent"}).css({width: "200px"})
.append($("<div/>", {id: "child"}).css({width: "50px"}))
.appendTo("#lab");
var child = document.getElementById("child");
$(child).data("patterns.auto-scale", {method: "zoom", minWidth: 0, maxWidth: 1000});
pattern.scale.apply(child, []);
expect(child.style.zoom).toBe("4");
});
it("Honour minimum width", function() {
$("<div/>", {id: "parent"}).css({width: "100px"})
.append($("<div/>", {id: "child"}).css({width: "400px"}))
.appendTo("#lab");
var child = document.getElementById("child");
$(child).data("patterns.auto-scale", {method: "zoom", minWidth: 200, maxWidth: 1000});
pattern.scale.apply(child, []);
expect(child.style.zoom).toBe("0.5");
});
it("Honour maximum width", function() {
$("<div/>", {id: "parent"}).css({width: "200px"})
.append($("<div/>", {id: "child"}).css({width: "50px"}))
.appendTo("#lab");
var child = document.getElementById("child");
$(child).data("patterns.auto-scale", {method: "zoom", minWidth: 0, maxWidth: 100});
pattern.scale.apply(child, []);
expect(child.style.zoom).toBe("2");
});
it("Add scaled class", function() {
$("<div/>", {id: "parent"}).css({width: "200px"})
.append($("<div/>", {id: "child"}).css({width: "50px"}))
.appendTo("#lab");
var child = document.getElementById("child");
$(child).data("patterns.auto-scale", {method: "zoom", minWidth: 0, maxWidth: 1000});
pattern.scale.apply(child, []);
expect($(child).hasClass("scaled")).toBeTruthy();
});
});
});
});
| Patternslib/Patterns-archive | tests/specs/pat/autoscale.js | JavaScript | bsd-3-clause | 6,201 |
function* f() {
var x;
try {
x = yield 1;
} catch (ex) {
yield ex;
}
return 2;
}
var g = f();
expect(g.next()).toEqual({value: 1, done: false});
expect(g.next()).toEqual({value: 2, done: true});
g = f();
expect(g.next()).toEqual({value: 1, done: false});
expect(g.throw(3)).toEqual({value: 3, done: false});
expect(g.next()).toEqual({value: 2, done: true});
| kellyselden/babel | packages/babel-preset-es2015/test/fixtures/traceur/Yield/YieldAssignThrow.js | JavaScript | mit | 378 |
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is
* regenerated.
*/
'use strict';
const models = require('./index');
/**
* Properties of an artifact source.
*
* @extends models['Resource']
*/
class ArtifactSource extends models['Resource'] {
/**
* Create a ArtifactSource.
* @member {string} [displayName] The artifact source's display name.
* @member {string} [uri] The artifact source's URI.
* @member {string} [sourceType] The artifact source's type. Possible values
* include: 'VsoGit', 'GitHub'
* @member {string} [folderPath] The folder containing artifacts.
* @member {string} [armTemplateFolderPath] The folder containing Azure
* Resource Manager templates.
* @member {string} [branchRef] The artifact source's branch reference.
* @member {string} [securityToken] The security token to authenticate to the
* artifact source.
* @member {string} [status] Indicates if the artifact source is enabled
* (values: Enabled, Disabled). Possible values include: 'Enabled',
* 'Disabled'
* @member {date} [createdDate] The artifact source's creation date.
* @member {string} [provisioningState] The provisioning status of the
* resource.
* @member {string} [uniqueIdentifier] The unique immutable identifier of a
* resource (Guid).
*/
constructor() {
super();
}
/**
* Defines the metadata of ArtifactSource
*
* @returns {object} metadata of ArtifactSource
*
*/
mapper() {
return {
required: false,
serializedName: 'ArtifactSource',
type: {
name: 'Composite',
className: 'ArtifactSource',
modelProperties: {
id: {
required: false,
readOnly: true,
serializedName: 'id',
type: {
name: 'String'
}
},
name: {
required: false,
readOnly: true,
serializedName: 'name',
type: {
name: 'String'
}
},
type: {
required: false,
readOnly: true,
serializedName: 'type',
type: {
name: 'String'
}
},
location: {
required: false,
serializedName: 'location',
type: {
name: 'String'
}
},
tags: {
required: false,
serializedName: 'tags',
type: {
name: 'Dictionary',
value: {
required: false,
serializedName: 'StringElementType',
type: {
name: 'String'
}
}
}
},
displayName: {
required: false,
serializedName: 'properties.displayName',
type: {
name: 'String'
}
},
uri: {
required: false,
serializedName: 'properties.uri',
type: {
name: 'String'
}
},
sourceType: {
required: false,
serializedName: 'properties.sourceType',
type: {
name: 'String'
}
},
folderPath: {
required: false,
serializedName: 'properties.folderPath',
type: {
name: 'String'
}
},
armTemplateFolderPath: {
required: false,
serializedName: 'properties.armTemplateFolderPath',
type: {
name: 'String'
}
},
branchRef: {
required: false,
serializedName: 'properties.branchRef',
type: {
name: 'String'
}
},
securityToken: {
required: false,
serializedName: 'properties.securityToken',
type: {
name: 'String'
}
},
status: {
required: false,
serializedName: 'properties.status',
type: {
name: 'String'
}
},
createdDate: {
required: false,
readOnly: true,
serializedName: 'properties.createdDate',
type: {
name: 'DateTime'
}
},
provisioningState: {
required: false,
serializedName: 'properties.provisioningState',
type: {
name: 'String'
}
},
uniqueIdentifier: {
required: false,
serializedName: 'properties.uniqueIdentifier',
type: {
name: 'String'
}
}
}
}
};
}
}
module.exports = ArtifactSource;
| lmazuel/azure-sdk-for-node | lib/services/devTestLabs/lib/models/artifactSource.js | JavaScript | mit | 5,125 |
Subsets and Splits