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 |
|---|---|---|---|---|---|
'use strict';
angular.module(ApplicationConfiguration.applicationModuleName).controller('LeftNavController',
function(Authentication, $mdSidenav, Menus, $log) {
this.authentication = Authentication;
this.isCollapsed = false;
this.menu = Menus.getMenu('sidenav');
this.selected = '';
this.isSelected = function(item) {
return this.selected === item;
};
this.selectItem = function(item) {
this.selected = item;
};
//this.toggleCollapsibleMenu = function() {
// this.isCollapsed = !this.isCollapsed;
//};
//
//// Collapsing the menu after navigation
//this.$on('$stateChangeSuccess', function() {
// this.isCollapsed = false;
//});
//
//this.toggleMenu = function() {
// $mdSidenav('left').toggle();
//};
//
//$mdSidenav('lefty').open();
this.toggleCollapsibleMenu = function() {
$mdSidenav('left').toggle();
console.log($mdSidenav('left').isOpen());
//$mdSidenav('left').close()
// .then(function(){
// $log.debug('close LEFT is done');
// });
};
}
);
| rivetsystems/angular-mean-material-seed | public/modules/core/controllers/leftnav.client.controller.js | JavaScript | mit | 1,053 |
/*
coerces a value into a boolean
*/
'use strict';
var value = require('useful-value');
module.exports = function boolean(val) {
val = value.coerce(val);
return !!val;
};
| super-useful/su-apiserver | lib/validators/boolean.js | JavaScript | mit | 181 |
'use strict';
const common = require('../common');
const assert = require('assert');
const URLSearchParams = require('url').URLSearchParams;
const { test, assert_equals, assert_true } = require('../common/wpt');
/* The following tests are copied from WPT. Modifications to them should be
upstreamed first. Refs:
https://github.com/w3c/web-platform-tests/blob/8791bed/url/urlsearchparams-set.html
License: http://www.w3.org/Consortium/Legal/2008/04-testsuite-copyright.html
*/
/* eslint-disable */
test(function() {
var params = new URLSearchParams('a=b&c=d');
params.set('a', 'B');
assert_equals(params + '', 'a=B&c=d');
params = new URLSearchParams('a=b&c=d&a=e');
params.set('a', 'B');
assert_equals(params + '', 'a=B&c=d')
params.set('e', 'f');
assert_equals(params + '', 'a=B&c=d&e=f')
}, 'Set basics');
test(function() {
var params = new URLSearchParams('a=1&a=2&a=3');
assert_true(params.has('a'), 'Search params object has name "a"');
assert_equals(params.get('a'), '1', 'Search params object has name "a" with value "1"');
params.set('first', 4);
assert_true(params.has('a'), 'Search params object has name "a"');
assert_equals(params.get('a'), '1', 'Search params object has name "a" with value "1"');
params.set('a', 4);
assert_true(params.has('a'), 'Search params object has name "a"');
assert_equals(params.get('a'), '4', 'Search params object has name "a" with value "4"');
}, 'URLSearchParams.set');
/* eslint-enable */
// Tests below are not from WPT.
{
const params = new URLSearchParams();
assert.throws(() => {
params.set.call(undefined);
}, common.expectsError({
code: 'ERR_INVALID_THIS',
type: TypeError,
message: 'Value of "this" must be of type URLSearchParams'
}));
assert.throws(() => {
params.set('a');
}, common.expectsError({
code: 'ERR_MISSING_ARGS',
type: TypeError,
message: 'The "name" and "value" arguments must be specified'
}));
const obj = {
toString() { throw new Error('toString'); },
valueOf() { throw new Error('valueOf'); }
};
const sym = Symbol();
assert.throws(() => params.append(obj, 'b'), /^Error: toString$/);
assert.throws(() => params.append('a', obj), /^Error: toString$/);
assert.throws(() => params.append(sym, 'b'),
/^TypeError: Cannot convert a Symbol value to a string$/);
assert.throws(() => params.append('a', sym),
/^TypeError: Cannot convert a Symbol value to a string$/);
}
| hoho/dosido | nodejs/test/parallel/test-whatwg-url-searchparams-set.js | JavaScript | mit | 2,515 |
module.exports={A:{A:{"1":"B","16":"mB","129":"F A","130":"M D H"},B:{"1":"C E q L O I J K"},C:{"1":"0 1 2 3 4 5 6 8 9 jB AB G M D H F A B C E q L O I J P Q R S T U V W X Y Z a b c d f g h i j k l m n o p N r s t u v w x y z LB BB CB DB EB FB HB IB JB eB cB"},D:{"1":"0 1 2 3 4 5 6 8 9 G M D H F A B C E q L O I J P Q R S T U V W X Y Z a b c d f g h i j k l m n o p N r s t u v w x y z LB BB CB DB EB FB HB IB JB bB VB PB oB K QB RB SB TB"},E:{"1":"5 7 G M D H F A B C E NB WB XB YB ZB aB e dB KB","16":"UB"},F:{"1":"0 1 2 3 4 7 8 B C L O I J P Q R S T U V W X Y Z a b c d f g h i j k l m n o p N r s t u v w x y z fB gB hB iB e MB kB","16":"F"},G:{"1":"H E lB GB nB OB pB qB rB sB tB uB vB wB xB yB KB","16":"NB"},H:{"1":"zB"},I:{"1":"AB G K 2B 3B GB 4B 5B","16":"0B 1B"},J:{"1":"D A"},K:{"1":"7 A B C N e MB"},L:{"1":"K"},M:{"1":"6"},N:{"1":"B","129":"A"},O:{"1":"6B"},P:{"1":"G 7B 8B 9B AC BC"},Q:{"1":"CC"},R:{"1":"DC"},S:{"1":"EC"}},B:1,C:"EventTarget.dispatchEvent"};
| emccosky/emccosky.github.io | node_modules/caniuse-lite/data/features/dispatchevent.js | JavaScript | mit | 974 |
version https://git-lfs.github.com/spec/v1
oid sha256:ba70bb48cb8b3fa4039462224a789adb71a3ff64f8c3c3da603a633299e783af
size 2528
| yogeshsaroya/new-cdnjs | ajax/libs/mathjax/2.5.1/jax/output/HTML-CSS/fonts/STIX/General/Bold/MathBold.js | JavaScript | mit | 129 |
const replaceSpritePlaceholder = require('./replace-sprite-placeholder');
/**
* @param {NormalModule|ExtractedModule} module
* @param {Object<string, string>} replacements
* @return {NormalModule|ExtractedModule}
*/
function replaceInModuleSource(module, replacements) {
const source = module._source;
if (typeof source === 'string') {
module._source = replaceSpritePlaceholder(source, replacements);
} else if (typeof source === 'object' && typeof source._value === 'string') {
source._value = replaceSpritePlaceholder(source._value, replacements);
}
return module;
}
module.exports = replaceInModuleSource;
| kisenka/svg-sprite-loader | lib/utils/replace-in-module-source.js | JavaScript | mit | 635 |
'use strict'; // eslint-disable-line semi
const request = require('supertest');
const {expect} = require('chai');
const db = require('APP/db');
const app = require('./start');
describe('/api/users', () => {
before('Await database sync', () => db.didSync);
afterEach('Clear the tables', () => db.truncate({ cascade: true }));
describe('GET /:id', () => {
describe('when not logged in', () => {
it('fails with a 401 (Unauthorized)', () =>
request(app)
.get(`/api/users/1`)
.expect(401)
);
});
});
describe('POST', () => {
describe('when not logged in', () => {
it('creates a user', () =>
request(app)
.post('/api/users')
.send({
email: 'beth@secrets.org',
password: '12345'
})
.expect(201)
);
it('redirects to the user it just made', () =>
request(app)
.post('/api/users')
.send({
email: 'eve@interloper.com',
password: '23456',
})
.redirects(1)
.then(res => expect(res.body).to.contain({
email: 'eve@interloper.com'
}))
);
});
});
});
| jzheng16/personal-website | server/users.test.js | JavaScript | mit | 1,217 |
'use strict';
var babelHelpers = require('./util/babelHelpers.js');
var React = require('react'),
_ = require('./util/_'),
cx = require('classnames'),
dates = require('./util/dates'),
localizers = require('./util/configuration').locale,
CustomPropTypes = require('./util/propTypes'),
Btn = require('./WidgetButton');
var format = function format(props) {
return props.yearFormat || localizers.date.formats.year;
};
module.exports = React.createClass({
displayName: 'DecadeView',
mixins: [require('./mixins/WidgetMixin'), require('./mixins/PureRenderMixin'), require('./mixins/RtlChildContextMixin')],
propTypes: {
culture: React.PropTypes.string,
value: React.PropTypes.instanceOf(Date),
focused: React.PropTypes.instanceOf(Date),
min: React.PropTypes.instanceOf(Date),
max: React.PropTypes.instanceOf(Date),
onChange: React.PropTypes.func.isRequired,
yearFormat: CustomPropTypes.dateFormat
},
render: function render() {
var props = _.omit(this.props, ['max', 'min', 'value', 'onChange']),
years = getDecadeYears(this.props.focused),
rows = _.chunk(years, 4);
return React.createElement(
'table',
babelHelpers._extends({}, props, {
role: 'grid',
className: 'rw-calendar-grid rw-nav-view',
'aria-activedescendant': this._id('_selected_item') }),
React.createElement(
'tbody',
null,
rows.map(this._row)
)
);
},
_row: function _row(row, i) {
var _this = this;
var id = this._id('_selected_item');
return React.createElement(
'tr',
{ key: 'row_' + i, role: 'row' },
row.map(function (date, i) {
var focused = dates.eq(date, _this.props.focused, 'year'),
selected = dates.eq(date, _this.props.value, 'year'),
currentYear = dates.eq(date, _this.props.today, 'year');
return !dates.inRange(date, _this.props.min, _this.props.max, 'year') ? React.createElement(
'td',
{ key: i, role: 'gridcell', className: 'rw-empty-cell' },
' '
) : React.createElement(
'td',
{ key: i, role: 'gridcell' },
React.createElement(
Btn,
{ onClick: _this.props.onChange.bind(null, date), tabIndex: '-1',
id: focused ? id : undefined,
'aria-pressed': selected,
'aria-disabled': _this.props.disabled,
disabled: _this.props.disabled || undefined,
className: cx({
'rw-off-range': !inDecade(date, _this.props.focused),
'rw-state-focus': focused,
'rw-state-selected': selected,
'rw-now': currentYear
}) },
localizers.date.format(date, format(_this.props), _this.props.culture)
)
);
})
);
}
});
function inDecade(date, start) {
return dates.gte(date, dates.startOf(start, 'decade'), 'year') && dates.lte(date, dates.endOf(start, 'decade'), 'year');
}
function getDecadeYears(_date) {
var days = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
date = dates.add(dates.startOf(_date, 'decade'), -2, 'year');
return days.map(function () {
return date = dates.add(date, 1, 'year');
});
}
//require('./mixins/DateFocusMixin')('decade', 'year') | rdjpalmer/react-widgets | lib/Decade.js | JavaScript | mit | 3,354 |
import React from 'react';
import ActionButton from './ActionButton';
import renderer from 'react-test-renderer';
describe('floating action button', () => {
it('renders initial view', () => {
const component = renderer.create(
<ActionButton />,
);
let tree = component.toJSON();
expect(tree).toMatchSnapshot();
});
it('changes menu state to open when main button clicked', () => {
const component = renderer.create(
<ActionButton />,
);
const mainMenu = component.root.findByProps({ className: 'mfb-slidein mfb-component--br'})
var mainMenuState = mainMenu.props['data-mfb-state'];
expect(mainMenuState).toBe('closed');
const button = component.root.findByProps({className: 'mfb-component__button--main'});
const eventMock = { preventDefault: jest.fn() };
button.props.onClick(eventMock);
mainMenuState = mainMenu.props['data-mfb-state'];
expect(mainMenuState).toBe('open');
});
it('calls onChoose function when child button is clicked', () => {
const onChoose = jest.fn();
const component = renderer.create(
<ActionButton onChoose={onChoose}/>,
);
const childButtons = component.root.findAllByProps({className: 'mfb-component__button--child'});
childButtons.forEach(child => child.props.onClick());
expect(onChoose).toBeCalledWith('dollar');
expect(onChoose).toBeCalledWith('group');
expect(onChoose).toBeCalledWith('refresh');
const tree = component.toJSON();
expect(tree).toMatchSnapshot();
});
});
| crosshj/nodeCents | client/components/ActionButton.test.js | JavaScript | mit | 1,542 |
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2022 Photon Storm Ltd.
* @license {@link https://opensource.org/licenses/MIT|MIT License}
*/
/**
* Returns the nearest power of 2 to the given `value`.
*
* @function Phaser.Math.Pow2.GetNext
* @since 3.0.0
*
* @param {number} value - The value.
*
* @return {number} The nearest power of 2 to `value`.
*/
var GetPowerOfTwo = function (value)
{
var index = Math.log(value) / 0.6931471805599453;
return (1 << Math.ceil(index));
};
module.exports = GetPowerOfTwo;
| photonstorm/phaser | src/math/pow2/GetPowerOfTwo.js | JavaScript | mit | 562 |
var map, layer, districtLayer;
var projectAPIKey = 'AIzaSyDdCELFax8-q-dUCHt9hn5Fbf_7ywY6yvA';// Personal Account
// var citiesTableID = '1CU4KNOJYGWoCkUZWrxgvleGq-k6PFFUO6qfqTCid';
var citiesTableID = '1cKfYbbWs6JJujJPk-lJfdBLWVaRRSMxfXNx6K6_y';
var districtsTableID = '1BYUolX-kQGfeEckoXMMBDk1Xh2llj8dhf-XpzJ7i';
var attributeNameX = "M-Achievement (percentage)";
var attributeNameY = "ULB Name";
var mode = "grade";
var districtName = "ANANTAPUR";
var regionName = "ANANTAPUR";
var gradeName = "G3";
var chartType = "ColumnChart";
var vizType = "split";
var sortType = "";
var unitOfIndicator = "";
var dataTable;
var tooltipValue, tooltipValueCol;
var centerAfterQuery, zoomAfterQuery;
var markers = [];
var chartInfoBubble1;
var chartInfoBubble2;
var chartInfoMarker;
var searchBarULBs;
var COLUMN_STYLES = {};
var timer;
var mainIndic = 1,
subMainIndic = 0;
var placeChartQuery = "";
var cumulativeValues = [];
var globalBucket;
var titleText = "";
var reportTitleText = "";
var generateReportQuery = "";
var multiSeries = false;
var subIndicators = [];
var overallSelected = false;
function initialize() {
var eGovAttributeList = [
"UPM-Target",
"UPM-Achievement",
"UPM-Achievement (percentage)",
"UPM-Marks",
"M-Target",
"M-Achievement",
"M-Achievement (percentage)",
"M-Marks",
"C-Target",
"C-Achievement",
"C-Achievement (percentage)",
"C-Marks",
"UPM-Rank",
"M-Rank",
"C-Rank",
"Annual Target"
];
var mapStyles3 = [{
"featureType": "road",
"stylers": [{
"visibility": "off"
}]
}, {
"featureType": "poi",
"stylers": [{
"visibility": "off"
}]
}, {
"featureType": "administrative",
"stylers": [{
"visibility": "off"
}]
}];
var styleOptions2 = [{
'min': 0,
'max': 100,
// 'color': '#FF1700',
'color': '#e74c3c',
'opacity': 1
}, {
'min': 100,
'max': 200,
// 'color': '#FFC200',
'color': '#f1c40f',
'opacity': 1
}, {
'min': 200,
'max': 500,
// 'color': '#27E833',
'color': '#2ecc71',
'opacity': 1
}];
for (var i = 0; i < eGovAttributeList.length; i++) {
COLUMN_STYLES[eGovAttributeList[i]] = styleOptions2;
}
var styledMap = new google.maps.StyledMapType(mapStyles3, {
name: "Styled Map"
});
var andhra = new google.maps.LatLng(16.0000, 80.6400);
map = new google.maps.Map(document.getElementById('map-canvas'), {
center: andhra,
scrollwheel: false,
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.LARGE,
position: google.maps.ControlPosition.LEFT_CENTER
},
streetViewControl: false,
mapTypeControl: false,
disableDefaultUI: true,
mapTypeId: google.maps.MapTypeId.TERRAIN,
zoom: 6
});
// map.mapTypes.set('map_style_2', styledMap);
// map.setMapTypeId('map_style_2');
zoomAfterQuery = 6;
centerAfterQuery = andhra;
chartInfoBubble1 = new InfoBubble({
map: map,
shadowStyle: 1,
padding: 10,
backgroundColor: 'rgb(255,255,255)',
borderRadius: 0,
arrowSize: 25,
minWidth: 300,
borderWidth: 0,
borderColor: '#2c2c2c',
disableAutoPan: false,
hideCloseButton: false,
arrowPosition: 50,
arrowStyle: 0
});
chartInfoBubble2 = new InfoBubble({
map: map,
shadowStyle: 1,
padding: 10,
backgroundColor: 'rgb(255,255,255)',
borderRadius: 0,
arrowSize: 25,
minWidth: 300,
borderWidth: 0,
borderColor: '#2c2c2c',
disableAutoPan: false,
hideCloseButton: false,
arrowPosition: 50,
arrowStyle: 0
});
chartInfoBubble1 = new InfoBubble({
minHeight: 160
});
chartInfoBubble2 = new InfoBubble({
minHeight: 225
});
chartInfoMarker = new google.maps.Marker({
map: map,
icon: 'http://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=|0000FF'
});
layer = new google.maps.FusionTablesLayer({
query: {
select: 'Polygon',
from: citiesTableID
},
map: map,
suppressInfoWindows: false
});
districtLayer = new google.maps.FusionTablesLayer({
query: {
select: '\'Geocodable address\'',
from: districtsTableID
},
map: map,
styleId: 1,
suppressInfoWindows: false
});
google.maps.event.addListener(layer, 'click', function(e) {
var cityChosen = e.row['ULB Name'].value.toString();
e.infoWindowHtml = "<div ><font size='2'>"
e.infoWindowHtml += "<b>" + cityChosen + "</b><br>" + "District: <b>" + e.row['District'].value.toString() + "</b><br>" + "Region: <b>" + e.row['Region'].value.toString() + "</b>";
e.infoWindowHtml += "</font></div>";
});
layer.setMap(map);
//layer.setMap(null);
google.maps.event.addListener(districtLayer, 'click', function(e) {
var districtTooltip = e.row['DISTRICT_2011'].value.toString();
var regionTooltip = e.row['Region'].value.toString();
e.infoWindowHtml = "<div ><font size='2'>"
e.infoWindowHtml += "District: <b>" + districtTooltip + "</b><br>" + "Region: <b>" + regionTooltip + "</b>";
e.infoWindowHtml += "</font></div>";
});
//drawChart();
applyStyle(layer, attributeNameX);
}
function drawChart() {
if (gradeName == "regwise") {
if(attributeNameX == 'UPM-Achievement (percentage)')
{
attributeNameX = 'UPM-Marks';
}else if(attributeNameX == 'M-Achievement (percentage)')
{
attributeNameX = 'M-Marks';
}else if(attributeNameX == 'C-Achievement (percentage)')
{
attributeNameX = 'C-Marks';
}
}
if (chartType == "Table" || chartType == "PieChart") {
document.getElementById('chartControl').style.display = "none";
} else {
document.getElementById('chartControl').style.display = "block";
}
placeChartQuery = "";
var chartModeTitle = "All ULBs";
var cumulativeChartQuery = "";
if (chartType == "MultiChart") {
sortType = "ORDER BY '" + attributeNameY + "' ASC";
}
if (chartType == "MultiChart" && gradeName == 'regwise') {
sortType = "ORDER BY 'Region' ASC";
}else if(gradeName == 'regwise'){
sortType = "ORDER BY AVERAGE('" + attributeNameX + "') DESC";
}
if (mode == "city") {
placeChartQuery = "SELECT '" + attributeNameY + "','" + attributeNameX + "' FROM " + citiesTableID + " " + sortType;
chartModeTitle = "All ULBs";
layer.setOptions({
query: {
select: 'Polygon',
from: citiesTableID
}
});
districtLayer.setOptions({
query: {
select: '\'Geocodable address\'',
from: districtsTableID
}
});
}
if (mode == "district") {
chartModeTitle = "District: " + districtName;
placeChartQuery = "SELECT '" + attributeNameY + "', '" + attributeNameX + "' FROM " + citiesTableID + " WHERE 'District' = '" + districtName + "'" + sortType;
layer.setOptions({
query: {
select: 'Polygon',
from: citiesTableID,
where: "District = '" + districtName + "'"
}
});
districtLayer.setOptions({
query: {
select: '\'Geocodable address\'',
from: districtsTableID,
where: "'DISTRICT_2011' = '" + districtName + "'"
}
});
}
if (mode == "region") {
chartModeTitle = "Region: " + regionName;
placeChartQuery = "SELECT '" + attributeNameY + "', '" + attributeNameX + "' FROM " + citiesTableID + " WHERE 'Region' = '" + regionName + "'" + sortType;
layer.setOptions({
query: {
select: 'Polygon',
from: citiesTableID,
where: "Region = '" + regionName + "'"
}
});
districtLayer.setOptions({
query: {
select: '\'Geocodable address\'',
from: districtsTableID,
where: "'Region' = '" + regionName + "'"
}
});
}
var layerWhereClause;
if (mode == "grade") {
if (gradeName == "G1") {
placeChartQuery = "SELECT '" + attributeNameY + "', '" + attributeNameX + "' FROM " + citiesTableID + " WHERE 'Grade' IN ('Special','Selection')" + sortType;
chartModeTitle = "Grade: Special, Selection";
layerWhereClause = "'Grade' IN ('Special','Selection')";
} else if (gradeName == "G2") {
placeChartQuery = "SELECT '" + attributeNameY + "', '" + attributeNameX + "' FROM " + citiesTableID + " WHERE 'Grade' IN ('I','II')" + sortType;
chartModeTitle = "Grade: I, II";
layerWhereClause = "'Grade' IN ('I','II')";
} else if (gradeName == "G3") {
placeChartQuery = "SELECT '" + attributeNameY + "', '" + attributeNameX + "' FROM " + citiesTableID + " WHERE 'Grade' IN ('III','NP')" + sortType;
chartModeTitle = "Grade: III, NP";
layerWhereClause = "'Grade' IN ('III','NP')";
} else if (gradeName == "G4") {
placeChartQuery = "SELECT '" + attributeNameY + "', '" + attributeNameX + "' FROM " + citiesTableID + " WHERE 'Grade' = 'Corp'" + sortType;
chartModeTitle = "Grade: Corp";
layerWhereClause = "'Grade' = 'Corp'";
} else if (gradeName == "elevenulb") {
placeChartQuery = "SELECT '" + attributeNameY + "', '" + attributeNameX + "' FROM " + citiesTableID + " WHERE 'ULB Name' IN ('TIRUPATI','KURNOOL','VISAKHAPATNAM','SRIKAKULAM','GUNTUR','KAKINADA','NELLIMARLA','RAJAM NP','KANDUKUR','ONGOLE CORP.','RAJAMPET')" + sortType;
chartModeTitle = "11 ULBs";
layerWhereClause = "'ULB Name' IN ('TIRUPATI','KURNOOL','VISAKHAPATNAM','SRIKAKULAM','GUNTUR','KAKINADA','NELLIMARLA','RAJAM NP','KANDUKUR','ONGOLE CORP.','RAJAMPET')";
} else if (gradeName == "regwise") {
placeChartQuery = "SELECT 'Region', AVERAGE('" + attributeNameX + "') FROM " + citiesTableID + " WHERE 'Region' IN ('ANANTAPUR','GUNTUR','RAJAHMUNDRY','VISAKHAPATNAM') GROUP BY 'Region' " + sortType;
chartModeTitle = "Region-wise";
layerWhereClause = "'Region' IN ('ANANTAPUR','GUNTUR','RAJAHMUNDRY','VISAKHAPATNAM') GROUP BY 'Region' ";
} else {
placeChartQuery = "SELECT '" + attributeNameY + "', '" + attributeNameX + "' FROM " + citiesTableID + " WHERE 'Grade' = '" + gradeName + "'" + sortType;
chartModeTitle = "Grade: " + gradeName;
layerWhereClause = "'Grade' = '" + gradeName + "'";
}
layer.setOptions({
query: {
select: 'Polygon',
from: citiesTableID,
where: layerWhereClause
}
});
districtLayer.setOptions({
query: {
select: '\'Geocodable address\'',
from: districtsTableID
}
});
}
cumulativeChartQuery = placeChartQuery.substring(placeChartQuery.indexOf("FROM"));
if (gradeName == "regwise") {
cumulativeChartQuery = "SELECT 'Region', AVERAGE('C-Marks') " + cumulativeChartQuery;
}else{
cumulativeChartQuery = "SELECT '" + attributeNameY + "','C-Achievement (percentage)' " + cumulativeChartQuery;
}
generateReportQuery = placeChartQuery.substring(placeChartQuery.indexOf("FROM"), placeChartQuery.indexOf("ORDER"));
//console.log(generateReportQuery);
if (!overallSelected) {
if (chartType == "MultiChart") {
if(gradeName == 'regwise'){
generateReportQuery = "SELECT 'Region',AVERAGE('Annual Target'),AVERAGE('C-Target'),AVERAGE('C-Achievement'),AVERAGE('C-Achievement (percentage)'),AVERAGE('C-Marks'),AVERAGE('Max Marks'),AVERAGE('M-Target'),AVERAGE('M-Achievement'),AVERAGE('M-Achievement (percentage)'),AVERAGE('M-Marks') " + generateReportQuery + "ORDER BY 'Region' ASC ";
}else{
generateReportQuery = "SELECT '" + attributeNameY + "','Annual Target','C-Target','C-Achievement','C-Achievement (percentage)','C-Marks','Max Marks', 'C-Rank','M-Target','M-Achievement','M-Achievement (percentage)','M-Marks','M-Rank' " + generateReportQuery + " ORDER BY '" + attributeNameY + "' ASC";
}
multiSeries = true;
} else {
if(gradeName == 'regwise'){
if (attributeNameX.indexOf("C-") > -1) {
generateReportQuery = "SELECT 'Region',AVERAGE('Annual Target'),AVERAGE('C-Target'),AVERAGE('C-Achievement'),AVERAGE('C-Achievement (percentage)'),AVERAGE('C-Marks'),AVERAGE('Max Marks') " + generateReportQuery + "ORDER BY AVERAGE('" + attributeNameX + "') DESC ";
} else if (attributeNameX.indexOf("UPM-") > -1) {
generateReportQuery = "SELECT 'Region',AVERAGE('Annual Target'),AVERAGE('UPM-Target'),AVERAGE('UPM-Achievement'),AVERAGE('UPM-Achievement (percentage)'),AVERAGE('UPM-Marks'),AVERAGE('Max Marks') " + generateReportQuery + "ORDER BY AVERAGE('" + attributeNameX + "') DESC ";
} else if (attributeNameX.indexOf("M-") > -1) {
generateReportQuery = "SELECT 'Region',AVERAGE('Annual Target'),AVERAGE('M-Target'),AVERAGE('M-Achievement'),AVERAGE('M-Achievement (percentage)'),AVERAGE('M-Marks'),AVERAGE('Max Marks') " + generateReportQuery + "ORDER BY AVERAGE('" + attributeNameX + "') DESC ";
}
}else{
if (attributeNameX.indexOf("C-") > -1) {
generateReportQuery = "SELECT '" + attributeNameY + "','Annual Target','C-Target','C-Achievement','C-Achievement (percentage)','C-Marks','Max Marks','C-Rank' " + generateReportQuery + " ORDER BY 'C-Rank' ASC";
} else if (attributeNameX.indexOf("UPM-") > -1) {
generateReportQuery = "SELECT '" + attributeNameY + "','Annual Target','UPM-Target','UPM-Achievement','UPM-Achievement (percentage)','UPM-Marks','Max Marks','UPM-Rank' " + generateReportQuery + " ORDER BY 'UPM-Rank' ASC";
} else if (attributeNameX.indexOf("M-") > -1) {
generateReportQuery = "SELECT '" + attributeNameY + "','Annual Target','M-Target','M-Achievement','M-Achievement (percentage)','M-Marks','Max Marks','M-Rank' " + generateReportQuery + " ORDER BY 'M-Rank' ASC";
}
}
}
} else {
if (chartType == "MultiChart") {
if(gradeName == 'regwise'){
generateReportQuery = "SELECT 'Region',AVERAGE('C-Marks'),AVERAGE('M-Marks'),AVERAGE('Max Marks') " + generateReportQuery + "ORDER BY 'Region' ASC "
}else{
generateReportQuery = "SELECT '" + attributeNameY + "','C-Marks','C-Rank','M-Marks','M-Rank','Max Marks' " + generateReportQuery + " ORDER BY '" + attributeNameY + "' ASC";
}
multiSeries = true;
} else {
if(gradeName == 'regwise'){
if (attributeNameX.indexOf("C-") > -1) {
generateReportQuery = "SELECT 'Region',AVERAGE('C-Marks'),AVERAGE('Max Marks') " + generateReportQuery + "ORDER BY AVERAGE('" + attributeNameX + "') DESC ";
} else if (attributeNameX.indexOf("UPM-") > -1) {
generateReportQuery = "SELECT 'Region',AVERAGE('UPM-Marks'),AVERAGE('Max Marks') " + generateReportQuery + "ORDER BY AVERAGE('" + attributeNameX + "') DESC ";
} else if (attributeNameX.indexOf("M-") > -1) {
generateReportQuery = "SELECT 'Region',AVERAGE('M-Marks'),AVERAGE('Max Marks') " + generateReportQuery + "ORDER BY AVERAGE('" + attributeNameX + "') DESC ";
}
}else{
if (attributeNameX.indexOf("C-") > -1) {
generateReportQuery = "SELECT '" + attributeNameY + "','C-Marks','Max Marks','C-Rank' " + generateReportQuery + " ORDER BY 'C-Rank' ASC";
} else if (attributeNameX.indexOf("UPM-") > -1) {
generateReportQuery = "SELECT '" + attributeNameY + "','UPM-Marks','Max Marks','UPM-Rank' " + generateReportQuery + " ORDER BY 'UPM-Rank' ASC";
} else if (attributeNameX.indexOf("M-") > -1) {
generateReportQuery = "SELECT '" + attributeNameY + "','M-Marks','Max Marks','M-Rank' " + generateReportQuery + " ORDER BY 'M-Rank' ASC";
}
}
}
}
var query = new google.visualization.Query('http://www.google.com/fusiontables/gvizdata?tq=');
//console.log('cumulativeChartQuery:'+cumulativeChartQuery);
query.setQuery(cumulativeChartQuery);
query.send(getCumulativeValues);
function getCumulativeValues(response) {
cumulativeValues = [];
//console.log('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
//console.log('First Response is:'+JSON.stringify(response));
for (var i = 0; i < response.getDataTable().getNumberOfRows(); i++) {
cumulativeValues.push(response.getDataTable().getValue(i, 1));
}
var query = new google.visualization.Query('http://www.google.com/fusiontables/gvizdata?tq=');
// Apply query language statement.
//console.log('placeChartQuery:'+placeChartQuery);
query.setQuery(placeChartQuery);
// Send the query with a callback function.
query.send(handleQueryResponse);
}
function handleQueryResponse(response) {
/* if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
*/
dataTable = response.getDataTable();
//console.log('chartType:'+chartType);
if (chartType != "MultiChart") {
dataTable.addColumn({
type: 'string',
role: 'style'
});
//alert(parseFloat(globalBucket[0][1]) + "," + globalBucket[1][1]);
var lastColorColumn = parseInt(dataTable.getNumberOfColumns());
var numberOfRowsInQuery = parseInt(dataTable.getNumberOfRows());
//console.log('Rows and columns is:'+numberOfRowsInQuery+'<--->'+lastColorColumn);
if(gradeName == 'regwise'){
for (var i = 0; i < numberOfRowsInQuery; i++) {
var color = 'rgb(0, 0, 0)';
if (dataTable.getValue(i, 0) == 'RAJAHMUNDRY') {
color = 'rgb(231, 76, 60)'; //red
} else if (dataTable.getValue(i, 0) == 'VISAKHAPATNAM') {
color = 'rgb(241, 196, 15)'; //amber
} else if (dataTable.getValue(i, 0) == 'GUNTUR') {
color = 'rgb(46, 204, 113)'; //green
} else if (dataTable.getValue(i, 0) == 'ANANTAPUR'){
color = 'rgb(0, 153, 204)'; //blue
}
dataTable.setValue(i, lastColorColumn - 2, (dataTable.getValue(i, 1)).toFixed(2));
dataTable.setValue(i, lastColorColumn - 1, color);
}
}else{
for (var i = 0; i < numberOfRowsInQuery; i++) {
var color = 'rgb(0, 0, 0)';
if (dataTable.getValue(i, 1) < globalBucket[0][1]) {
color = 'rgb(231, 76, 60)'; //red
} else if (dataTable.getValue(i, 1) < globalBucket[1][1]) {
color = 'rgb(241, 196, 15)'; //amber
} else {
color = 'rgb(46, 204, 113)'; //green
}
dataTable.setValue(i, lastColorColumn - 1, color);
}
}
} else {
//Multichart
if(gradeName == 'regwise'){
dataTable.addColumn('number', 'AVERAGE(C-Marks)');
}else{
dataTable.addColumn('number', 'Cumulative Achievement (percentage)');
}
var lastColumn = parseInt(dataTable.getNumberOfColumns());
var numberOfRowsInQuery = parseInt(dataTable.getNumberOfRows());
for (var i = 0; i < numberOfRowsInQuery; i++) {
dataTable.setValue(i, lastColumn - 2, dataTable.getValue(i,1).toFixed(2));
dataTable.setValue(i, lastColumn - 1, cumulativeValues[i].toFixed(2));
}
chartType = "ColumnChart";
}
var MAX;
var MIN;
if (attributeNameY == "ULB Name") {
MAX = dataTable.getNumberOfRows();
} else {
MAX = dataTable.getColumnRange(0).max;
}
if (MAX < 4) {
MIN = 2;
} else if (MAX < 10) {
MIN = 5;
} else if (MAX < 30) {
MIN = 10;
} else if (MAX < 50) {
MIN = 15;
} else if (MAX < 115) {
MIN = 30;
} else if (MAX < 1000) {
MIN = 250;
} else if (MAX < 10000) {
MIN = 2500;
} else if (MAX < 50000) {
MIN = 12500;
} else if (MAX < 100000) {
MIN = 25000;
} else if (MAX < 200000) {
MIN = 50000;
} else if (MAX < 500000) {
MIN = 100000;
} else {
MIN = 150000;
}
var prevButton = document.getElementById('chartPrev');
var nextButton = document.getElementById('chartNext');
var changeZoomButton = document.getElementById('chartZoom');
prevButton.disabled = true;
nextButton.disabled = true;
changeZoomButton.disabled = true;
//alert($('#chartVizDiv').width());
var chartDivWidth = $('#chartVizDiv').width() - 100;
var chartDivHeight = $('#chartVizDiv').height() - 215;
var myOptions = {
chartArea: {
top: 70,
left: 85,
width: chartDivWidth,
height: chartDivHeight
},
axisTitlesPosition: 'out',
// title: chartModeTitle,
title: '',
series: {
0: {
color: '#F5861F'
},
1: {
color: '#6B4F2C'
},
2: {
color: '#17365D'
},
3: {
color: '#FFC000'
}
},
titlePosition: 'start',
titleTextStyle: {
color: '#000',
fontSize: 20,
fontName: 'Open Sans'
},
animation: {
duration: 1500,
easing: 'linear',
startup: true
},
annotations: {
alwaysOutside: true,
/* boxStyle: {
// Color of the box outline.
stroke: '#000',
// Thickness of the box outline.
strokeWidth: 1,
gradient: {
color1: '#FFFFFF',
color2: '#FFFFFF',
x1: '0%', y1: '0%',
x2: '100%', y2: '100%',
useObjectBoundingBoxUnits: true
}
},*/
textStyle: {
fontName: 'Times-Roman',
fontSize: 14,
bold: true,
opacity: 1
}
},
/* explorer: {
keepInBounds:true
},*/
vAxis: {
title: '',
textStyle: {
fontSize: 14,
color: '#000',
fontName: 'Open Sans'
},
titleTextStyle: {
color: '#000',
fontSize: 18,
italic: false,
bold: false
},
baselineColor: '#000',
gridlines: {
count: 5
},
viewWindowMode: 'pretty'
},
trendlines: {
0: {
type: 'linear',
visibleInLegend: true,
color: 'purple',
lineWidth: 3,
opacity: 1,
showR2: true
}
},
hAxis: {
title: '',
viewWindow: {
min: 0,
max: MAX
},
textStyle: {
fontSize: 14,
color: '#000',
fontName: 'Open Sans'
},
titleTextStyle: {
color: '#000',
fontSize: 18,
italic: false,
bold: false
},
baselineColor: '#000',
gridlines: {
count: 5
},
viewWindowMode: 'pretty'
},
tooltip: {
isHtml: false
},
areaOpacity: 0.5,
backgroundColor: '#FFFFFF',
legend: {
textStyle: {
color: 'black',
fontSize: 14,
fontName: 'Open Sans'
},
position: 'none',
alignment: 'end'
}
};
var hisBarOptions = {
chartArea: {
// left:10,
// top:100,
left: 75,
width: '90%',
height: '70%'
},
// title: chartModeTitle,
title: '',
titleTextStyle: {
color: '#000000',
fontSize: 20,
fontName: 'Open Sans'
},
animation: {
duration: 1500,
easing: 'linear',
startup: true
},
vAxis: {
title: attributeNameY,
viewWindow: {
min: 0,
max: MAX
},
textStyle: {
fontSize: 14,
color: '#000000',
fontName: 'Open Sans'
},
titleTextStyle: {
color: '#000000',
fontSize: 18
}
},
hAxis: {
title: attributeNameX,
textStyle: {
fontSize: 14,
color: '#000000',
fontName: 'Open Sans'
},
titleTextStyle: {
color: '#000000',
fontSize: 18
}
},
tooltip: {
isHtml: false
},
backgroundColor: '#FFFFFF',
legend: {
textStyle: {
color: 'black',
fontSize: 14,
fontName: 'Open Sans'
},
position: 'none',
alignment: 'end'
}
};
var wrapper = new google.visualization.ChartWrapper({
containerId: "chartVizDiv",
//dataSourceUrl: "http://www.google.com/fusiontables/gvizdata?tq=",
//query: placeChartQuery,
dataTable: dataTable,
chartType: chartType,
options: (chartType == "Histogram" || chartType == "BarChart") ? hisBarOptions : myOptions
});
google.visualization.events.addListener(wrapper, 'ready', onReady);
wrapper.draw();
function onReady() {
google.visualization.events.addListener(wrapper.getChart(), 'onmouseover', barMouseOver);
google.visualization.events.addListener(wrapper.getChart(), 'onmouseout', barMouseOut);
google.visualization.events.addListener(wrapper.getChart(), 'select', barSelect);
prevButton.disabled = hisBarOptions.vAxis.viewWindow.min <= 0;
nextButton.disabled = hisBarOptions.vAxis.viewWindow.max >= MAX;
prevButton.disabled = myOptions.hAxis.viewWindow.min <= 0;
nextButton.disabled = myOptions.hAxis.viewWindow.max >= MAX;
changeZoomButton.disabled = false;
}
prevButton.onclick = function() {
myOptions.hAxis.viewWindow.min -= MIN - 1;
myOptions.hAxis.viewWindow.max -= MIN - 1;
hisBarOptions.vAxis.viewWindow.min -= MIN - 1;
hisBarOptions.vAxis.viewWindow.max -= MIN - 1;
wrapper.draw();
}
nextButton.onclick = function() {
myOptions.hAxis.viewWindow.min += MIN - 1;
myOptions.hAxis.viewWindow.max += MIN - 1;
hisBarOptions.vAxis.viewWindow.min += MIN - 1;
hisBarOptions.vAxis.viewWindow.max += MIN - 1;
wrapper.draw();
}
var zoomed = true;
changeZoomButton.onclick = function() {
if (zoomed) {
myOptions.hAxis.viewWindow.min = 0;
myOptions.hAxis.viewWindow.max = MIN;
hisBarOptions.vAxis.viewWindow.min = 0;
hisBarOptions.vAxis.viewWindow.max = MIN;
} else {
myOptions.hAxis.viewWindow.min = 0;
myOptions.hAxis.viewWindow.max = MAX;
hisBarOptions.vAxis.viewWindow.min = 0;
hisBarOptions.vAxis.viewWindow.max = MAX;
}
zoomed = !zoomed;
wrapper.draw();
}
function barSelect(e) {
//alert(tooltipValue);
//var selectedItem = wrapper.getChart().getSelection()[0];
//tooltipValue = dataTable.getValue(e.row, 0);
//addTooltipScript('https://www.googleapis.com/fusiontables/v2/query?sql=');
}
function barMouseOver(e) {
timer = setTimeout(function() {
// do your stuff here
if (e.row < dataTable.getNumberOfRows()) {
tooltipValue = dataTable.getValue(e.row, 0);
tooltipValueCol = dataTable.getValue(e.row, 1);
//setMapOnAll(null);
//if overall and combined show report in modal else show in marker
if(mainIndic == 0 || (mainIndic == 1 && subMainIndic == 0) || (mainIndic == 3 && subMainIndic == 0) || (mainIndic == 4 && subMainIndic == 0) || (mainIndic == 5 && subMainIndic == 0) || (mainIndic == 6 && subMainIndic == 0)|| (mainIndic == 8 && subMainIndic == 0)|| (mainIndic == 9 && subMainIndic == 0)|| (mainIndic == 12 && subMainIndic == 0)){
ulbsummary('https://www.googleapis.com/fusiontables/v2/query?sql=',tooltipValue);
}else{
addTooltipScript('https://www.googleapis.com/fusiontables/v2/query?sql=', false);
}
$("#chosenNames").attr("placeholder", "Search ULBs").val("").focus().blur();
$('#chosenNames').chosen().trigger("chosen:updated");
}
}, 1500);
}
function barMouseOut(e) {
// on mouse out, cancel the timer
clearTimeout(timer);
chartInfoBubble2.close();
chartInfoMarker.setMap(null);
//setMapOnAll(map);
}
}
}
var rankAttri;
var targetAttri;
var achievedAttri;
var marksObtained;
function ulbsummary(src,ulb){
$('#ulbsummary-title').html('<b>'+ulb+' - '+titleText.split('-')[0]+'</b>');
$('#ulbreport_table').hide();
$('#ulbreport').modal('show');
$('#loadingIndicatorforreport').show();
if (attributeNameX.indexOf("C-") > -1) {
rankAttri = "C-Rank";
targetAttri = "C-Target";
achievedAttri = "C-Achievement";
marksObtained = "C-Marks";
} else if (attributeNameX.indexOf("UPM-") > -1) {
rankAttri = "UPM-Rank";
targetAttri = "UPM-Target";
achievedAttri = "UPM-Achievement";
marksObtained = "UPM-Marks";
} else if (attributeNameX.indexOf("M-") > -1) {
rankAttri = "M-Rank";
targetAttri = "M-Target";
achievedAttri = "M-Achievement";
marksObtained = "M-Marks";
}
var selectText = "SELECT+'ULB Name',Centroid,'" + attributeNameX + "'" + ",'" + attributeNameY + "','Grade','Annual Target','" + rankAttri + "','" + targetAttri + "','" + achievedAttri + "','" + marksObtained + "','Max Marks'";
var tableIDString = "+from+" + citiesTableID;
var whereText = "+where+'" + attributeNameY + "'='" + ulb + "'";
var key_callback_string = "&key=" + projectAPIKey;
var source = src + selectText + tableIDString + whereText + key_callback_string;
//console.log(src);
var ulbPoint;
$.ajax({url: source, async: false, success: function(response){
ulbPoint = response.rows[0];
}});
if(gradeName == 'regwise'){
}else{
$('#ulbreport_table').html('');
$('#ulbreport_table').append('<table class="table table-bordered table-hover"> <tbody> <tr> <th>Parameter</th> <th>Annual Target</th> <th>Target</th> <th>Achievement</th> <th>Marks</th> <th>Weightage</th> <th>Rank</th> </tr> <tr> <td>'+titleText.split('-')[1]+'</td><td>'+((typeof(ulbPoint[5]) == 'number') ? (ulbPoint[5].toFixed(2)) : ulbPoint[5])+'</td> <td>'+((typeof(ulbPoint[7]) == 'number') ? (ulbPoint[7].toFixed(2)) : ulbPoint[7])+'</td> <td>'+((typeof(ulbPoint[8]) == 'number') ? (ulbPoint[8].toFixed(2)) : ulbPoint[8])+'</td> <td>'+((typeof(ulbPoint[9]) == 'number') ? (ulbPoint[9].toFixed(2)) : ulbPoint[9])+'</td> <td>'+((typeof(ulbPoint[10]) == 'number') ? (ulbPoint[10].toFixed(2)) : ulbPoint[10])+'</td> <td>'+((typeof(ulbPoint[6]) == 'number') ? (ulbPoint[6].toFixed(2)) : ulbPoint[6])+'</td> </tr> </tbody> </table>');
//Show Parameter Data
if(mainIndic == 3 && subMainIndic == 0){//Solid Waste Management
var tablearray = [{"tableid":"1_nR3f6Z1TzTgCJ5UT0Do6QYf9Ok0hVfxkKf2vAfG","text":"Door To Door Collection"},
{"tableid":"1HlptexkOhseTkl7ujc13LYb7uELXJBQduRM6QmLu","text":"Garbage Lifting"}];
queryhandling(tablearray,src,ulb);
}else if(mainIndic == 4 && subMainIndic == 0){//Property Tax
var tablearray = [{"tableid":"1Ft7BVfp-V8hpucsmWoW3Zal7p1qc5o6FwPSw3i4O","text":"Collection Efficiency"},
{"tableid":"175Ocis9sGqWTBLhXd2wVIawnlddbpKE1fvB-j_SZ","text":"Demand Increase"}];
queryhandling(tablearray,src,ulb);
}else if(mainIndic == 5 && subMainIndic == 0){//Citizen Services
var tablearray = [{"tableid":"1K6vPTSthe2-X__IHsi42Roq5RReNZ9xy-nVTcgMc","text":"Citizen Charter"},
{"tableid":"1SbLuxSFUquS7q-mmLKp8_zYeKbdwvbbV3fMVmL5W","text":"Grievance Redressal"}];
queryhandling(tablearray,src,ulb);
}else if(mainIndic == 6 && subMainIndic == 0){//Finance
var tablearray = [{"tableid":"1t3_EJG6Ppn4apIrONT0Wz1b6OYMix1OZkenzEcOd","text":"Double Entry Accounting"},
{"tableid":"10591kbl5tAaWG4Kamh9QCQ1HWjY4-ESWRDQ1GQZ0","text":"Pending Accounts and Audits"}];
queryhandling(tablearray,src,ulb);
}else if(mainIndic == 0){//Combined
if(hod == 1){//DMA - Combined
var tablearray = [{"tableid":"1BgiIsyij_n9vB7cuCFRn6UgE9Cq0rgCZ57FePIWm","text":"Solid Waste Management"},
{"tableid":"1gidez_jsV4mxBSZ0a_lfo6cwunZXsSUxlRpNb_Ut","text":"Property Tax"},
{"tableid":"1XXalUDbRkTKbNbv7Dntueqd-BB7Pz5y_-ZxRqDvF","text":"Citizen Services"},
{"tableid":"1q7GNaD1WoY8g2acTpXq9DbOggJnW-crbIxd7ixRY","text":"Finance"},
{"tableid":"1UOltn1AicEOL-FkG4mKsay6pEi8SZQKmf5y5xX9m","text":"Education"}];
queryhandling(tablearray,src,ulb);
}else if(hod == 2){//CE - Combined
var tablearray = [{"tableid":"1KVFlQd2zfJ5soZv_kJrMsxZNPEzZSdCzvJoKAGlE","text":"Water Supply"},
{"tableid":"1WjL0SBK8k3NgOMS8YjiirnuA1JgnqOuQjAAfSKZ-","text":"Street Lighting"}];
queryhandling(tablearray,src,ulb);
}else if(hod == 3){//DTCP - Combined
//No need
}else if(hod == 4){//MEPMA - Combined
//No need
}else if(hod == 5){//Swach Andhra - Combined
//No need
}else if(hod == 6){//Greening Corporation - Combined
//No need
}else if(hod == 7){//Combined - Combined
var tablearray = [{"tableid":"15PCNLfKkPZGc35wtThugjW0FBTlK2U9hCKIFNLTL","text":"DMA"},
{"tableid":"1AMkLyA2vz2xNXTHTX5JnxOZwnrVS6PNqu9xkhS7L","text":"CE"},
{"tableid":"1xCuO37vnXEN0Ake02ErGetRTZUo8W6mueNugmdhq","text":"DTCP"},
{"tableid":"1ufZzYeUN40B-5u0Msggo8UIHddJ-jQMvES8IAqWL","text":"MEPMA"},
{"tableid":"10DDREC-__XHoPjL1FFVZ5G6Beh-Bs3yzuP59t5hL","text":"Swacha Andhra"},
{"tableid":"13zBQvJvzrdj8vf63MnvUcJOgo5pG8MYcqYP1hVjh","text":"Greening Corp."},];
queryhandling(tablearray,src,ulb);
}
}else if(mainIndic == 8 && subMainIndic == 0){//Water Supply
var tablearray = [{"tableid":"1dHEUFs9Edz-pfbBmX7dDczXZXdvHyhIT50681RiI","text":"Connections Coverage"},
{"tableid":"1f6ZA4wqY7V3gJAOhz3M2jMi9VMpVtQFGG6_ExJH-","text":"Cost Recovery"}];
queryhandling(tablearray,src,ulb);
}else if(mainIndic == 9 && subMainIndic == 0){//Street Lighting
var tablearray = [{"tableid":"1XiO6lKhyPdCLTR6E_9ltEBaM20wQWDgt3X0E6Xqk","text":"LED Coverage"},
{"tableid":"1SJZL2t_DchzylwR2zoSE-Zk1NOPVrQ-hitSn8KXx","text":"Additional Fixtures"}];
queryhandling(tablearray,src,ulb);
}else if(mainIndic == 12 && subMainIndic == 0){//Community Development
var tablearray = [{"tableid":"1ShLFRlL4D_O05ant_kRkkSprShJPYb_nQ8S4MCvT","text":"SHG Bank Linkage"},
{"tableid":"1QjN7go-OdeLVtKnart_yuwWuKavxEJP_lSy9tyV4","text":"Liveihood"},
{"tableid":"1Oua3hYGMx3knhsK7yf36TspEvV_rJbE2lsCEWqLT","text":"Skill Training Programmes"}];
queryhandling(tablearray,src,ulb);
}else if(mainIndic == 1 && subMainIndic == 0){//Swach Andhra
var tablearray = [{"tableid":"1VlRSa6bRH67nzwoZNNg5Hi7RrADs6nrpL9XGKZxk","text":"Household Toilet Coverage"},
{"tableid":"1gEkwIO7LC2ga5nS7fNiSZjrFaUyVcgQORdMAHs0d","text":"Community Toilet Coverage"}];
queryhandling(tablearray,src,ulb);
}
$('#loadingIndicatorforreport').hide();
$('#ulbreport_table').show();
}
}
function queryhandling(tablearray,src,ulb){
//Common Query
var selectText = "SELECT+'ULB Name',Centroid,'" + attributeNameX + "'" + ",'" + attributeNameY + "','Grade','Annual Target','" + rankAttri + "','" + targetAttri + "','" + achievedAttri + "','" + marksObtained + "','Max Marks'";
var whereText = "+where+'" + attributeNameY + "'='" + ulb + "'";
var key_callback_string = "&key=" + projectAPIKey;
$.each(tablearray, function(k, v) {
//display the key and value pair
var ts = v.tableid;
var tableIDString = "from " + ts;
var parameter_src = src + selectText + tableIDString + whereText + key_callback_string;
parameter_report(parameter_src, v.text);//Function call
});
}
function parameter_report(source, parameter_text){
var ulbpoint;
$.ajax({url: source, async: false, success: function(response){
ulbPoint = response.rows[0];
}});
$('#ulbreport_table table tbody').append('<tr> <td>'+parameter_text+'</td> <td>'+((typeof(ulbPoint[5]) == 'number') ? (ulbPoint[5].toFixed(2)) : ulbPoint[5])+'</td> <td>'+((typeof(ulbPoint[7]) == 'number') ? (ulbPoint[7].toFixed(2)) : ulbPoint[7])+'</td> <td>'+((typeof(ulbPoint[8]) == 'number') ? (ulbPoint[8].toFixed(2)) : ulbPoint[8])+'</td> <td>'+((typeof(ulbPoint[9]) == 'number') ? (ulbPoint[9].toFixed(2)) : ulbPoint[9])+'</td> <td>'+((typeof(ulbPoint[10]) == 'number') ? (ulbPoint[10].toFixed(2)) : ulbPoint[10])+'</td> <td>'+((typeof(ulbPoint[6]) == 'number') ? (ulbPoint[6].toFixed(2)) : ulbPoint[6])+'</td> </tr>');
}
function addTooltipScript(src, fromSearchBar) {
var rankAttri;
var targetAttri;
var achievedAttri;
var marksObtained;
if (attributeNameX.indexOf("C-") > -1) {
rankAttri = "C-Rank";
targetAttri = "C-Target";
achievedAttri = "C-Achievement";
marksObtained = "C-Marks";
} else if (attributeNameX.indexOf("UPM-") > -1) {
rankAttri = "UPM-Rank";
targetAttri = "UPM-Target";
achievedAttri = "UPM-Achievement";
marksObtained = "UPM-Marks";
} else if (attributeNameX.indexOf("M-") > -1) {
rankAttri = "M-Rank";
targetAttri = "M-Target";
achievedAttri = "M-Achievement";
marksObtained = "M-Marks";
}
var selectText = "SELECT+'ULB Name',Centroid,'" + attributeNameX + "'" + ",'" + attributeNameY + "','Grade','Annual Target','" + rankAttri + "','" + targetAttri + "','" + achievedAttri + "','" + marksObtained + "','Max Marks'";
var tableIDString = "+from+" + citiesTableID;
var whereText = "+where+'" + attributeNameY + "'='" + tooltipValue + "'";
if (fromSearchBar) {
whereText = "+where+'" + 'ULB Name' + "'='" + tooltipValue + "'";
}
var key_callback_string = "&key=" + projectAPIKey + "&callback=tooltiphandler";
src = src + selectText + tableIDString + whereText + key_callback_string;
var s = document.createElement('script');
s.setAttribute('src', src);
document.body.appendChild(s);
}
function tooltiphandler(response) {
var ulbPoint = response.rows[0];
if(gradeName == 'regwise'){
}else{
showULBonMap(ulbPoint[0], ulbPoint[1], ulbPoint[2], ulbPoint[3], ulbPoint[4], ulbPoint[5], ulbPoint[6], ulbPoint[7], ulbPoint[8], ulbPoint[9], ulbPoint[10]);
}
}
function showULBonMap(ulb, centroid, ttValueY, ttValueX, grad, annualTar, rank, target, achieved, marks, maxMarks) {
var bubbleLoc = centroid.split(',');
if (chartInfoBubble1.isOpen()) { // unless the InfoBubble is open, we open it
chartInfoBubble1.close();
}
if (unitOfIndicator == "-") {
target = " NA";
achieved = " NA";
annualTar = " NA";
}
chartInfoBubble1.setContent("<div ><font size='2'><b>" + ulb + "</b><br/>Grade: <b>" + grad + "</b><br/>Unit of indicator: <b>" + unitOfIndicator + "</b></br><table border='1' class='infoWindowTable' style='width=100%;'><tr><th>Annual Target</th><th>Target</th><th>Achievement</th><th>" + attributeNameX + "</th><th>Marks (" + maxMarks + ")</th><th>Rank</th></tr><tr><td><b>" + ((typeof(annualTar) == 'number') ? (annualTar.toFixed(2)) : annualTar) + "</b></td><td><b>" + ((typeof(target) == 'number') ? (target.toFixed(2)) : target) + "</b></td><td><b>" + ((typeof(achieved) == 'number') ? (achieved.toFixed(2)) : achieved) + "</b></td><td><b>" + ((typeof(ttValueY) == 'number') ? (ttValueY.toFixed(2)) : ttValueY) + "</b></td><td><b>" + ((typeof(marks) == 'number') ? (marks.toFixed(2)) : marks) + "</b></td><td><b>" + rank + "</b></td></tr></table></font></div>");
chartInfoBubble1.setPosition(new google.maps.LatLng(parseFloat(bubbleLoc[1]) + zoomLevelBasedBubblePos(), parseFloat(bubbleLoc[0])));
if (!chartInfoBubble1.isOpen()) { // unless the InfoBubble is open, we open it
chartInfoBubble1.open(map);
}
}
function zoomLevelBasedBubblePos() {
switch (map.getZoom()) {
case 6:
return 0.7;
case 7:
return 0.35;
case 8:
return 0.18;
}
return 0.04;
}
function setMapOnAll(map) {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(map);
}
}
function bucketGenerator(myar) {
myar.sort(function(a, b) {
return a - b;
});
var array1 = [];
for (i = 0; i < myar.length; i++) {
if (myar[i] != null)
array1.push(myar[i]);
}
var array = [];
for (i = 0; i < array1.length; i++) {
array.push(array1[i]);
while (array1[i] == 0)
i++;
}
var buck = 3;
var len1 = Math.floor(array.length * (0.2));
var len2 = Math.ceil(array.length * (0.6));
var len3 = array.length - (len1 + len2);
var bucket = [];
var bucketMin = [];
var bucketMax = [];
var max1 = array
// if(array[0]==0)
// bucket.push([0.01, array[len1 - 1]]);
// else
bucket.push([array[0], array[len1 - 1]]);
bucket.push([array[len1], array[len1 + len2 - 1]]);
bucket.push([array[len1 + len2], array[array.length - 1]]);
var bucketF = [];
var max;
var min = parseFloat(bucket[0][0], 3);
for (i = 0; i < buck; i++) {
if (i < (buck - 1)) {
var x = parseFloat(bucket[i + 1][0], 3);
max = Math.ceil(parseFloat((parseFloat(bucket[i][1], 3) + parseFloat(bucket[i + 1][0], 3)) / 2));
if (x < max) {
var max1 = (parseFloat(bucket[i][1], 3) + parseFloat(bucket[i + 1][0], 3)) / 2;
max = parseFloat(max1).toFixed(2);
}
} else
max = Math.ceil(parseFloat(bucket[i][1], 3));
bucketF.push([min, max]);
min = max;
}
return bucketF;
}
function applyStyle(layer, column) {
addScript('https://www.googleapis.com/fusiontables/v2/query?sql=');
}
function addScript(src) {
var selectText = "SELECT '" + attributeNameX + "',Centroid,'ULB Name','Grade','" + attributeNameY + "','" + "Annual Target','C-Rank','M-Rank','UPM-Rank','C-Marks','UPM-Marks','M-Marks','Max Marks','Region'";
var whereText;
if (mode == "city") {
whereText = '';
} else if (mode == 'district') {
whereText = " WHERE " + "District" + "='" + districtName + "'";
} else if (mode == 'region') {
whereText = " WHERE " + "Region" + "='" + regionName + "'";
} else if (mode == 'grade') {
if (gradeName == "G1") {
whereText = " WHERE " + "'Grade' IN ('Special','Selection')";
} else if (gradeName == "G2") {
whereText = " WHERE " + "'Grade' IN ('I','II')";
} else if (gradeName == "G3") {
whereText = " WHERE " + "'Grade' IN ('III','NP')";
} else if (gradeName == "G4") {
whereText = " WHERE " + "Grade" + "='Corp'";
} else if (gradeName == "elevenulb") {
whereText = " WHERE " + "'ULB Name' IN ('TIRUPATI','KURNOOL','VISAKHAPATNAM','SRIKAKULAM','GUNTUR','KAKINADA','NELLIMARLA','RAJAM NP','KANDUKUR','ONGOLE CORP.','RAJAMPET')";
}else if (gradeName == "regwise") {
whereText = " WHERE " + "'Region' IN ('ANANTAPUR','GUNTUR','RAJAHMUNDRY','VISAKHAPATNAM')";
} else {
whereText = " WHERE " + "Grade" + "='" + gradeName + "'";
}
} else {
whereText = '';
}
var tableIDString = " from " + citiesTableID;
var key_callback_string = "&key=" + projectAPIKey + "&callback=handler";
src = src + selectText + tableIDString + whereText + key_callback_string;
var s = document.createElement('script');
s.setAttribute('src', src);
document.body.appendChild(s);
}
//var dummycount = 0;
function handler(response) {
markerLocations = [];
searchBarULBs = [];
var anantapur_count = 0, guntur_count = 0, raj_count = 0, vizag_count = 0;
var anantapur=0, guntur=0, rajahmundry=0, vizag=0;
var hisArray = [];
for (var i = 0; i < response.rows.length; i++) {
var attValX = response.rows[i][0];//timeframe
hisArray.push(attValX);
var pos = response.rows[i][1].toString().split(",");//latlong
var lat = pos[1];
var lon = pos[0];
var city = (response.rows[i])[4].toString();//ulbname
var grad = (response.rows[i])[3].toString();
var attValY = (response.rows[i])[4];//ulbname
var annualTarget = (response.rows[i])[5];
var cRank = (response.rows[i])[6];
var mRank = (response.rows[i])[7];
var upmRank = (response.rows[i])[8];
var cMarks = (response.rows[i])[9];
var mMarks = (response.rows[i])[10];
var upmMarks = (response.rows[i])[11];
var maxMarks = (response.rows[i])[12];
var ulb_region = (response.rows[i])[13];
/*if((response.rows[i])[10] == 0 )
dummycount+= 1;*/
//do it only when region wise chart
/*if (gradeName == "regwise") {
if(ulb_region == 'ANANTAPUR'){
anantapur+=attValX;
anantapur_count++;//total sum of 'attValX' by this anantapur_count
}else if(ulb_region == 'GUNTUR'){
guntur+=attValX;
guntur_count++;//total sum of 'attValX' by this guntur_count
}else if(ulb_region == 'RAJAHMUNDRY'){
rajahmundry+=attValX;
raj_count++;//total sum of 'attValX' by this raj_count
}else if(ulb_region == 'VISAKHAPATNAM'){
vizag+=attValX;
vizag_count++;//total sum of 'attValX' by this vizag_count
}
markerLocations.push([lat, lon, city, grad, attValX, attValY, annualTarget, cRank, mRank, upmRank, cMarks, upmMarks, mMarks, maxMarks,ulb_region]);
searchBarULBs.push(city);
}else{*/
markerLocations.push([lat, lon, city, grad, attValX, attValY, annualTarget, cRank, mRank, upmRank, cMarks, upmMarks, mMarks, maxMarks,ulb_region]);
searchBarULBs.push(city);
//}
}
//console.log('dummycount'+dummycount);
/*if((attributeNameX.indexOf("UPM-") > -1) && (dummycount == 110))
document.getElementById("titleText").innerHTML = "<b style='color:red'>Since financial year starts from April. Previous month data won't be available for this month</b>";
*/
//console.log(anantapur_count+'<-->'+guntur_count+'<-->'+raj_count+'<-->'+vizag_count);
globalBucket = bucketGenerator(hisArray);
//console.log(globalBucket);
if (globalBucket[2][1] == 0 || isNaN(globalBucket[2][1])) {
globalBucket[2][1] = 100;
}
if (isNaN(globalBucket[2][0])) {
globalBucket[2][0] = globalBucket[2][1];
}
if (isNaN(globalBucket[1][1])) {
globalBucket[1][1] = globalBucket[2][1];
}
if (isNaN(globalBucket[0][0])) {
globalBucket[0][0] = 0;
}
if (isNaN(globalBucket[0][1])) {
globalBucket[0][1] = 0;
}
if (isNaN(globalBucket[1][0])) {
globalBucket[1][0] = 0;
}
/*
if (globalBucket[1][1] == 100.00) {
globalBucket[1][1] = 99.99;
globalBucket[2][0] = 100;
globalBucket[2][1] = 100;
}
*/
var select = document.getElementById("chosenNames");
select.options.length = 0;
//$('#chosenNames').append("<option value='"+searchBarULBs.length+"'>"+searchBarULBs.length+" ULBs</option>");
for (var i = 0; i < searchBarULBs.length; i++) {
$('#chosenNames').append("<option value='" + searchBarULBs[i] + "'>" + searchBarULBs[i] + "</option>");
}
$("#chosenNames").attr("placeholder", "Search ULBs").val("").focus().blur();
$('#chosenNames').chosen().trigger("chosen:updated");
drop(markerLocations, globalBucket);
/*
var columnStyle = COLUMN_STYLES[attributeNameX]; // was column previously
var styles = [];
for (var i in columnStyle) {
var style = columnStyle[i];
style.min = bucket[i][0]-0.0001;
style.max = bucket[i][1]+0.0001;
styles.push({
where: generateWhere(attributeNameX, style.min, style.max),
polygonOptions: {
fillColor: style.color,
fillOpacity: style.opacity ? style.opacity : 0.8
}
});
}
*/
var styles = [];
for (var i in COLUMN_STYLES[attributeNameX]) {
var style = COLUMN_STYLES[attributeNameX][i];
// style.min = parseFloat(bucket[i][0],2) - 0.01;
// style.max = parseFloat(bucket[i][1],2) + 0.01;
style.min = parseFloat(globalBucket[i][0], 2) - 0.01;
style.max = parseFloat(globalBucket[i][1], 2) + 0.01;
styles.push({
where: generateWhere(attributeNameX, style.min, style.max),
polygonOptions: {
fillColor: style.color,
fillOpacity: style.opacity ? style.opacity : 0.8
}
});
}
if(gradeName == 'regwise'){
layer.setMap(null);
$('#searchChosenDiv').hide();
}else{
layer.set('styles', styles);
}
changeMap();
drawChart();
}
function generateWhere(columnName, low, high) {
var whereClause = [];
whereClause.push("'");
whereClause.push(columnName);
whereClause.push("' > ");
whereClause.push(low);
whereClause.push(" AND '");
whereClause.push(columnName);
whereClause.push("' <= ");
whereClause.push(high);
return whereClause.join('');
}
function changeMap() {
var query = "";
if (mode == "city") {
query = "SELECT 'geometry' FROM " + districtsTableID;
districtLayer.setOptions({
query: {
from: districtsTableID,
select: 'geometry'
},
styleId: 1,
});
}
if (mode == "district") {
query = "SELECT 'geometry' FROM " + districtsTableID + " WHERE 'DISTRICT_2011' = '" + districtName + "'";
districtLayer.setOptions({
query: {
from: districtsTableID,
select: 'geometry',
where: "'DISTRICT_2011' = '" + districtName + "'"
},
styleId: 1
});
}
if (mode == "region") {
query = "SELECT 'geometry' FROM " + districtsTableID + " WHERE 'Region' = '" + regionName + "'";
districtLayer.setOptions({
query: {
from: districtsTableID,
select: 'geometry',
where: "'Region' = '" + regionName + "'"
},
styleId: 1
});
}
if (mode == "grade") {
query = "SELECT 'geometry' FROM " + districtsTableID;
districtLayer.setOptions({
query: {
from: districtsTableID,
select: 'geometry'
},
styleId: 1
});
}
zoom2query(query);
}
function zoom2query(query) {
map.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(document.getElementById('legendWrapper'));
var column = attributeNameX;
$('#legendTitle').html(column);
var columnStyle = COLUMN_STYLES[column];
var style = columnStyle[0];
$('#legendItem1Content').html((parseFloat(style.min, 2) + 0.01).toFixed(2) + ' - ' + (parseFloat(style.max, 2) - 0.01).toFixed(2));
style = columnStyle[1];
$('#legendItem2Content').html((parseFloat(style.min, 2) + 0.01).toFixed(2) + ' - ' + (parseFloat(style.max, 2) - 0.01).toFixed(2));
style = columnStyle[2];
$('#legendItem3Content').html((parseFloat(style.min, 2) + 0.01).toFixed(2) + ' - ' + (parseFloat(style.max, 2) - 0.01).toFixed(2));
$('#legendItem4Content').html(0 + ' or ' + 'undefined');
$('#legendWrapper').show();
// zoom and center map on query results
//set the query using the parameter
var queryText = encodeURIComponent(query);
var query = new google.visualization.Query('http://www.google.com/fusiontables/gvizdata?tq=' + queryText);
//set the callback function
query.send(zoomTo);
}
function centerMap() {
map.setZoom(zoomAfterQuery);
map.panTo(centerAfterQuery);
//wrapper.getChart().setSelection([{row:0, column:null}]);
//updateLegend(attributeNameX);
}
function zoomTo(response) {
if (!response) {
//alert('no response');
return;
}
if (response.isError()) {
//alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
FTresponse = response;
//for more information on the response object, see the documentation
//http://code.google.com/apis/visualization/documentation/reference.html#QueryResponse
numRows = response.getDataTable().getNumberOfRows();
numCols = response.getDataTable().getNumberOfColumns();
// handle multiple matches
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < numRows; i++) {
var kml = FTresponse.getDataTable().getValue(i, 0);
// create a geoXml3 parser for the click handlers
var geoXml = new geoXML3.parser({
map: map,
zoom: false
});
geoXml.parseKmlString("<Placemark>" + kml + "</Placemark>");
// handle all possible kml placmarks
if (geoXml.docs[0].gpolylines.length > 0) {
geoXml.docs[0].gpolylines[0].setMap(null);
if (i == 0) var bounds = geoXml.docs[0].gpolylines[0].bounds;
else bounds.union(geoXml.docs[0].gpolylines[0].bounds);
} else if (geoXml.docs[0].markers.length > 0) {
geoXml.docs[0].markers[0].setMap(null);
if (i == 0) bounds.extend(geoXml.docs[0].markers[0].getPosition());
else bounds.extend(geoXml.docs[0].markers[0].getPosition());
} else if (geoXml.docs[0].gpolygons.length > 0) {
geoXml.docs[0].gpolygons[0].setMap(null);
if (i == 0) var bounds = geoXml.docs[0].gpolygons[0].bounds;
else bounds.union(geoXml.docs[0].gpolygons[0].bounds);
}
}
map.fitBounds(bounds);
centerAfterQuery = map.getCenter();
zoomAfterQuery = map.getZoom();
}
function getQueryStrings() {
var assoc = {};
var decode = function(s) {
return decodeURIComponent(s.replace(/\+/g, " "));
};
var queryString = location.search.substring(1);
var keyValues = queryString.split('&');
for (var i in keyValues) {
var key = keyValues[i].split('=');
if (key.length > 1) {
assoc[decode(key[0])] = decode(key[1]);
}
}
return assoc;
}
function fetchDataFromBrowserQueryAndUpdateUI() {
var qs = getQueryStrings();
var status = qs["status"]; //if you want to use ahead
/* if (status=="init") {
parent.document.getElementById('visuals').src = "visuals.html?X=C-Achievement&Y=ULB Name&area=grade&grade=G3&chart=ColumnChart&sort=XDESC&viz=split&status=start";
return;
}
*/
var sort = qs["sort"];
attributeNameX = qs["X"];
attributeNameY = qs["Y"];
chartType = qs["chart"];
mode = qs["area"];
districtName = qs["dis"];
regionName = qs["reg"];
gradeName = qs["grade"];
vizType = qs["viz"];
mainIndic = qs["main"];
subMainIndic = qs["sub"];
hod = qs["hod"];
//document.getElementById("titleText").textContent = attributeNameX + " for " + attributeNameY;
overallSelected = false;
if (mainIndic == 0 || (mainIndic == 1 && subMainIndic == 0) || (mainIndic == 3 && subMainIndic == 0) || (mainIndic == 4 && subMainIndic == 0) || (mainIndic == 5 && subMainIndic == 0) || (mainIndic == 6 && subMainIndic == 0) || (mainIndic == 8 && subMainIndic == 0) || (mainIndic == 9 && subMainIndic == 0) || (mainIndic == 12 && subMainIndic == 0) ) {
overallSelected = true;
}
if (sort == "XASC") {
sortType = "ORDER BY '" + attributeNameX + "' ASC";
} else if (sort == "XDESC") {
sortType = "ORDER BY '" + attributeNameX + "' DESC";
} else if (sort == "YASC") {
sortType = "ORDER BY '" + attributeNameY + "' ASC";
} else if (sort == "YDESC") {
sortType = "ORDER BY '" + attributeNameY + "' DESC";
} else if (sort == "NOSORT") {
sortType = "";
}
if (vizType == "split") {
$('.mapsection').show().removeClass('col-xs-12').addClass('col-xs-6');;
$('.chartsection').show().removeClass('col-xs-12').addClass('col-xs-6');;
} else if (vizType == "map") {
$('.mapsection').show().removeClass('col-xs-6').addClass('col-xs-12');
$('.chartsection').hide();
} else if (vizType == "chart") {
$('.mapsection').hide();
$('.chartsection').show().removeClass('col-xs-6').addClass('col-xs-12');
}
// alert(mainIndic+","+subMainIndic);
citiesTableID = '';
if (mainIndic == 0) {
if(hod == 1){
citiesTableID = '15PCNLfKkPZGc35wtThugjW0FBTlK2U9hCKIFNLTL';
titleText = "DMA Overall - Combined";
unitOfIndicator = "-";
}else if(hod == 2){
citiesTableID = '1AMkLyA2vz2xNXTHTX5JnxOZwnrVS6PNqu9xkhS7L';
titleText = "CE Overall - Combined";
unitOfIndicator = "-";
}else if(hod == 7){
citiesTableID = '1oh1JDpEiha7iByWwEo96IQpc_K3zkfdmJx-aE-Li';
titleText = "Combined - Combined";
unitOfIndicator = "-";
}
}else if (mainIndic == 1) {
if (subMainIndic == 0) {
citiesTableID = '10DDREC-__XHoPjL1FFVZ5G6Beh-Bs3yzuP59t5hL';
titleText = "Swachcha Andhra - Overall";
unitOfIndicator = "-";
}else if (subMainIndic == 1) {
citiesTableID = '1VlRSa6bRH67nzwoZNNg5Hi7RrADs6nrpL9XGKZxk';
titleText = "Swachcha Andhra - Individual Household Toilets (IHT) coverage";
unitOfIndicator = "No. of Toilets";
}else if (subMainIndic == 2) {
citiesTableID = '1gEkwIO7LC2ga5nS7fNiSZjrFaUyVcgQORdMAHs0d';
titleText = "Swachcha Andhra - Community Toilets coverage";
unitOfIndicator = "No. of Toilets";
}
}else if (mainIndic == 2) {
if (subMainIndic == 0) {
citiesTableID = '13zBQvJvzrdj8vf63MnvUcJOgo5pG8MYcqYP1hVjh';
titleText = "Greenery - Tree Plantation";
unitOfIndicator = "No. of plantations";
}
}else if (mainIndic == 3) {
if (subMainIndic == 0) {
citiesTableID = '1BgiIsyij_n9vB7cuCFRn6UgE9Cq0rgCZ57FePIWm';
titleText = "Solid Waste Management - Overall";
unitOfIndicator = "-";
} else if (subMainIndic == 1) {
citiesTableID = '1_nR3f6Z1TzTgCJ5UT0Do6QYf9Ok0hVfxkKf2vAfG';
titleText = "Solid Waste Management - Door to Door Garbage Collection";
unitOfIndicator = "No. of Households";
} else if (subMainIndic == 2) {
citiesTableID = '1HlptexkOhseTkl7ujc13LYb7uELXJBQduRM6QmLu';
titleText = "Solid Waste Management - Garbage Lifting";
unitOfIndicator = "Metric tonnes";
}
}else if (mainIndic == 4) {
if (subMainIndic == 0) {
citiesTableID = '1gidez_jsV4mxBSZ0a_lfo6cwunZXsSUxlRpNb_Ut';
titleText = "Property Tax - Overall";
unitOfIndicator = "-";
} else if (subMainIndic == 1) {
citiesTableID = '1Ft7BVfp-V8hpucsmWoW3Zal7p1qc5o6FwPSw3i4O';
titleText = "Property Tax - Collection Efficiency";
unitOfIndicator = "Rupees (in lakhs)";
} else if (subMainIndic == 2) {
citiesTableID = '175Ocis9sGqWTBLhXd2wVIawnlddbpKE1fvB-j_SZ';
titleText = "Property Tax - Demand Increase";
unitOfIndicator = "Rupees (in lakhs)";
}
}else if (mainIndic == 5) {
if (subMainIndic == 0) {
citiesTableID = '1XXalUDbRkTKbNbv7Dntueqd-BB7Pz5y_-ZxRqDvF';
titleText = "Citizen Services - Overall";
unitOfIndicator = "-";
} else if (subMainIndic == 1) {
citiesTableID = '1K6vPTSthe2-X__IHsi42Roq5RReNZ9xy-nVTcgMc';
titleText = "Citizen Services - Citizen Charter (office)";
unitOfIndicator = "No. of applications";
} else if (subMainIndic == 2) {
citiesTableID = '1SbLuxSFUquS7q-mmLKp8_zYeKbdwvbbV3fMVmL5W';
titleText = "Citizen Services - Grievances Redressal (field)";
unitOfIndicator = "No. of grievances";
}
}else if (mainIndic == 6) {
if (subMainIndic == 0) {
citiesTableID = '1q7GNaD1WoY8g2acTpXq9DbOggJnW-crbIxd7ixRY';
titleText = "Finance - Overall";
unitOfIndicator = "-";
} else if (subMainIndic == 1) {
citiesTableID = '1t3_EJG6Ppn4apIrONT0Wz1b6OYMix1OZkenzEcOd';
titleText = "Finance - Double Entry Accounting";
unitOfIndicator = "No. of days";
} else if (subMainIndic == 2) {
citiesTableID = '10591kbl5tAaWG4Kamh9QCQ1HWjY4-ESWRDQ1GQZ0';
titleText = "Finance - Pending Accounts and Audit";
unitOfIndicator = "No. of years";
}
}else if (mainIndic == 7) {
citiesTableID = '1UOltn1AicEOL-FkG4mKsay6pEi8SZQKmf5y5xX9m';
titleText = "Education - High schools with IIT foundation";
unitOfIndicator = "No. of High schools";
}else if (mainIndic == 8) {
if (subMainIndic == 0) {
citiesTableID = '1KVFlQd2zfJ5soZv_kJrMsxZNPEzZSdCzvJoKAGlE';
titleText = "Water Supply Connections - Overall Coverage";
unitOfIndicator = "-";
} else if (subMainIndic == 1) {
citiesTableID = '1dHEUFs9Edz-pfbBmX7dDczXZXdvHyhIT50681RiI';
titleText = "Water Supply - Connections Coverage";
unitOfIndicator = "No. of Connections";
} else if (subMainIndic == 2) {
citiesTableID = '1f6ZA4wqY7V3gJAOhz3M2jMi9VMpVtQFGG6_ExJH-';
titleText = "Water Supply per month - Cost Recovery";
unitOfIndicator = "Rupees (in Lakhs)";
}
}else if (mainIndic == 9) {
if (subMainIndic == 0) {
citiesTableID = '1WjL0SBK8k3NgOMS8YjiirnuA1JgnqOuQjAAfSKZ-';
titleText = "Street Lighting - Overall";
unitOfIndicator = "-";
} else if (subMainIndic == 1) {
citiesTableID = '1XiO6lKhyPdCLTR6E_9ltEBaM20wQWDgt3X0E6Xqk';
titleText = "Street Lighting - LED Coverage";
unitOfIndicator = "No. of LEDs";
} else if (subMainIndic == 2) {
citiesTableID = '1SJZL2t_DchzylwR2zoSE-Zk1NOPVrQ-hitSn8KXx';
titleText = "Street Lighting - Additional Fixtures";
unitOfIndicator = "No. of Fixtures";
}
}else if (mainIndic == 11) {
if (subMainIndic == 0) {
citiesTableID = '1xCuO37vnXEN0Ake02ErGetRTZUo8W6mueNugmdhq';
titleText = "Town Planning Activities - Building Online Permissions";
unitOfIndicator = "No.of Applications";
}
}else if (mainIndic == 12) {
if (subMainIndic == 0) {
citiesTableID = '1ufZzYeUN40B-5u0Msggo8UIHddJ-jQMvES8IAqWL';
titleText = "Community Development - Overall";
unitOfIndicator = "-";
} else if (subMainIndic == 1) {
citiesTableID = '1ShLFRlL4D_O05ant_kRkkSprShJPYb_nQ8S4MCvT';
titleText = "Community Development - SHG Bank Linkage";
unitOfIndicator = "Rupees (in lakhs)";
} else if (subMainIndic == 2) {
citiesTableID = '1QjN7go-OdeLVtKnart_yuwWuKavxEJP_lSy9tyV4';
titleText = "Community Development - Livelihood";
unitOfIndicator = "No.";
}else if (subMainIndic == 3) {
citiesTableID = '1Oua3hYGMx3knhsK7yf36TspEvV_rJbE2lsCEWqLT';
titleText = "Community Development - Skill Training Programmes";
unitOfIndicator = "No.";
}
}
if (mode == "city") {
titleText += " - All ULBs";
} else if (mode == "district") {
titleText += " - " + districtName + " District";
} else if (mode == "region") {
titleText += " - " + regionName + " Region";
} else if (mode == "grade") {
if (gradeName == "G1") {
titleText += " - Special, Selection Grades";
} else if (gradeName == "G2") {
titleText += " - Grade I, II";
} else if (gradeName == "G3") {
titleText += " - Grades III, NP";
} else if (gradeName == "G4") {
titleText += " - Corporations Grade";
}else if (gradeName == "elevenulb") {
titleText += " - 11 ULBs";
}else if (gradeName == "regwise") {
titleText += " - Region-wise";
}
}
multiSeries = false;
reportTitleText = titleText;
if (chartType == "MultiChart") {
if(gradeName === 'regwise'){
titleText += " - <span style='color:#F5861F;font-weight:bold;'>Monthly</span> and <span style='color:#6B4F2C;font-weight:bold;'>Cumulative</span> Marks";
}else{
titleText += " - <span style='color:#F5861F;font-weight:bold;'>Monthly</span> and <span style='color:#6B4F2C;font-weight:bold;'>Cumulative</span> Achievement (%)";
}
multiSeries = true;
reportTitleText += " - Monthly v/s Cumulative Report";
} else {
if(gradeName === 'regwise'){
if (attributeNameX.indexOf("C-") > -1) {
titleText += " - Cumulative Marks";
reportTitleText += " - Cumulative Report";
} else if (attributeNameX.indexOf("UPM-") > -1) {
titleText += " - Upto Previous Month Marks";
reportTitleText += " - Upto previous month Report";
} else if (attributeNameX.indexOf("M-") > -1) {
reportTitleText += " - Monthly Report";
titleText += " - Monthly Marks";
}
}else{
if (attributeNameX.indexOf("C-") > -1) {
titleText += " - Cumulative Achievement (%)";
reportTitleText += " - Cumulative Report";
} else if (attributeNameX.indexOf("UPM-") > -1) {
titleText += " - Upto previous month Achievement (%)";
reportTitleText += " - Upto previous month Report";
} else if (attributeNameX.indexOf("M-") > -1) {
reportTitleText += " - Monthly Report";
titleText += " - Monthly Achievement (%)";
}
}
}
document.getElementById("titleText").innerHTML = "<b>" + titleText + "</b>";
initialize();
}
function drop(cities, bucket) {
clearMarkers();
for (var i = 0; i < cities.length; i++) {
addMarkerWithTimeout(cities[i], 1, bucket);
}
}
function addMarkerWithTimeout(position, timeout, bucket) {
var mrkr;
var image;
if (position[4] < bucket[0][1]) {
//console.log("red: " + position[4]);
image = 'http://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=|e74c3c';
} else if (position[4] < bucket[1][1]) {
//console.log("amber: " + position[4]);
image = 'http://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=|f1c40f';
} else if (position[4] <= bucket[2][1]) {
//console.log("green: " + position[4]);
image = 'http://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=|2ecc71';
}
if (position[4] == 100) {
image = 'http://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=|2ecc71';
}
//console.log(position[14]);//region-wise
if (gradeName == "regwise") {
if(position[14] == 'RAJAHMUNDRY'){
image = 'http://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=|e74c3c'; //red
}else if(position[14] == 'VISAKHAPATNAM'){
image = 'http://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=|f1c40f';//amber
}else if(position[14] == 'GUNTUR'){
image = 'http://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=|2ecc71';//green
}else if(position[14] == 'ANANTAPUR'){
image = 'http://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=|0099cc';//blue
}
}
var myLatLng = {
lat: parseFloat(position[0]),
lng: parseFloat(position[1])
};
if (unitOfIndicator == "-") {
position[6] = " NA";
}
mrkr = new google.maps.Marker({
position: myLatLng,
map: map,
icon: image,
animation: google.maps.Animation.DROP
});
mrkr.addListener('mouseover', function() {
chartInfoBubble2.setContent("<div ><font size='2'><b>" + position[2] + "</b><br>" + "Grade: <b>" + position[3] + "</b></br>" + attributeNameX + ": <b>" + ((typeof(position[4]) == 'number') ? (position[4].toFixed(2)) : position[4]) + "</b></br>" + attributeNameY + ": <b>" + position[5] + "</b></br><table border='1' class='infoWindowTable' style='width=100%;'><tr><th>-</th><th>Upto previous month</th><th>Monthly</th><th>Cumulative</th></tr><tr><td><b>Marks (" + position[13] + ")</b></td><td><b>" + ((typeof(position[12]) == 'number') ? (position[12].toFixed(2)) : position[12]) + "</b></td><td><b>" + ((typeof(position[11]) == 'number') ? (position[11].toFixed(2)) : position[11]) + "</b></td><td><b>" + ((typeof(position[10]) == 'number') ? (position[10].toFixed(2)) : position[10]) + "</b></td></tr><tr><td><b>Rank</b></td><td><b>" + position[9] + "</b></td><td><b>" + position[8] + "</b></td><td><b>" + position[7] + "</b></td></tr></table></font></div>");
chartInfoBubble2.open(map,mrkr);
});
mrkr.addListener('mouseout', function() {
chartInfoBubble2.close();
});
//mrkr.setZIndex(101);
markers.push(mrkr);
}
function clearMarkers() {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(null);
}
markers = [];
}
function selectChosenItemSelected() {
var selectBox = document.getElementById("chosenNames");
var selectedValue = selectBox.options[selectBox.selectedIndex].value;
tooltipValue = selectedValue;
ulbsummary('https://www.googleapis.com/fusiontables/v2/query?sql=', tooltipValue);
}
function generateReport() {
// alert(generateReportQuery);
var query = new google.visualization.Query('http://www.google.com/fusiontables/gvizdata?tq=');
//console.log('generateReportQuery:'+generateReportQuery);
query.setQuery(generateReportQuery);
query.send(openTableModal);
$('#loadingIndicator').show();
$('#table_div').hide();
}
function openTableModal(response) {
var data = response.getDataTable();
var myTableDiv = document.getElementById("table_div");
var table = document.getElementById('print_data_table');
var tableBody = document.getElementById('table_body');
while (tableBody.firstChild) {
tableBody.removeChild(tableBody.firstChild);
}
var heading = new Array();
var heading = [];
if (!overallSelected) {
if(gradeName == 'regwise'){
if (!multiSeries) {
heading = ["Sr No.", "Region", "Annual Target", "Target", "Achievement", "Achievement %", "Marks", "Max Marks"];
} else {
heading = ["Sr No.", "Region", "Annual Target", "C-Target", "C-Achievement", "C-Achievement %", "C-Marks", "Max Marks", "M-Target", "M-Achievement", "M-Achievement %", "M-Marks"];
}
}else{
if (!multiSeries) {
heading = ["Sr No.", "ULB Name", "Annual Target", "Target", "Achievement", "Achievement %", "Marks", "Max Marks", "Rank"];
} else {
heading = ["Sr No.", "ULB Name", "Annual Target", "C-Target", "C-Achievement", "C-Achievement %", "C-Marks", "Max Marks", "C-Rank", "M-Target", "M-Achievement", "M-Achievement %", "M-Marks", "M-Rank"];
}
}
} else {
if(gradeName == 'regwise'){
if (!multiSeries) {
heading = ["Sr No.", "Region", "Marks", "Max Marks"];
} else {
heading = ["Sr No.", "Region", "C-Marks", "M-Marks", "Max Marks"];
}
}else{
if (!multiSeries) {
heading = ["Sr No.", "ULB Name", "Marks", "Max Marks", "Rank"];
} else {
heading = ["Sr No.", "ULB Name", "C-Marks", "C-Rank", "M-Marks", "M-Rank", "Max Marks"];
}
}
}
var tr = document.createElement('TR');
tableBody.appendChild(tr);
for (i = 0; i < heading.length; i++) {
var th = document.createElement('TH')
//th.width = '200';
th.appendChild(document.createTextNode(heading[i]));
tr.appendChild(th);
}
var rows = [],
columns = [];
for (var i = 0; i < data.getNumberOfRows(); i++) {
var tr = document.createElement('TR');
var td = document.createElement('TD');
td.appendChild(document.createTextNode(i + 1));
tr.appendChild(td);
for (var j = 0; j < data.getNumberOfColumns(); j++) {
var td = document.createElement('TD');
var val = data.getValue(i, j);
//td.appendChild(document.createTextNode(val));
//console.log(val+'<--->'+typeof(val));
if(j == (data.getNumberOfColumns()-1)){
td.appendChild(document.createTextNode(val));
}else{
if(typeof(val) == 'string'){
td.appendChild(document.createTextNode(val));
}else if(typeof(val) == 'number'){
td.appendChild(document.createTextNode(val.toFixed(2)));
}
}
tr.appendChild(td);
}
tableBody.appendChild(tr);
}
myTableDiv.appendChild(table);
$('#loadingIndicator').hide();
$('#table_div').show();
$('#m-title').text(reportTitleText);
$('#m-subtitle').text('UOM : '+unitOfIndicator);
}
function paperPrint() {
$(".modal-content").printElement({
printBodyOptions: {
styleToAdd: 'height:auto;overflow:auto;margin-left:-25px;'
}
});
}
| DataKind-BLR/analytics | kpi/cm-demo-tool/js/visuals.js | JavaScript | mit | 88,580 |
'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
/**
* Tfile Schema
*/
var TfileSchema = new Schema({
name: {
type: String,
default: '',
required: 'Please add a TestFile name',
trim: true
},
created: {
type: Date,
default: Date.now
},
user: {
type: Schema.ObjectId,
ref: 'User'
},
content: {
type:String,
default: ''
},
tags: {
type:[String],
default: {}
}
});
mongoose.model('Tfile', TfileSchema); | kaseyalusi/tests | app/models/tfile.server.model.js | JavaScript | mit | 557 |
'use strict';
// event
// eventType - 'dragStart', 'drag', 'dragStop'
// pos - absolute pos,
// returnCallback
var app = angular.module('utilsDrag', []);
app.directive('utilsDrag', function ( ) {
return {
restrict: 'A',
scope:
{
dragCallback: '&utilsDrag'
},
replace: true,
controller: [ '$scope', '$rootScope', function ( $scope )
{
window.ud = $scope;
$scope.dragElement = U;
$scope.dragStartPosition = U;
$scope.returnCallback = function ()
{
$scope.dragElement.css( $scope.dragStartPosition );
}
}],
link: function ( scope, element )
{
var cursorTop = $(element).height() / 2;
var cursorLeft = $(element).width() / 2;
function getCursorPosition ( topLeft, event )
{
// console.log( 'event: ', event );
// var eventPos = getEventPos( event );
var x = event.pageX;
var y = event.pageY;
return { x: x, y: y };
}
$(element).draggable(
{
cursorAt:
{
top: cursorTop,
left: cursorLeft
},
start: function ( event, ui )
{
scope.dragElement = $(this);
scope.dragElement.css('pointer-events', 'none');
var startDragging = scope.dragCallback(
{
event: event,
eventType: 'dragStart',
pos: getCursorPosition( ui.position, event ),
returnCallback: scope.returnCallback
});
scope.dragStartPosition = ui.position;
},
drag: function( event, ui )
{
var drag = scope.dragCallback(
{
event: event,
eventType: 'drag',
pos: getCursorPosition( ui.position, event ),
returnCallback: scope.returnCallback
});
if ( drag )
return false;
},
stop: function ( event, ui )
{
var stopDragging = scope.dragCallback(
{
event: event,
eventType: 'dragStop',
pos: getCursorPosition( ui.position, event ),
returnCallback: scope.returnCallback
});
scope.dragElement.css('pointer-events', 'all');
}
});
}
};
}); | nangelova/utils-drag | utils-drag.js | JavaScript | mit | 3,120 |
/* jshint node: true */
'use strict';
var assign = require('object-assign');
module.exports = {
name: 'ember-cli-cloudinary-images',
config: function(environment, appConfig) {
var CLOUDINARY = appConfig.CLOUDINARY || {};
return {
CLOUDINARY: assign({
/** For future support */
API_KEY: '',
/** The user in Cloudinary */
CLOUD_NAME: '',
/** Used for private CDN or as for sub-domain for given domain */
SUB_DOMAIN: '',
/** The domain of the account if exists (default to shared domain of Cloudinary) */
DOMAIN: '',
/** Use HTTPs or HTTP. The default is HTTPs */
SECURE: true,
/** Use distributions CDN (example: https://res-[1-5].cloudinary.com) */
CDN_DISTRIBUTION: false,
/** Transforms for concatenation with given transforms */
CONCATENATED_TRANSFORMS: [],
/** Default transforms that can be override */
DEFAULT_TRANSFORMS: [],
/** Default images file extensions */
DEFAULT_IMAGE_FORMAT: 'jpg'
}, CLOUDINARY)
};
}
};
| oriSomething/ember-cli-cloudinary-images | index.js | JavaScript | mit | 1,098 |
/* Magic Mirror Test config default weather
*
* By rejas
* MIT Licensed.
*/
let config = {
units: "imperial",
modules: [
{
module: "weather",
position: "bottom_bar",
config: {
type: "forecast",
location: "Munich",
mockData: '"#####WEATHERDATA#####"',
weatherEndpoint: "/forecast/daily",
decimalSymbol: "_"
}
}
]
};
/*************** DO NOT EDIT THE LINE BELOW ***************/
if (typeof module !== "undefined") {
module.exports = config;
}
| Tyvonne/MagicMirror | tests/configs/modules/weather/forecastweather_units.js | JavaScript | mit | 486 |
/**
* Produces optimized XTemplates for chunks of tables to be
* used in grids, trees and other table based widgets.
*/
Ext.define('Ext.view.TableChunker', {
singleton: true,
requires: ['Ext.XTemplate'],
metaTableTpl: [
'{%if (this.openTableWrap)out.push(this.openTableWrap())%}',
'<table class="' + Ext.baseCSSPrefix + 'grid-table ' + Ext.baseCSSPrefix + 'grid-table-resizer" border="0" cellspacing="0" cellpadding="0" {[this.embedFullWidth(values)]}>',
'<tbody>',
'<tr class="' + Ext.baseCSSPrefix + 'grid-header-row">',
'<tpl for="columns">',
'<th class="' + Ext.baseCSSPrefix + 'grid-col-resizer-{id}" style="width: {width}px; height: 0px;"></th>',
'</tpl>',
'</tr>',
'{[this.openRows()]}',
'{row}',
'<tpl for="features">',
'{[this.embedFeature(values, parent, xindex, xcount)]}',
'</tpl>',
'{[this.closeRows()]}',
'</tbody>',
'</table>',
'{%if (this.closeTableWrap)out.push(this.closeTableWrap())%}'
],
constructor: function() {
Ext.XTemplate.prototype.recurse = function(values, reference) {
return this.apply(reference ? values[reference] : values);
};
},
embedFeature: function(values, parent, x, xcount) {
if (!values.disabled) {
return values.getFeatureTpl(values, parent, x, xcount);
}
return '';
},
embedFullWidth: function(values) {
var result = 'style="width:{fullWidth}px;';
// If there are no records, we need to give the table a height so that it
// is displayed and causes q scrollbar if the width exceeds the View's width.
if (!values.rowCount) {
result += 'height:1px;';
}
return result + '"';
},
openRows: function() {
return '<tpl for="rows">';
},
closeRows: function() {
return '</tpl>';
},
metaRowTpl: [
'<tr class="' + Ext.baseCSSPrefix + 'grid-row {[this.embedRowCls()]}" {[this.embedRowAttr()]}>',
'<tpl for="columns">',
'<td class="{cls} ' + Ext.baseCSSPrefix + 'grid-cell ' + Ext.baseCSSPrefix + 'grid-cell-{columnId} {{id}-modified} {{id}-tdCls} {[this.firstOrLastCls(xindex, xcount)]}" {{id}-tdAttr}>',
'<div {unselectableAttr} class="' + Ext.baseCSSPrefix + 'grid-cell-inner {unselectableCls}" style="text-align: {align}; {{id}-style};">{{id}}</div>',
'</td>',
'</tpl>',
'</tr>'
],
firstOrLastCls: function(xindex, xcount) {
var result = '';
if (xindex === 1) {
result = Ext.view.Table.prototype.firstCls;
}
if (xindex === xcount) {
result += ' ' + Ext.view.Table.prototype.lastCls;
}
return result;
},
embedRowCls: function() {
return '{rowCls}';
},
embedRowAttr: function() {
return '{rowAttr}';
},
openTableWrap: undefined,
closeTableWrap: undefined,
getTableTpl: function(cfg, textOnly) {
var me = this,
tpl,
tableTplMemberFns = {
openRows: me.openRows,
closeRows: me.closeRows,
embedFeature: me.embedFeature,
embedFullWidth: me.embedFullWidth,
openTableWrap: me.openTableWrap,
closeTableWrap: me.closeTableWrap
},
tplMemberFns = {},
features = cfg.features,
featureCount = features ? features.length : 0,
i = 0,
memberFns = {
embedRowCls: me.embedRowCls,
embedRowAttr: me.embedRowAttr,
firstOrLastCls: me.firstOrLastCls,
unselectableAttr: cfg.enableTextSelection ? '' : 'unselectable="on"',
unselectableCls: cfg.enableTextSelection ? '' : Ext.baseCSSPrefix + 'unselectable'
},
// copy the template spec array if there are Features which might mutate it
metaRowTpl = featureCount ? Array.prototype.slice.call(me.metaRowTpl, 0) : me.metaRowTpl;
for (; i < featureCount; i++) {
if (!features[i].disabled) {
features[i].mutateMetaRowTpl(metaRowTpl);
Ext.apply(memberFns, features[i].getMetaRowTplFragments());
Ext.apply(tplMemberFns, features[i].getFragmentTpl());
Ext.apply(tableTplMemberFns, features[i].getTableFragments());
}
}
cfg.row = new Ext.XTemplate(metaRowTpl.join(''), memberFns).applyTemplate(cfg);
tpl = new Ext.XTemplate(me.metaTableTpl.join(''), tableTplMemberFns).applyTemplate(cfg);
// TODO: Investigate eliminating.
if (!textOnly) {
tpl = new Ext.XTemplate(tpl, tplMemberFns);
}
return tpl;
}
});
| brunotavares/Ext.ux.Router | examples/ext/src/view/TableChunker.js | JavaScript | mit | 5,033 |
///////////////
/// main.js //
/////////////
jQuery(function () {
var $ = jQuery;
// happy coding!
}); | arsylum/meouz | ouz/haz/js/main.js | JavaScript | mit | 106 |
import {
collection
} from 'ember-cli-page-object';
export default {
scope: '.user__skills-list',
emptyState: {
scope: '[data-test-user-skills-list-empty-state]'
},
skills: collection('[data-test-user-skills-list-item]')
};
| jderr-mx/code-corps-ember | tests/pages/components/user/skills-list.js | JavaScript | mit | 241 |
/** @module utils/nodes */
/**
* The default testnet node
*
* @type {string}
*/
let defaultTestnetNode = 'http://bob.nem.ninja:7778';
/**
* The default mainnet node
*
* @type {string}
*/
let defaultMainnetNode = 'http://alice6.nem.ninja:7778';
/**
* The default mijin node
*
* @type {string}
*/
let defaultMijinNode = '';
/**
* The default mainnet block explorer
*
* @type {string}
*/
let defaultMainnetExplorer = 'http://chain.nem.ninja/#/transfer/';
/**
* The default testnet block explorer
*
* @type {string}
*/
let defaultTestnetExplorer = 'http://bob.nem.ninja:8765/#/transfer/';
/**
* The default mijin block explorer
*
* @type {string}
*/
let defaultMijinExplorer = '';
/**
* The nodes allowing search by transaction hash on testnet
*
* @type {array}
*/
let testnetSearchNodes = [
{
'uri': 'http://bigalice2.nem.ninja:7890',
'location': 'America / New_York'
},
{
'uri': 'http://192.3.61.243:7890',
'location': 'America / Los_Angeles'
},
{
'uri': 'http://23.228.67.85:7890',
'location': 'America / Los_Angeles'
}
];
/**
* The nodes allowing search by transaction hash on mainnet
*
* @type {array}
*/
let mainnetSearchNodes = [
{
'uri': 'http://62.75.171.41:7890',
'location': 'Germany'
}, {
'uri': 'http://104.251.212.131:7890',
'location': 'USA'
}, {
'uri': 'http://45.124.65.125:7890',
'location': 'Hong Kong'
}, {
'uri': 'http://185.53.131.101:7890',
'location': 'Netherlands'
}, {
'uri': 'http://sz.nemchina.com:7890',
'location': 'China'
}
];
/**
* The nodes allowing search by transaction hash on mijin
*
* @type {array}
*/
let mijinSearchNodes = [
{
'uri': '',
'location': ''
}
];
/**
* The testnet nodes
*
* @type {array}
*/
let testnetNodes = [
{
uri: 'http://bob.nem.ninja:7778'
}, {
uri: 'http://104.128.226.60:7778'
}, {
uri: 'http://23.228.67.85:7778'
}, {
uri: 'http://192.3.61.243:7778'
}, {
uri: 'http://50.3.87.123:7778'
}, {
uri: 'http://localhost:7778'
}
];
/**
* The mainnet nodes
*
* @type {array}
*/
let mainnetNodes = [
{
uri: 'http://62.75.171.41:7778'
}, {
uri: 'http://san.nem.ninja:7778'
}, {
uri: 'http://go.nem.ninja:7778'
}, {
uri: 'http://hachi.nem.ninja:7778'
}, {
uri: 'http://jusan.nem.ninja:7778'
}, {
uri: 'http://nijuichi.nem.ninja:7778'
}, {
uri: 'http://alice2.nem.ninja:7778'
}, {
uri: 'http://alice3.nem.ninja:7778'
}, {
uri: 'http://alice4.nem.ninja:7778'
}, {
uri: 'http://alice5.nem.ninja:7778'
}, {
uri: 'http://alice6.nem.ninja:7778'
}, {
uri: 'http://alice7.nem.ninja:7778'
}, {
uri: 'http://localhost:7778'
}
];
/**
* The mijin nodes
*
* @type {array}
*/
let mijinNodes = [
{
uri: ''
}
];
/**
* The server verifying signed apostilles
*
* @type {string}
*/
let apostilleAuditServer = 'http://185.117.22.58:4567/verify';
module.exports = {
defaultTestnetNode,
defaultMainnetNode,
defaultMijinNode,
defaultMainnetExplorer,
defaultTestnetExplorer,
defaultMijinExplorer,
testnetSearchNodes,
mainnetSearchNodes,
mijinSearchNodes,
testnetNodes,
mainnetNodes,
mijinNodes,
apostilleAuditServer
} | AtrauraBlockchain/Landstead | src/app/utils/nodes.js | JavaScript | mit | 3,382 |
/*
Copyright (c) 2011 Cimaron Shanahan
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/**
* IR Instruction Class
*
* Represents a single assembly-like instruction
*/
function IrInstruction(op, d, s1, s2, s3) {
var args;
this.str = null;
this.line = null;
if (arguments.length == 1) {
args = op.split(/[\s,]/);
op = args[0];
d = args[1];
s1 = args[2];
s2 = args[3];
s3 = args[4];
}
this.op = op;
this.d = this.operand(d);
this.s1 = this.operand(s1);
this.s2 = this.operand(s2);
this.s3 = this.operand(s3);
}
IrInstruction.operands = ['d', 's1', 's2', 's3'];
/**
* Create operand for instruction
*
* @param mixed opr String or IrOperand
*
* @return mixed
*/
IrInstruction.prototype.operand = function(opr) {
if (!opr) {
return "";
}
if (opr instanceof IrOperand) {
return opr;
}
return new IrOperand(opr);
};
/**
* Adds the offset to all operands
*
* @param integer The offset to set
*/
IrInstruction.prototype.addOffset = function(offset) {
var i, o;
for (i = 0; i < IrInstruction.operands.length; i++) {
o = IrInstruction.operands[i];
if (this[o]) {
this[o].addOffset(offset);
}
}
};
/**
* Set the swizzle components on all operands
*
* @param string The swizzle to set
*/
IrInstruction.prototype.setSwizzle = function(swz) {
var i, o;
for (i = 0; i < IrInstruction.operands.length; i++) {
o = IrInstruction.operands[i];
if (this[o] && !this[o].swizzle) {
this[o].swizzle = swz;
}
}
};
/**
* toString method
*
* @return string
*/
IrInstruction.prototype.toString = function() {
var out;
out = util.format("%s%s%s%s%s;",
this.op,
this.d ? ' ' + this.d : '',
this.s1 ? ', ' + this.s1 : '',
this.s2 ? ', ' + this.s2 : '',
this.s3 ? ', ' + this.s3 : ''
);
return out;
};
/**
* IR Comment Class
*
* Represents a single comment
*/
function IrComment(comment, loc) {
this.comment = comment;
this.loc = loc;
}
IrComment.prototype.toString = function() {
var c = this.comment;
if (this.loc) {
c = util.format("%s [%s:%s-%s:%s]", c, this.loc.first_line, this.loc.first_column, this.loc.last_line, this.loc.last_column);
}
c = "\n# " + c;
return c;
};
/**
* IR Operand Class
*
* Represents a single operand
*/
function IrOperand(str, raw) {
this.full = "";
this.neg = "";
this.name = "";
this.address = "";
this.swizzle = "";
this.number = "";
this.raw = "";
this.index = "";
if (raw) {
this.full = str;
this.raw = str;
} else {
this.parse(str);
}
}
/**
* Parses operand string
*
* @param string string that represents a single variable
*/
IrOperand.prototype.parse = function(str) {
var parts, regex;
if (!str) {
return;
}
if (!isNaN(parseFloat(str))) {
this.raw = str;
return;
}
//neg
regex = "(\-)?";
//name (include '%' for our code substitution rules)
regex += "([\\w%]+)";
//number
regex += "(?:@(\\d+))?";
//index
regex += "(?:\\[(\\d+)\\])?";
//swizzle
regex += "(?:\\.([xyzw]+))?";
regex = new RegExp("^" + regex + "$");
if (parts = str.match(regex)) {
this.neg = parts[1] || "";
this.name = parts[2];
this.address = parseInt(parts[3]) || 0;
this.index = parseInt(parts[4]) || 0;
this.swizzle = parts[5] || "";
} else {
if (parts = str.match(/^"(.*)"$/)) {
this.raw = parts[1];
} else {
this.raw = str;
}
}
this.full = this.toString();
};
/**
* Adds an offset
*
* @param integer Offset to add
*/
IrOperand.prototype.addOffset = function(offset) {
this.address = this.address || 0;
this.address += offset;
};
/**
* Set components size if not already set
*/
IrOperand.prototype.makeSize = function(size) {
if (!this.swizzle) {
this.swizzle = "xyzw".substring(0, size);
} else if (this.swizzle.length != size) {
throw new Error(util.format("Cannot coerce operand to size %s", size));
}
};
/**
* toString method
*
* @return string
*/
IrOperand.prototype.toString = function() {
var str;
if (this.raw) {
str = this.raw;
} else {
str = this.neg + this.name + ("@" + this.address) + (this.index !== "" ? "[" + this.index + "]" : "") + (this.swizzle ? "." + this.swizzle : "");
}
return str;
};
| DelvarWorld/glsl2js | ir/instruction.js | JavaScript | mit | 5,157 |
/** @license MIT License (c) copyright B Cavalier & J Hann */
/**
* wire/on plugin
* wire plugin that provides an "on" facet to connect to dom events,
* and includes support for delegation
*
* wire is part of the cujo.js family of libraries (http://cujojs.com/)
*
* Licensed under the MIT License at:
* http://www.opensource.org/licenses/mit-license.php
*/
(function (define) {
define(['./lib/plugin-base/on', './lib/dom/base'], function (createOnPlugin, base) {
'use strict';
var contains;
/**
* Listens for dom events at the given node. If a selector is provided,
* events are filtered to only nodes matching the selector. Note, however,
* that children of the matching nodes can also fire events that bubble.
* To determine the matching node, use the event object's selectorTarget
* property instead of it's target property.
* @param node {HTMLElement} element at which to listen
* @param event {String} event name ('click', 'mouseenter')
* @param handler {Function} handler function with the following signature: function (e) {}
* @param [selector] {String} optional css query string to use to
* @return {Function} removes the event handler
*/
function on (node, event, handler /*, selector */) {
var selector = arguments[3];
if (selector) {
handler = filteringHandler(node, selector, handler);
}
node.addEventListener(event, handler, false);
return function remove () {
node.removeEventListener(node, handler, false);
};
}
on.wire$plugin = createOnPlugin({
on: on
});
if (document && document.compareDocumentPosition) {
contains = function w3cContains (refNode, testNode) {
return (refNode.compareDocumentPosition(testNode) & 16) == 16;
};
}
else {
contains = function oldContains (refNode, testNode) {
return refNode.contains(testNode);
};
}
return on;
/**
* This is a brute-force method of checking if an event target
* matches a query selector.
* @private
* @param node {Node}
* @param selector {String}
* @param handler {Function} function (e) {}
* @returns {Function} function (e) {}
*/
function filteringHandler (node, selector, handler) {
return function (e) {
var target, matches, i, len, match;
// if e.target matches the selector, call the handler
target = e.target;
matches = base.querySelectorAll(selector, node);
for (i = 0, len = matches.length; i < len; i++) {
match = matches[i];
if (target == match || contains(match, target)) {
e.selectorTarget = match;
return handler(e);
}
}
};
}
});
}(
typeof define == 'function' && define.amd
? define
: function (deps, factory) { module.exports = factory.apply(this, deps.map(require)); }
));
| cujojs/wire | on.js | JavaScript | mit | 2,712 |
import {
extend,
colorRgbToHex,
colorRgbToHsl,
colorHslToHsb,
colorHslToRgb,
colorHsbToHsl,
colorHexToRgb,
nextTick,
deleteProps,
} from '../../shared/utils';
import Framework7Class from '../../shared/class';
import $ from '../../shared/dom7';
import { getDevice } from '../../shared/get-device';
import moduleAlphaSlider from './modules/alpha-slider';
import moduleCurrentColor from './modules/current-color';
import moduleHex from './modules/hex';
import moduleHsbSliders from './modules/hsb-sliders';
import moduleHueSlider from './modules/hue-slider';
import moduleBrightnessSlider from './modules/brightness-slider';
import modulePalette from './modules/palette';
import moduleInitialCurrentColors from './modules/initial-current-colors';
import moduleRgbBars from './modules/rgb-bars';
import moduleRgbSliders from './modules/rgb-sliders';
import moduleSbSpectrum from './modules/sb-spectrum';
import moduleHsSpectrum from './modules/hs-spectrum';
import moduleWheel from './modules/wheel';
/** @jsx $jsx */
import $jsx from '../../shared/$jsx';
class ColorPicker extends Framework7Class {
constructor(app, params = {}) {
super(params, [app]);
const self = this;
self.params = extend({}, app.params.colorPicker, params);
let $containerEl;
if (self.params.containerEl) {
$containerEl = $(self.params.containerEl);
if ($containerEl.length === 0) return self;
}
let $inputEl;
if (self.params.inputEl) {
$inputEl = $(self.params.inputEl);
}
let $targetEl;
if (self.params.targetEl) {
$targetEl = $(self.params.targetEl);
}
extend(self, {
app,
$containerEl,
containerEl: $containerEl && $containerEl[0],
inline: $containerEl && $containerEl.length > 0,
$inputEl,
inputEl: $inputEl && $inputEl[0],
$targetEl,
targetEl: $targetEl && $targetEl[0],
initialized: false,
opened: false,
url: self.params.url,
modules: {
'alpha-slider': moduleAlphaSlider,
'current-color': moduleCurrentColor,
hex: moduleHex, // eslint-disable-line
'hsb-sliders': moduleHsbSliders,
'hue-slider': moduleHueSlider,
'brightness-slider': moduleBrightnessSlider,
palette: modulePalette, // eslint-disable-line
'initial-current-colors': moduleInitialCurrentColors,
'rgb-bars': moduleRgbBars,
'rgb-sliders': moduleRgbSliders,
'sb-spectrum': moduleSbSpectrum,
'hs-spectrum': moduleHsSpectrum,
wheel: moduleWheel, // eslint-disable-line
},
});
function onInputClick() {
self.open();
}
function onInputFocus(e) {
e.preventDefault();
}
function onTargetClick() {
self.open();
}
function onHtmlClick(e) {
if (self.destroyed || !self.params) return;
if (self.params.openIn === 'page') return;
const $clickTargetEl = $(e.target);
if (!self.opened || self.closing) return;
if ($clickTargetEl.closest('[class*="backdrop"]').length) return;
if ($clickTargetEl.closest('.color-picker-popup, .color-picker-popover').length) return;
if ($inputEl && $inputEl.length > 0) {
if (
$clickTargetEl[0] !== $inputEl[0] &&
$clickTargetEl.closest('.sheet-modal').length === 0
) {
self.close();
}
} else if ($(e.target).closest('.sheet-modal').length === 0) {
self.close();
}
}
// Events
extend(self, {
attachInputEvents() {
self.$inputEl.on('click', onInputClick);
if (self.params.inputReadOnly) {
self.$inputEl.on('focus mousedown', onInputFocus);
if (self.$inputEl[0]) {
self.$inputEl[0].f7ValidateReadonly = true;
}
}
},
detachInputEvents() {
self.$inputEl.off('click', onInputClick);
if (self.params.inputReadOnly) {
self.$inputEl.off('focus mousedown', onInputFocus);
if (self.$inputEl[0]) {
delete self.$inputEl[0].f7ValidateReadonly;
}
}
},
attachTargetEvents() {
self.$targetEl.on('click', onTargetClick);
},
detachTargetEvents() {
self.$targetEl.off('click', onTargetClick);
},
attachHtmlEvents() {
app.on('click', onHtmlClick);
},
detachHtmlEvents() {
app.off('click', onHtmlClick);
},
});
self.init();
return self;
}
get view() {
const { $inputEl, $targetEl, app, params } = this;
let view;
if (params.view) {
view = params.view;
} else {
if ($inputEl) {
view = $inputEl.parents('.view').length && $inputEl.parents('.view')[0].f7View;
}
if (!view && $targetEl) {
view = $targetEl.parents('.view').length && $targetEl.parents('.view')[0].f7View;
}
}
if (!view) view = app.views.main;
return view;
}
attachEvents() {
const self = this;
self.centerModules = self.centerModules.bind(self);
if (self.params.centerModules) {
self.app.on('resize', self.centerModules);
}
}
detachEvents() {
const self = this;
if (self.params.centerModules) {
self.app.off('resize', self.centerModules);
}
}
centerModules() {
const self = this;
if (!self.opened || !self.$el || self.inline) return;
const $pageContentEl = self.$el.find('.page-content');
if (!$pageContentEl.length) return;
const { scrollHeight, offsetHeight } = $pageContentEl[0];
if (scrollHeight <= offsetHeight) {
$pageContentEl.addClass('justify-content-center');
} else {
$pageContentEl.removeClass('justify-content-center');
}
}
initInput() {
const self = this;
if (!self.$inputEl) return;
if (self.params.inputReadOnly) self.$inputEl.prop('readOnly', true);
}
getModalType() {
const self = this;
const { app, modal, params } = self;
const { openIn, openInPhone } = params;
const device = getDevice();
if (modal && modal.type) return modal.type;
if (openIn !== 'auto') return openIn;
if (self.inline) return null;
if (device.ios) {
return device.ipad ? 'popover' : openInPhone;
}
if (app.width >= 768 || (device.desktop && app.theme === 'aurora')) {
return 'popover';
}
return openInPhone;
}
formatValue() {
const self = this;
const { value } = self;
if (self.params.formatValue) {
return self.params.formatValue.call(self, value);
}
return value.hex;
}
// eslint-disable-next-line
normalizeHsValues(arr) {
return [
Math.floor(arr[0] * 10) / 10,
Math.floor(arr[1] * 1000) / 1000,
Math.floor(arr[2] * 1000) / 1000,
];
}
setValue(value = {}, updateModules = true) {
const self = this;
if (typeof value === 'undefined') return;
let { hex, rgb, hsl, hsb, alpha = 1, hue, rgba, hsla } = self.value || {};
const needChangeEvent = self.value || (!self.value && !self.params.value);
let valueChanged;
Object.keys(value).forEach((k) => {
if (!self.value || typeof self.value[k] === 'undefined') {
valueChanged = true;
return;
}
const v = value[k];
if (Array.isArray(v)) {
v.forEach((subV, subIndex) => {
if (subV !== self.value[k][subIndex]) {
valueChanged = true;
}
});
} else if (v !== self.value[k]) {
valueChanged = true;
}
});
if (!valueChanged) return;
if (value.rgb || value.rgba) {
const [r, g, b, a = alpha] = value.rgb || value.rgba;
rgb = [r, g, b];
hex = colorRgbToHex(...rgb);
hsl = colorRgbToHsl(...rgb);
hsb = colorHslToHsb(...hsl);
hsl = self.normalizeHsValues(hsl);
hsb = self.normalizeHsValues(hsb);
hue = hsb[0];
alpha = a;
rgba = [rgb[0], rgb[1], rgb[2], a];
hsla = [hsl[0], hsl[1], hsl[2], a];
}
if (value.hsl || value.hsla) {
const [h, s, l, a = alpha] = value.hsl || value.hsla;
hsl = [h, s, l];
rgb = colorHslToRgb(...hsl);
hex = colorRgbToHex(...rgb);
hsb = colorHslToHsb(...hsl);
hsl = self.normalizeHsValues(hsl);
hsb = self.normalizeHsValues(hsb);
hue = hsb[0];
alpha = a;
rgba = [rgb[0], rgb[1], rgb[2], a];
hsla = [hsl[0], hsl[1], hsl[2], a];
}
if (value.hsb) {
const [h, s, b, a = alpha] = value.hsb;
hsb = [h, s, b];
hsl = colorHsbToHsl(...hsb);
rgb = colorHslToRgb(...hsl);
hex = colorRgbToHex(...rgb);
hsl = self.normalizeHsValues(hsl);
hsb = self.normalizeHsValues(hsb);
hue = hsb[0];
alpha = a;
rgba = [rgb[0], rgb[1], rgb[2], a];
hsla = [hsl[0], hsl[1], hsl[2], a];
}
if (value.hex) {
rgb = colorHexToRgb(value.hex);
hex = colorRgbToHex(...rgb);
hsl = colorRgbToHsl(...rgb);
hsb = colorHslToHsb(...hsl);
hsl = self.normalizeHsValues(hsl);
hsb = self.normalizeHsValues(hsb);
hue = hsb[0];
rgba = [rgb[0], rgb[1], rgb[2], alpha];
hsla = [hsl[0], hsl[1], hsl[2], alpha];
}
if (typeof value.alpha !== 'undefined') {
alpha = value.alpha;
if (typeof rgb !== 'undefined') {
rgba = [rgb[0], rgb[1], rgb[2], alpha];
}
if (typeof hsl !== 'undefined') {
hsla = [hsl[0], hsl[1], hsl[2], alpha];
}
}
if (typeof value.hue !== 'undefined') {
const [h, s, l] = hsl; // eslint-disable-line
hsl = [value.hue, s, l];
hsb = colorHslToHsb(...hsl);
rgb = colorHslToRgb(...hsl);
hex = colorRgbToHex(...rgb);
hsl = self.normalizeHsValues(hsl);
hsb = self.normalizeHsValues(hsb);
hue = hsb[0];
rgba = [rgb[0], rgb[1], rgb[2], alpha];
hsla = [hsl[0], hsl[1], hsl[2], alpha];
}
self.value = {
hex,
alpha,
hue,
rgb,
hsl,
hsb,
rgba,
hsla,
};
if (!self.initialValue) self.initialValue = extend({}, self.value);
self.updateValue(needChangeEvent);
if (self.opened && updateModules) {
self.updateModules();
}
}
getValue() {
const self = this;
return self.value;
}
updateValue(fireEvents = true) {
const self = this;
const { $inputEl, value, $targetEl } = self;
if ($targetEl && self.params.targetElSetBackgroundColor) {
const { rgba } = value;
$targetEl.css('background-color', `rgba(${rgba.join(', ')})`);
}
if (fireEvents) {
self.emit('local::change colorPickerChange', self, value);
}
if ($inputEl && $inputEl.length) {
const inputValue = self.formatValue(value);
if ($inputEl && $inputEl.length) {
$inputEl.val(inputValue);
if (fireEvents) {
$inputEl.trigger('change');
}
}
}
}
updateModules() {
const self = this;
const { modules } = self;
self.params.modules.forEach((m) => {
if (typeof m === 'string' && modules[m] && modules[m].update) {
modules[m].update(self);
} else if (m && m.update) {
m.update(self);
}
});
}
update() {
const self = this;
self.updateModules();
}
renderPicker() {
const self = this;
const { params, modules } = self;
let html = '';
params.modules.forEach((m) => {
if (typeof m === 'string' && modules[m] && modules[m].render) {
html += modules[m].render(self);
} else if (m && m.render) {
html += m.render(self);
}
});
return html;
}
renderNavbar() {
const self = this;
if (self.params.renderNavbar) {
return self.params.renderNavbar.call(self, self);
}
const { openIn, navbarTitleText, navbarBackLinkText, navbarCloseText } = self.params;
return (
<div class="navbar">
<div class="navbar-bg"></div>
<div class="navbar-inner sliding">
{openIn === 'page' && (
<div class="left">
<a class="link back">
<i class="icon icon-back"></i>
<span class="if-not-md">{navbarBackLinkText}</span>
</a>
</div>
)}
<div class="title">{navbarTitleText}</div>
{openIn !== 'page' && (
<div class="right">
<a class="link popup-close" data-popup=".color-picker-popup">
{navbarCloseText}
</a>
</div>
)}
</div>
</div>
);
}
renderToolbar() {
const self = this;
if (self.params.renderToolbar) {
return self.params.renderToolbar.call(self, self);
}
return (
<div class="toolbar toolbar-top no-shadow">
<div class="toolbar-inner">
<div class="left"></div>
<div class="right">
<a
class="link sheet-close popover-close"
data-sheet=".color-picker-sheet-modal"
data-popover=".color-picker-popover"
>
{self.params.toolbarCloseText}
</a>
</div>
</div>
</div>
);
}
renderInline() {
const self = this;
const { cssClass, groupedModules } = self.params;
return (
<div
class={`color-picker color-picker-inline ${
groupedModules ? 'color-picker-grouped-modules' : ''
} ${cssClass || ''}`}
>
{self.renderPicker()}
</div>
);
}
renderSheet() {
const self = this;
const { cssClass, toolbarSheet, groupedModules } = self.params;
return (
<div
class={`sheet-modal color-picker color-picker-sheet-modal ${
groupedModules ? 'color-picker-grouped-modules' : ''
} ${cssClass || ''}`}
>
{toolbarSheet && self.renderToolbar()}
<div class="sheet-modal-inner">
<div class="page-content">{self.renderPicker()}</div>
</div>
</div>
);
}
renderPopover() {
const self = this;
const { cssClass, toolbarPopover, groupedModules } = self.params;
return (
<div class={`popover color-picker-popover ${cssClass || ''}`}>
<div class="popover-inner">
<div class={`color-picker ${groupedModules ? 'color-picker-grouped-modules' : ''}`}>
{toolbarPopover && self.renderToolbar()}
<div class="page-content">{self.renderPicker()}</div>
</div>
</div>
</div>
);
}
renderPopup() {
const self = this;
const { cssClass, navbarPopup, groupedModules } = self.params;
return (
<div class={`popup color-picker-popup ${cssClass || ''}`}>
<div class="page">
{navbarPopup && self.renderNavbar()}
<div class={`color-picker ${groupedModules ? 'color-picker-grouped-modules' : ''}`}>
<div class="page-content">{self.renderPicker()}</div>
</div>
</div>
</div>
);
}
renderPage() {
const self = this;
const { cssClass, groupedModules } = self.params;
return (
<div class={`page color-picker-page ${cssClass || ''}`} data-name="color-picker-page">
{self.renderNavbar()}
<div class={`color-picker ${groupedModules ? 'color-picker-grouped-modules' : ''}`}>
<div class="page-content">{self.renderPicker()}</div>
</div>
</div>
);
}
// eslint-disable-next-line
render() {
const self = this;
const { params } = self;
if (params.render) return params.render.call(self);
if (self.inline) return self.renderInline();
if (params.openIn === 'page') {
return self.renderPage();
}
const modalType = self.getModalType();
if (modalType === 'popover') return self.renderPopover();
if (modalType === 'sheet') return self.renderSheet();
if (modalType === 'popup') return self.renderPopup();
}
onOpen() {
const self = this;
const { initialized, $el, app, $inputEl, inline, value, params, modules } = self;
self.closing = false;
self.opened = true;
self.opening = true;
// Init main events
self.attachEvents();
params.modules.forEach((m) => {
if (typeof m === 'string' && modules[m] && modules[m].init) {
modules[m].init(self);
} else if (m && m.init) {
m.init(self);
}
});
const updateValue = !value && params.value;
// Set value
if (!initialized) {
if (value) self.setValue(value);
else if (params.value) {
self.setValue(params.value, false);
} else if (!params.value) {
self.setValue({ hex: '#ff0000' }, false);
}
} else if (value) {
self.initialValue = extend({}, value);
self.setValue(value, false);
}
// Update input value
if (updateValue) self.updateValue();
self.updateModules();
// Center modules
if (params.centerModules) {
self.centerModules();
}
// Extra focus
if (!inline && $inputEl && $inputEl.length && app.theme === 'md') {
$inputEl.trigger('focus');
}
self.initialized = true;
// Trigger events
if ($el) {
$el.trigger('colorpicker:open');
}
if ($inputEl) {
$inputEl.trigger('colorpicker:open');
}
self.emit('local::open colorPickerOpen', self);
}
onOpened() {
const self = this;
self.opening = false;
if (self.$el) {
self.$el.trigger('colorpicker:opened');
}
if (self.$inputEl) {
self.$inputEl.trigger('colorpicker:opened');
}
self.emit('local::opened colorPickerOpened', self);
}
onClose() {
const self = this;
const { app, params, modules } = self;
self.opening = false;
self.closing = true;
// Detach events
self.detachEvents();
if (self.$inputEl) {
if (app.theme === 'md') {
self.$inputEl.trigger('blur');
} else {
const validate = self.$inputEl.attr('validate');
const required = self.$inputEl.attr('required');
if (validate && required) {
app.input.validate(self.$inputEl);
}
}
}
params.modules.forEach((m) => {
if (typeof m === 'string' && modules[m] && modules[m].destroy) {
modules[m].destroy(self);
} else if (m && m.destroy) {
m.destroy(self);
}
});
if (self.$el) {
self.$el.trigger('colorpicker:close');
}
if (self.$inputEl) {
self.$inputEl.trigger('colorpicker:close');
}
self.emit('local::close colorPickerClose', self);
}
onClosed() {
const self = this;
self.opened = false;
self.closing = false;
if (!self.inline) {
nextTick(() => {
if (self.modal && self.modal.el && self.modal.destroy) {
if (!self.params.routableModals) {
self.modal.destroy();
}
}
delete self.modal;
});
}
if (self.$el) {
self.$el.trigger('colorpicker:closed');
}
if (self.$inputEl) {
self.$inputEl.trigger('colorpicker:closed');
}
self.emit('local::closed colorPickerClosed', self);
}
open() {
const self = this;
const { app, opened, inline, $inputEl, $targetEl, params } = self;
if (opened) return;
if (inline) {
self.$el = $(self.render());
self.$el[0].f7ColorPicker = self;
self.$containerEl.append(self.$el);
self.onOpen();
self.onOpened();
return;
}
const colorPickerContent = self.render();
if (params.openIn === 'page') {
self.view.router.navigate({
url: self.url,
route: {
content: colorPickerContent,
path: self.url,
on: {
pageBeforeIn(e, page) {
self.$el = page.$el.find('.color-picker');
self.$el[0].f7ColorPicker = self;
self.onOpen();
},
pageAfterIn() {
self.onOpened();
},
pageBeforeOut() {
self.onClose();
},
pageAfterOut() {
self.onClosed();
if (self.$el && self.$el[0]) {
self.$el[0].f7ColorPicker = null;
delete self.$el[0].f7ColorPicker;
}
},
},
},
});
} else {
const modalType = self.getModalType();
let backdrop = params.backdrop;
if (backdrop === null || typeof backdrop === 'undefined') {
if (modalType === 'popover' && app.params.popover.backdrop !== false) backdrop = true;
if (modalType === 'popup') backdrop = true;
}
const modalParams = {
targetEl: $targetEl || $inputEl,
scrollToEl: params.scrollToInput ? $targetEl || $inputEl : undefined,
content: colorPickerContent,
backdrop,
closeByBackdropClick: params.closeByBackdropClick,
on: {
open() {
const modal = this;
self.modal = modal;
self.$el =
modalType === 'popover' || modalType === 'popup'
? modal.$el.find('.color-picker')
: modal.$el;
self.$el[0].f7ColorPicker = self;
self.onOpen();
},
opened() {
self.onOpened();
},
close() {
self.onClose();
},
closed() {
self.onClosed();
if (self.$el && self.$el[0]) {
self.$el[0].f7ColorPicker = null;
delete self.$el[0].f7ColorPicker;
}
},
},
};
if (modalType === 'popup') {
modalParams.push = params.popupPush;
modalParams.swipeToClose = params.popupSwipeToClose;
}
if (modalType === 'sheet') {
modalParams.push = params.sheetPush;
modalParams.swipeToClose = params.sheetSwipeToClose;
}
if (params.routableModals && self.view) {
self.view.router.navigate({
url: self.url,
route: {
path: self.url,
[modalType]: modalParams,
},
});
} else {
self.modal = app[modalType].create(modalParams);
self.modal.open();
}
}
}
close() {
const self = this;
const { opened, inline } = self;
if (!opened) return;
if (inline) {
self.onClose();
self.onClosed();
return;
}
if ((self.params.routableModals && self.view) || self.params.openIn === 'page') {
self.view.router.back();
} else {
self.modal.close();
}
}
init() {
const self = this;
self.initInput();
if (self.inline) {
self.open();
self.emit('local::init colorPickerInit', self);
return;
}
if (!self.initialized && self.params.value) {
self.setValue(self.params.value);
}
// Attach input Events
if (self.$inputEl) {
self.attachInputEvents();
}
if (self.$targetEl) {
self.attachTargetEvents();
}
if (self.params.closeByOutsideClick) {
self.attachHtmlEvents();
}
self.emit('local::init colorPickerInit', self);
}
destroy() {
const self = this;
if (self.destroyed) return;
const { $el } = self;
self.emit('local::beforeDestroy colorPickerBeforeDestroy', self);
if ($el) $el.trigger('colorpicker:beforedestroy');
self.close();
// Detach Events
self.detachEvents();
if (self.$inputEl) {
self.detachInputEvents();
}
if (self.$targetEl) {
self.detachTargetEvents();
}
if (self.params.closeByOutsideClick) {
self.detachHtmlEvents();
}
if ($el && $el.length) delete self.$el[0].f7ColorPicker;
deleteProps(self);
self.destroyed = true;
}
}
export default ColorPicker;
| framework7io/Framework7 | src/core/components/color-picker/color-picker-class.js | JavaScript | mit | 23,717 |
/* *
*
* (c) 2010-2019 Torstein Honsi
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
/* globals Image, window */
/**
* Reference to the global SVGElement class as a workaround for a name conflict
* in the Highcharts namespace.
*
* @global
* @typedef {global.SVGElement} GlobalSVGElement
*
* @see https://developer.mozilla.org/en-US/docs/Web/API/SVGElement
*/
// glob is a temporary fix to allow our es-modules to work.
var glob = ( // @todo UMD variable named `window`, and glob named `win`
typeof win !== 'undefined' ?
win :
typeof window !== 'undefined' ?
window :
{}), doc = glob.document, SVG_NS = 'http://www.w3.org/2000/svg', userAgent = (glob.navigator && glob.navigator.userAgent) || '', svg = (doc &&
doc.createElementNS &&
!!doc.createElementNS(SVG_NS, 'svg').createSVGRect), isMS = /(edge|msie|trident)/i.test(userAgent) && !glob.opera, isFirefox = userAgent.indexOf('Firefox') !== -1, isChrome = userAgent.indexOf('Chrome') !== -1, hasBidiBug = (isFirefox &&
parseInt(userAgent.split('Firefox/')[1], 10) < 4 // issue #38
);
var H = {
product: 'Highcharts',
version: '8.0.0',
deg2rad: Math.PI * 2 / 360,
doc: doc,
hasBidiBug: hasBidiBug,
hasTouch: !!glob.TouchEvent,
isMS: isMS,
isWebKit: userAgent.indexOf('AppleWebKit') !== -1,
isFirefox: isFirefox,
isChrome: isChrome,
isSafari: !isChrome && userAgent.indexOf('Safari') !== -1,
isTouchDevice: /(Mobile|Android|Windows Phone)/.test(userAgent),
SVG_NS: SVG_NS,
chartCount: 0,
seriesTypes: {},
symbolSizes: {},
svg: svg,
win: glob,
marginNames: ['plotTop', 'marginRight', 'marginBottom', 'plotLeft'],
noop: function () { },
/**
* An array containing the current chart objects in the page. A chart's
* position in the array is preserved throughout the page's lifetime. When
* a chart is destroyed, the array item becomes `undefined`.
*
* @name Highcharts.charts
* @type {Array<Highcharts.Chart|undefined>}
*/
charts: [],
/**
* A hook for defining additional date format specifiers. New
* specifiers are defined as key-value pairs by using the
* specifier as key, and a function which takes the timestamp as
* value. This function returns the formatted portion of the
* date.
*
* @sample highcharts/global/dateformats/
* Adding support for week number
*
* @name Highcharts.dateFormats
* @type {Highcharts.Dictionary<Highcharts.TimeFormatCallbackFunction>}
*/
dateFormats: {}
};
export default H;
| cdnjs/cdnjs | ajax/libs/highcharts/8.0.0/es-modules/parts/Globals.js | JavaScript | mit | 2,700 |
/*!-----------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Version: 0.5.3(793ede49d53dba79d39e52205f16321278f5183c)
* Released under the MIT license
* https://github.com/Microsoft/vscode/blob/master/LICENSE.txt
*-----------------------------------------------------------*/
define("vs/base/common/worker/simpleWorker.nls.zh-cn", {
"vs/base/common/errors": [
"{0}。错误代码: {1}",
"权限被拒绝 (HTTP {0})",
"权限被拒绝",
"{0} (HTTP {1}: {2})",
"{0} (HTTP {1})",
"未知连接错误 ({0})",
"出现未知连接错误。您的 Internet 连接已断开,或者您连接的服务器已脱机。",
"{0}: {1}",
"出现未知错误。有关详细信息,请参阅日志。",
"发生了系统错误({0})",
"出现未知错误。有关详细信息,请参阅日志。",
"{0} 个(共 {1} 个错误)",
"出现未知错误。有关详细信息,请参阅日志。",
"未实施",
"非法参数: {0}",
"非法参数",
"非法状态: {0}",
"非法状态",
"无法加载需要的文件。您的 Internet 连接已断开,或者您连接的服务器已脱机。请刷新浏览器并重试。",
"未能加载所需文件。请重启应用程序重试。详细信息: {0}",
],
"vs/base/common/keyCodes": [
"Windows",
"控件",
"Shift",
"Alt",
"命令",
"Windows",
"Ctrl",
"Shift",
"Alt",
"命令",
"Windows",
],
"vs/base/common/severity": [
"错误",
"警告",
"信息",
]
}); | smurfpandey/mysqlweb | static/js/vs/base/common/worker/simpleWorker.nls.zh-cn.js | JavaScript | mit | 1,521 |
/**
* Spacelet Manager, 2013 Spaceify Inc.
* SpaceletManager is a class for managing Spacelets and their processes. It launches spacelet processes, manages their quotas and access rights and terminates them when needed.
*
* @class SpaceletManager
*/
var fs = require("fs");
var fibrous = require("fibrous");
var Config = require("./config")();
var Utility = require("./utility");
var Language = require("./language");
var Application = require("./application");
var Database = require("./database");
var DockerContainer = require("./dockercontainer");
function SpaceletManager()
{
var self = this;
var applications = Object();
var ordinal = 0;
var database = new Database();
var isStarting = false;
var delayedStart = [];
self.start = function(unique_name, callback)
{
var application = null;
if(isStarting) // Start one application at a time - retain call order
delayedStart.push({"unique_name": unique_name, "callback": callback});
else
{
isStarting = true;
try {
var build_application = self.find(applications, "unique_name", unique_name); // Application by this unique name alredy build?
// SHARE SPACELET OR START A NEW
//if(!build_application || (build_application && !build_application.isShared())) // 'No' OR 'yes and is not shared' -> add the build application to the applications
// {
// application = self.build.sync(unique_name);
// add(application);
// }
//else if(build_application && build_application.isShared()) // 'Yes and is shared' -> use the existing application
// application = build_application;
// SPACELETS ARE NOW SHARED BY DEFAULT - CREATE IF SPACELET DOESN'T EXIST
if(!build_application)
{
application = self.build.sync(unique_name);
add(application);
}
else
application = build_application;
// START APPLICATION
run.sync(application);
if(!application.isInitialized())
throw Utility.error(Language.E_SPACELET_FAILED_INIT_ITSELF.p("SpaceletManager::start()"));
callback(null, application);
}
catch(err)
{
callback(Utility.error(err), null);
}
isStarting = false;
if(delayedStart.length != 0) // Start next application?
{
var sp = delayedStart.splice(0, 1);
self.start(sp[0].unique_name, sp[0].callback);
}
}
}
self.build = fibrous( function(unique_name)
{
var application = null;
var _applications = null;
try {
database.open(Config.SPACEIFY_DATABASE_FILE);
if(unique_name) // Build one application
_applications = [database.sync.getApplication(unique_name)];
else // Build all applications
_applications = database.sync.getApplication([Config.SPACELET], true);
for(var i=0; i<_applications.length; i++)
{
if((manifest = Utility.sync.loadManifest(Config.SPACELETS_PATH + _applications[i].unique_directory + Config.VOLUME_DIRECTORY + Config.APPLICATION_DIRECTORY + Config.MANIFEST, true)) == null)
throw Utility.error(Language.E_FAILED_TO_READ_SPACELET_MANIFEST.p("SpaceletManager::build()"));
application = self.find("unique_name", manifest.unique_name); // Don't create/add existing application
if(application) continue;
application = new Application.obj(manifest);
application.setDockerImageId(_applications[i].docker_image_id);
add(application);
}
}
catch(err)
{
throw Utility.error(err);
}
finally
{
database.close();
}
return application;
} );
var run = fibrous( function(application)
{
// Start the application in a Docker container
try {
if(application.isRunning()) // Return ports if already running ([] = not running and has no ports)
return application.getServices();
var volumes = {};
volumes[Config.VOLUME_PATH] = {};
volumes[Config.API_PATH] = {};
var binds = [Config.SPACELETS_PATH + application.getUniqueDirectory() + Config.VOLUME_DIRECTORY + ":" + Config.VOLUME_PATH + ":rw",
Config.SPACEIFY_CODE_PATH + ":" + Config.API_PATH + ":r"];
var dockerContainer = new DockerContainer();
application.setDockerContainer(dockerContainer);
dockerContainer.sync.startContainer(application.getProvidesServicesCount(), application.getDockerImageId(), volumes, binds);
application.makeServices(dockerContainer.getPublicPorts(), dockerContainer.getIpAddress());
dockerContainer.sync.runApplication(application);
application.setRunning(true);
return application.getServices();
}
catch(err)
{
throw Utility.error(Language.E_SPACELET_FAILED_RUN.p("SpaceletManager::run()"), err);
}
});
self.stop = fibrous( function(application)
{
if(typeof application == "string")
application = self.find("unique_name", application);
if((dockerContainer = application.getDockerContainer()) != null)
dockerContainer.sync.stopContainer(application);
application.setRunning(false);
});
var add = function(application)
{
application.setOrdinal(++ordinal);
applications[ordinal] = application;
}
self.remove = function(application)
{
if(typeof application == "string")
application = self.find("unique_name", application);
for(i in applications)
{
if(application.getOrdinal() == applications[i].getOrdinal())
{
self.sync.stop(applications[i]);
delete applications[i];
break;
}
}
}
self.removeAll = fibrous( function()
{
for(i in applications)
self.sync.stop(applications[i]);
});
self.isRunning = function(unique_name)
{
var application = self.find("unique_name", unique_name);
return (application ? application.isRunning() : false);
}
self.find = function(_param, _find)
{ // Find based on _param and _find object
return Application.inst.find(applications, _param, _find);
}
self.initialized = function(application, success)
{
application.setInitialized(success);
if((dc = application.getDockerContainer()) != null)
dc.sendClientReadyToStdIn();
}
}
module.exports = SpaceletManager;
| citsym/PointerTest | spaceifyapplication/api/spaceletmanager.js | JavaScript | mit | 5,915 |
import React, { Component } from 'react';
import {DataTable} from 'datatables.net-responsive-bs';
const settingsMock = {
header: 'Test Header'
};
describe('DataTables component', () => {
class mock extends Component {}
var comp = new mock(settingsMock);
it('Should have props', () => {
expect(comp.props.header).toEqual('Test Header');
});
});
| NuCivic/react-dash | tests/datatable_spec.js | JavaScript | mit | 373 |
var util = require('util');
var async = require('async');
var path = require('path');
var Router = require('../utils/router.js');
var sandboxHelper = require('../utils/sandbox.js');
// Private fields
var modules, library, self, private = {}, shared = {};
private.loaded = false
// Constructor
function Server(cb, scope) {
library = scope;
self = this;
self.__private = private;
private.attachApi();
setImmediate(cb, null, self);
}
// Private methods
private.attachApi = function() {
var router = new Router();
router.use(function (req, res, next) {
if (modules) return next();
res.status(500).send({success: false, error: "Blockchain is loading"});
});
router.get('/', function (req, res) {
if (private.loaded) {
res.render('wallet.html', {layout: false});
} else {
res.render('index.html');
}
});
router.get('/dapps/:id', function (req, res) {
res.render('dapps/' + req.params.id + '/index.html');
});
router.use(function (req, res, next) {
if (req.url.indexOf('/api/') == -1 && req.url.indexOf('/peer/') == -1) {
return res.redirect('/');
}
next();
// res.status(500).send({ success: false, error: 'api not found' });
});
library.network.app.use('/', router);
}
// Public methods
Server.prototype.sandboxApi = function (call, args, cb) {
sandboxHelper.callMethod(shared, call, args, cb);
}
// Events
Server.prototype.onBind = function (scope) {
modules = scope;
}
Server.prototype.onBlockchainReady = function () {
private.loaded = true;
}
Server.prototype.cleanup = function (cb) {
private.loaded = false;
cb();
}
// Shared
// Export
module.exports = Server;
| anshuman-singh-93/agrichain | src/core/server.js | JavaScript | mit | 1,677 |
(function(global) {
// simplified version of Object.assign for es3
function assign() {
var result = {};
for (var i = 0, len = arguments.length; i < len; i++) {
var arg = arguments[i];
for (var prop in arg) {
result[prop] = arg[prop];
}
}
return result;
}
var sjsPaths = {};
if (typeof systemJsPaths !== "undefined") {
sjsPaths = systemJsPaths;
}
System.config({
transpiler: 'plugin-babel',
defaultExtension: 'js',
paths: assign({
// paths serve as alias
"npm:": "https://unpkg.com/",
}, sjsPaths),
map: assign(
{
// css plugin
'css': 'npm:systemjs-plugin-css/css.js',
// babel transpiler
'plugin-babel': 'npm:systemjs-plugin-babel@0.0.25/plugin-babel.js',
'systemjs-babel-build': 'npm:systemjs-plugin-babel@0.0.25/systemjs-babel-browser.js',
// react
react: 'npm:react@16.12.0',
'react-dom': 'npm:react-dom@16.12.0',
'react-dom-factories': 'npm:react-dom-factories',
redux: 'npm:redux@3.6.0',
'react-redux': 'npm:react-redux@5.0.6',
'prop-types': 'npm:prop-types',
lodash: 'npm:lodash@4.17.15',
app: 'app'
},
systemJsMap
), // systemJsMap comes from index.html
packages: {
react: {
main: './umd/react.production.min.js'
},
'react-dom': {
main: './umd/react-dom.production.min.js'
},
'prop-types': {
main: './prop-types.min.js',
defaultExtension: 'js'
},
redux: {
main: './dist/redux.min.js',
defaultExtension: 'js'
},
'react-redux': {
main: './dist/react-redux.min.js',
defaultExtension: 'js'
},
app: {
defaultExtension: 'jsx'
},
'ag-charts-react': {
main: './main.js',
defaultExtension: 'js'
}
},
meta: {
'*.jsx': {
babelOptions: {
react: true
}
},
'*.css': { loader: 'css' }
}
});
})(this);
| ceolter/angular-grid | grid-packages/ag-grid-docs/documentation/static/example-runner/charts-react-boilerplate/systemjs.config.js | JavaScript | mit | 2,518 |
module.exports={title:'Discover',slug:'discover',svg:'<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>Discover icon</title><path d="M12 0A12 12 0 1 0 12 24A12 12 0 1 0 12 0Z"/></svg>',get path(){return this.svg.match(/<path\s+d="([^"]*)/)[1];},source:'https://www.discovernetwork.com/en-us/business-resources/free-signage-logos',hex:'FF6000'}; | cdnjs/cdnjs | ajax/libs/simple-icons/1.13.0/discover.js | JavaScript | mit | 373 |
import Coordinator from '../models/coordinator';
export default {
name: "setup coordinator",
initialize: function() {
let app = arguments[1] || arguments[0];
app.register("drag:coordinator",Coordinator);
app.inject("component","coordinator","drag:coordinator");
}
};
| drourke/ember-drag-drop | app/initializers/coordinator-setup.js | JavaScript | mit | 287 |
import { EventEmitter, Input, Output, Component, ViewContainerRef, ContentChildren, ElementRef, NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { TooltipModule } from 'primeng/tooltip';
import { PrimeTemplate, SharedModule } from 'primeng/api';
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
let idx = 0;
let TabViewNav = class TabViewNav {
constructor() {
this.orientation = 'top';
this.onTabClick = new EventEmitter();
this.onTabCloseClick = new EventEmitter();
}
getDefaultHeaderClass(tab) {
let styleClass = 'ui-state-default ui-corner-' + this.orientation;
if (tab.headerStyleClass) {
styleClass = styleClass + " " + tab.headerStyleClass;
}
return styleClass;
}
clickTab(event, tab) {
this.onTabClick.emit({
originalEvent: event,
tab: tab
});
}
clickClose(event, tab) {
this.onTabCloseClick.emit({
originalEvent: event,
tab: tab
});
}
};
__decorate([
Input()
], TabViewNav.prototype, "tabs", void 0);
__decorate([
Input()
], TabViewNav.prototype, "orientation", void 0);
__decorate([
Output()
], TabViewNav.prototype, "onTabClick", void 0);
__decorate([
Output()
], TabViewNav.prototype, "onTabCloseClick", void 0);
TabViewNav = __decorate([
Component({
selector: '[p-tabViewNav]',
host: {
'[class.ui-tabview-nav]': 'true',
'[class.ui-helper-reset]': 'true',
'[class.ui-helper-clearfix]': 'true',
'[class.ui-widget-header]': 'true',
'[class.ui-corner-all]': 'true'
},
template: `
<ng-template ngFor let-tab [ngForOf]="tabs">
<li [class]="getDefaultHeaderClass(tab)" [ngStyle]="tab.headerStyle" role="presentation"
[ngClass]="{'ui-tabview-selected ui-state-active': tab.selected, 'ui-state-disabled': tab.disabled}"
(click)="clickTab($event,tab)" *ngIf="!tab.closed" tabindex="0" (keydown.enter)="clickTab($event,tab)">
<a [attr.id]="tab.id + '-label'" role="tab" [attr.aria-selected]="tab.selected" [attr.aria-controls]="tab.id" [pTooltip]="tab.tooltip" [tooltipPosition]="tab.tooltipPosition"
[attr.aria-selected]="tab.selected" [positionStyle]="tab.tooltipPositionStyle" [tooltipStyleClass]="tab.tooltipStyleClass">
<ng-container *ngIf="!tab.headerTemplate" >
<span class="ui-tabview-left-icon" [ngClass]="tab.leftIcon" *ngIf="tab.leftIcon"></span>
<span class="ui-tabview-title">{{tab.header}}</span>
<span class="ui-tabview-right-icon" [ngClass]="tab.rightIcon" *ngIf="tab.rightIcon"></span>
</ng-container>
<ng-container *ngIf="tab.headerTemplate">
<ng-container *ngTemplateOutlet="tab.headerTemplate"></ng-container>
</ng-container>
</a>
<span *ngIf="tab.closable" class="ui-tabview-close pi pi-times" (click)="clickClose($event,tab)"></span>
</li>
</ng-template>
`
})
], TabViewNav);
let TabPanel = class TabPanel {
constructor(viewContainer) {
this.viewContainer = viewContainer;
this.cache = true;
this.tooltipPosition = 'top';
this.tooltipPositionStyle = 'absolute';
this.id = `ui-tabpanel-${idx++}`;
}
ngAfterContentInit() {
this.templates.forEach((item) => {
switch (item.getType()) {
case 'header':
this.headerTemplate = item.template;
break;
case 'content':
this.contentTemplate = item.template;
break;
default:
this.contentTemplate = item.template;
break;
}
});
}
get selected() {
return this._selected;
}
set selected(val) {
this._selected = val;
this.loaded = true;
}
ngOnDestroy() {
this.view = null;
}
};
TabPanel.ctorParameters = () => [
{ type: ViewContainerRef }
];
__decorate([
Input()
], TabPanel.prototype, "header", void 0);
__decorate([
Input()
], TabPanel.prototype, "disabled", void 0);
__decorate([
Input()
], TabPanel.prototype, "closable", void 0);
__decorate([
Input()
], TabPanel.prototype, "headerStyle", void 0);
__decorate([
Input()
], TabPanel.prototype, "headerStyleClass", void 0);
__decorate([
Input()
], TabPanel.prototype, "leftIcon", void 0);
__decorate([
Input()
], TabPanel.prototype, "rightIcon", void 0);
__decorate([
Input()
], TabPanel.prototype, "cache", void 0);
__decorate([
Input()
], TabPanel.prototype, "tooltip", void 0);
__decorate([
Input()
], TabPanel.prototype, "tooltipPosition", void 0);
__decorate([
Input()
], TabPanel.prototype, "tooltipPositionStyle", void 0);
__decorate([
Input()
], TabPanel.prototype, "tooltipStyleClass", void 0);
__decorate([
ContentChildren(PrimeTemplate)
], TabPanel.prototype, "templates", void 0);
__decorate([
Input()
], TabPanel.prototype, "selected", null);
TabPanel = __decorate([
Component({
selector: 'p-tabPanel',
template: `
<div [attr.id]="id" class="ui-tabview-panel ui-widget-content" [ngClass]="{'ui-helper-hidden': !selected}"
role="tabpanel" [attr.aria-hidden]="!selected" [attr.aria-labelledby]="id + '-label'" *ngIf="!closed">
<ng-content></ng-content>
<ng-container *ngIf="contentTemplate && (cache ? loaded : selected)">
<ng-container *ngTemplateOutlet="contentTemplate"></ng-container>
</ng-container>
</div>
`
})
], TabPanel);
let TabView = class TabView {
constructor(el) {
this.el = el;
this.orientation = 'top';
this.onChange = new EventEmitter();
this.onClose = new EventEmitter();
this.activeIndexChange = new EventEmitter();
}
ngAfterContentInit() {
this.initTabs();
this.tabPanels.changes.subscribe(_ => {
this.initTabs();
});
}
initTabs() {
this.tabs = this.tabPanels.toArray();
let selectedTab = this.findSelectedTab();
if (!selectedTab && this.tabs.length) {
if (this.activeIndex != null && this.tabs.length > this.activeIndex)
this.tabs[this.activeIndex].selected = true;
else
this.tabs[0].selected = true;
}
}
open(event, tab) {
if (tab.disabled) {
if (event) {
event.preventDefault();
}
return;
}
if (!tab.selected) {
let selectedTab = this.findSelectedTab();
if (selectedTab) {
selectedTab.selected = false;
}
tab.selected = true;
let selectedTabIndex = this.findTabIndex(tab);
this.preventActiveIndexPropagation = true;
this.activeIndexChange.emit(selectedTabIndex);
this.onChange.emit({ originalEvent: event, index: selectedTabIndex });
}
if (event) {
event.preventDefault();
}
}
close(event, tab) {
if (this.controlClose) {
this.onClose.emit({
originalEvent: event,
index: this.findTabIndex(tab),
close: () => {
this.closeTab(tab);
}
});
}
else {
this.closeTab(tab);
this.onClose.emit({
originalEvent: event,
index: this.findTabIndex(tab)
});
}
event.stopPropagation();
}
closeTab(tab) {
if (tab.disabled) {
return;
}
if (tab.selected) {
tab.selected = false;
for (let i = 0; i < this.tabs.length; i++) {
let tabPanel = this.tabs[i];
if (!tabPanel.closed && !tab.disabled) {
tabPanel.selected = true;
break;
}
}
}
tab.closed = true;
}
findSelectedTab() {
for (let i = 0; i < this.tabs.length; i++) {
if (this.tabs[i].selected) {
return this.tabs[i];
}
}
return null;
}
findTabIndex(tab) {
let index = -1;
for (let i = 0; i < this.tabs.length; i++) {
if (this.tabs[i] == tab) {
index = i;
break;
}
}
return index;
}
getBlockableElement() {
return this.el.nativeElement.children[0];
}
get activeIndex() {
return this._activeIndex;
}
set activeIndex(val) {
this._activeIndex = val;
if (this.preventActiveIndexPropagation) {
this.preventActiveIndexPropagation = false;
return;
}
if (this.tabs && this.tabs.length && this._activeIndex != null && this.tabs.length > this._activeIndex) {
this.findSelectedTab().selected = false;
this.tabs[this._activeIndex].selected = true;
}
}
};
TabView.ctorParameters = () => [
{ type: ElementRef }
];
__decorate([
Input()
], TabView.prototype, "orientation", void 0);
__decorate([
Input()
], TabView.prototype, "style", void 0);
__decorate([
Input()
], TabView.prototype, "styleClass", void 0);
__decorate([
Input()
], TabView.prototype, "controlClose", void 0);
__decorate([
ContentChildren(TabPanel)
], TabView.prototype, "tabPanels", void 0);
__decorate([
Output()
], TabView.prototype, "onChange", void 0);
__decorate([
Output()
], TabView.prototype, "onClose", void 0);
__decorate([
Output()
], TabView.prototype, "activeIndexChange", void 0);
__decorate([
Input()
], TabView.prototype, "activeIndex", null);
TabView = __decorate([
Component({
selector: 'p-tabView',
template: `
<div [ngClass]="'ui-tabview ui-widget ui-widget-content ui-corner-all ui-tabview-' + orientation" [ngStyle]="style" [class]="styleClass">
<ul p-tabViewNav role="tablist" *ngIf="orientation!='bottom'" [tabs]="tabs" [orientation]="orientation"
(onTabClick)="open($event.originalEvent, $event.tab)" (onTabCloseClick)="close($event.originalEvent, $event.tab)"></ul>
<div class="ui-tabview-panels">
<ng-content></ng-content>
</div>
<ul p-tabViewNav role="tablist" *ngIf="orientation=='bottom'" [tabs]="tabs" [orientation]="orientation"
(onTabClick)="open($event.originalEvent, $event.tab)" (onTabCloseClick)="close($event.originalEvent, $event.tab)"></ul>
</div>
`
})
], TabView);
let TabViewModule = class TabViewModule {
};
TabViewModule = __decorate([
NgModule({
imports: [CommonModule, SharedModule, TooltipModule],
exports: [TabView, TabPanel, TabViewNav, SharedModule],
declarations: [TabView, TabPanel, TabViewNav]
})
], TabViewModule);
/**
* Generated bundle index. Do not edit.
*/
export { TabPanel, TabView, TabViewModule, TabViewNav };
//# sourceMappingURL=primeng-tabview.js.map
| cdnjs/cdnjs | ajax/libs/primeng/9.0.0-rc.4/fesm2015/primeng-tabview.js | JavaScript | mit | 11,946 |
//>>built
define({"dgrid/extensions/nls/columnHider":{popupTriggerLabel:"Show or hide columns",popupLabel:"Vis eller skjul kolonner",_localized:{}},"widgets/AttributeTable/nls/strings":{_widgetLabel:"Attributtabel",ok:"OK",cancel:"Annuller",unsupportQueryWarning:"Laget skal underst\u00f8tte, at foresp\u00f8rgsler bliver vist i attributtabel-widget. Kontroll\u00e9r, at foresp\u00f8rgselsfunktionen er aktiveret i tjenesten.",exportMessage:"Skal dataene eksporteres til en CSV-fil?",exportFiles:"Eksport\u00e9r til CSV",
options:"Indstillinger",zoomto:"Zoom til",highlight:"Fremh\u00e6v grafik",selectAll:"Mark\u00e9r poster p\u00e5 alle sider",selectPage:"Mark\u00e9r poster p\u00e5 den aktuelle side",clearSelection:"Ryd markering",filter:"Filtr\u00e9r",setFilterTip:"Angiv filteret korrekt.",noFilterTip:"Defineres der ikke et filterudtryk, viser denne foresp\u00f8rgsel alle objekter i den angivne datakilde.",filterByExtent:"Filtr\u00e9r efter kortudstr\u00e6kning",showSelectedRecords:"Vis udvalgte poster",showRelatedRecords:"Vis relaterede poster",
noRelatedRecords:"Ingen relaterede poster",refresh:"Opdat\u00e9r",features:"objekter",selected:"valgt",transparent:"Transparent tilstand",indicate:"Valg af landeindstillinger",columns:"Vis/Skjul kolonner",selectionSymbol:"Markeringssymbol",closeMessage:"Skjul tabel [Vis den igen nedefra]",dataNotAvailable:"Dataene er ikke tilg\u00e6ngelige!\x3cbr\x3eKlik p\u00e5 knappen [Opdater] for at pr\u00f8ve igen",openTableTip:"\u00c5bn attributtabel",closeTableTip:"Skjul attributtabel",_localized:{}}}); | pjdohertygis/MapSAROnline | Web Mapping Application/widgets/AttributeTable/nls/Widget_da.js | JavaScript | cc0-1.0 | 1,556 |
//>>built
define({"widgets/Print/nls/strings":{_widgetLabel:"Print",title:"Map Title",format:"Format",layout:"Layout",settings:"Advanced",mapScaleExtent:"Map scale/extent",preserve:"Preserve",mapScale:"map scale",mapExtent:"map extent",forceScale:"Force scale",getCurrentScale:"current",mapMetadata:"Layout metadata",author:"Author",copyright:"Copyright",fullLayoutOptions:"Full layout options",scaleBarUnitsMetric:"Scale bar units metric",scaleBarUnitsNonMetric:"Scale bar units non-metric",unitsMiles:"Miles",
unitsKilometers:"Kilometers",unitsMeters:"Meters",unitsFeet:"Feet",unitsYards:"Yards",unitsNauticalMiles:"Nautical Miles",lncludeLegend:"Include legend",printQualityOptions:"Print quality",dpi:"DPI",mapOnlyOptions:"MAP_ONLY size",width:"Width (px)",height:"Height (px)",print:"Print",clearList:"Clear Prints",creatingPrint:"Creating Print",printError:"Error, try again",_localized:{ar:1,cs:1,da:1,de:1,el:1,es:1,et:1,fi:1,fr:1,he:1,it:1,ja:1,ko:1,lt:1,lv:1,nb:1,nl:1,pl:1,"pt-br":1,"pt-pt":1,ro:1,ru:1,
sv:1,th:1,tr:1,vi:1,"zh-cn":1,"zh-hk":1,"zh-tw":1}}}); | pjdohertygis/MapSAROnline | Web Mapping Application/widgets/Print/nls/Widget_ROOT.js | JavaScript | cc0-1.0 | 1,069 |
SimileAjax.History={maxHistoryLength:10,historyFile:"__history__.html",enabled:!1,_initialized:!1,_listeners:new SimileAjax.ListenerQueue,_actions:[],_baseIndex:0,_currentIndex:0,_plainDocumentTitle:document.title},SimileAjax.History.formatHistoryEntryTitle=function(i){return SimileAjax.History._plainDocumentTitle+" {"+i+"}"
},SimileAjax.History.initialize=function(){if(!SimileAjax.History._initialized){if(SimileAjax.History.enabled){var i=document.createElement("iframe");
i.id="simile-ajax-history",i.style.position="absolute",i.style.width="10px",i.style.height="10px",i.style.top="0px",i.style.left="0px",i.style.visibility="hidden",i.src=SimileAjax.History.historyFile+"?0",document.body.appendChild(i),SimileAjax.DOM.registerEvent(i,"load",SimileAjax.History._handleIFrameOnLoad),SimileAjax.History._iframe=i
}SimileAjax.History._initialized=!0}},SimileAjax.History.addListener=function(i){SimileAjax.History.initialize(),SimileAjax.History._listeners.add(i)
},SimileAjax.History.removeListener=function(i){SimileAjax.History.initialize(),SimileAjax.History._listeners.remove(i)
},SimileAjax.History.addAction=function(i){SimileAjax.History.initialize(),SimileAjax.History._listeners.fire("onBeforePerform",[i]),window.setTimeout(function(){try{if(i.perform(),SimileAjax.History._listeners.fire("onAfterPerform",[i]),SimileAjax.History.enabled){SimileAjax.History._actions=SimileAjax.History._actions.slice(0,SimileAjax.History._currentIndex-SimileAjax.History._baseIndex),SimileAjax.History._actions.push(i),SimileAjax.History._currentIndex++;
var e=SimileAjax.History._actions.length-SimileAjax.History.maxHistoryLength;e>0&&(SimileAjax.History._actions=SimileAjax.History._actions.slice(e),SimileAjax.History._baseIndex+=e);
try{SimileAjax.History._iframe.contentWindow.location.search="?"+SimileAjax.History._currentIndex
}catch(t){var r=SimileAjax.History.formatHistoryEntryTitle(i.label);document.title=r
}}}catch(t){SimileAjax.Debug.exception(t,"Error adding action {"+i.label+"} to history")
}},0)},SimileAjax.History.addLengthyAction=function(i,e,t){SimileAjax.History.addAction({perform:i,undo:e,label:t,uiLayer:SimileAjax.WindowManager.getBaseLayer(),lengthy:!0})
},SimileAjax.History._handleIFrameOnLoad=function(){try{var i=SimileAjax.History._iframe.contentWindow.location.search,e=0==i.length?0:Math.max(0,parseInt(i.substr(1))),t=function(){var i=e-SimileAjax.History._currentIndex;
SimileAjax.History._currentIndex+=i,SimileAjax.History._baseIndex+=i,SimileAjax.History._iframe.contentWindow.location.search="?"+e
};if(e<SimileAjax.History._currentIndex)SimileAjax.History._listeners.fire("onBeforeUndoSeveral",[]),window.setTimeout(function(){for(;SimileAjax.History._currentIndex>e&&SimileAjax.History._currentIndex>SimileAjax.History._baseIndex;){SimileAjax.History._currentIndex--;
var i=SimileAjax.History._actions[SimileAjax.History._currentIndex-SimileAjax.History._baseIndex];
try{i.undo()}catch(r){SimileAjax.Debug.exception(r,"History: Failed to undo action {"+i.label+"}")
}}SimileAjax.History._listeners.fire("onAfterUndoSeveral",[]),t()},0);else if(e>SimileAjax.History._currentIndex)SimileAjax.History._listeners.fire("onBeforeRedoSeveral",[]),window.setTimeout(function(){for(;SimileAjax.History._currentIndex<e&&SimileAjax.History._currentIndex-SimileAjax.History._baseIndex<SimileAjax.History._actions.length;){var i=SimileAjax.History._actions[SimileAjax.History._currentIndex-SimileAjax.History._baseIndex];
try{i.perform()}catch(r){SimileAjax.Debug.exception(r,"History: Failed to redo action {"+i.label+"}")
}SimileAjax.History._currentIndex++}SimileAjax.History._listeners.fire("onAfterRedoSeveral",[]),t()
},0);else{var r=SimileAjax.History._currentIndex-SimileAjax.History._baseIndex-1,o=r>=0&&r<SimileAjax.History._actions.length?SimileAjax.History.formatHistoryEntryTitle(SimileAjax.History._actions[r].label):SimileAjax.History._plainDocumentTitle;
SimileAjax.History._iframe.contentWindow.document.title=o,document.title=o}}catch(a){}},SimileAjax.History.getNextUndoAction=function(){try{var i=SimileAjax.History._currentIndex-SimileAjax.History._baseIndex-1;
return SimileAjax.History._actions[i]}catch(e){return null}},SimileAjax.History.getNextRedoAction=function(){try{var i=SimileAjax.History._currentIndex-SimileAjax.History._baseIndex;
return SimileAjax.History._actions[i]}catch(e){return null}}; | SteveSchafer-Innovent/innovent-pentaho-birt-plugin | js-lib/expanded/cdf/js/compressed/lib/simile/ajax/scripts/history.js | JavaScript | epl-1.0 | 4,359 |
/*-- Addition for remembering expanded state of pages --*/
function writeSessionCookie(cookieName, cookieValue) {
document.cookie = escape(cookieName) + "=" + escape(cookieValue) + ";";
}
function toggle_viewers() {
if (document.add.visibility.value == 'private') {
document.getElementById('viewers').style.display = 'block';
} else if (document.add.visibility.value == 'registered') {
document.getElementById('viewers').style.display = 'block';
} else {
document.getElementById('viewers').style.display = 'none';
}
}
function toggle_visibility(id) {
if (document.getElementById(id).style.display == "block") {
document.getElementById(id).style.display = "none";
writeSessionCookie(id, "0");//Addition for remembering expanded state of pages
} else {
document.getElementById(id).style.display = "block";
writeSessionCookie(id, "1");//Addition for remembering expanded state of pages
}
}
var plus = new Image;
plus.src = THEME_URL + "/images/expand.png";
var minus = new Image;
minus.src = THEME_URL + "/images/collapse.png";
function toggle_plus_minus(id) {
var img_src = document.images['plus_minus_' + id].src;
if (img_src == plus.src) {
document.images['plus_minus_' + id].src = minus.src;
} else {
document.images['plus_minus_' + id].src = plus.src;
}
}
if (typeof jQuery != 'undefined') {
jQuery(document).ready(function ($) {
// fix for Flat Theme
$('div.pages_list table td').css('padding-top', 0).css('padding-bottom', 0);
$('table.pages_view tbody tr td').css('line-height', '12px');
//$('table.pages_view tbody tr td.list_menu_title').css('width','300px');
//$('table.pages_view tbody tr td.list_page_id').css('width','68px');
//$('td.header_list_page_id').css('width','60px').next('td').css('width','78px');
});
} | WBCE/WebsiteBaker_CommunityEdition | wbce/admin/pages/page_index.js | JavaScript | gpl-2.0 | 1,953 |
/*
* Copyright (C) 2014 rafa
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
function fNotaRoutes() {
// Path.map("#/nota").to(function () {
// $('#indexContenidoJsp').spinner();
// control('nota').list($('#indexContenido'), param().defaultizeUrlObjectParameters({}), null);
// //notaControl.modalListEventsLoading(notaObject, notaView, $('#indexContenido'), param().defaultizeUrlObjectParameters({}), null);
// $('#indexContenidoJsp').empty();
// return false;
// });
Path.map("#/nota").to(function () {
$('#indexContenidoJsp').spinner();
oNotaControl.list($('#indexContenido'), param().defaultizeUrlObjectParameters({}), null, oNotaModel, oNotaView);
//notaControl.modalListEventsLoading(notaObject, notaView, $('#indexContenido'), param().defaultizeUrlObjectParameters({}), null);
$('#indexContenidoJsp').empty();
//$('#indexContenidoJsp').append(oNotaControl.getClassNameNota());
return false;
});
Path.map("#/nota/list/:url").to(function () {
$('#indexContenidoJsp').spinner();
var paramsObject = param().defaultizeUrlObjectParameters(param().getUrlObjectFromUrlString(this.params['url']));
oNotaControl.list($('#indexContenido'), paramsObject, null, oNotaModel, oNotaView);
$('#indexContenidoJsp').empty();
return false;
});
Path.map("#/nota/view/:id").to(function () {
$('#indexContenidoJsp').spinner();
var paramsObject = param().defaultizeUrlObjectParameters(param().getUrlObjectFromUrlString(this.params['url']));
oNotaControl.view($('#indexContenido'), paramsObject['id'], oNotaModel, oNotaView);
$('#indexContenidoJsp').empty();
return false;
});
Path.map("#/nota/edit/:id").to(function () {
$('#indexContenidoJsp').spinner();
var paramsObject = param().defaultizeUrlObjectParameters(param().getUrlObjectFromUrlString(this.params['url']));
oNotaControl.edit($('#indexContenido'), paramsObject['id'], oNotaModel, oNotaView);
$('#indexContenidoJsp').empty();
});
Path.map("#/nota/new").to(function () {
$('#indexContenidoJsp').spinner();
//var paramsObject = param().defaultizeUrlObjectParameters(param().getUrlObjectFromUrlString(this.params['url']));
oNotaControl.new($('#indexContenido'), null, oNotaModel, oNotaView);
$('#indexContenidoJsp').empty();
return false;
});
Path.map("#/nota/new/:url").to(function () {
$('#indexContenidoJsp').spinner();
var paramsObject = param().defaultizeUrlObjectParameters(param().getUrlObjectFromUrlString(this.params['url']));
oNotaControl.new($('#indexContenido'), paramsObject, oNotaModel, oNotaView);
$('#indexContenidoJsp').empty();
return false;
});
Path.map("#/nota/remove/:id").to(function () {
$('#indexContenidoJsp').spinner();
var paramsObject = param().defaultizeUrlObjectParameters(param().getUrlObjectFromUrlString(this.params['url']));
oNotaControl.remove($('#indexContenido'), paramsObject['id'], oNotaModel, oNotaView);
$('#indexContenidoJsp').empty();
return false;
});
} | jesuspablo/proyectoFinal2015 | src/main/webapp/js/specific/nota/routes.js | JavaScript | gpl-2.0 | 3,915 |
var searchData=
[
['takeaction',['takeAction',['../classBasicStar.html#aadca2b88ce5766a1a6cd95accbb72bfb',1,'BasicStar::takeAction()'],['../classMovingStar.html#a273dfe02f9eab1148da09619e34480e9',1,'MovingStar::takeAction()']]],
['touches',['touches',['../classPlayer.html#ab6c3ad981fd782f3b59fe19d66bc15d8',1,'Player']]]
];
| lollek/JumpMan | doc/html/search/functions_74.js | JavaScript | gpl-2.0 | 329 |
var ZTMenu = function(boxTimer, xOffset, yOffset, smartBoxSuffix, smartBoxClose, isub, xduration, xtransition)
{
var smartBoxes = $(document.body).getElements('[id$=' + smartBoxSuffix + ']');
var closeElem = $(document.body).getElements('.' + smartBoxClose);
var closeBoxes = function() { smartBoxes.setStyle('display', 'none'); };
closeElem.addEvent('click', function(){ closeBoxes() });
var closeBoxesTimer = 0;
var fx = Array();
var h = Array();
var w = Array();
smartBoxes.each(function(item, i)
{
var currentBox = item.getProperty('id');
currentBox = currentBox.replace('' + smartBoxSuffix + '', '');
fx[i] = new Fx.Elements(item.getChildren(), {wait: false, duration: xduration, transition: xtransition,
onComplete: function(){item.setStyle('overflow', '');}});
$(currentBox).addEvent('mouseleave', function(){
item.setStyle('overflow', 'hidden');
fx[i].start({
'0':{
'opacity': [1, 0],
'height': [h[i], 0]
}
});
closeBoxesTimer = closeBoxes.delay(boxTimer);
});
item.addEvent('mouseleave', function(){
closeBoxesTimer = closeBoxes.delay(boxTimer);
});
$(currentBox).addEvent('mouseenter', function(){
if($defined(closeBoxesTimer)) $clear(closeBoxesTimer);
});
item.addEvent('mouseenter', function(){
if($defined(closeBoxesTimer)) $clear(closeBoxesTimer);
});
item.setStyle('margin', '0');
$(currentBox).addEvent('mouseenter', function()
{
smartBoxes.setStyle('display', 'none');
item.setStyles({ display: 'block', position: 'absolute' });
var WindowX = window.getWidth();
var boxSize = item.getSize();
var inputPOS = $(currentBox).getCoordinates();
var inputCOOR = $(currentBox).getPosition();
var inputSize = $(currentBox).getSize();
var inputBottomPOS = inputPOS.top + inputSize.y;
var inputBottomPOSAdjust = inputBottomPOS - window.getScrollHeight();
var inputLeftPOS = inputPOS.left + xOffset;
var inputRightPOS = inputPOS.right;
var leftOffset = inputCOOR.x + xOffset;
if(item.getProperty('id').split("_")[2] == 'sub0') {
item.setStyle('top', inputBottomPOS);
if((inputLeftPOS + boxSize.x - WindowX) < 0) { item.setStyle('left', leftOffset - 10); }
else{ item.setStyle('left', (inputPOS.right - boxSize.x) - xOffset + 10); };
} else {
if((inputLeftPOS + boxSize.x + inputSize.x - WindowX) < 0) {
var space = inputLeftPOS - boxSize.x - inputSize.x;
var left = (space > inputSize.x) ? space : inputSize.x;
item.setStyle('left', left);
} else {
var space = WindowX - inputLeftPOS - inputSize.x/2;
var right = (space > inputSize.x) ? space : inputSize.x;
item.setStyle('right', right);
};
}
if(h[i] == null){ h[i] = boxSize.y; };
fx[i].start({
'0':{
'opacity': [0, 1],
'height': [0, h[i]]
}
});
});
});
};
window.addEvent("domready", function(){
$$('ul#menusys_mega li').each(function(li, i){
li.addEvent('mouseleave', function(){li.removeClass('hover');});
li.addEvent('mouseenter', function(){li.addClass('hover');});
});
}); | cyberalpha/UbicoArte | templates/zt_xenia25/zt_menus/zt_megamenu/zt.megamenu.js | JavaScript | gpl-2.0 | 3,213 |
/*! jQuery UI - v1.9.0-rc.1 - 2012-08-24
* http://jqueryui.com
* Includes: jquery.ui.datepicker-ta.js
* Copyright 2012 jQuery Foundation and other contributors; Licensed MIT */
jQuery(function(a){a.datepicker.regional.ta={closeText:"மூடு",prevText:"முன்னையது",nextText:"அடுத்தது",currentText:"இன்று",monthNames:["தை","மாசி","பங்குனி","சித்திரை","வைகாசி","ஆனி","ஆடி","ஆவணி","புரட்டாசி","ஐப்பசி","கார்த்திகை","மார்கழி"],monthNamesShort:["தை","மாசி","பங்","சித்","வைகா","ஆனி","ஆடி","ஆவ","புர","ஐப்","கார்","மார்"],dayNames:["ஞாயிற்றுக்கிழமை","திங்கட்கிழமை","செவ்வாய்க்கிழமை","புதன்கிழமை","வியாழக்கிழமை","வெள்ளிக்கிழமை","சனிக்கிழமை"],dayNamesShort:["ஞாயிறு","திங்கள்","செவ்வாய்","புதன்","வியாழன்","வெள்ளி","சனி"],dayNamesMin:["ஞா","தி","செ","பு","வி","வெ","ச"],weekHeader:"Не",dateFormat:"dd/mm/yy",firstDay:1,isRTL:!1,showMonthAfterYear:!1,yearSuffix:""},a.datepicker.setDefaults(a.datepicker.regional.ta)}); | eauxnguyen/civicrm-starterkit-drops-7 | profiles/civicrm_starterkit/modules/civicrm/packages/jquery/jquery-ui-1.9.0/development-bundle/ui/minified/i18n/jquery.ui.datepicker-ta.min.js | JavaScript | gpl-2.0 | 1,459 |
/*
*
*/
Ext.define("core.cbf.model.CbfModel",{
extend:"Ext.data.Model",
fields:[
{name:"id",type:"int",srotable:false},
{name:"cbfbm",type:"string",srotable:false},
{name:"cbflx",type:"char",srotable:false},
{name:"cbfmc",type:"string",srotable:false},
{name:"cbfxb",type:"char",srotable:false},
{name:"cbfmz",type:"string",srotable:false},
{name:"cbfzjlx",type:"char",srotable:false},
{name:"cbfzjhm",type:"string",srotable:false},
{name:"cbfdz",type:"string",srotable:false},
{name:"yzbm",type:"string",srotable:false},
{name:"lxdh",type:"string",srotable:false},
{name:"cbfcysl",type:"int",srotable:false},
{name:"cbfdcrq",type:"date",srotable:false},
{name:"cbfdcy",type:"string",srotable:false},
{name:"cbfdcjs",type:"string",srotable:false},
{name:"gsjs",type:"string",srotable:false},
{name:"gsjsr",type:"string",srotable:false},
{name:"gsshrq",type:"string",srotable:false}, //date
{name:"gsshr",type:"string",srotable:false}
]
}); | argqzh/qzh | src/main/webapp/core/coreApp/cbf/model/CbfModel.js | JavaScript | gpl-2.0 | 1,034 |
/**
* @file
* Javascript for Goole Map widget of Geolocation field.
*/
(function ($) {
var geocoder;
Drupal.geolocation = Drupal.geolocation || {};
Drupal.geolocation.maps = Drupal.geolocation.maps || {};
Drupal.geolocation.markers = Drupal.geolocation.markers || {};
/**
* Set the latitude and longitude values to the input fields
* And optionaly update the address field
*
* @param latLng
* a location (latLng) object from google maps api
* @param i
* the index from the maps array we are working on
* @param op
* the op that was performed
*/
Drupal.geolocation.codeLatLng = function(latLng, i, op) {
// Update the lat and lng input fields
$('#geolocation-lat-' + i + ' input').attr('value', latLng.lat());
$('#geolocation-lat-item-' + i + ' .geolocation-lat-item-value').html(latLng.lat());
$('#geolocation-lng-' + i + ' input').attr('value', latLng.lng());
$('#geolocation-lng-item-' + i + ' .geolocation-lat-item-value').html(latLng.lng());
// Update the address field
if ((op == 'marker' || op == 'geocoder') && geocoder) {
geocoder.geocode({'latLng': latLng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
$('#geolocation-address-' + i + ' input').val(results[0].formatted_address);
if (op == 'geocoder') {
Drupal.geolocation.setZoom(i, results[0].geometry.location_type);
}
}
else {
$('#geolocation-address-' + i + ' input').val('');
if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
alert(Drupal.t('Geocoder failed due to: ') + status);
}
}
});
}
}
/**
* Get the location from the address field
*
* @param i
* the index from the maps array we are working on
*/
Drupal.geolocation.codeAddress = function(i) {
var address = $('#geolocation-address-' + i + ' input').val();
geocoder.geocode( { 'address': address }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
Drupal.geolocation.maps[i].setCenter(results[0].geometry.location);
Drupal.geolocation.setMapMarker(results[0].geometry.location, i);
Drupal.geolocation.codeLatLng(results[0].geometry.location, i, 'textinput');
Drupal.geolocation.setZoom(i, results[0].geometry.location_type);
}
else {
alert(Drupal.t('Geocode was not successful for the following reason: ') + status);
}
});
}
/**
* Set zoom level depending on accuracy (location_type)
*
* @param location_type
* location type as provided by google maps after geocoding a location
*/
Drupal.geolocation.setZoom = function(i, location_type) {
if (location_type == 'APPROXIMATE') {
Drupal.geolocation.maps[i].setZoom(10);
}
else if (location_type == 'GEOMETRIC_CENTER') {
Drupal.geolocation.maps[i].setZoom(12);
}
else if (location_type == 'RANGE_INTERPOLATED' || location_type == 'ROOFTOP') {
Drupal.geolocation.maps[i].setZoom(16);
}
}
/**
* Set/Update a marker on a map
*
* @param latLng
* a location (latLng) object from google maps api
* @param i
* the index from the maps array we are working on
*/
Drupal.geolocation.setMapMarker = function(latLng, i) {
// remove old marker
if (Drupal.geolocation.markers[i]) {
Drupal.geolocation.markers[i].setMap(null);
}
Drupal.geolocation.markers[i] = new google.maps.Marker({
map: Drupal.geolocation.maps[i],
draggable: Drupal.settings.geolocation.settings.marker_draggable ? true : false,
// I dont like this much, rather have no effect
// Will leave it to see if someone notice and shouts at me!
// If so, will see consider enabling it again
// animation: google.maps.Animation.DROP,
position: latLng
});
google.maps.event.addListener(Drupal.geolocation.markers[i], 'dragend', function(me) {
Drupal.geolocation.codeLatLng(me.latLng, i, 'marker');
Drupal.geolocation.setMapMarker(me.latLng, i);
});
return false; // if called from <a>-Tag
}
/**
* Get the current user location if one is given
* @return
* Formatted location
*/
Drupal.geolocation.getFormattedLocation = function() {
if (google.loader.ClientLocation.address.country_code == "US" &&
google.loader.ClientLocation.address.region) {
return google.loader.ClientLocation.address.city + ", "
+ google.loader.ClientLocation.address.region.toUpperCase();
}
else {
return google.loader.ClientLocation.address.city + ", "
+ google.loader.ClientLocation.address.country_code;
}
}
/**
* Clear/Remove the values and the marker
*
* @param i
* the index from the maps array we are working on
*/
Drupal.geolocation.clearLocation = function(i) {
$('#geolocation-lat-' + i + ' input').attr('value', '');
$('#geolocation-lat-item-' + i + ' .geolocation-lat-item-value').html('');
$('#geolocation-lng-' + i + ' input').attr('value', '');
$('#geolocation-lng-item-' + i + ' .geolocation-lat-item-value').html('');
$('#geolocation-address-' + i + ' input').attr('value', '');
Drupal.geolocation.markers[i].setMap();
}
/**
* Do something when no location can be found
*
* @param supportFlag
* Whether the browser supports geolocation or not
* @param i
* the index from the maps array we are working on
*/
Drupal.geolocation.handleNoGeolocation = function(supportFlag, i) {
var siberia = new google.maps.LatLng(60, 105);
var newyork = new google.maps.LatLng(40.69847032728747, -73.9514422416687);
if (supportFlag == true) {
alert(Drupal.t("Geolocation service failed. We've placed you in NewYork."));
initialLocation = newyork;
}
else {
alert(Drupal.t("Your browser doesn't support geolocation. We've placed you in Siberia."));
initialLocation = siberia;
}
Drupal.geolocation.maps[i].setCenter(initialLocation);
Drupal.geolocation.setMapMarker(initialLocation, i);
}
Drupal.behaviors.geolocationGooglemaps = {
attach: function(context, settings) {
geocoder = new google.maps.Geocoder();
var lat;
var lng;
var latLng;
var mapOptions;
var browserSupportFlag = new Boolean();
var singleClick;
// Work on each map
$.each(Drupal.settings.geolocation.defaults, function(i, mapDefaults) {
// Only make this once ;)
$("#geolocation-map-" + i).once('geolocation-googlemaps', function(){
// Attach listeners
$('#geolocation-address-' + i + ' input').keypress(function(ev){
if(ev.which == 13){
ev.preventDefault();
Drupal.geolocation.codeAddress(i);
}
});
$('#geolocation-address-geocode-' + i).click(function(e) {
Drupal.geolocation.codeAddress(i);
});
$('#geolocation-remove-' + i).click(function(e) {
Drupal.geolocation.clearLocation(i);
});
// START: Autodetect clientlocation.
// First use browser geolocation
if (navigator.geolocation) {
browserSupportFlag = true;
$('#geolocation-help-' + i + ':not(.geolocation-googlemaps-processed)').addClass('geolocation-googlemaps-processed').append(Drupal.t(', or use your browser geolocation system by clicking this link') +': <span id="geolocation-client-location-' + i + '" class="geolocation-client-location">' + Drupal.t('My Location') + '</span>');
// Set current user location, if available
$('#geolocation-client-location-' + i + ':not(.geolocation-googlemaps-processed)').addClass('geolocation-googlemaps-processed').click(function() {
navigator.geolocation.getCurrentPosition(function(position) {
latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
Drupal.geolocation.maps[i].setCenter(latLng);
Drupal.geolocation.setMapMarker(latLng, i);
Drupal.geolocation.codeLatLng(latLng, i, 'geocoder');
}, function() {
Drupal.geolocation.handleNoGeolocation(browserSupportFlag, i);
});
});
}
// If browser geolication is not supoprted, try ip location
else if (google.loader.ClientLocation) {
latLng = new google.maps.LatLng(google.loader.ClientLocation.latitude, google.loader.ClientLocation.longitude);
$('#geolocation-help-' + i + ':not(.geolocation-googlemaps-processed)').addClass('geolocation-googlemaps-processed').append(Drupal.t(', or use the IP-based location by clicking this link') +': <span id="geolocation-client-location-' + i + '" class="geolocation-client-location">' + Drupal.geolocation.getFormattedLocation() + '</span>');
// Set current user location, if available
$('#geolocation-client-location-' + i + ':not(.geolocation-googlemaps-processed)').addClass('geolocation-googlemaps-processed').click(function() {
latLng = new google.maps.LatLng(google.loader.ClientLocation.latitude, google.loader.ClientLocation.longitude);
Drupal.geolocation.maps[i].setCenter(latLng);
Drupal.geolocation.setMapMarker(latLng, i);
Drupal.geolocation.codeLatLng(latLng, i, 'geocoder');
});
}
// END: Autodetect clientlocation.
// Get current/default values
// Get default values
// This might not be necesarry
// It can always come from e
lat = $('#geolocation-lat-' + i + ' input').attr('value') == false ? mapDefaults.lat : $('#geolocation-lat-' + i + ' input').attr('value');
lng = $('#geolocation-lng-' + i + ' input').attr('value') == false ? mapDefaults.lng : $('#geolocation-lng-' + i + ' input').attr('value');
latLng = new google.maps.LatLng(lat, lng);
// Set map options
mapOptions = {
zoom: 2,
center: latLng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
scrollwheel: (Drupal.settings.geolocation.settings.scrollwheel != undefined) ? Drupal.settings.geolocation.settings.scrollwheel : false
}
// Create map
Drupal.geolocation.maps[i] = new google.maps.Map(document.getElementById("geolocation-map-" + i), mapOptions);
if (lat && lng) {
// Set initial marker
Drupal.geolocation.codeLatLng(latLng, i, 'geocoder');
Drupal.geolocation.setMapMarker(latLng, i);
}
// Listener to set marker
google.maps.event.addListener(Drupal.geolocation.maps[i], 'click', function(me) {
// Set a timeOut so that it doesn't execute if dbclick is detected
singleClick = setTimeout(function() {
Drupal.geolocation.codeLatLng(me.latLng, i, 'marker');
Drupal.geolocation.setMapMarker(me.latLng, i);
}, 500);
});
// Detect double click to avoid setting marker
google.maps.event.addListener(Drupal.geolocation.maps[i], 'dblclick', function(me) {
clearTimeout(singleClick);
});
})
});
}
};
})(jQuery);
;
| tungcan1501/hdtv | sites/default/files/js/js_JIzlcM6aM0LMxxWAo8iNMOVxFXtNamiOTTx6GLKu6cc.js | JavaScript | gpl-2.0 | 11,459 |
require("../mapper").define("priority", "priority-view-model", {
"id": "_id",
name: "name",
order: "order",
colour: "colour"
});
require("../mapper").define("priority-view-model", "priority", {
"_id": "id",
name: "name",
order: "order",
colour: "colour"
}); | shamim8888/Leaf | data/mapping/definitions/priority.js | JavaScript | gpl-2.0 | 266 |
function enter(pi) {
pi.warp(926110401, 0); //next
return(true);
} | xstory61/server | scripts/portal/jnr12_in.js | JavaScript | gpl-2.0 | 74 |
var searchData=
[
['nullvalue',['nullValue',['../namespaceJson.html#a7d654b75c16a57007925868e38212b4ea7d9899633b4409bd3fc107e6737f8391',1,'Json']]],
['numberofcommentplacement',['numberOfCommentPlacement',['../namespaceJson.html#a4fc417c23905b2ae9e2c47d197a45351abcbd3eb00417335e094e4a03379659b5',1,'Json']]]
];
| wgml/RouteFinder | doxygen/doc/html/search/enumvalues_4.js | JavaScript | gpl-2.0 | 316 |
;(function($){
var page_container, current_select = null;
$(document).ready(function(){
page_container = $('#launch_suite_pages');
$('#funnel_select').change(function(){
if(parseInt($('#funnel_id').val()) > 0){
if($(this).val() != $('#funnel_id').val()){
document.location.href = OptimizePress.launch_suite_url.replace(/&/g, '&')+$(this).val();
}
}
}).trigger('change');
page_container.sortable({
items:'> div.section-stage',
handle:'div.show-hide-panel',
axis: 'y',
update: refresh_titles
});
page_container.find('.panel-controlx').iButton().end().delegate('select.value_page','change',function(e){
var url = OptimizePress.launch_page_urls[$(this).val()] || '';
//console.log($(this).val());
var title = $(this).find('option:selected').text();
var $value_page = $(this).parent().siblings('.tab-navigation_text').find('.active-link-text');
if ($.trim($value_page.val())=='') $value_page.val(title);
if ($.trim($value_page.val())=='(Select Page...)') $value_page.val('');
$(this).parent().find('input.value_page_url').val(url).end().find('input.value_page_access_url').val(add_key(url));
}).delegate('div.tab-delete_stage button','click',function(){
$(this).closest('.section-stage').remove();
refresh_titles();
});
// open cart on, removes hide cart and sets it to false
$('input[name="op[funnel_pages][sales][page_setup][open_sales_cart]"]').change(function(e){
if($(this).is(':checked')){
$('input[name="op[funnel_pages][sales][page_setup][hide_cart]"]').removeAttr('checked').trigger('change');
$('#hide_cart').hide();
} else {
$('#hide_cart').show();
}
}).trigger('change');
$('#launch_suite_sales select.value_page').change(function(){
var url = OptimizePress.launch_page_urls[$(this).val()] || '';
$(this).parent().find('input.value_page_url').val(url).end().find('input.value_page_access_url').val(add_key(url));
}).trigger('change');
$('#op_launch_settings_gateway_key_key').change(function(){
page_container.find('select.value_page').trigger('change');
});
$('#op_gateway_key_enabled').change(function(){
page_container.find('select.value_page').trigger('change');
var cl1 = '.gateway_off', cl2 = '.gateway_on';
if($(this).is(':checked')){
cl1 = '.gateway_on';
cl2 = '.gateway_off';
}
page_container.add('#launch_suite_sales').find(cl1).css('display','block').end().find(cl2).css('display','none');
}).trigger('change');
var selected_class = 'op-bsw-grey-panel-tabs-selected';
$('#launch_suite_add_section').click(function(e){
e.preventDefault();
var tmpl = $('#launch_suite_new_item').html(),
elcount = page_container.find('div.section-stage').length+1;
tmpl = tmpl.replace(/9999/g,elcount).replace(/# TITLE #/ig,OptimizePress.launch_section_title.replace(/%1\$s/,elcount));
page_container.append(tmpl).find('div.section-stage:last').find('ul.op-bsw-grey-panel-tabs').op_tabs().end().find('.panel-controlx').iButton().end().find('select.value_page').trigger('change');
$('#op_gateway_key_enabled').trigger('change');
add_page_link();
bind_content_sliders();
});
add_page_link();
init_funnel_switch();
bind_content_sliders();
});
function add_page_link(){
$('#launch_suite_pages .add-new-page,#launch_suite_sales .add-new-page').click(function(e){
e.preventDefault();
current_select = $(this).prev();
$('#toplevel_page_optimizepress a[href$="page=optimizepress-page-builder"]').trigger('click');
});
};
function init_funnel_switch(){
$('#funnel_delete').click(function(e) {
var funnel_id = $('#funnel_select').val();
if (!confirm('Are you sure you want to delete this funnel?')) {
return false;
}
$.post(
OptimizePress.ajaxurl,
{
action: OptimizePress.SN + '-launch-suite-delete',
_wpnonce: $('#_wpnonce').val(),
funnel_id: funnel_id
},
function(response) {
document.location.replace(document.location.href.replace('&funnel_id=' + funnel_id, ''));
}
);
return false;
});
$('#funnel_switch_create_new').click(function(e){
e.preventDefault();
$('#launch_funnel_select:visible').fadeOut('fast',function(){
$('#launch_funnel_new').fadeIn('fast');
});
});
$('#funnel_switch_select').click(function(e){
e.preventDefault();
$('#launch_funnel_new:visible').fadeOut('fast',function(){
$('#launch_funnel_select').fadeIn('fast');
});
});
$('#add_new_funnel').click(function(e){
e.preventDefault();
var waiting = $(this).next().find('img').fadeIn('fast'), name = $('#new_funnel').val(),
data = {
action: OptimizePress.SN+'-launch-suite-create',
_wpnonce: $('#_wpnonce').val(),
funnel_name: name
};
$.post(OptimizePress.ajaxurl,data,function(resp){
waiting.fadeOut('fast');
if(typeof resp.error != 'undefined'){
alert(resp.error);
} else {
$('#funnel_select').html(resp.html).trigger('change');
document.location.reload();
}
},'json');
});
};
function refresh_titles(){
var counter = 1;
page_container.find('> div.section-stage > div.op-bsw-grey-panel-header > h3 > a').each(function(){
$(this).text(OptimizePress.launch_section_title.replace(/%1\$s/,counter));
counter++;
});
};
function add_key(url){
if(url == ''){
return '';
}
if($('#op_gateway_key_enabled').is(':checked')){
return add_param(url,'gw',$('#op_launch_settings_gateway_key_key').val());
}
return url;
};
function add_param(url,name,value){
return url + (url.indexOf('?') != -1 ? '&' : '?') + name+'='+encodeURIComponent(value);
};
window.op_launch_suite_update_selects = function(page_id){
var data = {
action: OptimizePress.SN+'-launch-suite-refresh_dropdown',
_wpnonce: $('#_wpnonce').val(),
funnel_id: $('#funnel_id').val()
};
$.post(OptimizePress.ajaxurl,data,function(resp){
if(typeof resp.error != 'undefined'){
alert(resp.error);
} else {
$('.landing_page,.value_page,#launch_suite_sales select,#launch_suite_new_item select').each(function(){
var curv = $(this).val();
//console.log(resp.html);
$(this).html(resp.html).val(curv);
});
if(current_select !== null){
current_select.val(page_id);
}
}
},'json');
};
function bind_content_sliders(){
var $btns = $('.op-content-slider-button'); //Get all the content slider buttons
//Loop through each one
$btns.each(function(index, value){
var $target = $(this).parent().prev('.op-content-slider'); //Get the target of the current button (the content slider)
var $cur_btn = $(this); //Used later on in the script for callbacks
//Initialize the show action on click of the show gallery button
$(this).unbind('click').click(function(e){
var scrollY = window.pageYOffset; //Get the current position of the viewport
$target.show().animate({top:scrollY},400); //Scroll the box to the viewport
e.preventDefault();
});
//Initialize the close button
$target.find('.hide-the-panda').unbind('click').click(function(e){
var scrollY = window.pageYOffset; //Get the current position of the viewport
//Scroll the box to the viewport
$target.animate({top:-(scrollY)},400, function(){
$(this).hide(); //Hide the box after it is out of sight
});
e.preventDefault();
});
//Init the click handlers for the images inside the content box
$target.delegate('ul.op-image-slider-content li a','click',function(e){
var $input = $cur_btn.next('input.op-gallery-value'); //Grab ahold of the hidden input for the gallery
var $preview = $input.next('.file-preview').find('.content'); //Get ahold of the preview area
var src = $(this).find('img').attr('src'); //Get ahold of the image src
//Create the html for the preview area
var html = '<a class="preview-image" target="_blank" href="' + src + '"><img alt="uploaded-image" src="' + src + '"></a><a class="remove-file button" href="#remove">Remove Image</a>';
//Put the image source into the hidden input for form submission
$input.val(src);
//Navigate through the DOM to the uploader preview image and value and set accordingly
$input.parent().next('.op-file-uploader').find('.file-preview .content').empty().html(html).find('.remove-file').click(function(){
$(this).parent().empty().parent('.file-preview').prev('.op-uploader-value').val('');
}).parent().parent('.file-preview').prev('.op-uploader-value').val(src);
//Animate the box off of the screen and hide it
$target.animate({top:-700},400, function(){
$(this).hide();
});
e.preventDefault();
});
});
}
}(opjq)); | sarahkpeck/thought-leaders | wp-content/plugins/optimizePressPlugin/lib/js/launch_suite.js | JavaScript | gpl-2.0 | 10,754 |
define(
"dojo/cldr/nls/zh-hk/gregorian", //begin v1.x content
{
"months-standAlone-narrow": [
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"10",
"11",
"12"
],
"quarters-format-wide": [
"第1季",
"第2季",
"第3季",
"第4季"
],
"eraAbbr": [
"西元前",
"西元"
],
"dateFormat-medium": "yyyy/M/d",
"dateFormat-short": "y/M/d",
"timeFormat-full": "zzzzah時mm分ss秒",
"timeFormat-long": "zah時mm分ss秒",
"dateFormatItem-Ed": "d日(E)",
"dateFormatItem-h": "ah時",
"dateFormatItem-H": "H時",
"dateFormatItem-Md": "M/d",
"dateFormatItem-MEd": "M/d(E)",
"dateFormatItem-yM": "y/M",
"dateFormatItem-yMd": "y/M/d",
"dateFormatItem-yMEd": "y/M/d(E)",
"field-era": "年代",
"field-week": "週",
"field-weekday": "週天",
"field-hour": "小時",
"field-minute": "分鐘",
"field-second": "秒",
"field-zone": "時區",
"dateFormatItem-MMdd": "MM/dd",
"field-month-relative+-1": "上個月",
"field-month-relative+1": "下個月",
"field-week-relative+-1": "上週",
"field-week-relative+0": "本週",
"field-week-relative+1": "下週",
"field-day-relative+2": "後天",
"quarters-format-abbr": [
"第1季",
"第2季",
"第3季",
"第4季"
],
"quarters-standAlone-abbr": [
"第1季",
"第2季",
"第3季",
"第4季"
],
"quarters-standAlone-wide": [
"第1季",
"第2季",
"第3季",
"第4季"
],
"eraNames": [
"西元前",
"西元"
],
"eraNarrow": [
"西元前",
"西元"
]
}
//end v1.x content
); | hariomkumarmth/champaranexpress | wp-content/plugins/dojo/dojo/cldr/nls/zh-hk/gregorian.js.uncompressed.js | JavaScript | gpl-2.0 | 1,602 |
/**
*
*
* @author Josh Lobe
* http://ultimatetinymcepro.com
*/
jQuery(document).ready(function($) {
// Declare global variables
// The New eXeLearning
// var editor = top.tinymce.activeEditor;
var editor = parent.tinymce.activeEditor;
// / The New eXeLearning
var lastQuery = null;
var lastPos = null;
var marked = [];
var autocompletion_active = true;
// Instantiate CodeMirror on textarea
var myCodeMirror = CodeMirror.fromTextArea($("#htmlSource")[0], {
mode: "text/html",
lineNumbers: true,
lineWrapping: true,
styleActiveLine: true,
styleSelectedText: true,
highlightSelectionMatches: true,
indentUnit: 4
});
// Beautify source HTML and populate CodeMirror textarea
// The New eXeLearning
// myCodeMirror.doc.setValue( style_html(editor.getContent({format : 'html'}), 4) );
myCodeMirror.doc.setValue( editor.getContent({format : 'html'}) );
// / The New eXeLearning
// Set focus to codemirror window
myCodeMirror.focus();
// Add change event to capture undo;redo events
myCodeMirror.on('change', function(i, e) {
// Set undo and redo levels
var undo = myCodeMirror.doc.historySize().undo;
var redo = myCodeMirror.doc.historySize().redo;
// Toggle class name for action buttons
if(undo > 1) $("#undo").attr('class', '');
else $("#undo").attr('class', 'disabled');
if(redo > 0) $("#redo").attr('class', '');
else $("#redo").attr('class', 'disabled');
});
// Initialize autocomplete
myCodeMirror.on('keypress', function(i, e) {
if(autocompletion_active) {
/* Hook into charcode '<' */
if(String.fromCharCode(e.which == null ? e.keyCode : e.which) == "<") {
// Prevent keypress of '<'
e.preventDefault();
var cur = myCodeMirror.getCursor(false), token = myCodeMirror.getTokenAt(cur);
myCodeMirror.replaceRange("<", cur); // Replace '<' back into range
setTimeout(startComplete, 50);
return true;
}
}
});
// Cancel button
$('#codemagic_cancel').click(function() {
editor.windowManager.close();
});
// Insert button
$('#codemagic_insert').click(function() {
window_content = myCodeMirror.doc.getValue(); // Get codemirror html
editor.setContent(window_content); // Set editor content to codermirror content
// The New eXeLearning
editor.undoManager.add();
// / The New eXeLearning
editor.windowManager.close(); // Close window
});
// Codemagic action buttons
// Undo
$('#undo').click(function() {
if($(this).attr('class') != 'disabled') {
// Check if undo button is disabled
className = $('#undo').attr('class');
if(className == 'disabled') return;
// Undo step
myCodeMirror.doc.undo();
}
});
// Redo
$('#redo').click(function() {
if($(this).attr('class') != 'disabled') {
// Redo step
myCodeMirror.doc.redo();
}
});
// Search and Replace
$( "#search_replace" ).click(function() {
if($(this).attr('class') != 'disabled') {
$( "#search_replace" ).toggleClass( 'selected' );
$( "#search_panel" ).slideToggle( "slow", function() {
// Animation complete.
});
}
});
// Re-format html window code
$('#re_beautify').click(function() {
if($(this).attr('class') != 'disabled') {
// Re-beautify html in window manager
window_html = myCodeMirror.doc.getValue();
myCodeMirror.doc.setValue(
style_html(window_html, 4)
);
}
});
// Toggle Line Wrapping
// The New eXeLearning
// $("#wraptext").click( function() {
var wraptext_checkbox = $("#wraptext");
wraptext_checkbox.click( function() {
// / The New eXeLearning
if ($(this).is(':checked')){ myCodeMirror.setOption('lineWrapping', true); }
else { myCodeMirror.setOption('lineWrapping', false); }
});
// The New eXeLearning
// Fix https://github.com/exelearning/iteexe/issues/133
wraptext_checkbox.trigger("click");
setTimeout(function(){
wraptext_checkbox.trigger("click");
},200);
// Toggle Full Screen mode
if (parent && parent.codemagicDialog && typeof(parent.codemagicDialog.fullscreen)=="function") {
$("#maximizeEditorWrapper").show();
$("#maximizeEditor").click( function() {
if ($(this).is(':checked')){
parent.codemagicDialog.fullscreen(true);
$("#codemagic_insert").css("margin-bottom","20px");
} else {
parent.codemagicDialog.fullscreen(false);
$("#codemagic_insert").css("margin-bottom","0");
}
});
}
// / The New eXeLearning
// Toggle Auto Completion
$("#autocompletion").click( function() {
if ($(this).is(':checked')){ autocompletion_active = true; }
else { autocompletion_active = false; }
});
// Toggle Code Highlighting
$("#highlighting").click( function() {
if ($(this).is(':checked')){ activateCodeColoring('htmlSource'); }
else { deactivateCodeColoring(); }
});
// Activate code highlighting
function activateCodeColoring(id) {
// Enable buttons
$("#search_replace").attr('class', '');
$("#re_beautify").attr('class', '');
$("#autocompletion").attr("disabled", false);
// Redraw codemirror textarea
myCodeMirror = CodeMirror.fromTextArea($("#htmlSource")[0], {
mode: "text/html",
lineNumbers: true,
styleActiveLine: true,
styleSelectedText: true,
highlightSelectionMatches: true,
indentUnit: 4
});
// Set focus to window
myCodeMirror.focus();
// Add change event to capture undo;redo events
myCodeMirror.on('change', function(e) {
// Set undo and redo levels
var undo = myCodeMirror.doc.historySize().undo;
var redo = myCodeMirror.doc.historySize().redo;
// Toggle class name for action buttons
if(undo > 0) $("#undo").attr('class', '');
else $("#undo").attr('class', 'disabled');
if(redo > 0) $("#redo").attr('class', '');
else $("#redo").attr('class', 'disabled');
});
// Initialize autocomplete
myCodeMirror.on('keypress', function(i, e) {
if(autocompletion_active) {
/* Hook into charcode '<' */
if(String.fromCharCode(e.which == null ? e.keyCode : e.which) == "<") {
// Prevent keypress of '<'
e.preventDefault();
var cur = myCodeMirror.getCursor(false), token = myCodeMirror.getTokenAt(cur);
myCodeMirror.replaceRange("<", cur); // Replace '<' back into range
setTimeout(startComplete, 50);
return true;
}
}
});
// Match linewrap option
if ($("#wraptext").is(':checked')) { myCodeMirror.setOption('lineWrapping', true); }
else { myCodeMirror.setOption('lineWrapping', false); }
}
// Deactivate code highlighting
function deactivateCodeColoring() {
// Clear undo history
myCodeMirror.doc.clearHistory();
// Disable buttons
$("#undo").attr('class', 'disabled');
$("#redo").attr('class', 'disabled');
$("#search_replace").attr('class', 'disabled');
$("#re_beautify").attr('class', 'disabled');
$("#autocompletion").attr("disabled", true);
// Send codemirror back to original textarea
myCodeMirror.toTextArea();
}
/***************************************
****************************************
Search and Replace
*/
// Search code button
$('#search_code').click(function() { searchCode(); });
// Replace code button
$('#replace_code').click(function() { replaceCode(); });
// Unmark all highlighted words
function unmark() { marked.length = 0; }
// Search code function
function searchCode() {
unmark();
var text = $("#query").val();
if (!text) return false;
if(!myCodeMirror.getSearchCursor(text).findNext()) {
alert('Nothing Found.');
return false;
}
for (var cursor = myCodeMirror.getSearchCursor(text); cursor.findNext();)
marked.push(myCodeMirror.markText(cursor.from(), cursor.to(), "searched"));
if (lastQuery != text) lastPos = null;
var cursor = myCodeMirror.getSearchCursor(text, lastPos || myCodeMirror.getCursor());
if (!cursor.findNext()) {
cursor = myCodeMirror.getSearchCursor(text);
if (!cursor.findNext()) return;
}
myCodeMirror.setSelection(cursor.from(), cursor.to());
lastQuery = text; lastPos = cursor.to();
}
// Replace code function
function replaceCode() {
unmark();
var s_text = $("#query").val();
var replace = $("#replace").val();
if (!s_text) return false;
if(!myCodeMirror.getSearchCursor(s_text).findNext()) {
alert('Nothing to Replace.');
return false;
}
for (var cursor = myCodeMirror.getSearchCursor(s_text); cursor.findNext();)
myCodeMirror.replaceRange(replace, cursor.from(), cursor.to());
}
/***************************************
****************************************
Autocompletion
*/
var tagNames = ("a abbr acronym address applet area b base basefont bdo big blockquote body br button" +
" caption center cite code col colgroup dd del dfn dir div dl dt em fieldset font form frame" +
" frameset h1 h2 h3 h4 h5 h6 head hr html i iframe img input ins isindex kbd label legend li link map" +
" menu meta noframes noscript object ol optgroup option p param pre q s samp script select small" +
" span strike strong style sub sup table tbody td textarea tfoot th thead title tr tt u ul var").split(" ");
var pairedTags = ("a abbr acronym address applet b bdo big blockquote body button" +
" caption center cite code colgroup del dfn dir div dl em fieldset font form" +
" frameset h1 h2 h3 h4 h5 h6 head html i iframe ins kbd label legend li map" +
" menu noframes noscript object ol optgroup option p pre q s samp script select small" +
" span strike strong style sub sup table tbody td textarea tfoot th thead title tr tt u ul var").split(" ");
var unPairedTags = ("area base basefont br col dd dt frame hr img input isindex link meta param").split(" ");
var specialTags = {
"applet" : { tag: 'applet width="" height=""></applet>', cusror: 8 },
"area" : { tag: 'area alt="" />', cusror: 6 },
"base" : { tag: 'base href="" />', cusror: 7 },
"form" : { tag: 'form action=""></form>', cusror: 9 },
"img" : { tag: 'img src="" alt="" />', cusror: 6 },
"map" : { tag: 'map name=""></map>', cusror: 7 },
"meta" : { tag: 'meta content="" />', cusror: 10 },
"optgroup" : { tag: 'optgroup label=""></optgroup>', cusror: 8 },
"param" : { tag: 'param name="" />', cusror: 7 },
"script" : { tag: 'script type=""></script>', cusror: 7 },
"style" : { tag: 'style type=""></style>', cusror: 7 },
"textarea" : { tag: 'textarea cols="" rows=""></textarea>', cusror: 7 }
}
function forEach(arr, f) { for (var i = 0, e = arr.length; i < e; ++i) f(arr[i]); }
Array.prototype.inArray = function(value){
for (var key in this)
if (this[key] === value) return true;
return false;
}
// Autocompletion Start
function startComplete() {
var startingTag, unPaired;
// We want a single cursor position.
if (myCodeMirror.somethingSelected()) return;
// Find the token at the cursor
var cur = myCodeMirror.getCursor(false),
token = myCodeMirror.getTokenAt(cur),
tprop = token;
if(token.string.indexOf("<") == 0 && token.string.indexOf("</") != 0) {
token.string = token.string.replace("<", "");
token.start++;
startingTag = true;
}
else if(token.string.indexOf("</") == 0) {
token.string = token.string.replace("</", "");
token.start += 2;
startingTag = false;
}
else {
return;
}
// Get the tags
var completions = getCompletions(token, startingTag);
if (!completions.length) return;
// Insert tag into codemirror window
function insert(str) {
if(str == "") return;
// Trim
str = str.replace(/^\s+|\s+$/g,"");
// Is this an unpaired tag?
unPaired = unPairedTags.inArray(str) ? true : false;
if(specialTags[str] != null && startingTag) {
var insertTag = specialTags[str].tag;
var jumpTo = (token.start + str.length + specialTags[str].cusror);
}
else if(startingTag && unPaired) {
var insertTag = str + " />";
var jumpTo = (token.start + str.length + 3);
}
else if (startingTag) {
var insertTag = str + "></" + str + ">";
var jumpTo = (token.start + str.length + 1);
}
else {
var insertTag = str + ">";
var jumpTo = (token.start + str.length + 1);
}
// Insert tag
myCodeMirror.replaceRange(insertTag, {line: cur.line, ch: token.start}, {line: cur.line, ch: token.end});
myCodeMirror.setCursor({line: cur.line, ch: jumpTo});
// Unbind events so additional uses of window don't populate all binded history events
$('body').off('dblclick', 'option');
$('body').off('keydown', 'select');
}
// Build the select widget
var complete = $( "<div class='completions'>" );
var option_tag = [];
for (var i = 0; i < completions.length; ++i) {
option_tag += "<option>" + completions[i] + "</option>";
}
var sel = complete.append('<select id="completions_options">'+option_tag+'</select>');
// Select first option
$('select option:first-child').attr("selected", "selected");
// Show six options in select box
complete.children().attr('size', '10');
// Left position
var pos = myCodeMirror.cursorCoords();
complete.css('margin-left', pos.left+'px');
// Top position
if(pos.top > 0) pos.top = pos.top - 550;
complete.css('margin-top', pos.top+'px');
// Append populated div and select box to body
$('body').append(complete);
// Apply focus to select box
$('select').focus();
// Close autocompletion window
function close_autocomplete() { complete.remove(); }
// Grab select option (tag) and run insert() function.
function pick() {
html_tag = $('#completions_options').find(":selected").text();
insert(html_tag);
close_autocomplete();
// Re-focus codemirror window after a brief delay
setTimeout(function(){ myCodeMirror.focus(); }, 50);
}
// Bind dblclick to autocomplete option box
$('body').on('dblclick', 'option', function() { pick(); });
// Bind keydown event to select box
$('body').on('keydown', 'select', function(e) {
var code = e.keyCode;
// Enter, space, tab
if (code == 13 || code == 32 || code == 9) {
e.preventDefault();
pick();
}
// Escape
else if (code == 27) {
e.preventDefault();
close_autocomplete();
myCodeMirror.focus();
}
// Other than arrow up/down
else if (code != 38 && code != 40 && code != 16 && code != 17 && code != 18 && code != 91 && code != 92) {
close_autocomplete();
myCodeMirror.focus();
if(code != 39 && code != 37) {
// Unbind event handlers
$('body').off('dblclick', 'option');
$('body').off('keydown', 'select');
setTimeout(startComplete, 50);
}
else {
e.preventDefault();
}
}
});
}
function getCompletions(token, startingTag) {
var found = [], start = token.string;
function maybeAdd(str) { if (str.indexOf(start) == 0) found.push(str); }
// Check if this is a starting tag
if(startingTag) { forEach(tagNames, maybeAdd) }
else { forEach(pairedTags, maybeAdd) }
return found;
}
}); | exelearning/iteexe | exe/webui/scripts/tinymce_4/js/tinymce/plugins/codemagic/includes/codemagic.js | JavaScript | gpl-2.0 | 15,364 |
require({cache:{
'url:dijit/templates/CheckedMenuItem.html':"<tr class=\"dijitReset dijitMenuItem\" data-dojo-attach-point=\"focusNode\" role=\"menuitemcheckbox\" tabIndex=\"-1\">\n\t<td class=\"dijitReset dijitMenuItemIconCell\" role=\"presentation\">\n\t\t<img src=\"${_blankGif}\" alt=\"\" class=\"dijitMenuItemIcon dijitCheckedMenuItemIcon\" data-dojo-attach-point=\"iconNode\"/>\n\t\t<span class=\"dijitCheckedMenuItemIconChar\">✓</span>\n\t</td>\n\t<td class=\"dijitReset dijitMenuItemLabel\" colspan=\"2\" data-dojo-attach-point=\"containerNode,labelNode\"></td>\n\t<td class=\"dijitReset dijitMenuItemAccelKey\" style=\"display: none\" data-dojo-attach-point=\"accelKeyNode\"></td>\n\t<td class=\"dijitReset dijitMenuArrowCell\" role=\"presentation\"> </td>\n</tr>\n"}});
define("dijit/CheckedMenuItem", [
"dojo/_base/declare", // declare
"dojo/dom-class", // domClass.toggle
"./MenuItem",
"dojo/text!./templates/CheckedMenuItem.html",
"./hccss"
], function(declare, domClass, MenuItem, template){
// module:
// dijit/CheckedMenuItem
return declare("dijit.CheckedMenuItem", MenuItem, {
// summary:
// A checkbox-like menu item for toggling on and off
templateString: template,
// checked: Boolean
// Our checked state
checked: false,
_setCheckedAttr: function(/*Boolean*/ checked){
// summary:
// Hook so attr('checked', bool) works.
// Sets the class and state for the check box.
domClass.toggle(this.domNode, "dijitCheckedMenuItemChecked", checked);
this.domNode.setAttribute("aria-checked", checked ? "true" : "false");
this._set("checked", checked);
},
iconClass: "", // override dijitNoIcon
onChange: function(/*Boolean*/ /*===== checked =====*/){
// summary:
// User defined function to handle check/uncheck events
// tags:
// callback
},
_onClick: function(evt){
// summary:
// Clicking this item just toggles its state
// tags:
// private
if(!this.disabled){
this.set("checked", !this.checked);
this.onChange(this.checked);
}
this.onClick(evt);
}
});
});
| hariomkumarmth/champaranexpress | wp-content/plugins/dojo/dijit/CheckedMenuItem.js.uncompressed.js | JavaScript | gpl-2.0 | 2,146 |
import BasisDrawerCloseZone from './_drawer-close-zone.js';
import BasisDrawer from './_drawer.js';
import BasisHamburgerBtn from './_hamburger-btn.js';
import BasisNavbar from './_navbar.js';
import BasisPageEffect from './_page-effect.js';
document.addEventListener(
'DOMContentLoaded',
() => {
new BasisDrawerCloseZone();
new BasisDrawer({drawer: '.c-drawer'});
new BasisDrawer({drawer: '.c-dropdown'});
new BasisHamburgerBtn();
new BasisNavbar();
new BasisPageEffect();
},
false
);
| inc2734/basis | src/js/basis.js | JavaScript | gpl-2.0 | 519 |
FusionCharts.ready(function () {
var salesChart = new FusionCharts({
type: 'bulb',
renderAt: 'chart-container',
id: 'myChart',
width: '200',
height: '200',
dataFormat: 'json',
dataSource: {
"chart": {
"caption": "Temperature status of deep freezers",
"upperlimit": "-5",
"lowerlimit": "-60",
"captionPadding":"30",
"showshadow":"0",
"showvalue": "1",
"useColorNameAsValue":"1",
"placeValuesInside":"1",
"valueFontSize": "16",
//Cosmetics
"baseFontColor" : "#333333",
"baseFont" : "Helvetica Neue,Arial",
"captionFontSize" : "14",
"showborder": "0",
"bgcolor": "#FFFFFF",
"toolTipColor" : "#ffffff",
"toolTipBorderThickness" : "0",
"toolTipBgColor" : "#000000",
"toolTipBgAlpha" : "80",
"toolTipBorderRadius" : "2",
"toolTipPadding" : "5",
},
"colorrange": {
"color": [
{
"minvalue": "-60",
"maxvalue": "-35",
"label": "Problem detected!",
"code": "#ff0000"
},
{
"minvalue": "-35",
"maxvalue": "-25",
"label": "Alert!",
"code": "#ff9900"
},
{
"minvalue": "-25",
"maxvalue": "-5",
"label": "All well!",
"code": "#00ff00"
}
]
},
"value": "-5"
},
"events":{
"rendered": function(evtObj, argObj){
setInterval(function () {
var num = (Math.floor(Math.random() * 55)*-1) -5;
FusionCharts("myChart").feedData("&value=" + num);
}, 10000);
}
}
});
salesChart.render();
});
| sguha-work/fiddletest | backup/fiddles/Gauge/Real-time_Gauges/A_sample_real-time_bulb_gauge/demo.js | JavaScript | gpl-2.0 | 2,294 |
define(
({
showLayerLabels: "Εμφάνιση των ονομάτων των θεματικών επιπέδων στο widget για χωρο-χρονικά θεματικά επίπεδα."
})
); | johnaagudelo/ofertaquequieres | visor-oferta/widgets/TimeSlider/setting/nls/el/strings.js | JavaScript | gpl-2.0 | 209 |
var nextTick = null;
if (process) {
if ('nextTick' in process) {
nextTick = process.nextTick;
if (typeof module !== 'undefined') {
if ('exports' in module)
module.exports = Array;
}
}
}
if (!nextTick) {
// For support general browser, using setTimeout instead of process.nextTick
nextTick = function(func) {
setTimeout(func, 0);
};
}
var forEachAsync = function(callback, complete) {
var self = this;
function next(index, length) {
var self = this;
if (index >= length) {
if (complete)
complete.apply(this, [ true ]);
return;
}
function _next(stop) {
if (stop === false) {
if (complete)
complete.apply(this, [ false ]);
return;
}
nextTick(function() {
if (ret === false) {
if (complete)
complete.apply(this, [ false ]);
return;
}
next.apply(self, [ index + 1, length ]);
});
}
var ret = callback.apply(self, [ self[index], index, self, _next ]);
if (ret != true)
_next();
}
next.apply(self, [ 0, self.length ]);
};
if (!Array.prototype.forEachAsync)
Object.defineProperty(Array.prototype, 'forEachAsync', { value: forEachAsync });
var parallel = function(workerNumber, callback, complete) {
if (!callback)
return;
var self = this;
var completed = 0;
var total = self.length;
var workerCount = 0;
var currentIndex = 0;
if (total == 0) {
if (complete)
complete();
return;
}
function _complete() {
completed++;
workerCount--;
if (workerCount == 0 && completed >= total) {
if (complete)
complete();
} else {
// Next item
nextTick(function() {
currentIndex++;
_parallel(currentIndex);
});
}
}
function _parallel(index) {
if (index >= total)
return;
if (workerCount < workerNumber) {
workerCount++;
if (workerCount < workerNumber) {
// New worker
nextTick(function() {
currentIndex++;
_parallel(currentIndex);
});
}
// Customized callback function
callback(self[index], index, self, _complete);
} else {
nextTick(function() {
_parallel(index);
});
}
}
_parallel(currentIndex);
}
if (!Array.prototype.parallel)
Object.defineProperty(Array.prototype, 'parallel', { value: parallel });
| nagerenxiong/ChromeExtension | shangzheng/node_modules/node-array/lib/array.js | JavaScript | gpl-2.0 | 2,234 |
function defined (constant_name) {
// http://kevin.vanzonneveld.net
// + original by: Waldo Malqui Silva
// + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + revised by: Brett Zamir (http://brett-zamir.me)
// % note 1: Because this function can (albeit only temporarily) overwrite a global variable,
// % note 1: it is not thread-safe (normally not a concern for JavaScript, but would be if used
// % note 1: in a threaded environment, e.g., DOM worker threads)
// * example 1: defined('IMAGINARY_CONSTANT1');
// * returns 1: false
var tmp = this.window[constant_name];
this.window[constant_name] = this.window[constant_name] ? 'changed' + this.window[constant_name].toString() : 'changed';
var returnval = this.window[constant_name] === tmp;
if (!returnval) { // Reset
this.window[constant_name] = tmp;
}
return returnval;
}
| thebillkidy/desple.com | wp-content/themes/capsule/ui/lib/phpjs/functions/misc/defined.js | JavaScript | gpl-2.0 | 960 |
/* https://github.com/crhallberg/autocomplete.js 0.16.3 */
(function autocomplete( $ ) {
var cache = {},
element = false,
options = { // default options
ajaxDelay: 200,
cache: true,
hidingClass: 'hidden',
highlight: true,
loadingString: 'Loading...',
maxResults: 20,
minLength: 3
};
var xhr = false;
function align(input) {
var position = input.offset();
element.css({
top: position.top + input.outerHeight(),
left: position.left,
minWidth: input.width(),
maxWidth: Math.max(input.width(), input.closest('form').width())
});
}
function show() {
element.removeClass(options.hidingClass);
}
function hide() {
element.addClass(options.hidingClass);
}
function populate(data, input, eventType) {
input.val(data.value);
input.data('selection', data);
if (options.callback) {
options.callback(data, input, eventType);
}
hide();
}
function createList(data, input) {
input.data('length', data.length);
// highlighting setup
// escape term for regex - https://github.com/sindresorhus/escape-string-regexp/blob/master/index.js
var escapedTerm = input.val().replace(/[|\\{}()\[\]\^$+*?.]/g, '\\$&');
var regex = new RegExp('(' + escapedTerm + ')', 'ig');
var shell = $('<div/>');
for (var i = 0; i < data.length; i++) {
if (typeof data[i] === 'string') {
data[i] = {value: data[i]};
}
var content = data[i].label || data[i].value;
if (options.highlight) {
content = content.replace(regex, '<b>$1</b>');
}
var item = typeof data[i].href === 'undefined'
? $('<div/>')
: $('<a/>').attr('href', data[i].href);
// Data
item.data(data[i])
.addClass('item')
.html(content);
if (typeof data[i].description !== 'undefined') {
item.append($('<small/>').html(
options.highlight
? data[i].description.replace(regex, '<b>$1</b>')
: data[i].description
));
}
shell.append(item);
}
element.html(shell);
element.find('.item').mousedown(function acItemClick() {
populate($(this).data(), input, {mouse: true});
setTimeout(function acClickDelay() {
input.focus();
hide();
}, 10);
});
align(input);
}
function handleResults(input, term, data) {
// Limit results
var data = data.slice(0, Math.min(options.maxResults, data.length));
var cid = input.data('cache-id');
cache[cid][term] = data;
if (data.length === 0) {
hide();
} else {
createList(data, input);
}
}
function search(input) {
if (xhr) { xhr.abort(); }
if (input.val().length >= options.minLength) {
element.html('<i class="item loading">' + options.loadingString + '</i>');
show();
align(input);
input.data('selected', -1);
var term = input.val();
// Check cache (only for handler-based setups)
var cid = input.data('cache-id');
if (options.cache && typeof cache[cid][term] !== "undefined") {
if (cache[cid][term].length === 0) {
hide();
} else {
createList(cache[cid][term], input);
}
// Check for static list
} else if (typeof options.static !== 'undefined') {
var lcterm = term.toLowerCase();
var matches = options.static.filter(function staticFilter(_item) {
return _item.match.match(lcterm);
});
if (typeof options.staticSort === 'function') {
matches.sort(options.staticSort);
} else {
matches.sort(function defaultStaticSort(a, b) {
return a.match.indexOf(lcterm) - b.match.indexOf(lcterm);
});
}
handleResults(input, term, matches);
// Call handler
} else {
options.handler(input, function achandlerCallback(data) {
handleResults(input, term, data);
});
}
} else {
hide();
}
}
function setup(input) {
if ($('.autocomplete-results').length === 0) {
element = $('<div/>')
.addClass('autocomplete-results hidden')
.html('<i class="item loading">' + options.loadingString + '</i>');
align(input);
$(document.body).append(element);
}
input.data('selected', -1);
input.data('length', 0);
if (options.cache) {
var cid = Math.floor(Math.random() * 1000);
input.data('cache-id', cid);
cache[cid] = {};
}
input.blur(function acinputBlur(e) {
if (e.target.acitem) {
setTimeout(hide, 10);
} else {
hide();
}
});
input.click(function acinputClick() {
search(input, element);
});
input.focus(function acinputFocus() {
search(input, element);
});
input.keyup(function acinputKeyup(event) {
// Ignore navigation keys
// - Ignore control functions
if (event.ctrlKey || event.which === 17) {
return;
}
// - Function keys (F1 - F15)
if (112 <= event.which && event.which <= 126) {
return;
}
switch (event.which) {
case 9: // tab
case 13: // enter
case 16: // shift
case 20: // caps lock
case 27: // esc
case 33: // page up
case 34: // page down
case 35: // end
case 36: // home
case 37: // arrows
case 38:
case 39:
case 40:
case 45: // insert
case 144: // num lock
case 145: // scroll lock
case 19: // pause/break
return;
default:
search(input, element);
}
});
input.keydown(function acinputKeydown(event) {
// - Ignore control functions
if (event.ctrlKey || event.which === 17) {
return;
}
var position = $(this).data('selected');
switch (event.which) {
// arrow keys through items
case 38: // up key
event.preventDefault();
element.find('.item.selected').removeClass('selected');
if (position-- > 0) {
element.find('.item:eq(' + position + ')').addClass('selected');
}
$(this).data('selected', position);
break;
case 40: // down key
event.preventDefault();
if (element.hasClass(options.hidingClass)) {
search(input, element);
} else if (position < input.data('length') - 1) {
position++;
element.find('.item.selected').removeClass('selected');
element.find('.item:eq(' + position + ')').addClass('selected');
$(this).data('selected', position);
}
break;
// enter to nav or populate
case 9:
case 13:
var selected = element.find('.item.selected');
if (selected.length > 0) {
event.preventDefault();
if (event.which === 13 && selected.attr('href')) {
window.location.assign(selected.attr('href'));
} else {
populate(selected.data(), $(this), {key: true});
element.find('.item.selected').removeClass('selected');
$(this).data('selected', -1);
}
}
break;
// hide on escape
case 27:
hide();
$(this).data('selected', -1);
break;
}
});
window.addEventListener("resize", hide, false);
return element;
}
$.fn.autocomplete = function acJQuery(settings) {
return this.each(function acJQueryEach() {
var input = $(this);
if (typeof settings === "string") {
if (settings === "show") {
show();
align(input);
} else if (settings === "hide") {
hide();
} else if (options.cache && settings === "clear cache") {
var cid = parseInt(input.data('cache-id'), 10);
cache[cid] = {};
}
return input;
} else if (typeof settings.handler === 'undefined' && typeof settings.static === 'undefined') {
console.error('Neither handler function nor static result list provided for autocomplete');
return this;
} else {
if (typeof settings.static !== 'undefined') {
// Preprocess strings into items
settings.static = settings.static.map(function preprocessStatic(_item) {
var item = typeof _item === 'string'
? { value: _item }
: _item;
item.match = (item.label || item.value).toLowerCase();
return item;
});
}
options = $.extend( {}, options, settings );
setup(input);
}
return input;
});
};
var timer = false;
$.fn.autocomplete.ajax = function acAjax(ops) {
if (timer) { clearTimeout(timer); }
if (xhr) { xhr.abort(); }
timer = setTimeout(
function acajaxDelay() { xhr = $.ajax(ops); },
options.ajaxDelay
);
};
}( jQuery ));
| CARLI/vufind | themes/bootstrap3/js/lib/autocomplete.js | JavaScript | gpl-2.0 | 8,954 |
var http = require('http');
var querystring = require('querystring');
var multipart = require('multipart');
function writeResponse(res, data) {
var total = 0;
for (fruit in data) {
total += Number(data[fruit]);
}
res.writeHead(200, "OK", {
"Content-Type": "text/html",
"Access-Control-Allow-Origin": "http://localhost"});
// res.write('<html><head><meta charset="UTF-8"><title>Sztuk razem</title></head><body>');
res.write("<?xml version='1.0'?>");
res.write("<fruitorder total='" + total + "'>");
for (fruit in data) {
res.write("<item name='" + fruit + "' quantity='" + data[fruit] + "'/>");
total += Number(data[fruit]);
}
res.write("</fruitorder>");
res.end();
}
http.createServer(function(req, res) {
console.log("[200] " + req.method + " to " + req.url);
if (req.method == 'OPTIONS') {
res.writeHead(200, "OK", {
"Access-Control-Allow-Headers": "Content-Type",
"Access-Control-Allow-Methods": "*",
"Access-Control-Allow-Origin": "*"
});
res.end();
} else if (req.url == "/form" && req.method == 'POST') {
var dataObj = new Object();
var contentType = req.headers["content-type"];
var fullBody = '';
if (contentType) {
if (contentType.indexOf("application/x-www-form-urlencoded") > -1) {
req.on('data', function(chunk) {
fullBody += chunk.toString();
});
req.on('end', function() {
var dBody = querystring.parse(fullBody);
dataObj.bananas = dBody["bananas"];
dataObj.appless = dBody["apples"];
dataObj.cherries = dBody["cherries"];
writeResponse(res, dataObj);
});
} else if (contentType.indexOf("application/json") > -1) {
req.on('data', function(chunk) {
fullBody += chunk.toString();
});
req.on('end', function() {
dataObj = JSON.parse(fullBody);
writeResponse(res, dataObj);
});
} else if (contentType.indexOf("multipart/form-data") > -1) {
var partName;
var partType;
var parser = multipart.parser();
parser.boundary = "--" + req.headers["content-type"].substring(30);
parser.onpartbegin = function(part) {
partName = part.name;
partType = part.contentType
};
parser.ondata = function(data) {
if (partName != "file") {
dataObj[partName] = data;
}
};
req.on('data', function(chunk) {
parser.write(chunk);
});
req.on('end', function() {
writeResponse(res, dataObj);
});
}
}
}
}).listen(8080);
| JedrzMar/avr | ch33 - ajax/13 - xml.js | JavaScript | gpl-2.0 | 2,428 |
/**
* Overscroll v1.6.3
* A jQuery Plugin that emulates the iPhone scrolling experience in a browser.
* http://azoffdesign.com/overscroll
*
* Intended for use with the latest jQuery
* http://code.jquery.com/jquery-latest.js
*
* Copyright 2012, Jonathan Azoff
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*
* For API documentation, see the README file
* http://azof.fr/pYCzuM
*
* Date: Thursday, May 17th 2012
*/
/*jslint onevar: true, strict: true */
/*global window, document, setTimeout, clearTimeout, jQuery */
(function(global, dom, browser, math, wait, cancel, namespace, $, none){
// We want to run this plug-in in strict-mode
// so that we may benefit from any optimizations
// strict execution
'use strict';
// The key used to bind-instance specific data to an object
var datakey = 'overscroll',
// runs feature detection for overscroll
compat = (function(){
var b = $.browser, fallback,
agent = browser.userAgent,
style = dom.createElement(datakey).style,
prefix = b.webkit ? 'webkit' : (b.mozilla ? 'moz' : (b.msie ? 'ms' : (b.opera ? 'o' : ''))),
cssprefix = prefix ? ['-','-'].join(prefix) : '';
compat = { prefix: prefix, overflowScrolling: false };
$.each(prefix ? [prefix, ''] : [prefix], function(i, prefix){
var animator = prefix ? (prefix + 'RequestAnimationFrame') : 'requestAnimationFrame',
scroller = prefix ? (prefix + 'OverflowScrolling') : 'overflowScrolling';
// check to see if requestAnimationFrame is available
if (global[animator] !== none) {
compat.animate = function(callback){
global[animator].call(global, callback);
};
}
// check to see if overflowScrolling is available
if (style[scroller] !== none) {
// Chrome 19 introduced overflow scrolling. Unfortunately, their touch
// implementation is incomplete. Hence, we act like it is not supported
// for chrome. #59
if (agent.indexOf('Chrome') < 0) {
compat.overflowScrolling = cssprefix + 'overflow-scrolling';
}
}
});
// check to see if the client supports touch
compat.touchEvents = 'ontouchstart' in global;
// fallback to set timeout for no animation support
if (!compat.animate) {
compat.animate = function(callback) {
wait(callback, 1000/60);
};
}
// firefox and webkit browsers support native grabbing cursors
if (prefix === 'moz' || prefix === 'webkit') {
compat.cursorGrab = cssprefix + 'grab';
compat.cursorGrabbing = cssprefix + 'grabbing';
// other browsers can user google's assets
} else {
fallback = 'https://mail.google.com/mail/images/2/';
compat.cursorGrab = 'url('+fallback+'openhand.cur), default';
compat.cursorGrabbing = 'url('+fallback+'closedhand.cur), default';
}
return compat;
})(),
// These are all the events that could possibly
// be used by the plug-in
events = {
drag: 'mousemove touchmove',
end: 'mouseup mouseleave click touchend touchcancel',
hover: 'mouseenter mouseleave',
ignored: 'select dragstart drag',
scroll: 'scroll',
start: 'mousedown touchstart',
wheel: 'mousewheel DOMMouseScroll'
},
// These settings are used to tweak drift settings
// for the plug-in
settings = {
captureThreshold: 3,
driftDecay: 1.1,
driftSequences: 22,
driftTimeout: 100,
scrollDelta: 15,
thumbOpacity: 0.7,
thumbThickness: 6,
thumbTimeout: 400,
wheelDelta: 20
},
// These defaults are used to complement any options
// passed into the plug-in entry point
defaults = {
cancelOn: '',
direction: 'multi',
dragHold: false,
hoverThumbs: false,
scrollDelta: settings.scrollDelta,
showThumbs: true,
persistThumbs: false,
wheelDelta: settings.wheelDelta,
wheelDirection: 'vertical',
zIndex: 999
},
// Triggers a DOM event on the overscrolled element.
// All events are namespaced under the overscroll name
triggerEvent = function (event, target) {
target.trigger('overscroll:' + event);
},
// Utility function to return a timestamp
time = function() {
return (new Date()).getTime();
},
// Captures the position from an event, modifies the properties
// of the second argument to persist the position, and then
// returns the modified object
capturePosition = function (event, position, index) {
position.x = event.pageX;
position.y = event.pageY;
position.time = time();
position.index = index;
return position;
},
// Used to move the thumbs around an overscrolled element
moveThumbs = function (thumbs, sizing, left, top) {
var ml, mt;
if (thumbs && thumbs.added) {
if (thumbs.horizontal) {
ml = left * (1 + sizing.container.width / sizing.container.scrollWidth);
mt = top + sizing.thumbs.horizontal.top;
thumbs.horizontal.css('margin', mt + 'px 0 0 ' + ml + 'px');
}
if (thumbs.vertical) {
ml = left + sizing.thumbs.vertical.left;
mt = top * (1 + sizing.container.height / sizing.container.scrollHeight);
thumbs.vertical.css('margin', mt + 'px 0 0 ' + ml + 'px');
}
}
},
// Used to toggle the thumbs on and off
// of an overscrolled element
toggleThumbs = function (thumbs, options, dragging) {
if (thumbs && thumbs.added && !options.persistThumbs) {
if (dragging) {
if (thumbs.vertical) {
thumbs.vertical.stop(true, true).fadeTo('fast', settings.thumbOpacity);
}
if (thumbs.horizontal) {
thumbs.horizontal.stop(true, true).fadeTo('fast', settings.thumbOpacity);
}
} else {
if (thumbs.vertical) {
thumbs.vertical.fadeTo('fast', 0);
}
if (thumbs.horizontal) {
thumbs.horizontal.fadeTo('fast', 0);
}
}
}
},
// Defers click event listeners to after a mouseup event.
// Used to avoid unintentional clicks
deferClick = function (target) {
var events = target.data('events'),
click = events && events.click ? events.click.slice() : [];
if (events) { delete events.click; }
target.one('mouseup touchend touchcancel', function () {
$.each(click, function(i, event){
target.click(event);
});
return false;
});
},
// Toggles thumbs on hover. This event is only triggered
// if the hoverThumbs option is set
hover = function (event) {
var data = event.data,
thumbs = data.thumbs,
options = data.options,
dragging = event.type === 'mouseenter';
toggleThumbs(thumbs, options, dragging);
},
// This function is only ever used when the overscrolled element
// scrolled outside of the scope of this plugin.
scroll = function (event) {
var data = event.data;
if (!data.flags.dragged) {
moveThumbs(data.thumbs, data.sizing, this.scrollLeft, this.scrollTop);
}
},
// handles mouse wheel scroll events
wheel = function (event) {
// prevent any default wheel behavior
event.preventDefault();
var data = event.data,
options = data.options,
sizing = data.sizing,
thumbs = data.thumbs,
wheel = data.wheel,
flags = data.flags, delta,
original = event.originalEvent;
// stop any drifts
flags.drifting = false;
// calculate how much to move the viewport by
// TODO: let's base this on some fact somewhere...
if (original.wheelDelta) {
delta = original.wheelDelta / (compat.prefix === 'o' ? -120 : 120);
} if (original.detail) {
delta = -original.detail / 3;
} delta *= options.wheelDelta;
// initialize flags if this is the first tick
if (!wheel) {
data.target.data(datakey).dragging = flags.dragging = true;
data.wheel = wheel = { timeout: null };
toggleThumbs(thumbs, options, true);
}
// actually modify scroll offsets
if (options.wheelDirection === 'horizontal') {
this.scrollLeft -= delta;
} else {
this.scrollTop -= delta;
}
if (wheel.timeout) { cancel(wheel.timeout); }
moveThumbs(thumbs, sizing, this.scrollLeft, this.scrollTop);
wheel.timeout = wait(function() {
data.target.data(datakey).dragging = flags.dragging = false;
toggleThumbs(thumbs, options, data.wheel = null);
}, settings.thumbTimeout);
},
// updates the current scroll offset during a mouse move
drag = function (event) {
event.preventDefault();
var data = event.data,
touches = event.originalEvent.touches,
options = data.options,
sizing = data.sizing,
thumbs = data.thumbs,
position = data.position,
flags = data.flags,
target = data.target.get(0);
// correct page coordinates for touch devices
if (compat.touchEvents && touches && touches.length) {
event = touches[0];
}
if (!flags.dragged) {
toggleThumbs(thumbs, options, true);
}
flags.dragged = true;
if (options.direction !== 'vertical') {
target.scrollLeft -= (event.pageX - position.x);
}
if (data.options.direction !== 'horizontal') {
target.scrollTop -= (event.pageY - position.y);
}
capturePosition(event, data.position);
if (--data.capture.index <= 0) {
data.target.data(datakey).dragging = flags.dragging = true;
capturePosition(event, data.capture, settings.captureThreshold);
}
moveThumbs(thumbs, sizing, target.scrollLeft, target.scrollTop);
triggerEvent('dragging', data.target);
},
// sends the overscrolled element into a drift
drift = function (target, event, callback) {
var data = event.data, dx, dy, xMod, yMod,
capture = data.capture,
options = data.options,
sizing = data.sizing,
thumbs = data.thumbs,
elapsed = time() - capture.time,
scrollLeft = target.scrollLeft,
scrollTop = target.scrollTop,
decay = settings.driftDecay;
// only drift if enough time has passed since
// the last capture event
if (elapsed > settings.driftTimeout) {
return callback(data);
}
// determine offset between last capture and current time
dx = options.scrollDelta * (event.pageX - capture.x);
dy = options.scrollDelta * (event.pageY - capture.y);
// update target scroll offsets
if (options.direction !== 'vertical') {
scrollLeft -= dx;
} if (options.direction !== 'horizontal') {
scrollTop -= dy;
}
// split the distance to travel into a set of sequences
xMod = dx / settings.driftSequences;
yMod = dy / settings.driftSequences;
triggerEvent('driftstart', data.target);
data.drifting = true;
// animate the drift sequence
compat.animate(function render() {
if (data.drifting) {
var min = 1, max = -1;
data.drifting = false;
if (yMod > min && target.scrollTop > scrollTop || yMod < max && target.scrollTop < scrollTop) {
data.drifting = true;
target.scrollTop -= yMod;
yMod /= decay;
}
if (xMod > min && target.scrollLeft > scrollLeft || xMod < max && target.scrollLeft < scrollLeft) {
data.drifting = true;
target.scrollLeft -= xMod;
xMod /= decay;
}
moveThumbs(thumbs, sizing, target.scrollLeft, target.scrollTop);
compat.animate(render);
triggerEvent('drifting', data.target);
} else {
triggerEvent('driftend', data.target);
callback(data);
}
});
},
// starts the drag operation and binds the mouse move handler
start = function (event) {
var data = event.data,
target = data.target,
start = data.start = $(event.target),
flags = data.flags;
// stop any drifts
flags.drifting = false;
// only start drag if the user has not explictly banned it.
if (start.size() && !start.is(data.options.cancelOn)) {
// without this the simple "click" event won't be recognized on touch clients
if (!compat.touchEvents) {
event.preventDefault();
}
target.css('cursor', compat.cursorGrabbing);
target.data(datakey).dragging = flags.dragging = flags.dragged = false;
// apply the drag listeners to the doc or target
if(data.options.dragHold) {
$(document).on(events.drag, data, drag);
} else {
target.on(events.drag, data, drag);
}
data.position = capturePosition(event, {});
data.capture = capturePosition(event, {}, settings.captureThreshold);
triggerEvent('dragstart', target);
}
},
// ends the drag operation and unbinds the mouse move handler
stop = function (event) {
var data = event.data,
target = data.target,
options = data.options,
flags = data.flags,
thumbs = data.thumbs,
// hides the thumbs after the animation is done
done = function () {
if (thumbs && !options.hoverThumbs) {
toggleThumbs(thumbs, options, false);
}
};
// remove drag listeners from doc or target
if(options.dragHold) {
$(document).unbind(events.drag, drag);
} else {
target.unbind(events.drag, drag);
}
// only fire events and drift if we started with a
// valid position
if (data.position) {
triggerEvent('dragend', target);
// only drift if a drag passed our threshold
if (flags.dragging) {
drift(target.get(0), event, done);
} else {
done();
}
}
// only if we moved, and the mouse down is the same as
// the mouse up target do we defer the event
if (flags.dragging && data.start.is(event.target)) {
deferClick(data.start);
}
// clear all internal flags and settings
target.data(datakey).dragging =
data.start =
data.capture =
data.position =
flags.dragged =
flags.dragging = false;
// set the cursor back to normal
target.css('cursor', compat.cursorGrab);
},
// Ensures that a full set of options are provided
// for the plug-in. Also does some validation
getOptions = function(options) {
// fill in missing values with defaults
options = $.extend({}, defaults, options);
// check for inconsistent directional restrictions
if (options.direction !== 'multi' && options.direction !== options.wheelDirection) {
options.wheelDirection = options.direction;
}
// ensure positive values for deltas
options.scrollDelta = math.abs(options.scrollDelta);
options.wheelDelta = math.abs(options.wheelDelta);
// fix values for scroll offset
options.scrollLeft = options.scrollLeft === none ? null : math.abs(options.scrollLeft);
options.scrollTop = options.scrollTop === none ? null : math.abs(options.scrollTop);
return options;
},
// Returns the sizing information (bounding box) for the
// target DOM element
getSizing = function (target) {
var $target = $(target),
width = $target.width(),
height = $target.height(),
scrollWidth = width >= target.scrollWidth ? width : target.scrollWidth,
scrollHeight = height >= target.scrollHeight ? height : target.scrollHeight,
hasScroll = scrollWidth > width || scrollHeight > height;
return {
valid: hasScroll,
container: {
width: width,
height: height,
scrollWidth: scrollWidth,
scrollHeight: scrollHeight
},
thumbs: {
horizontal: {
width: width * width / scrollWidth,
height: settings.thumbThickness,
corner: settings.thumbThickness / 2,
left: 0,
top: height - settings.thumbThickness
},
vertical: {
width: settings.thumbThickness,
height: height * height / scrollHeight,
corner: settings.thumbThickness / 2,
left: width - settings.thumbThickness,
top: 0
}
}
};
},
// Attempts to get (or implicitly creates) the
// remover function for the target passed
// in as an argument
getRemover = function (target, orCreate) {
var $target = $(target), thumbs,
data = $target.data(datakey) || {},
style = $target.attr('style'),
fallback = orCreate ? function () {
data = $target.data(datakey);
thumbs = data.thumbs;
// restore original styles (if any)
if (style) {
$target.attr('style', style);
} else {
$target.removeAttr('style');
}
// remove any created thumbs
if (thumbs) {
if (thumbs.horizontal) { thumbs.horizontal.remove(); }
if (thumbs.vertical) { thumbs.vertical.remove(); }
}
// remove any bound overscroll events and data
$target
.removeData(datakey)
.off(events.wheel, wheel)
.off(events.start, start)
.off(events.end, stop)
.off(events.ignored, false);
} : $.noop;
return $.isFunction(data.remover) ? data.remover : fallback;
},
// Genterates CSS specific to a particular thumb.
// It requires sizing data and options
getThumbCss = function(size, options) {
return {
position: 'absolute',
opacity: options.persistThumbs ? settings.thumbOpacity : 0,
'background-color': 'black',
width: size.width + 'px',
height: size.height + 'px',
'border-radius': size.corner + 'px',
'margin': size.top + 'px 0 0 ' + size.left + 'px',
'z-index': options.zIndex
};
},
// Creates the DOM elements used as "thumbs" within
// the target container.
createThumbs = function(target, sizing, options) {
var div = '<div/>',
thumbs = {},
css = false;
if (sizing.container.scrollWidth > 0 && options.direction !== 'vertical') {
css = getThumbCss(sizing.thumbs.horizontal, options);
thumbs.horizontal = $(div).css(css).prependTo(target);
}
if (sizing.container.scrollHeight > 0 && options.direction !== 'horizontal') {
css = getThumbCss(sizing.thumbs.vertical, options);
thumbs.vertical = $(div).css(css).prependTo(target);
}
thumbs.added = !!css;
return thumbs;
},
// This function takes a jQuery element, some
// (optional) options, and sets up event metadata
// for each instance the plug-in affects
setup = function(target, options) {
// create initial data properties for this instance
options = getOptions(options);
var sizing = getSizing(target),
thumbs, data = {
options: options, sizing: sizing,
flags: { dragging: false },
remover: getRemover(target, true)
};
// only apply handlers if the overscrolled element
// actually has an area to scroll
if (sizing.valid) {
// provide a circular-reference, enable events, and
// apply any required CSS
data.target = target = $(target).css({
position: 'relative',
overflow: 'hidden',
cursor: compat.cursorGrab
}).on(events.wheel, data, wheel)
.on(events.start, data, start)
.on(events.end, data, stop)
.on(events.scroll, data, scroll)
.on(events.ignored, false);
// apply the stop listeners for drag end
if(options.dragHold) {
$(document).on(events.end, data, stop);
} else {
data.target.on(events.end, data, stop);
}
// apply any user-provided scroll offsets
if (options.scrollLeft !== null) {
target.scrollLeft(options.scrollLeft);
} if (options.scrollTop !== null) {
target.scrollTop(options.scrollTop);
}
// add thumbs and listeners (if we're showing them)
if (options.showThumbs) {
data.thumbs = thumbs = createThumbs(target, sizing, options);
if (thumbs.added) {
moveThumbs(thumbs, sizing, target.scrollLeft(), target.scrollTop());
if (options.hoverThumbs) {
target.on(events.hover, data, hover);
}
}
}
target.data(datakey, data);
}
},
// Removes any event listeners and other instance-specific
// data from the target. It attempts to leave the target
// at the state it found it.
teardown = function(target) {
getRemover(target)();
},
// This is the entry-point for enabling the plug-in;
// You can find it's exposure point at the end
// of this closure
overscroll = function(options) {
return this.removeOverscroll().each(function() {
setup(this, options);
});
},
// This function applies touch-specific CSS to enable
// the behavior that Overscroll emulates. This function
// is called instead of overscroll if the device supports
// it
touchscroll = function() {
return this.removeOverscroll().each(function() {
$(this).data(datakey, { remover: getRemover(this) })
.css(compat.overflowScrolling, 'touch')
.css('overflow', 'auto');
});
},
// This is the entry-point for disabling the plug-in;
// You can find it's exposure point at the end
// of this closure
removeOverscroll = function() {
return this.each(function () {
teardown(this);
});
};
// Extend overscroll to expose settings to the user
overscroll.settings = settings;
// Extend jQuery's prototype to expose the plug-in.
// If the supports native overflowScrolling, overscroll will not
// attempt to override the browser's built in support
$.extend(namespace, {
overscroll: compat.overflowScrolling ? touchscroll : overscroll,
removeOverscroll: removeOverscroll
});
})(window, document, navigator, Math, setTimeout, clearTimeout, jQuery.fn, jQuery);
| JoelPub/wordpress-amazon | works/lincoln/themes/default/js/lib/jquery.overscroll.js | JavaScript | gpl-2.0 | 24,796 |
// #ifndef jquery
/*
* Sizzle CSS Selector Engine
* Copyright, The Dojo Foundation
* Released under the MIT, BSD, and GPL Licenses.
* More information: http://sizzlejs.com/
*/
(function(){
var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,
expando = "sizcache",
done = 0,
toString = Object.prototype.toString,
hasDuplicate = false,
baseHasDuplicate = true,
rBackslash = /\\/g,
rReturn = /\r\n/g,
rNonWord = /\W/;
// Here we check if the JavaScript engine is using some sort of
// optimization where it does not always call our comparision
// function. If that is the case, discard the hasDuplicate value.
// Thus far that includes Google Chrome.
[0, 0].sort(function() {
baseHasDuplicate = false;
return 0;
});
var Sizzle = function( selector, context, results, seed ) {
results = results || [];
context = context || document;
var origContext = context;
if ( context.nodeType !== 1 && context.nodeType !== 9 ) {
return [];
}
if ( !selector || typeof selector !== "string" ) {
return results;
}
var m, set, checkSet, extra, ret, cur, pop, i,
prune = true,
contextXML = Sizzle.isXML( context ),
parts = [],
soFar = selector;
// Reset the position of the chunker regexp (start from head)
do {
chunker.exec( "" );
m = chunker.exec( soFar );
if ( m ) {
soFar = m[3];
parts.push( m[1] );
if ( m[2] ) {
extra = m[3];
break;
}
}
} while ( m );
if ( parts.length > 1 && origPOS.exec( selector ) ) {
if ( parts.length === 2 && Expr.relative[ parts[0] ] ) {
set = posProcess( parts[0] + parts[1], context, seed );
} else {
set = Expr.relative[ parts[0] ] ?
[ context ] :
Sizzle( parts.shift(), context );
while ( parts.length ) {
selector = parts.shift();
if ( Expr.relative[ selector ] ) {
selector += parts.shift();
}
set = posProcess( selector, set, seed );
}
}
} else {
// Take a shortcut and set the context if the root selector is an ID
// (but not if it'll be faster if the inner selector is an ID)
if ( !seed && parts.length > 1 && context.nodeType === 9 && !contextXML &&
Expr.match.ID.test(parts[0]) && !Expr.match.ID.test(parts[parts.length - 1]) ) {
ret = Sizzle.find( parts.shift(), context, contextXML );
context = ret.expr ?
Sizzle.filter( ret.expr, ret.set )[0] :
ret.set[0];
}
if ( context ) {
ret = seed ?
{ expr: parts.pop(), set: makeArray(seed) } :
Sizzle.find( parts.pop(), parts.length === 1 && (parts[0] === "~" || parts[0] === "+") && context.parentNode ? context.parentNode : context, contextXML );
set = ret.expr ?
Sizzle.filter( ret.expr, ret.set ) :
ret.set;
if ( parts.length > 0 ) {
checkSet = makeArray( set );
} else {
prune = false;
}
while ( parts.length ) {
cur = parts.pop();
pop = cur;
if ( !Expr.relative[ cur ] ) {
cur = "";
} else {
pop = parts.pop();
}
if ( pop == null ) {
pop = context;
}
Expr.relative[ cur ]( checkSet, pop, contextXML );
}
} else {
checkSet = parts = [];
}
}
if ( !checkSet ) {
checkSet = set;
}
if ( !checkSet ) {
Sizzle.error( cur || selector );
}
if ( toString.call(checkSet) === "[object Array]" ) {
if ( !prune ) {
results.push.apply( results, checkSet );
} else if ( context && context.nodeType === 1 ) {
for ( i = 0; checkSet[i] != null; i++ ) {
if ( checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && Sizzle.contains(context, checkSet[i])) ) {
results.push( set[i] );
}
}
} else {
for ( i = 0; checkSet[i] != null; i++ ) {
if ( checkSet[i] && checkSet[i].nodeType === 1 ) {
results.push( set[i] );
}
}
}
} else {
makeArray( checkSet, results );
}
if ( extra ) {
Sizzle( extra, origContext, results, seed );
Sizzle.uniqueSort( results );
}
return results;
};
Sizzle.uniqueSort = function( results ) {
if ( sortOrder ) {
hasDuplicate = baseHasDuplicate;
results.sort( sortOrder );
if ( hasDuplicate ) {
for ( var i = 1; i < results.length; i++ ) {
if ( results[i] === results[ i - 1 ] ) {
results.splice( i--, 1 );
}
}
}
}
return results;
};
Sizzle.matches = function( expr, set ) {
return Sizzle( expr, null, null, set );
};
Sizzle.matchesSelector = function( node, expr ) {
return Sizzle( expr, null, null, [node] ).length > 0;
};
Sizzle.find = function( expr, context, isXML ) {
var set, i, len, match, type, left;
if ( !expr ) {
return [];
}
for ( i = 0, len = Expr.order.length; i < len; i++ ) {
type = Expr.order[i];
if ( (match = Expr.leftMatch[ type ].exec( expr )) ) {
left = match[1];
match.splice( 1, 1 );
if ( left.substr( left.length - 1 ) !== "\\" ) {
match[1] = (match[1] || "").replace( rBackslash, "" );
set = Expr.find[ type ]( match, context, isXML );
if ( set != null ) {
expr = expr.replace( Expr.match[ type ], "" );
break;
}
}
}
}
if ( !set ) {
set = typeof context.getElementsByTagName !== "undefined" ?
context.getElementsByTagName( "*" ) :
[];
}
return { set: set, expr: expr };
};
Sizzle.filter = function( expr, set, inplace, not ) {
var match, anyFound,
type, found, item, filter, left,
i, pass,
old = expr,
result = [],
curLoop = set,
isXMLFilter = set && set[0] && Sizzle.isXML( set[0] );
while ( expr && set.length ) {
for ( type in Expr.filter ) {
if ( (match = Expr.leftMatch[ type ].exec( expr )) != null && match[2] ) {
filter = Expr.filter[ type ];
left = match[1];
anyFound = false;
match.splice(1,1);
if ( left.substr( left.length - 1 ) === "\\" ) {
continue;
}
if ( curLoop === result ) {
result = [];
}
if ( Expr.preFilter[ type ] ) {
match = Expr.preFilter[ type ]( match, curLoop, inplace, result, not, isXMLFilter );
if ( !match ) {
anyFound = found = true;
} else if ( match === true ) {
continue;
}
}
if ( match ) {
for ( i = 0; (item = curLoop[i]) != null; i++ ) {
if ( item ) {
found = filter( item, match, i, curLoop );
pass = not ^ found;
if ( inplace && found != null ) {
if ( pass ) {
anyFound = true;
} else {
curLoop[i] = false;
}
} else if ( pass ) {
result.push( item );
anyFound = true;
}
}
}
}
if ( found !== undefined ) {
if ( !inplace ) {
curLoop = result;
}
expr = expr.replace( Expr.match[ type ], "" );
if ( !anyFound ) {
return [];
}
break;
}
}
}
// Improper expression
if ( expr === old ) {
if ( anyFound == null ) {
Sizzle.error( expr );
} else {
break;
}
}
old = expr;
}
return curLoop;
};
Sizzle.error = function( msg ) {
throw new Error( "Syntax error, unrecognized expression: " + msg );
};
/**
* Utility function for retreiving the text value of an array of DOM nodes
* @param {Array|Element} elem
*/
var getText = Sizzle.getText = function( elem ) {
var i, node,
nodeType = elem.nodeType,
ret = "";
if ( nodeType ) {
if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) {
// Use textContent || innerText for elements
if ( typeof elem.textContent === 'string' ) {
return elem.textContent;
} else if ( typeof elem.innerText === 'string' ) {
// Replace IE's carriage returns
return elem.innerText.replace( rReturn, '' );
} else {
// Traverse it's children
for ( elem = elem.firstChild; elem; elem = elem.nextSibling) {
ret += getText( elem );
}
}
} else if ( nodeType === 3 || nodeType === 4 ) {
return elem.nodeValue;
}
} else {
// If no nodeType, this is expected to be an array
for ( i = 0; (node = elem[i]); i++ ) {
// Do not traverse comment nodes
if ( node.nodeType !== 8 ) {
ret += getText( node );
}
}
}
return ret;
};
var Expr = Sizzle.selectors = {
order: [ "ID", "NAME", "TAG" ],
match: {
ID: /#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,
CLASS: /\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,
NAME: /\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/,
ATTR: /\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(?:(['"])(.*?)\3|(#?(?:[\w\u00c0-\uFFFF\-]|\\.)*)|)|)\s*\]/,
TAG: /^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/,
CHILD: /:(only|nth|last|first)-child(?:\(\s*(even|odd|(?:[+\-]?\d+|(?:[+\-]?\d*)?n\s*(?:[+\-]\s*\d+)?))\s*\))?/,
POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/,
PSEUDO: /:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/
},
leftMatch: {},
attrMap: {
"class": "className",
"for": "htmlFor"
},
attrHandle: {
href: function( elem ) {
return elem.getAttribute( "href" );
},
type: function( elem ) {
return elem.getAttribute( "type" );
}
},
relative: {
"+": function(checkSet, part){
var isPartStr = typeof part === "string",
isTag = isPartStr && !rNonWord.test( part ),
isPartStrNotTag = isPartStr && !isTag;
if ( isTag ) {
part = part.toLowerCase();
}
for ( var i = 0, l = checkSet.length, elem; i < l; i++ ) {
if ( (elem = checkSet[i]) ) {
while ( (elem = elem.previousSibling) && elem.nodeType !== 1 ) {}
checkSet[i] = isPartStrNotTag || elem && elem.nodeName.toLowerCase() === part ?
elem || false :
elem === part;
}
}
if ( isPartStrNotTag ) {
Sizzle.filter( part, checkSet, true );
}
},
">": function( checkSet, part ) {
var elem,
isPartStr = typeof part === "string",
i = 0,
l = checkSet.length;
if ( isPartStr && !rNonWord.test( part ) ) {
part = part.toLowerCase();
for ( ; i < l; i++ ) {
elem = checkSet[i];
if ( elem ) {
var parent = elem.parentNode;
checkSet[i] = parent.nodeName.toLowerCase() === part ? parent : false;
}
}
} else {
for ( ; i < l; i++ ) {
elem = checkSet[i];
if ( elem ) {
checkSet[i] = isPartStr ?
elem.parentNode :
elem.parentNode === part;
}
}
if ( isPartStr ) {
Sizzle.filter( part, checkSet, true );
}
}
},
"": function(checkSet, part, isXML){
var nodeCheck,
doneName = done++,
checkFn = dirCheck;
if ( typeof part === "string" && !rNonWord.test( part ) ) {
part = part.toLowerCase();
nodeCheck = part;
checkFn = dirNodeCheck;
}
checkFn( "parentNode", part, doneName, checkSet, nodeCheck, isXML );
},
"~": function( checkSet, part, isXML ) {
var nodeCheck,
doneName = done++,
checkFn = dirCheck;
if ( typeof part === "string" && !rNonWord.test( part ) ) {
part = part.toLowerCase();
nodeCheck = part;
checkFn = dirNodeCheck;
}
checkFn( "previousSibling", part, doneName, checkSet, nodeCheck, isXML );
}
},
find: {
ID: function( match, context, isXML ) {
if ( typeof context.getElementById !== "undefined" && !isXML ) {
var m = context.getElementById(match[1]);
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
return m && m.parentNode ? [m] : [];
}
},
NAME: function( match, context ) {
if ( typeof context.getElementsByName !== "undefined" ) {
var ret = [],
results = context.getElementsByName( match[1] );
for ( var i = 0, l = results.length; i < l; i++ ) {
if ( results[i].getAttribute("name") === match[1] ) {
ret.push( results[i] );
}
}
return ret.length === 0 ? null : ret;
}
},
TAG: function( match, context ) {
if ( typeof context.getElementsByTagName !== "undefined" ) {
return context.getElementsByTagName( match[1] );
}
}
},
preFilter: {
CLASS: function( match, curLoop, inplace, result, not, isXML ) {
match = " " + match[1].replace( rBackslash, "" ) + " ";
if ( isXML ) {
return match;
}
for ( var i = 0, elem; (elem = curLoop[i]) != null; i++ ) {
if ( elem ) {
if ( not ^ (elem.className && (" " + elem.className + " ").replace(/[\t\n\r]/g, " ").indexOf(match) >= 0) ) {
if ( !inplace ) {
result.push( elem );
}
} else if ( inplace ) {
curLoop[i] = false;
}
}
}
return false;
},
ID: function( match ) {
return match[1].replace( rBackslash, "" );
},
TAG: function( match, curLoop ) {
return match[1].replace( rBackslash, "" ).toLowerCase();
},
CHILD: function( match ) {
if ( match[1] === "nth" ) {
if ( !match[2] ) {
Sizzle.error( match[0] );
}
match[2] = match[2].replace(/^\+|\s*/g, '');
// parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6'
var test = /(-?)(\d*)(?:n([+\-]?\d*))?/.exec(
match[2] === "even" && "2n" || match[2] === "odd" && "2n+1" ||
!/\D/.test( match[2] ) && "0n+" + match[2] || match[2]);
// calculate the numbers (first)n+(last) including if they are negative
match[2] = (test[1] + (test[2] || 1)) - 0;
match[3] = test[3] - 0;
}
else if ( match[2] ) {
Sizzle.error( match[0] );
}
// TODO: Move to normal caching system
match[0] = done++;
return match;
},
ATTR: function( match, curLoop, inplace, result, not, isXML ) {
var name = match[1] = match[1].replace( rBackslash, "" );
if ( !isXML && Expr.attrMap[name] ) {
match[1] = Expr.attrMap[name];
}
// Handle if an un-quoted value was used
match[4] = ( match[4] || match[5] || "" ).replace( rBackslash, "" );
if ( match[2] === "~=" ) {
match[4] = " " + match[4] + " ";
}
return match;
},
PSEUDO: function( match, curLoop, inplace, result, not ) {
if ( match[1] === "not" ) {
// If we're dealing with a complex expression, or a simple one
if ( ( chunker.exec(match[3]) || "" ).length > 1 || /^\w/.test(match[3]) ) {
match[3] = Sizzle(match[3], null, null, curLoop);
} else {
var ret = Sizzle.filter(match[3], curLoop, inplace, true ^ not);
if ( !inplace ) {
result.push.apply( result, ret );
}
return false;
}
} else if ( Expr.match.POS.test( match[0] ) || Expr.match.CHILD.test( match[0] ) ) {
return true;
}
return match;
},
POS: function( match ) {
match.unshift( true );
return match;
}
},
filters: {
enabled: function( elem ) {
return elem.disabled === false && elem.type !== "hidden";
},
disabled: function( elem ) {
return elem.disabled === true;
},
checked: function( elem ) {
return elem.checked === true;
},
selected: function( elem ) {
// Accessing this property makes selected-by-default
// options in Safari work properly
if ( elem.parentNode ) {
elem.parentNode.selectedIndex;
}
return elem.selected === true;
},
parent: function( elem ) {
return !!elem.firstChild;
},
empty: function( elem ) {
return !elem.firstChild;
},
has: function( elem, i, match ) {
return !!Sizzle( match[3], elem ).length;
},
header: function( elem ) {
return (/h\d/i).test( elem.nodeName );
},
text: function( elem ) {
var attr = elem.getAttribute( "type" ), type = elem.type;
// IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc)
// use getAttribute instead to test this case
return elem.nodeName.toLowerCase() === "input" && "text" === type && ( attr === type || attr === null );
},
radio: function( elem ) {
return elem.nodeName.toLowerCase() === "input" && "radio" === elem.type;
},
checkbox: function( elem ) {
return elem.nodeName.toLowerCase() === "input" && "checkbox" === elem.type;
},
file: function( elem ) {
return elem.nodeName.toLowerCase() === "input" && "file" === elem.type;
},
password: function( elem ) {
return elem.nodeName.toLowerCase() === "input" && "password" === elem.type;
},
submit: function( elem ) {
var name = elem.nodeName.toLowerCase();
return (name === "input" || name === "button") && "submit" === elem.type;
},
image: function( elem ) {
return elem.nodeName.toLowerCase() === "input" && "image" === elem.type;
},
reset: function( elem ) {
var name = elem.nodeName.toLowerCase();
return (name === "input" || name === "button") && "reset" === elem.type;
},
button: function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && "button" === elem.type || name === "button";
},
input: function( elem ) {
return (/input|select|textarea|button/i).test( elem.nodeName );
},
focus: function( elem ) {
return elem === elem.ownerDocument.activeElement;
}
},
setFilters: {
first: function( elem, i ) {
return i === 0;
},
last: function( elem, i, match, array ) {
return i === array.length - 1;
},
even: function( elem, i ) {
return i % 2 === 0;
},
odd: function( elem, i ) {
return i % 2 === 1;
},
lt: function( elem, i, match ) {
return i < match[3] - 0;
},
gt: function( elem, i, match ) {
return i > match[3] - 0;
},
nth: function( elem, i, match ) {
return match[3] - 0 === i;
},
eq: function( elem, i, match ) {
return match[3] - 0 === i;
}
},
filter: {
PSEUDO: function( elem, match, i, array ) {
var name = match[1],
filter = Expr.filters[ name ];
if ( filter ) {
return filter( elem, i, match, array );
} else if ( name === "contains" ) {
return (elem.textContent || elem.innerText || getText([ elem ]) || "").indexOf(match[3]) >= 0;
} else if ( name === "not" ) {
var not = match[3];
for ( var j = 0, l = not.length; j < l; j++ ) {
if ( not[j] === elem ) {
return false;
}
}
return true;
} else {
Sizzle.error( name );
}
},
CHILD: function( elem, match ) {
var first, last,
doneName, parent, cache,
count, diff,
type = match[1],
node = elem;
switch ( type ) {
case "only":
case "first":
while ( (node = node.previousSibling) ) {
if ( node.nodeType === 1 ) {
return false;
}
}
if ( type === "first" ) {
return true;
}
node = elem;
/* falls through */
case "last":
while ( (node = node.nextSibling) ) {
if ( node.nodeType === 1 ) {
return false;
}
}
return true;
case "nth":
first = match[2];
last = match[3];
if ( first === 1 && last === 0 ) {
return true;
}
doneName = match[0];
parent = elem.parentNode;
if ( parent && (parent[ expando ] !== doneName || !elem.nodeIndex) ) {
count = 0;
for ( node = parent.firstChild; node; node = node.nextSibling ) {
if ( node.nodeType === 1 ) {
node.nodeIndex = ++count;
}
}
parent[ expando ] = doneName;
}
diff = elem.nodeIndex - last;
if ( first === 0 ) {
return diff === 0;
} else {
return ( diff % first === 0 && diff / first >= 0 );
}
}
},
ID: function( elem, match ) {
return elem.nodeType === 1 && elem.getAttribute("id") === match;
},
TAG: function( elem, match ) {
return (match === "*" && elem.nodeType === 1) || !!elem.nodeName && elem.nodeName.toLowerCase() === match;
},
CLASS: function( elem, match ) {
return (" " + (elem.className || elem.getAttribute("class")) + " ")
.indexOf( match ) > -1;
},
ATTR: function( elem, match ) {
var name = match[1],
result = Sizzle.attr ?
Sizzle.attr( elem, name ) :
Expr.attrHandle[ name ] ?
Expr.attrHandle[ name ]( elem ) :
elem[ name ] != null ?
elem[ name ] :
elem.getAttribute( name ),
value = result + "",
type = match[2],
check = match[4];
return result == null ?
type === "!=" :
!type && Sizzle.attr ?
result != null :
type === "=" ?
value === check :
type === "*=" ?
value.indexOf(check) >= 0 :
type === "~=" ?
(" " + value + " ").indexOf(check) >= 0 :
!check ?
value && result !== false :
type === "!=" ?
value !== check :
type === "^=" ?
value.indexOf(check) === 0 :
type === "$=" ?
value.substr(value.length - check.length) === check :
type === "|=" ?
value === check || value.substr(0, check.length + 1) === check + "-" :
false;
},
POS: function( elem, match, i, array ) {
var name = match[2],
filter = Expr.setFilters[ name ];
if ( filter ) {
return filter( elem, i, match, array );
}
}
}
};
var origPOS = Expr.match.POS,
fescape = function(all, num){
return "\\" + (num - 0 + 1);
};
for ( var type in Expr.match ) {
Expr.match[ type ] = new RegExp( Expr.match[ type ].source + (/(?![^\[]*\])(?![^\(]*\))/.source) );
Expr.leftMatch[ type ] = new RegExp( /(^(?:.|\r|\n)*?)/.source + Expr.match[ type ].source.replace(/\\(\d+)/g, fescape) );
}
// Expose origPOS
// "global" as in regardless of relation to brackets/parens
Expr.match.globalPOS = origPOS;
var makeArray = function( array, results ) {
array = Array.prototype.slice.call( array, 0 );
if ( results ) {
results.push.apply( results, array );
return results;
}
return array;
};
// Perform a simple check to determine if the browser is capable of
// converting a NodeList to an array using builtin methods.
// Also verifies that the returned array holds DOM nodes
// (which is not the case in the Blackberry browser)
try {
Array.prototype.slice.call( document.documentElement.childNodes, 0 )[0].nodeType;
// Provide a fallback method if it does not work
} catch( e ) {
makeArray = function( array, results ) {
var i = 0,
ret = results || [];
if ( toString.call(array) === "[object Array]" ) {
Array.prototype.push.apply( ret, array );
} else {
if ( typeof array.length === "number" ) {
for ( var l = array.length; i < l; i++ ) {
ret.push( array[i] );
}
} else {
for ( ; array[i]; i++ ) {
ret.push( array[i] );
}
}
}
return ret;
};
}
var sortOrder, siblingCheck;
if ( document.documentElement.compareDocumentPosition ) {
sortOrder = function( a, b ) {
if ( a === b ) {
hasDuplicate = true;
return 0;
}
if ( !a.compareDocumentPosition || !b.compareDocumentPosition ) {
return a.compareDocumentPosition ? -1 : 1;
}
return a.compareDocumentPosition(b) & 4 ? -1 : 1;
};
} else {
sortOrder = function( a, b ) {
// The nodes are identical, we can exit early
if ( a === b ) {
hasDuplicate = true;
return 0;
// Fallback to using sourceIndex (in IE) if it's available on both nodes
} else if ( a.sourceIndex && b.sourceIndex ) {
return a.sourceIndex - b.sourceIndex;
}
var al, bl,
ap = [],
bp = [],
aup = a.parentNode,
bup = b.parentNode,
cur = aup;
// If the nodes are siblings (or identical) we can do a quick check
if ( aup === bup ) {
return siblingCheck( a, b );
// If no parents were found then the nodes are disconnected
} else if ( !aup ) {
return -1;
} else if ( !bup ) {
return 1;
}
// Otherwise they're somewhere else in the tree so we need
// to build up a full list of the parentNodes for comparison
while ( cur ) {
ap.unshift( cur );
cur = cur.parentNode;
}
cur = bup;
while ( cur ) {
bp.unshift( cur );
cur = cur.parentNode;
}
al = ap.length;
bl = bp.length;
// Start walking down the tree looking for a discrepancy
for ( var i = 0; i < al && i < bl; i++ ) {
if ( ap[i] !== bp[i] ) {
return siblingCheck( ap[i], bp[i] );
}
}
// We ended someplace up the tree so do a sibling check
return i === al ?
siblingCheck( a, bp[i], -1 ) :
siblingCheck( ap[i], b, 1 );
};
siblingCheck = function( a, b, ret ) {
if ( a === b ) {
return ret;
}
var cur = a.nextSibling;
while ( cur ) {
if ( cur === b ) {
return -1;
}
cur = cur.nextSibling;
}
return 1;
};
}
// Check to see if the browser returns elements by name when
// querying by getElementById (and provide a workaround)
(function(){
// We're going to inject a fake input element with a specified name
var form = document.createElement("div"),
id = "script" + (new Date()).getTime(),
root = document.documentElement;
form.innerHTML = "<a name='" + id + "'/>";
// Inject it into the root element, check its status, and remove it quickly
root.insertBefore( form, root.firstChild );
// The workaround has to do additional checks after a getElementById
// Which slows things down for other browsers (hence the branching)
if ( document.getElementById( id ) ) {
Expr.find.ID = function( match, context, isXML ) {
if ( typeof context.getElementById !== "undefined" && !isXML ) {
var m = context.getElementById(match[1]);
return m ?
m.id === match[1] || typeof m.getAttributeNode !== "undefined" && m.getAttributeNode("id").nodeValue === match[1] ?
[m] :
undefined :
[];
}
};
Expr.filter.ID = function( elem, match ) {
var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id");
return elem.nodeType === 1 && node && node.nodeValue === match;
};
}
root.removeChild( form );
// release memory in IE
root = form = null;
})();
(function(){
// Check to see if the browser returns only elements
// when doing getElementsByTagName("*")
// Create a fake element
var div = document.createElement("div");
div.appendChild( document.createComment("") );
// Make sure no comments are found
if ( div.getElementsByTagName("*").length > 0 ) {
Expr.find.TAG = function( match, context ) {
var results = context.getElementsByTagName( match[1] );
// Filter out possible comments
if ( match[1] === "*" ) {
var tmp = [];
for ( var i = 0; results[i]; i++ ) {
if ( results[i].nodeType === 1 ) {
tmp.push( results[i] );
}
}
results = tmp;
}
return results;
};
}
// Check to see if an attribute returns normalized href attributes
div.innerHTML = "<a href='#'></a>";
if ( div.firstChild && typeof div.firstChild.getAttribute !== "undefined" &&
div.firstChild.getAttribute("href") !== "#" ) {
Expr.attrHandle.href = function( elem ) {
return elem.getAttribute( "href", 2 );
};
}
// release memory in IE
div = null;
})();
if ( document.querySelectorAll ) {
(function(){
var oldSizzle = Sizzle,
div = document.createElement("div"),
id = "__sizzle__";
div.innerHTML = "<p class='TEST'></p>";
// Safari can't handle uppercase or unicode characters when
// in quirks mode.
if ( div.querySelectorAll && div.querySelectorAll(".TEST").length === 0 ) {
return;
}
Sizzle = function( query, context, extra, seed ) {
context = context || document;
// Only use querySelectorAll on non-XML documents
// (ID selectors don't work in non-HTML documents)
if ( !seed && !Sizzle.isXML(context) ) {
// See if we find a selector to speed up
var match = /^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec( query );
if ( match && (context.nodeType === 1 || context.nodeType === 9) ) {
// Speed-up: Sizzle("TAG")
if ( match[1] ) {
return makeArray( context.getElementsByTagName( query ), extra );
// Speed-up: Sizzle(".CLASS")
} else if ( match[2] && Expr.find.CLASS && context.getElementsByClassName ) {
return makeArray( context.getElementsByClassName( match[2] ), extra );
}
}
if ( context.nodeType === 9 ) {
// Speed-up: Sizzle("body")
// The body element only exists once, optimize finding it
if ( query === "body" && context.body ) {
return makeArray( [ context.body ], extra );
// Speed-up: Sizzle("#ID")
} else if ( match && match[3] ) {
var elem = context.getElementById( match[3] );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Handle the case where IE and Opera return items
// by name instead of ID
if ( elem.id === match[3] ) {
return makeArray( [ elem ], extra );
}
} else {
return makeArray( [], extra );
}
}
try {
return makeArray( context.querySelectorAll(query), extra );
} catch(qsaError) {}
// qSA works strangely on Element-rooted queries
// We can work around this by specifying an extra ID on the root
// and working up from there (Thanks to Andrew Dupont for the technique)
// IE 8 doesn't work on object elements
} else if ( context.nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) {
var oldContext = context,
old = context.getAttribute( "id" ),
nid = old || id,
hasParent = context.parentNode,
relativeHierarchySelector = /^\s*[+~]/.test( query );
if ( !old ) {
context.setAttribute( "id", nid );
} else {
nid = nid.replace( /'/g, "\\$&" );
}
if ( relativeHierarchySelector && hasParent ) {
context = context.parentNode;
}
try {
if ( !relativeHierarchySelector || hasParent ) {
return makeArray( context.querySelectorAll( "[id='" + nid + "'] " + query ), extra );
}
} catch(pseudoError) {
} finally {
if ( !old ) {
oldContext.removeAttribute( "id" );
}
}
}
}
return oldSizzle(query, context, extra, seed);
};
for ( var prop in oldSizzle ) {
Sizzle[ prop ] = oldSizzle[ prop ];
}
// release memory in IE
div = null;
})();
}
(function(){
var html = document.documentElement,
matches = html.matchesSelector || html.mozMatchesSelector || html.webkitMatchesSelector || html.msMatchesSelector;
if ( matches ) {
// Check to see if it's possible to do matchesSelector
// on a disconnected node (IE 9 fails this)
var disconnectedMatch = !matches.call( document.createElement( "div" ), "div" ),
pseudoWorks = false;
try {
// This should fail with an exception
// Gecko does not error, returns false instead
matches.call( document.documentElement, "[test!='']:sizzle" );
} catch( pseudoError ) {
pseudoWorks = true;
}
Sizzle.matchesSelector = function( node, expr ) {
// Make sure that attribute selectors are quoted
expr = expr.replace(/\=\s*([^'"\]]*)\s*\]/g, "='$1']");
if ( !Sizzle.isXML( node ) ) {
try {
if ( pseudoWorks || !Expr.match.PSEUDO.test( expr ) && !/!=/.test( expr ) ) {
var ret = matches.call( node, expr );
// IE 9's matchesSelector returns false on disconnected nodes
if ( ret || !disconnectedMatch ||
// As well, disconnected nodes are said to be in a document
// fragment in IE 9, so check for that
node.document && node.document.nodeType !== 11 ) {
return ret;
}
}
} catch(e) {}
}
return Sizzle(expr, null, null, [node]).length > 0;
};
}
})();
(function(){
var div = document.createElement("div");
div.innerHTML = "<div class='test e'></div><div class='test'></div>";
// Opera can't find a second classname (in 9.6)
// Also, make sure that getElementsByClassName actually exists
if ( !div.getElementsByClassName || div.getElementsByClassName("e").length === 0 ) {
return;
}
// Safari caches class attributes, doesn't catch changes (in 3.2)
div.lastChild.className = "e";
if ( div.getElementsByClassName("e").length === 1 ) {
return;
}
Expr.order.splice(1, 0, "CLASS");
Expr.find.CLASS = function( match, context, isXML ) {
if ( typeof context.getElementsByClassName !== "undefined" && !isXML ) {
return context.getElementsByClassName(match[1]);
}
};
// release memory in IE
div = null;
})();
function dirNodeCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) {
for ( var i = 0, l = checkSet.length; i < l; i++ ) {
var elem = checkSet[i];
if ( elem ) {
var match = false;
elem = elem[dir];
while ( elem ) {
if ( elem[ expando ] === doneName ) {
match = checkSet[elem.sizset];
break;
}
if ( elem.nodeType === 1 && !isXML ){
elem[ expando ] = doneName;
elem.sizset = i;
}
if ( elem.nodeName.toLowerCase() === cur ) {
match = elem;
break;
}
elem = elem[dir];
}
checkSet[i] = match;
}
}
}
function dirCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) {
for ( var i = 0, l = checkSet.length; i < l; i++ ) {
var elem = checkSet[i];
if ( elem ) {
var match = false;
elem = elem[dir];
while ( elem ) {
if ( elem[ expando ] === doneName ) {
match = checkSet[elem.sizset];
break;
}
if ( elem.nodeType === 1 ) {
if ( !isXML ) {
elem[ expando ] = doneName;
elem.sizset = i;
}
if ( typeof cur !== "string" ) {
if ( elem === cur ) {
match = true;
break;
}
} else if ( Sizzle.filter( cur, [elem] ).length > 0 ) {
match = elem;
break;
}
}
elem = elem[dir];
}
checkSet[i] = match;
}
}
}
if ( document.documentElement.contains ) {
Sizzle.contains = function( a, b ) {
return a !== b && (a.contains ? a.contains(b) : true);
};
} else if ( document.documentElement.compareDocumentPosition ) {
Sizzle.contains = function( a, b ) {
return !!(a.compareDocumentPosition(b) & 16);
};
} else {
Sizzle.contains = function() {
return false;
};
}
Sizzle.isXML = function( elem ) {
// documentElement is verified for cases where it doesn't yet exist
// (such as loading iframes in IE - #4833)
var documentElement = (elem ? elem.ownerDocument || elem : 0).documentElement;
return documentElement ? documentElement.nodeName !== "HTML" : false;
};
var posProcess = function( selector, context, seed ) {
var match,
tmpSet = [],
later = "",
root = context.nodeType ? [context] : context;
// Position selectors must be done after the filter
// And so must :not(positional) so we move all PSEUDOs to the end
while ( (match = Expr.match.PSEUDO.exec( selector )) ) {
later += match[0];
selector = selector.replace( Expr.match.PSEUDO, "" );
}
selector = Expr.relative[selector] ? selector + "*" : selector;
for ( var i = 0, l = root.length; i < l; i++ ) {
Sizzle( selector, root[i], tmpSet, seed );
}
return Sizzle.filter( later, tmpSet );
};
// EXPOSE
window.tinymce.dom.Sizzle = Sizzle;
})();
// #endif
| alafon/ezpublish-community-built | ezpublish_legacy/extension/ezoe/design/standard/javascript/classes/dom/Sizzle.js | JavaScript | gpl-2.0 | 57,974 |
'use strict';
module.exports = function (grunt) {
// Time how long tasks take. Can help when optimizing build times
require('time-grunt')(grunt);
// Automatically load required grunt tasks
require('jit-grunt')(grunt, {
lockfile: 'grunt-lock'
});
// Configurable paths
var config = {
sass_dir: 'bundle/Resources/sass/admin',
public_dir: 'bundle/Resources/public/admin'
};
// Define the configuration for all the tasks
grunt.initConfig({
// Project settings
config: config,
//Prevent multiple grunt instances
lockfile: {
grunt: {
path: 'grunt.lock'
}
},
// Watches files for changes and runs tasks based on the changed files
watch: {
gruntfile: {
files: ['Gruntfile.js'],
options: {
reload: true
}
},
sass: {
files: ['<%= config.sass_dir %>/{,*/}*.{scss,sass}'],
tasks: ['sass', 'postcss']
}
},
// Compiles Sass to CSS and generates necessary files if requested
sass: {
options: {
sourceMap: true,
sourceMapEmbed: true,
sourceMapContents: true,
includePaths: ['.']
},
dist: {
files: [{
expand: true,
cwd: '<%= config.sass_dir %>',
src: ['*.{scss,sass}'],
dest: '.tmp/css',
ext: '.css'
}]
}
},
postcss: {
options: {
map: true,
processors: [
// Add vendor prefixed styles
require('autoprefixer')({
browsers: ['> 1%', 'last 3 versions', 'Firefox ESR', 'Opera 12.1']
})
]
},
dist: {
files: [{
expand: true,
cwd: '.tmp/css/',
src: '{,*/}*.css',
dest: '<%= config.public_dir %>/css'
}]
}
}
});
grunt.registerTask('serve', 'Start the server and preview your app', function () {
grunt.task.run([
'lockfile',
'sass:dist',
'postcss',
'watch'
]);
});
grunt.registerTask('default', [
'serve'
]);
};
| wizhippo/TagsBundle | Gruntfile.js | JavaScript | gpl-2.0 | 2,579 |
// +------------------------------------------------------------------+
// | ____ _ _ __ __ _ __ |
// | / ___| |__ ___ ___| | __ | \/ | |/ / |
// | | | | '_ \ / _ \/ __| |/ / | |\/| | ' / |
// | | |___| | | | __/ (__| < | | | | . \ |
// | \____|_| |_|\___|\___|_|\_\___|_| |_|_|\_\ |
// | |
// | Copyright Mathias Kettner 2012 mk@mathias-kettner.de |
// +------------------------------------------------------------------+
//
// This file is part of Check_MK.
// The official homepage is at http://mathias-kettner.de/check_mk.
//
// check_mk is free software; you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by
// the Free Software Foundation in version 2. check_mk is distributed
// in the hope that it will be useful, but WITHOUT ANY WARRANTY; with-
// out even the implied warranty of MERCHANTABILITY or FITNESS FOR A
// PARTICULAR PURPOSE. See the GNU General Public License for more de-
// ails. You should have received a copy of the GNU General Public
// License along with GNU Make; see the file COPYING. If not, write
// to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
// Boston, MA 02110-1301 USA.
/* Disable data-ajax per default, as it makes problems in most
of our cases */
$(document).ready(function() {
$("a").attr("data-ajax", "false");
$("form").attr("data-ajax", "false");
$("div.error").addClass("ui-shadow");
$("div.success").addClass("ui-shadow");
$("div.really").addClass("ui-shadow");
$("div.warning").addClass("ui-shadow");
});
$(document).bind("mobileinit", function(){
$.mobile.ajaxEnabled = false;
$.mobile.hashListeningEnabled = false;
});
| sileht/check_mk | web/htdocs/js/mobile.js | JavaScript | gpl-2.0 | 1,933 |
(function($) {
$.fn.extend({
stickyMojo: function(options) {
// Exit if there are no elements to avoid errors:
if (this.length === 0) {
return this;
}
var settings = $.extend({
'footerID': '',
'contentID': '',
'orientation': $(this).css('float')
}, options);
var sticky = {
'el': $(this),
'stickyLeft': $(settings.contentID).outerWidth() + $(settings.contentID).offset.left,
'stickyTop2': $(this).offset().top,
'stickyHeight': $(this).outerHeight(true),
'contentHeight': $(settings.contentID).outerHeight(true),
'win': $(window),
'breakPoint': $(this).outerWidth(true) + $(settings.contentID).outerWidth(true),
'marg': parseInt($(this).css('margin-top'), 10)
};
var errors = checkSettings();
cacheElements();
return this.each(function() {
buildSticky();
});
function buildSticky() {
if (!errors.length) {
sticky.el.css('left', sticky.stickyLeft);
sticky.win.bind({
'load': stick,
'scroll': stick,
'resize': function() {
sticky.el.css('left', sticky.stickyLeft);
stick();
}
});
} else {
if (console && console.warn) {
console.warn(errors);
} else {
alert(errors);
}
}
}
// Caches the footer and content elements into jquery objects
function cacheElements() {
settings.footerID = $(settings.footerID);
settings.contentID = $(settings.contentID);
}
// Calcualtes the limits top and bottom limits for the sidebar
function calculateLimits() {
return {
limit: settings.footerID.offset().top - sticky.stickyHeight,
windowTop: sticky.win.scrollTop(),
stickyTop: sticky.stickyTop2 - sticky.marg
}
}
// Sets sidebar to fixed position
function setFixedSidebar() {
sticky.el.css({
position: 'fixed',
top: 0
});
}
// Determines the sidebar orientation and sets margins accordingly
function checkOrientation() {
if (settings.orientation === "left") {
settings.contentID.css('margin-left', sticky.el.outerWidth(true));
} else {
sticky.el.css('margin-left', settings.contentID.outerWidth(true));
}
}
// sets sidebar to a static positioned element
function setStaticSidebar() {
sticky.el.css({
'position': 'static',
'margin-left': '0px'
});
settings.contentID.css('margin-left', '0px');
}
// initiated to stop the sidebar from intersecting the footer
function setLimitedSidebar(diff) {
sticky.el.css({
top: diff
});
}
//determines whether sidebar should stick and applies appropriate settings to make it stick
function stick() {
var tops = calculateLimits();
var hitBreakPoint = tops.stickyTop < tops.windowTop && (sticky.win.width() >= sticky.breakPoint);
if (hitBreakPoint) {
setFixedSidebar();
checkOrientation();
} else {
setStaticSidebar();
}
if (tops.limit < tops.windowTop) {
var diff = tops.limit - tops.windowTop;
setLimitedSidebar(diff);
}
}
// verifies that all settings are correct
function checkSettings() {
var errors = [];
for (var key in settings) {
if (!settings[key]) {
errors.push(settings[key]);
}
}
ieVersion() && errors.push("NO IE 7");
return errors;
}
function ieVersion() {
if(document.querySelector) {
return false;
}
else {
return true;
}
}
}
});
})(jQuery);
| tittee/jarem | wp-content/themes/spalab/framework/js/public/stickyMojo.js | JavaScript | gpl-2.0 | 4,105 |
import { apiUrl } from '../../constants';
export default class DataService {
/** @ngInject */
constructor($http, $q) {
this.$http = $http;
this.$q = $q;
this.dataStore = {
categories: [],
providers: [],
resources: [],
services: [],
stages: [],
currentFilters: {
stages: [],
categories: [],
providers: [],
resources: []
}
};
}
getCategories() {
return getItems.bind(this)('categories');
}
createProvider (provider) {
return createItem.bind(this)(provider, 'providers');
}
deleteProvider (id) {
return deleteItem.bind(this)(id, 'providers');
}
getProvider(id) {
return getItem.bind(this)(id, 'providers');
}
getProviders() {
return getItems.bind(this)('providers');
}
updateProvider (provider) {
return updateItem.bind(this)(provider, 'providers');
}
createResource (resource) {
return createItem.bind(this)(resource, 'resources');
}
deleteResource (id) {
return deleteItem.bind(this)(id, 'resources');
}
getResource(id) {
return getItem.bind(this)(id, 'resources');
}
getResources() {
return getItems.bind(this)('resources');
}
updateResource (resource) {
return updateItem.bind(this)(resource, 'resources');
}
createService (service) {
return createItem.bind(this)(service, 'services');
}
deleteService(id) {
return deleteItem.bind(this)(id, 'services');
}
getService(id) {
return getItem.bind(this)(id, 'services');
}
getServices() {
return getItems.bind(this)('services');
}
updateService (service) {
return updateItem.bind(this)(service, 'services');
}
getStages() {
return getItems.bind(this)('stages');
}
resetCurrentFilters() {
return this.dataStore.currentFilters = {
stages: [],
categories: [],
providers: [],
resources: []
}
}
getNonEmptyFilters() {
const nonEmptyFilters = {};
if (this.dataStore.currentFilters.stages.length) {
nonEmptyFilters.stages = angular.copy(this.dataStore.currentFilters.stages);
}
if (this.dataStore.currentFilters.categories.length) {
nonEmptyFilters.categories = angular.copy(this.dataStore.currentFilters.categories);
}
if (this.dataStore.currentFilters.providers.length) {
nonEmptyFilters.providers = angular.copy(this.dataStore.currentFilters.providers);
}
if (this.dataStore.currentFilters.resources.length) {
nonEmptyFilters.resources = angular.copy(this.dataStore.currentFilters.resources);
}
return nonEmptyFilters;
}
}
function createItem (item, type) {
const deferred = this.$q.defer();
return this.$http.post(`${apiUrl}${type}`, item).then((response) => {
const location = response.headers().location;
const id = location.split(`/${type}/`).pop();
if (this.dataStore[type].length) {
item.id = id;
this.dataStore[type].push(item);
}
deferred.resolve(item.id);
return deferred.promise;
}, error => {
deferred.reject(error);
return deferred.promise;
});
}
function deleteItem (id, type) {
const deferred = this.$q.defer();
return this.$http.delete(`${apiUrl}${type}/${id}`).then(() => {
const index = this.dataStore[type].map((x) => {return x.id; }).indexOf(id);
this.dataStore[type].splice(index, 1);
deferred.resolve();
return deferred.promise;
}, error => {
deferred.reject(error);
return deferred.promise;
});
}
function getItem (id, type) {
const deferred = this.$q.defer();
const item = this.dataStore[type].filter(s => {
return s.id === id;
})[0];
if (item) {
deferred.resolve(item);
return deferred.promise;
}
return this.$http.get(`${apiUrl}${type}/${id}`).then(response => {
deferred.resolve(response.data);
return deferred.promise;
}, error => {
deferred.reject(error);
return deferred.promise;
});
}
function getItems (type) {
const deferred = this.$q.defer();
if (this.dataStore[type].length) {
deferred.resolve();
return deferred.promise;
}
return this.$http.get(`${apiUrl}${type}`).then(response => {
this.dataStore[type] = angular.copy(response.data._embedded[type]);
deferred.resolve();
return deferred.promise;
}, error => {
deferred.reject(error);
return deferred.promise;
});
}
function updateItem (item, type) {
const deferred = this.$q.defer();
return this.$http.put(`${apiUrl}${type}/${item.id}`, item).then(() => {
if (this.dataStore[type].length) {
const index = this.dataStore[type].map((x) => {return x.id; }).indexOf(item.id);
this.dataStore[type][index] = item;
}
deferred.resolve();
return deferred.promise;
}, error => {
deferred.reject(error);
return deferred.promise;
});
} | amyvbenson/asylumjourney-frontend | src/app/services/data.js | JavaScript | gpl-3.0 | 4,827 |
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// 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 Google Inc. 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 THE COPYRIGHT
// OWNER OR CONTRIBUTORS 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.
goog.setTestOnly();
goog.require('goog.testing.asserts');
// CommonJS-LoadFromFile: google-protobuf
goog.require('jspb.debug');
// CommonJS-LoadFromFile: test_pb
goog.require('proto.jspb.test.HasExtensions');
goog.require('proto.jspb.test.IsExtension');
goog.require('proto.jspb.test.Simple1');
describe('debugTest', function() {
it('testSimple1', function() {
if (COMPILED) {
return;
}
var message = new proto.jspb.test.Simple1();
message.setAString('foo');
assertObjectEquals({
$name: 'proto.jspb.test.Simple1',
'aString': 'foo',
'aRepeatedStringList': []
}, jspb.debug.dump(message));
message.setABoolean(true);
message.setARepeatedStringList(['1', '2']);
assertObjectEquals({
$name: 'proto.jspb.test.Simple1',
'aString': 'foo',
'aRepeatedStringList': ['1', '2'],
'aBoolean': true
}, jspb.debug.dump(message));
message.setAString(undefined);
assertObjectEquals({
$name: 'proto.jspb.test.Simple1',
'aRepeatedStringList': ['1', '2'],
'aBoolean': true
}, jspb.debug.dump(message));
});
it('testExtensions', function() {
if (COMPILED) {
return;
}
var extension = new proto.jspb.test.IsExtension();
extension.setExt1('ext1field');
var extendable = new proto.jspb.test.HasExtensions();
extendable.setStr1('v1');
extendable.setStr2('v2');
extendable.setStr3('v3');
extendable.setExtension(proto.jspb.test.IsExtension.extField, extension);
assertObjectEquals({
'$name': 'proto.jspb.test.HasExtensions',
'str1': 'v1',
'str2': 'v2',
'str3': 'v3',
'$extensions': {
'extField': {
'$name': 'proto.jspb.test.IsExtension',
'ext1': 'ext1field'
},
'repeatedSimpleList': []
}
}, jspb.debug.dump(extendable));
});
});
| gwq5210/litlib | thirdparty/sources/protobuf/js/debug_test.js | JavaScript | gpl-3.0 | 3,531 |
import classnames from 'classnames';
import PropTypes from 'prop-types';
import React from 'react';
class SidebarItem extends React.Component {
static propTypes = {
baseClassName: PropTypes.string,
children: PropTypes.node,
modifier: PropTypes.string,
};
static defaultProps = {
baseClassName: 'sidebar__item',
};
render() {
const classes = classnames(this.props.baseClassName, {
[`${this.props.baseClassName}--${this.props.modifier}`]: this.props.modifier,
});
return <div className={classes}>{this.props.children}</div>;
}
}
export default SidebarItem;
| jfurrow/flood | client/src/javascript/components/sidebar/SidebarItem.js | JavaScript | gpl-3.0 | 606 |
/*
* @package jsDAV
* @subpackage DAV
* @copyright Copyright(c) 2011 Ajax.org B.V. <info AT ajax DOT org>
* @author Mike de Boer <info AT mikedeboer DOT nl>
* @license http://github.com/mikedeboer/jsDAV/blob/master/LICENSE MIT License
*/
"use strict";
var jsDAV_Ftp_Node = require("./node").jsDAV_Ftp_Node;
var jsDAV_iFile = require("./../iFile").jsDAV_iFile;
var Exc = require("./../exceptions");
var Util = require("./../util");
var Path = require("path");
function jsDAV_Ftp_File(path, ftp) {
this.path = path || "";
this.ftp = ftp;
}
exports.jsDAV_Ftp_File = jsDAV_Ftp_File;
(function() {
this.implement(jsDAV_iFile);
/**
* Creates or updates the data of this node
*
* @param {mixed} data
* @return void
*/
this.put = function(data, type, cbftpput) {
var path = this.path;
var ftp = this.ftp;
var cached = ftp.$cache[path];
if (cached && cached.$stat && cached.$stat.target)
path = Path.resolve(Path.dirname(path), cached.$stat.target);
if (!Buffer.isBuffer(data))
data = new Buffer(data, type || "binary");
ftp.put(path, data, function(err) {
if (err)
return cbftpput(err);
// @todo what about parent node's cache??
delete ftp.$cache[path];
cbftpput();
});
};
/**
* Returns the data
*
* @return Buffer
*/
this.get = function(cbftpfileget) {
var path = this.path;
var cached = this.ftp.$cache[path];
if (cached && cached.$stat && cached.$stat.target)
path = Path.resolve(Path.dirname(path), cached.$stat.target);
this.ftp.get(path, function(err, data) {
cbftpfileget(err, data);
});
};
/**
* Delete the current file
*
* @return void
*/
this["delete"] = function(cbftpfiledel) {
var self = this;
var path = this.path;
this.ftp.raw.dele(path, function(err){
if (err)
return cbftpfiledel(new Exc.jsDAV_Exception_FileNotFound(
"File " + path + " not found"));
delete self.ftp.$cache[path];
cbftpfiledel();
});
};
/**
* Returns the size of the node, in bytes
*
* @return int
*/
this.getSize = function(cbftpgetsize) {
var path = this.path;
var cached = this.ftp.$cache[path];
if (cached && cached.$stat) {
if (cached.$stat.target)
path = Path.resolve(Path.dirname(path), cached.$stat.target);
cbftpgetsize(null, cached.$stat.size);
}
else {
cbftpgetsize("The file '"+ path + "' was not cached and its information couldn't be determined");
}
};
/**
* Returns the ETag for a file
* An ETag is a unique identifier representing the current version of the file.
* If the file changes, the ETag MUST change.
* Return null if the ETag can not effectively be determined
*
* @return mixed
*/
this.getETag = function(cbftpgetetag) {
cbftpgetetag(null, null);
};
/**
* Returns the mime-type for a file
* If null is returned, we'll assume application/octet-stream
*
* @return mixed
*/
this.getContentType = function(cbftpmime) {
return cbftpmime(null, Util.mime.type(this.path));
};
}).call(jsDAV_Ftp_File.prototype = new jsDAV_Ftp_Node());
| ashking/Cloud9 | node_modules/jsDAV/lib/DAV/ftp/file.js | JavaScript | gpl-3.0 | 3,544 |
var path = require('path');
console.log(path.join(path.relative('.', __dirname),'include'));
| geminy/aidear | oss/qt/qt-everywhere-opensource-src-5.9.0/qtlocation/src/3rdparty/mapbox-gl-native/src/3rd_party/protozero/include_dirs.js | JavaScript | gpl-3.0 | 93 |
WScript.Echo("** The end of copyright notices **");
function quote(arg) {
arg = arg.replace(/"/g, '""');
return '"' + arg + '"';
}
var app = WScript.Arguments(0);
var args = [];
for (var i = 1; i < WScript.Arguments.Count(); ++i) {
args.push(quote(WScript.Arguments(i)));
}
var shell = new ActiveXObject("WScript.Shell");
var cmd = quote(app) + " " + args.join(" ");
shell.run(cmd);
WScript.Sleep(200);
// attempt to activate the app.
// MSDN about Shell.AppActivate:
//
// "In determining which application to activate, the specified
// title is compared to the title string of each running
// application. If no exact match exists, any application whose
// title string begins with title is activated. If an application
// still cannot be found, any application whose title string ends
// with title is activated. If more than one instance of the
// application named by title exists, one instance is arbitrarily
// activated."
// taking a wild guess about the *title* of the window here:
var exename = app.replace(/^.*[\\\/]([^\\\/]+)$/, "$1").replace(/\.[^.]*$/, "");
shell.AppActivate(exename);
| kendo-labs/kendo-bootstrapper | tools/win/run-in-foreground.js | JavaScript | gpl-3.0 | 1,150 |
/**
* Copyright © 2016 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
define([
'Magento_Ui/js/form/components/fieldset',
'Magento_Catalog/js/components/visible-on-option/strategy'
], function (Fieldset, strategy) {
'use strict';
return Fieldset.extend(strategy).extend(
{
defaults: {
openOnShow: true
},
/**
* Toggle visibility state.
*/
toggleVisibility: function () {
this._super();
if (this.openOnShow) {
this.opened(this.inverseVisibility ? !this.isShown : this.isShown);
}
}
}
);
});
| rajmahesh/magento2-master | vendor/magento/module-catalog/view/adminhtml/web/js/components/visible-on-option/fieldset.js | JavaScript | gpl-3.0 | 727 |
module.exports.parse = function ( arr, obj ) {
obj = obj || {};
for ( var i = 0; i < arr.length; ++i ) {
var val = arr[i];
var matches = val.match( /^-(\w+):("?)([^"]+)\2$/ );
if ( matches ) {
obj[matches[1]] = matches[3];
}
}
return obj;
}; | beni55/Primrose | server/options.js | JavaScript | gpl-3.0 | 271 |
import filterReducer from "../filters";
describe("store/reducers/ui/filters", () => {
it("should return the initial state", () => {
const state = filterReducer(undefined, { type: "SOME_ACTION" });
expect(state).toEqual({ project: {} });
});
it("should set the project filter correctly", () => {
const action = {
type: "SET_PROJECT_FILTERS",
payload: { published: true }
};
const state = filterReducer({}, action);
expect(state).toEqual({ project: { published: true } });
});
});
| zdavis/manifold | client/src/store/reducers/ui/transitory/__tests__/filters-test.js | JavaScript | gpl-3.0 | 525 |
/*
* Copyright (C) 2005-2013 University of Sydney
*
* Licensed under the GNU License, Version 3.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.gnu.org/licenses/gpl-3.0.txt
*
* 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.
*/
/**
* brief description of file
*
* @author Tom Murtagh
* @author Kim Jackson
* @author Ian Johnson <ian.johnson@sydney.edu.au>
* @author Stephen White <stephen.white@sydney.edu.au>
* @author Artem Osmakov <artem.osmakov@sydney.edu.au>
* @copyright (C) 2005-2013 University of Sydney
* @link http://Sydney.edu.au/Heurist
* @version 3.1.0
* @license http://www.gnu.org/licenses/gpl-3.0.txt GNU License 3.0
* @package Heurist academic knowledge management system
* @subpackage !!!subpackagename for file such as Administration, Search, Edit, Application, Library
*/
javascript:(function(){h='http://heuristscholar.org/h3/';d=document;c=d.contentType;if(c=='text/html'||!c){if(d.getElementById('__heurist_bookmarklet_div'))return Heurist.init();s=d.createElement('script');s.type='text/javascript';s.src=(h+'import/bookmarklet/bookmarkletPopup.php?'+new Date().getTime()).slice(0,-8);d.getElementsByTagName('head')[0].appendChild(s);}else{e=encodeURIComponent;w=open(h+'records/add/addRecordPopup.php?t='+e(d.title)+'&u='+e(location.href));window.setTimeout('w.focus()',200);}})(); | thegooglecodearchive/heurist | import/bookmarklet/bookmarkletSource.js | JavaScript | gpl-3.0 | 1,719 |
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
CodeMirror.defineOption("fullScreen", false, function(cm, val, old) {
if (old == CodeMirror.Init) old = false;
if (!old == !val) return;
if (val) setFullscreen(cm);
else setNormal(cm);
});
function setFullscreen(cm) {
var wrap = cm.getWrapperElement();
cm.state.fullScreenRestore = {scrollTop: window.pageYOffset, scrollLeft: window.pageXOffset,
width: wrap.style.width, height: wrap.style.height};
wrap.style.width = "";
wrap.style.height = "auto";
wrap.className += " CodeMirror-fullscreen";
document.documentElement.style.overflow = "hidden";
cm.refresh();
}
function setNormal(cm) {
var wrap = cm.getWrapperElement();
wrap.className = wrap.className.replace(/\s*CodeMirror-fullscreen\b/, "");
document.documentElement.style.overflow = "";
var info = cm.state.fullScreenRestore;
wrap.style.width = info.width; wrap.style.height = info.height;
window.scrollTo(info.scrollLeft, info.scrollTop);
cm.refresh();
}
}); | vsc55/endpointman | assets/js/addon/fullscreen.js | JavaScript | gpl-3.0 | 1,493 |
(function(){
var languageNav = $('.js-language-nav');
languageNav.on('click', function(){
languageNav.toggleClass('active');
});
//close opened stuff
$(document).on('click', function(e) {
if (!$(e.target).closest('.js-language-nav').length) {
languageNav.removeClass('active');
}
});
})(); | eeriks/velo.lv | velo/static/template/velo-2016/html/js/components/_components.language-nav.js | JavaScript | gpl-3.0 | 354 |
import {makeInstanceAction} from '#/main/app/store/actions'
import {makeReducer} from '#/main/app/store/reducer'
import {makeFormReducer} from '#/main/app/content/form/store/reducer'
import {RESOURCE_LOAD} from '#/main/core/resource/store/actions'
import {selectors as rssSelectors} from '#/plugin/rss/resources/rss-feed/store/selectors'
import {selectors} from '#/plugin/rss/resources/rss-feed/editor/store/selectors'
const reducer = {
rssFeedForm: makeFormReducer(selectors.FORM_NAME, {}, {
originalData: makeReducer({}, {
[makeInstanceAction(RESOURCE_LOAD, rssSelectors.STORE_NAME)]: (state, action) => action.resourceData.slideshow || state
}),
data: makeReducer({}, {
[makeInstanceAction(RESOURCE_LOAD, rssSelectors.STORE_NAME)]: (state, action) => action.resourceData.slideshow || state
})
})
}
export {
reducer
}
| claroline/Distribution | plugin/rss/Resources/modules/resources/rss-feed/editor/store/reducer.js | JavaScript | gpl-3.0 | 858 |
/**
GaiaEHR (Electronic Health Records)
Copyright (C) 2013 Certun, LLC.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
Ext.define('App.store.patient.AmendmentRequests', {
extend: 'Ext.data.Store',
model: 'App.model.patient.AmendmentRequest'
}); | gaiaehr/gaiaehr | app/store/patient/AmendmentRequests.js | JavaScript | gpl-3.0 | 829 |
var searchData=
[
['map',['Map',['../d7/db0/classMap.html',1,'']]],
['memorystream',['MemoryStream',['../dd/d97/classMemoryStream.html',1,'']]],
['message',['Message',['../d6/d28/classMessage.html',1,'']]],
['module',['module',['../d0/dd3/classmodule.html',1,'']]],
['mongocollection',['MongoCollection',['../d2/d07/classMongoCollection.html',1,'']]],
['mongocursor',['MongoCursor',['../db/d7d/classMongoCursor.html',1,'']]],
['mongodb',['MongoDB',['../d6/d3d/classMongoDB.html',1,'']]],
['mongoid',['MongoID',['../d2/d6d/classMongoID.html',1,'']]],
['mq',['mq',['../d4/d86/classmq.html',1,'']]],
['mysql',['MySQL',['../d3/da8/classMySQL.html',1,'']]]
];
| xushiwei/fibjs | docs/search/classes_a.js | JavaScript | gpl-3.0 | 675 |
if(!window.nabor)
window.nabor={};
window.nabor.importFrom({
nZad:14,
adres:'../zdn/matege2015p/',
name:'matege2015p',
prefix:'',
});
| DrMGC/chas-ege | zdn/matege2015p/matege2015p.js | JavaScript | gpl-3.0 | 139 |
cordova.define('cordova/plugin_list', function(require, exports, module) {
module.exports = [
{
"id": "cordova-plugin-console.console",
"file": "plugins/cordova-plugin-console/www/console-via-logger.js",
"pluginId": "cordova-plugin-console",
"clobbers": [
"console"
]
},
{
"id": "cordova-plugin-console.logger",
"file": "plugins/cordova-plugin-console/www/logger.js",
"pluginId": "cordova-plugin-console",
"clobbers": [
"cordova.logger"
]
},
{
"id": "cordova-plugin-device.device",
"file": "plugins/cordova-plugin-device/www/device.js",
"pluginId": "cordova-plugin-device",
"clobbers": [
"device"
]
},
{
"id": "cordova-plugin-splashscreen.SplashScreen",
"file": "plugins/cordova-plugin-splashscreen/www/splashscreen.js",
"pluginId": "cordova-plugin-splashscreen",
"clobbers": [
"navigator.splashscreen"
]
},
{
"id": "cordova-plugin-statusbar.statusbar",
"file": "plugins/cordova-plugin-statusbar/www/statusbar.js",
"pluginId": "cordova-plugin-statusbar",
"clobbers": [
"window.StatusBar"
]
},
{
"id": "ionic-plugin-keyboard.keyboard",
"file": "plugins/ionic-plugin-keyboard/www/ios/keyboard.js",
"pluginId": "ionic-plugin-keyboard",
"clobbers": [
"cordova.plugins.Keyboard"
],
"runs": true
},
{
"id": "cordova-plugin-geolocation.Coordinates",
"file": "plugins/cordova-plugin-geolocation/www/Coordinates.js",
"pluginId": "cordova-plugin-geolocation",
"clobbers": [
"Coordinates"
]
},
{
"id": "cordova-plugin-geolocation.PositionError",
"file": "plugins/cordova-plugin-geolocation/www/PositionError.js",
"pluginId": "cordova-plugin-geolocation",
"clobbers": [
"PositionError"
]
},
{
"id": "cordova-plugin-geolocation.Position",
"file": "plugins/cordova-plugin-geolocation/www/Position.js",
"pluginId": "cordova-plugin-geolocation",
"clobbers": [
"Position"
]
},
{
"id": "cordova-plugin-geolocation.geolocation",
"file": "plugins/cordova-plugin-geolocation/www/geolocation.js",
"pluginId": "cordova-plugin-geolocation",
"clobbers": [
"navigator.geolocation"
]
},
{
"id": "cordova-sqlite-storage.SQLitePlugin",
"file": "plugins/cordova-sqlite-storage/www/SQLitePlugin.js",
"pluginId": "cordova-sqlite-storage",
"clobbers": [
"SQLitePlugin"
]
}
];
module.exports.metadata =
// TOP OF METADATA
{
"cordova-plugin-console": "1.0.5",
"cordova-plugin-device": "1.1.4",
"cordova-plugin-splashscreen": "4.0.1",
"cordova-plugin-statusbar": "2.2.1",
"cordova-plugin-whitelist": "1.3.1",
"ionic-plugin-keyboard": "2.2.1",
"cordova-plugin-compat": "1.1.0",
"cordova-plugin-geolocation": "2.4.1",
"cordova-sqlite-storage": "2.0.3"
};
// BOTTOM OF METADATA
}); | chitranshi21/home_service_ionic | platforms/ios/www/cordova_plugins.js | JavaScript | gpl-3.0 | 3,247 |
/**
* LayoutBase
* A Mithril component Base class for Layouts, e.g. HorizontalLayout and
* CircosLayout.
*/
import {Bounds} from '../../model/Bounds';
export class LayoutBase {
// constructor() - prefer do not use in mithril components
/**
* mithril lifecycle callback
* @param vnode
*/
oninit(vnode) {
this.appState = vnode.attrs.appState;
}
/**
* mithril lifecycle method
* @param vnode
*/
oncreate(vnode) {
// save a reference to this component's dom element
this.el = vnode.dom;
this.bounds = new Bounds(vnode.dom.getBoundingClientRect());
}
/**
* mithril lifecycle method
* @param vnode
*/
onupdate(vnode) {
this.bounds = new Bounds(vnode.dom.getBoundingClientRect());
}
}
| ncgr/cmap-js | src/ui/layout/LayoutBase.js | JavaScript | gpl-3.0 | 758 |
var config = require('../config').assets,
gulp = require('gulp');
gulp.task('assets', function() {
gulp.src(config.src)
.pipe(gulp.dest(config.dst));
});
| arsgeografica/kinderstadt-registry | registry/static.in/gulp/tasks/assets.js | JavaScript | gpl-3.0 | 172 |
import BarButton from '../bar-button/bar-button';
import { useRef, useEffect } from 'react';
export default function ConnectionButton() {
const buttonRef = useRef();
const isUserConnected = elementorAdminTopBarConfig.is_user_connected;
useEffect( () => {
if ( ! buttonRef.current || isUserConnected ) {
return;
}
jQuery( buttonRef.current ).elementorConnect();
}, [] );
let tooltipText = __( 'Connect your account to get access to Elementor\'s Template Library & more.', 'elementor' ),
connectUrl = elementorAdminTopBarConfig.connect_url,
buttonText = __( 'Connect Account', 'elementor' ),
targetUrl = '_self';
if ( isUserConnected ) {
tooltipText = '';
connectUrl = 'https://go.elementor.com/wp-dash-admin-bar-account/';
buttonText = __( 'My Elementor', 'elementor' );
targetUrl = '_blank';
}
return (
<BarButton icon="eicon-user-circle-o" buttonRef={buttonRef} dataInfo={tooltipText} href={connectUrl} target={targetUrl}>{ buttonText }</BarButton>
);
}
| pojome/elementor | modules/admin-top-bar/assets/js/components/connection-button/connection-button.js | JavaScript | gpl-3.0 | 996 |
/**
* Run this using node_modules/gulp/bin/gulp.js !!!
* mhm 8.6.2017
*/
'use strict';
import plugins from 'gulp-load-plugins';
//import rename from 'gulp-rename';
import yargs from 'yargs';
import gulp from 'gulp';
import rimraf from 'rimraf';
import yaml from 'js-yaml';
import fs from 'fs';
// Load all Gulp plugins into one variable
const $ = plugins();
// Load settings from config.yml
const { PATHS } = loadConfig();
function loadConfig() {
let ymlFile = fs.readFileSync('config.yml', 'utf8');
return yaml.load(ymlFile);
}
// Build the "dist" folder by running all of the below tasks
gulp.task('build',
gulp.series(clean, copyJS));
// Delete the "dist" folder
// This happens every time a build starts
function clean(done) {
rimraf(PATHS.dist, done);
}
/**
* Copies JavaScript files as-is from e.g. bower_components
* The path is manipulated to simplify the destination path.
*/
function copyJS(done) {
if (PATHS.copyjavascript) {
gulp.src(PATHS.copyjavascript, { base: '.' })
.pipe($.concat('libs.js'))
.pipe(gulp.dest(PATHS.dist + '/assets/js'));
}
if(done){
done();
}
}
| mhmli/helpers | playground/twigjs/gulpfile.babel.js | JavaScript | gpl-3.0 | 1,155 |
Ext.define('Redwood.view.ExecutionView', {
extend: 'Ext.panel.Panel',
alias: 'widget.executionview',
overflowY: 'auto',
bodyPadding: 5,
dataRecord: null,
dirty: false,
loadingData: true,
viewType: "Execution",
noteChanged: false,
tcDataRefreshed: false,
initComponent: function () {
var me = this;
if (me.dataRecord == null){
me.itemId = Ext.uniqueId();
}
else{
me.itemId = me.dataRecord.get("_id");
}
this.markDirty = function(){
this.dirty = true;
if(me.title.charAt(me.title.length-1) != "*"){
me.setTitle(me.title+"*")
}
};
me.on("beforeclose",function(panel){
if (this.dirty == true){
var me = this;
Ext.Msg.show({
title:'Save Changes?',
msg: 'You are closing a tab that has unsaved changes. Would you like to save your changes?',
buttons: Ext.Msg.YESNOCANCEL,
icon: Ext.Msg.QUESTION,
fn: function(id){
if (id == "no"){
me.destroy();
}
if (id == "yes"){
var editor = me.up('executionsEditor');
editor.fireEvent('save');
me.destroy();
}
}
});
return false;
}
});
var variables = [];
var variablesStore = Ext.data.StoreManager.lookup('Variables');
variablesStore.query("_id",/.*/).each(function(variable){
var foundVarValue = variable.get("value");
if (me.dataRecord != null){
me.dataRecord.get("variables").forEach(function(recordedVariable){
if(recordedVariable._id === variable.get("_id")){
foundVarValue = recordedVariable.value;
}
})
}
if (variable.get("taskVar") == true){
variables.push({possibleValues:variable.get("possibleValues"),tag:variable.get("tag"),value:foundVarValue,name:variable.get("name"),_id:variable.get("_id")})
}
});
var linkedVarStore = new Ext.data.Store({
sorters: [{
property : 'name'
}],
fields: [
{name: 'name', type: 'string'},
{name: 'value', type: 'string'},
{name: 'tag', type: 'array'},
{name: 'possibleValues', type: 'array'},
{name: '_id', type: 'string'}
],
data: variables,
listeners:{
update:function(){
if (me.loadingData === false){
me.markDirty();
}
}
}
});
me.variablesListener = function(options,eOpts){
if (options.create){
options.create.forEach(function(variable){
if (variable.get("taskVar") == true){
linkedVarStore.add(variable);
}
});
}
if (options.destroy){
options.destroy.forEach(function(variable){
if (variable.get("taskVar") == true){
linkedVarStore.remove(linkedVarStore.findRecord("_id", variable.get("_id")));
}
});
}
if (options.update){
options.update.forEach(function(variable){
var linkedRecord = linkedVarStore.findRecord("_id", variable.get("_id"));
if (variable.get("taskVar") == true){
//if null it means the taskVar flag changed and we need to add instead of update
if (linkedRecord == null){
linkedVarStore.add(variable);
return;
}
linkedRecord.set("name", variable.get("name"));
linkedRecord.set("tag", variable.get("tag"));
linkedRecord.set("possibleValues", variable.get("possibleValues"));
}
//looks like the variable no longer belongs here
else if(linkedRecord != null){
linkedVarStore.remove(linkedRecord);
}
});
}
};
variablesStore.on("beforesync",me.variablesListener);
var variablesGrid = new Ext.grid.Panel({
listeners:{
beforeedit: function(editor,e){
var data = [];
if(e.field === "value"){
e.record.get("possibleValues").forEach(function(value){
if (!Ext.Array.contains(e.record.get("value"),value)){
data.push({text:Ext.util.Format.htmlEncode(value),value:value});
}
});
var valuesStore = new Ext.data.Store({
fields: [
{type: 'string', name: 'value'}
],
data: data
});
e.column.setEditor({
xtype:"combo",
displayField:"value",
overflowY:"auto",
descField:"value",
height:24,
labelWidth: 100,
forceSelection:false,
createNewOnEnter:true,
encodeSubmitValue:true,
autoSelect: true,
store: valuesStore,
valueField:"value",
queryMode: 'local',
removeOnDblClick:true
});
}
}
},
store: linkedVarStore,
itemId:"executionVars",
selType: 'rowmodel',
viewConfig: {
markDirty: false
},
plugins: [
Ext.create('Ext.grid.plugin.CellEditing', {
clicksToEdit: 1
})],
maxHeight: 250,
minHeight: 150,
manageHeight: true,
flex: 1,
overflowY: 'auto',
columns:[
{
header: 'Name',
dataIndex: 'name',
width: 200
},
{
header: 'Value',
dataIndex: 'value',
itemId: "varValue",
renderer:function(value, meta, record){
return Ext.util.Format.htmlEncode(value);
},
editor: {},
flex: 1
},
{
header: 'Tags',
dataIndex: 'tag',
//flex: 1,
width: 250
}
]
});
var machines = [];
var machinesStore = Ext.data.StoreManager.lookup('Machines');
//machinesStore.each(function(machine){
machinesStore.query("_id",/.*/).each(function(machine){
//var foundMachine = false;
var baseState = null;
var baseStateTCID = null;
var result = null;
var resultID = null;
var threads = 1;
if ((me.dataRecord != null)&&(me.dataRecord.get("machines"))){
me.dataRecord.get("machines").forEach(function(recordedMachine){
if(recordedMachine._id === machine.get("_id")){
baseState = recordedMachine.baseState;
baseStateTCID = recordedMachine.baseStateTCID;
result = recordedMachine.result;
resultID = recordedMachine.resultID;
if (recordedMachine.threads){
threads = recordedMachine.threads;
}
else{
threads = 1;
}
}
})
}
if (baseStateTCID == null) baseStateTCID = Ext.uniqueId();
machines.push({host:machine.get("host"),machineVars:machine.get("machineVars"),tag:machine.get("tag"),state:machine.get("state"),maxThreads:machine.get("maxThreads"),threads:threads,result:result,resultID:resultID,baseState:baseState,baseStateTCID:baseStateTCID,description:machine.get("description"),roles:machine.get("roles"),port:machine.get("port"),vncport:machine.get("vncport"),_id:machine.get("_id")})
});
var linkedMachineStore = new Ext.data.Store({
sorters: [{
property : 'host'
}],
fields: [
{name: 'host', type: 'string'},
{name: 'vncport', type: 'string'},
{name: 'port', type: 'string'},
{name: 'maxThreads', type: 'int'},
{name: 'threads', type: 'int'},
{name: 'tag', type: 'array'},
{name: 'state', type: 'string'},
{name: 'baseState', type: 'string'},
{name: 'resultID', type: 'string'},
{name: 'baseStateTCID', type: 'string'},
{name: 'result', type: 'string'},
{name: 'description', type: 'string'},
{name: 'machineVars', type: 'array'},
{name: 'roles', type: 'array'},
{name: '_id', type: 'string'}
],
data: machines,
listeners:{
update:function(store, record, operation, modifiedFieldNames){
if (me.loadingData === false){
if (modifiedFieldNames){
modifiedFieldNames.forEach(function(field){
if (field === "baseState"){
me.markDirty();
}
});
}
}
}
}
});
me.machinesListener = function(options,eOpts){
if (options.create){
options.create.forEach(function(r){
r.set("threads",1);
linkedMachineStore.add(r);
});
}
if (options.destroy){
options.destroy.forEach(function(r){
if (r) linkedMachineStore.remove(linkedMachineStore.query("_id", r.get("_id")).getAt(0));
});
}
if (options.update){
options.update.forEach(function(r){
var linkedRecord = linkedMachineStore.query("_id", r.get("_id")).getAt(0);
if(!linkedRecord) return;
if (r.get("host") != linkedRecord.get("host")){
linkedRecord.set("host", r.get("host"));
}
if (r.get("maxThreads") != linkedRecord.get("maxThreads")){
linkedRecord.set("maxThreads", r.get("maxThreads"));
}
if (r.get("port") != linkedRecord.get("port")){
linkedRecord.set("port", r.get("port"));
}
if (r.get("vncport") != linkedRecord.get("vncport")){
linkedRecord.set("vncport", r.get("vncport"));
}
if (Ext.arraysEqual(r.get("tag"),linkedRecord.get("tag")) == false){
linkedRecord.set("tag", r.get("tag"));
}
if (r.get("description") != linkedRecord.get("description")){
linkedRecord.set("description", r.get("description"));
}
if (Ext.arraysEqual(r.get("roles"),linkedRecord.get("roles")) == false){
linkedRecord.set("roles", r.get("roles"));
}
if (r.get("state") != linkedRecord.get("state")){
linkedRecord.set("state", r.get("state"));
}
if (Ext.arraysEqual(r.get("machineVars"),linkedRecord.get("machineVars")) == false){
linkedRecord.set("machineVars", r.get("machineVars"));
}
});
}
};
machinesStore.on("beforesync", me.machinesListener);
var machinesGrid = new Ext.grid.Panel({
store: linkedMachineStore,
itemId:"executionMachines",
selType: 'rowmodel',
tbar:{
xtype: 'toolbar',
dock: 'top',
items: [
{
width: 400,
fieldLabel: 'Search',
labelWidth: 50,
xtype: 'searchfield',
paramNames: ["tag","host","description","roles"],
store: linkedMachineStore
}
]
},
viewConfig: {
preserveScrollOnRefresh: true,
markDirty: false
},
plugins: [
Ext.create('Ext.grid.plugin.CellEditing', {
clicksToEdit: 1,
listeners:{
beforeedit: function(editor,e){
if(e.field == "threads"){
machinesGrid.editingRecord = e.record;
//editor.setMaxValue(e.record.get("maxThreads"))
}
}
}
})],
maxHeight: 250,
minHeight: 150,
manageHeight: true,
flex: 1,
overflowY: 'auto',
selModel: Ext.create('Ext.selection.CheckboxModel', {
singleSelect: false,
sortable: true,
//checkOnly: true,
stateful: true,
showHeaderCheckbox: true
}),
listeners:{
edit: function(editor, e ){
machinesGrid.getSelectionModel().select([e.record]);
}
},
columns:[
{
header: 'Host Name/IP',
dataIndex: 'host',
itemId:"hostMachineColumn",
width: 200,
renderer: function (value, meta, record) {
return "<a style= 'color: blue;' href='javascript:vncToMachine(""+ value +"",""+ record.get("vncport") +"")'>" + value +"</a>";
}
},
{
header: 'Threads',
dataIndex: 'threads',
//flex: 1,
width: 100,
editor: {
xtype: 'numberfield',
allowBlank: false,
minValue: 1,
listeners:{
focus: function(field){
field.setMaxValue(machinesGrid.editingRecord.get("maxThreads"))
}
}
}
},
{
header: 'Max Threads',
dataIndex: 'maxThreads',
//flex: 1,
width: 100
},
{
header: 'Port',
dataIndex: 'port',
width: 100
},
{
header: 'Roles',
dataIndex: 'roles',
width: 200
},
{
header: 'State',
dataIndex: 'state',
width: 120,
renderer: function(value,record){
if (value.indexOf("Running") != -1){
return "<p style='color:green'>"+value+"</p>";
}
return value;
}
},
{
header: 'Description',
dataIndex: 'description',
flex: 1
},
{
header: "Base State Result",
dataIndex: "result",
width: 120,
renderer: function(value,style,record){
//style.tdAttr = 'data-qtip="' + record.get("error") + '"';
if((value == "") &&(record.get("resultID")) &&(record.get("baseState"))){
value = "Running";
}
if ((value == "Passed") || (value == "Running")){
return "<a style= 'color: blue;' href='javascript:openResultDetails(""+ record.get("resultID") +"")'>" + value +"</a>";
//return "<p style='color:green'>"+value+"</p>"
}
else if (value == "Failed"){
return "<a style= 'color: red;' href='javascript:openResultDetails(""+ record.get("resultID") +"")'>" + value +"</a>";
//return "<p style='color:red'>"+value+"</p>"
}
else{
return value;
}
}
},
{
header: 'Machine Base State',
dataIndex: "baseState",
width:200,
renderer: function(value,metaData,record, rowIndex, colIndex, store, view){
if (value){
var action = Ext.data.StoreManager.lookup('Actions').getById(value);
if(action){
return action.get("name");
}
else{
record.set("baseState",null);
record.set("result",null);
return "";
}
var actionName = Ext.data.StoreManager.lookup('Actions').getById(value).get("name");
var url = "<a style= 'color: red;' href='javascript:openAction(""+ record.get("baseState") +"")'>" + actionName +"</a>";
return url;
}
else{
if(record.get("result")) record.set("result",null);
return value
}
},
editor: {
xtype: "actionpicker",
itemId: "actionpicker",
width: 400,
plugins:[
Ext.create('Ext.ux.SearchPlugin')
],
paramNames:["tag","name"],
store: Ext.data.StoreManager.lookup('ActionsCombo'),
autoSelect:false,
forceSelection:false,
queryMode: 'local',
triggerAction: 'all',
lastQuery: '',
typeAhead: false,
displayField: 'name',
valueField: '_id'
}
},
{
header: 'Tags',
dataIndex: 'tag',
//flex: 1,
width: 250
}
]
});
var templates = [];
var templatesStore = Ext.data.StoreManager.lookup('Templates');
templatesStore.query("_id",/.*/).each(function(template){
//var foundMachine = false;
var baseState = null;
var baseStateTCID = null;
var result = null;
var resultID = null;
var threads = 1;
var instances = 1;
if ((me.dataRecord != null)&&(me.dataRecord.get("templates"))){
me.dataRecord.get("templates").forEach(function(recordedTemplate){
if(recordedTemplate._id === template.get("_id")){
//baseState = recordedTemplate.baseState;
//baseStateTCID = recordedTemplate.baseStateTCID;
result = recordedTemplate.result;
//resultID = recordedTemplate.resultID;
if (recordedTemplate.threads){
threads = recordedTemplate.threads;
}
else{
threads = 1;
}
if (recordedTemplate.instances){
instances = recordedTemplate.instances;
}
else{
instances = 1;
}
}
})
}
//if (baseStateTCID == null) baseStateTCID = Ext.uniqueId();
templates.push({name:template.get("name"),threads:threads,instances:instances,result:result,description:template.get("description"),_id:template.get("_id")});
//templates.push({host:template.get("name"),tag:template.get("tag"),state:template.get("state"),maxThreads:template.get("maxThreads"),threads:threads,result:result,resultID:resultID,baseState:baseState,baseStateTCID:baseStateTCID,description:template.get("description"),roles:template.get("roles"),port:template.get("port"),vncport:template.get("vncport"),_id:template.get("_id")})
});
var linkedTemplateStore = new Ext.data.Store({
sorters: [{
property : 'name'
}],
fields: [
{name: 'name', type: 'string'},
{name: 'instances', type: 'int'},
{name: 'threads', type: 'int'},
{name: 'result', type: 'string'},
{name: 'description', type: 'string'},
{name: '_id', type: 'string'}
],
data: templates/*,
listeners:{
update:function(store, record, operation, modifiedFieldNames){
if (me.loadingData === false){
if (modifiedFieldNames){
modifiedFieldNames.forEach(function(field){
if (field === "baseState"){
me.markDirty();
}
});
}
}
}
}
*/
});
me.templatesListener = function(options,eOpts){
if (options.create){
options.create.forEach(function(r){
r.set("threads",1);
r.set("instances",1);
linkedTemplateStore.add(r);
});
}
if (options.destroy){
options.destroy.forEach(function(r){
if (r) linkedTemplateStore.remove(linkedTemplateStore.query("_id", r.get("_id")).getAt(0));
});
}
if (options.update){
options.update.forEach(function(r){
var linkedRecord = linkedTemplateStore.query("_id", r.get("_id")).getAt(0);
if(!linkedRecord) return;
if (r.get("name") != linkedRecord.get("name")){
linkedRecord.set("name", r.get("name"));
}
if (r.get("description") != linkedRecord.get("description")){
linkedRecord.set("description", r.get("description"));
}
});
}
};
templatesStore.on("beforesync", me.templatesListener);
var templatesGrid = new Ext.grid.Panel({
store: linkedTemplateStore,
itemId:"executionTemplates",
selType: 'rowmodel',
tbar:{
xtype: 'toolbar',
dock: 'top',
items: [
{
width: 400,
fieldLabel: 'Search',
labelWidth: 50,
xtype: 'searchfield',
paramNames: ["name"],
store: linkedTemplateStore
}
]
},
viewConfig: {
preserveScrollOnRefresh: true,
markDirty: false
},
plugins: [
Ext.create('Ext.grid.plugin.CellEditing', {
clicksToEdit: 1,
listeners:{
beforeedit: function(editor,e){
if(e.field == "threads"){
templatesGrid.editingRecord = e.record;
}
else if(e.field == "instances"){
templatesGrid.editingRecord = e.record;
}
}
}
})],
maxHeight: 250,
minHeight: 150,
manageHeight: true,
flex: 1,
overflowY: 'auto',
selModel: Ext.create('Ext.selection.CheckboxModel', {
singleSelect: true,
mode:"SINGLE",
sortable: true,
stateful: true,
showHeaderCheckbox: true
}),
listeners:{
edit: function(editor, e ){
templatesGrid.getSelectionModel().select([e.record]);
}
},
columns:[
{
header: 'Name',
dataIndex: 'name',
itemId:"nameColumn",
width: 200
},
{
header: 'Instances',
dataIndex: 'instances',
width: 100,
editor: {
xtype: 'numberfield',
allowBlank: false,
minValue: 1,
listeners:{
focus: function(field){
//field.setMaxValue(machinesGrid.editingRecord.get("maxThreads"))
}
}
}
},
{
header: 'Threads',
dataIndex: 'threads',
width: 100,
editor: {
xtype: 'numberfield',
allowBlank: false,
minValue: 1,
listeners:{
focus: function(field){
//field.setMaxValue(machinesGrid.editingRecord.get("maxThreads"))
}
}
}
},
{
header: 'Description',
dataIndex: 'description',
flex: 1
},
{
header: "Result",
dataIndex: "result",
width: 120
/*
renderer: function(value,style,record){
//style.tdAttr = 'data-qtip="' + record.get("error") + '"';
if((value == "") &&(record.get("resultID")) &&(record.get("baseState"))){
value = "Running";
}
if ((value == "Passed") || (value == "Running")){
return "<a style= 'color: blue;' href='javascript:openResultDetails(""+ record.get("resultID") +"")'>" + value +"</a>";
//return "<p style='color:green'>"+value+"</p>"
}
else if (value == "Failed"){
return "<a style= 'color: red;' href='javascript:openResultDetails(""+ record.get("resultID") +"")'>" + value +"</a>";
//return "<p style='color:red'>"+value+"</p>"
}
else{
return value;
}
}
*/
}
]
});
var executionTCStore = new Ext.data.Store({
storeId: "ExecutionTCs"+this.itemId,
//groupField: 'status',
sorters: [{
property : 'name'
}],
fields: [
{name: 'name', type: 'string'},
{name: 'tag', type: 'array'},
{name: 'status', type: 'string'},
{name: 'host', type: 'string'},
{name: 'vncport', type: 'string'},
{name: 'resultID', type: 'string'},
{name: 'result', type: 'string'},
{name: 'startAction', type: 'string'},
{name: 'endAction', type: 'string'},
{name: 'startdate', type: 'date'},
{name: 'enddate', type: 'date'},
{name: 'runtime', type: 'string'},
{name: 'rowIndex' },
{name: 'tcData', convert:null},
{name: 'updated', type: 'boolean'},
{name: 'error', type: 'string'},
{name: 'note', type: 'string'},
{name: '_id', type: 'string'},
{name: 'testcaseID', type: 'string'}
],
data: []
});
me.executionTCStore = executionTCStore;
me.updateTotals = function(execution){
me.down("#totalPassed").setRawValue(execution.passed);
me.down("#totalFailed").setRawValue(execution.failed);
me.down("#totalNotRun").setRawValue(execution.notRun);
me.down("#totalTestCases").setRawValue(execution.total);
me.down("#runtime").setRawValue(execution.runtime);
me.chartStore.findRecord("name","Passed").set("data",execution.passed);
me.chartStore.findRecord("name","Failed").set("data",execution.failed);
me.chartStore.findRecord("name","Not Run").set("data",execution.notRun);
};
me.updateCloudStatus = function(execution){
me.down("#cloudStatus").setValue(execution.cloudStatus);
};
me.initialTotals = function(){
if (me.dataRecord){
me.down("#totalPassed").setRawValue(me.dataRecord.get("passed"));
me.down("#totalFailed").setRawValue(me.dataRecord.get("failed"));
me.down("#totalNotRun").setRawValue(me.dataRecord.get("notRun"));
me.down("#totalTestCases").setRawValue(me.dataRecord.get("total"));
me.down("#runtime").setRawValue(me.dataRecord.get("runtime"));
me.chartStore.findRecord("name","Passed").set("data",me.dataRecord.get("passed"));
me.chartStore.findRecord("name","Failed").set("data",me.dataRecord.get("failed"));
me.chartStore.findRecord("name","Not Run").set("data",me.dataRecord.get("notRun"));
}
else{
me.down("#totalPassed").setRawValue(0);
me.down("#totalFailed").setRawValue(0);
me.down("#totalNotRun").setRawValue(0);
me.down("#totalTestCases").setRawValue(0);
me.down("#runtime").setRawValue(0);
}
};
executionTCStore.on("datachanged",function(store){
//me.updateTotals(store);
});
executionTCStore.on("beforesync",function(options){
if (options.update){
//me.updateTotals(executionTCStore);
}
});
var testcasesGrid = new Ext.grid.Panel({
store: executionTCStore,
itemId:"executionTestcases",
selType: 'rowmodel',
overflowY: 'auto',
tbar:{
xtype: 'toolbar',
dock: 'top',
items: [
{
width: 400,
fieldLabel: 'Search',
labelWidth: 50,
xtype: 'searchfield',
paramNames: ["name","tag"],
//paramNames: ["tempName","tag","status","result"],
store: executionTCStore
},
{
icon:'images/refresh.png',
tooltip:"Get Latest Data Driven Data",
handler: function(){
var testSet = Ext.data.StoreManager.lookup('TestSets').query("_id",me.dataRecord.get("testset")).getAt(0);
testSet.get("testcases").forEach(function(testcaseId){
var testcase = Ext.data.StoreManager.lookup('TestCases').query("_id",testcaseId._id).getAt(0);
var execTestCases = me.down("#executionTestcases").store.query("testcaseID",testcaseId._id);
if(testcase && execTestCases){
if(testcase.get("tcData") && testcase.get("tcData").length > 0){
//if this was a regular tc and now its data driven
if(execTestCases.getAt(0).get("tcData") == "" || execTestCases.getAt(0).get("tcData").length == 0){
me.down("#executionTestcases").store.remove(execTestCases.getAt(0));
testcase.get("tcData").forEach(function(row,index){
me.down("#executionTestcases").store.add({updated:true,rowIndex:index+1,tcData:row,name:testcase.get("name")+"_"+(index+1),tag:testcase.get("tag"),status:"Not Run",testcaseID:testcase.get("_id"),_id: Ext.uniqueId()});
})
}
else{
execTestCases.each(function(execTestCase,index){
if(index+1 > testcase.get("tcData").length){
me.down("#executionTestcases").store.remove(execTestCase);
}
else if(JSON.stringify(execTestCase.get("tcData")) != JSON.stringify(testcase.get("tcData")[execTestCase.get("rowIndex")-1])){
me.down("#executionTestcases").store.remove(execTestCase);
me.down("#executionTestcases").store.add({updated:true,rowIndex:index+1,tcData:testcase.get("tcData")[index],name:testcase.get("name")+"_"+(index+1),tag:testcase.get("tag"),status:"Not Run",testcaseID:testcase.get("_id"),_id: Ext.uniqueId()});
}
});
if(testcase.get("tcData").length > execTestCases.length){
for(var tcCount=execTestCases.length;tcCount<testcase.get("tcData").length;tcCount++){
me.down("#executionTestcases").store.add({updated:true,rowIndex:tcCount+1,tcData:testcase.get("tcData")[tcCount],name:testcase.get("name")+"_"+(tcCount+1),tag:testcase.get("tag"),status:"Not Run",testcaseID:testcase.get("_id"),_id: Ext.uniqueId()});
}
}
}
}
else if ((!testcase.get("tcData") || testcase.get("tcData").length == 0)&& (execTestCases.getAt(0).get("tcData") == "" || execTestCases.getAt(0).get("tcData").length == 0)){
//execTestCases.each(function(execTestCase){
// me.down("#executionTestcases").store.remove(execTestCase);
//});
//me.down("#executionTestcases").store.add({rowIndex:-1,updated:true,name:testcase.get("name"),tag:testcase.get("tag"),status:"Not Run",testcaseID:testcase.get("_id"),_id: Ext.uniqueId()});
}
//if tc was data driven and now is not
else if(execTestCases.getAt(0).get("tcData") && testcase.get("tcData").length == 0){
execTestCases.each(function(execTestCase){
me.down("#executionTestcases").store.remove(execTestCase);
});
me.down("#executionTestcases").store.add({rowIndex:-1,updated:true,name:testcase.get("name"),tag:testcase.get("tag"),status:"Not Run",testcaseID:testcase.get("_id"),_id: Ext.uniqueId()});
}
}
});
me.down("#totalNotRun").setRawValue(me.down("#executionTestcases").store.query("status","Not Run").getCount());
me.down("#totalTestCases").setRawValue(me.down("#executionTestcases").store.getCount());
me.tcDataRefreshed = true;
me.markDirty();
var editor = me.up('executionsEditor');
editor.fireEvent('save');
}
},
"->",
{
xtype:"checkbox",
fieldLabel: "Debug",
labelWidth: 40,
checked: false,
handler: function(widget){
if(widget.getValue() == true){
testcasesGrid.down('[dataIndex=startAction]').setVisible(true);
testcasesGrid.down('[dataIndex=endAction]').setVisible(true);
}
else{
testcasesGrid.down('[dataIndex=startAction]').setVisible(false);
testcasesGrid.down('[dataIndex=endAction]').setVisible(false);
}
}
},
{
icon: 'images/note_add.png',
hidden:true,
tooltip:"Add Note to Selected Test Cases",
handler: function(){
if(testcasesGrid.getSelectionModel().getSelection().length == 0){
Ext.Msg.alert('Error', "Please select test cases you want to attach note to.");
return;
}
var win = Ext.create('Redwood.view.TestCaseNote',{
onNoteSave:function(note){
testcasesGrid.getSelectionModel().getSelection().forEach(function(testcase){
testcase.set("note",note);
me.markDirty();
me.noteChanged = true;
});
}
});
win.show();
}
},"-","",
{
width: 400,
fieldLabel: 'Search Notes',
labelWidth: 80,
xtype: 'searchfield',
paramNames: ["note"],
//paramNames: ["tempName","tag","status","result"],
store: executionTCStore
}
]
},
viewConfig: {
markDirty: false,
enableTextSelection: true
},
selModel: Ext.create('Ext.selection.CheckboxModel', {
singleSelect: false,
sortable: true,
stateful: true,
showHeaderCheckbox: true,
listeners: {}
}),
minHeight: 150,
height: 500,
manageHeight: true,
flex: 1,
plugins: [
"bufferedrenderer",
Ext.create('Ext.grid.plugin.CellEditing', {
clicksToEdit: 1
})],
listeners:{
validateedit: function(editor,e){
if(e.field == "note"){
Ext.Ajax.request({
url:"/executiontestcasenotes",
method:"PUT",
jsonData : {_id:e.record.get("_id"),note:e.value},
success: function(response) {
//if(obj.error != null){
// Ext.Msg.alert('Error', obj.error);
//}
}
});
}
},
edit: function(editor, e ){
if ((e.field == "endAction") &&(e.value != "") &&(e.record.get("startAction") == "")){
e.record.set("startAction",1);
}
testcasesGrid.getSelectionModel().select([e.record]);
}/*,
cellclick: function(grid, td, cellIndex, record, tr, rowIndex, e ) {
if (cellIndex == 11){
var win = Ext.create('Redwood.view.TestCaseNote',{
value: record.get("note"),
onNoteSave:function(note){
record.set("note",note);
me.markDirty();
me.noteChanged = true;
}
});
win.show();
}
}*/
},
columns:[
{
header: 'Name',
dataIndex: 'name',
flex: 1,
minWidth:200,
renderer: function (value, meta, record) {
//if (record.get("status") == "Finished"){
//if (record.get("resultID")){
// return "<a style= 'color: blue;' href='javascript:openResultDetails(""+ record.get("resultID") +"")'>" + value +"</a>";
//}
//else{
// return value;
//}
//console.log(value);
if (record.get("resultID")){
//if(value.indexOf("<a style") == -1){
//record.set("tempName",value);
//record.set("name","<a style= 'color: blue;' href='javascript:openResultDetails(""+ record.get("resultID") +"")'>" + value +"</a>");
//}
//return value;
return "<a style= 'color: blue;' href='javascript:openResultDetails(""+ record.get("resultID") +"",""+ me.itemId +"")'>" + value +"</a>";
}
//record.set("name")
return value;
}
},
{
header: 'Tags',
dataIndex: 'tag',
width: 120
},
{
header: 'Start Action',
dataIndex: 'startAction',
width: 80,
hidden:true,
editor: {
xtype: 'textfield',
maskRe: /^\d+$/,
allowBlank: true,
listeners:{
focus: function(){
this.selectText();
}
}
}
},
{
header: 'End Action',
dataIndex: 'endAction',
hidden:true,
width: 80,
editor: {
xtype: 'textfield',
maskRe: /^\d+$/,
allowBlank: true,
listeners:{
focus: function(){
this.selectText();
}
}
}
},
{
header: 'Status',
dataIndex: 'status',
width: 100,
renderer: function (value, meta, record) {
//if(record.get("resultID") != ""){
// record.set("name","<a style= 'color: blue;' href='javascript:openResultDetails(""+ record.get("resultID") +"")'>" + record.get("tempName") +"</a>");
//}
if(record.get("host") && (value == "Running")){
return "<a style= 'color: blue;' href='javascript:vncToMachine(""+ record.get("host") +"",""+ record.get("vncport") +"")'>" + value +"</a>";
}
else if (value == "Finished"){
return "<p style='color:green'>"+value+"</p>";
}
else if ( value == "Not Run"){
return "<p style='color:#ffb013'>"+value+"</p>";
}
else{
return value;
}
}
},
{
xtype:"datecolumn",
format:'m/d h:i:s',
header: 'Started',
dataIndex: 'startdate',
width: 100
},
{
xtype:"datecolumn",
format:'m/d h:i:s',
header: 'Finished',
dataIndex: 'enddate',
width: 100
},
{
header: 'Elapsed Time',
dataIndex: 'runtime',
width: 75,
renderer: function(value,meta,record){
if (value == "") return "";
var hours = Math.floor(parseInt(value,10) / 36e5),
mins = Math.floor((parseInt(value,10) % 36e5) / 6e4),
secs = Math.floor((parseInt(value,10) % 6e4) / 1000);
return hours+"h:"+mins+"m:"+secs+"s";
}
},
{
header: 'Error',
dataIndex: 'error',
width: 250,
renderer: function(value,meta,record){
if (value == "") return value;
//if(value.indexOf("<div style") == -1){
//
// record.set("error",'<div style="color:red" ext:qwidth="150" ext:qtip="' + value + '">' + value + '</div>');
//}
value = Ext.util.Format.htmlEncode(value);
meta.tdAttr = 'data-qtip="' + value + '"';
return '<div style="color:red" ext:qwidth="150" ext:qtip="' + value + '">' + value + '</div>'
}
},
{
header: 'Result',
dataIndex: 'result',
width: 120,
renderer: function(value,record){
if (value == "Passed"){
return "<p style='color:green'>"+value+"</p>"
}
else if (value == "Failed"){
return "<p style='color:red'>"+value+"</p>"
}
else{
return value;
}
}
},
{
header: 'Note',
dataIndex: 'note',
width: 300,
editor: {
xtype: 'textfield',
allowBlank: true,
listeners:{
focus: function(){
//this.selectText();
}
}
},
renderer: function(value,metadata,record){
if (value == ""){
return value;
}
metadata.tdCls = 'x-redwood-results-cell';
return Autolinker.link( value, {} );
/*
else{
metadata.style = 'background-image: url(images/note_pinned.png);background-position: center; background-repeat: no-repeat;';
//metadata.tdAttr = 'data-qalign="tl-tl?" data-qtip="' + Ext.util.Format.htmlEncode(value) + '"';
//metadata.tdAttr = 'data-qwidth=500 data-qtip="' + Ext.util.Format.htmlEncode(value) + '"';
return "";
//return '<div ext:qtip="' + value + '"/>';
//return "<img src='images/note_pinned.png'/>";
}
*/
}
}
]
});
me.statusListener = function(options,eOpts){
if (options.update){
options.update.forEach(function(r){
if (r.get("_id") != me.itemId) return;
var status = r.get("status");
var lastScrollPos = me.getEl().dom.children[0].scrollTop;
me.down("#status").setValue(status);
me.getEl().dom.children[0].scrollTop = lastScrollPos;
if (status == "Running"){
if (me.title.indexOf("[Running]") == -1){
me.up("executionsEditor").down("#runExecution").setDisabled(true);
me.up("executionsEditor").down("#stopExecution").setDisabled(false);
me.setTitle(me.title+" [Running]")
}
}
else{
me.up("executionsEditor").down("#runExecution").setDisabled(false);
me.up("executionsEditor").down("#stopExecution").setDisabled(true);
me.setTitle(me.title.replace(" [Running]",""))
}
});
}
};
Ext.data.StoreManager.lookup("Executions").on("beforesync",me.statusListener);
me.chartStore = new Ext.data.Store({
fields: [
{name: 'name', type: 'string'},
{name: 'data', type: 'int'}
],
data: [
{ 'name': 'Passed', 'data': 0 , color:"green"},
{ 'name': 'Failed', 'data': 0, color:"red" },
{ 'name': 'Not Run', 'data': 0, color:"#ffb013" }
]
});
me.usersStore = new Ext.data.Store({
fields: [
{name: 'name', type: 'string'},
{name: 'email', type: 'string'},
{name: 'username', type: 'string'}
],
data: []
});
me.savedEmails = [];
Ext.data.StoreManager.lookup('Users').each(function(user){
var newRecord = me.usersStore.add({name:user.get("name"),email:user.get("email"),username:user.get("username")});
if((me.dataRecord != null) && (me.dataRecord.get("emails"))){
if(me.dataRecord.get("emails").indexOf(user.get("email")) != -1){
me.savedEmails.push(user.get("email"));
}
}
});
this.items = [
{
xtype: 'fieldset',
title: 'Details',
defaultType: 'textfield',
flex: 1,
collapsible: true,
defaults: {
flex: 1
},
items: [
{
fieldLabel: "Name",
allowBlank: false,
labelStyle: "font-weight: bold",
itemId:"name",
anchor:'90%',
listeners:{
change: function(field){
if (me.loadingData === false){
me.markDirty();
}
}
}
},
{
xtype:"combofieldbox",
typeAhead:true,
fieldLabel: "Tags",
displayField:"value",
descField:"value",
height:24,
anchor:'90%',
//labelWidth: 100,
forceSelection:false,
createNewOnEnter:true,
encodeSubmitValue:true,
autoSelect: true,
createNewOnBlur: true,
store:Ext.data.StoreManager.lookup('ExecutionTags'),
valueField:"value",
queryMode: 'local',
maskRe: /[a-z_0-9_A-Z_-]/,
removeOnDblClick:true,
itemId:"tag",
listeners:{
change: function(){
if (me.loadingData === false){
me.markDirty();
}
}
}
},
{
xtype: "combo",
anchor:'90%',
fieldLabel: 'Test Set',
store: Ext.data.StoreManager.lookup('TestSets'),
labelStyle: "font-weight: bold",
//value: "",
queryMode: 'local',
displayField: 'name',
valueField: '_id',
forceSelection: true,
editable: false,
allowBlank: false,
itemId:"testset",
listeners:{
change: function(combo,newVal,oldVal){
if (me.dataRecord != null) return;
if (me.loadingData === false){
me.markDirty();
}
var testSet = combo.store.findRecord("_id",newVal);
me.down("#executionTestcases").store.removeAll();
var allTCs = [];
testSet.get("testcases").forEach(function(testcaseId){
var testcase = Ext.data.StoreManager.lookup('TestCases').query("_id",testcaseId._id).getAt(0);
//me.down("#executionTestcases").store.add({name:testcase.get("name"),tag:testcase.get("tag"),status:"Not Run",testcaseID:testcase.get("_id"),_id: Ext.uniqueId()});
if(testcase){
if(testcase.get("tcData") && testcase.get("tcData").length > 0){
testcase.get("tcData").forEach(function(row,index){
allTCs.push({rowIndex:index+1,tcData:row,name:testcase.get("name")+"_"+(index+1),tag:testcase.get("tag"),status:"Not Run",testcaseID:testcase.get("_id"),_id: Ext.uniqueId()});
})
}
else{
allTCs.push({name:testcase.get("name"),tag:testcase.get("tag"),status:"Not Run",testcaseID:testcase.get("_id"),_id: Ext.uniqueId()});
}
}
});
me.down("#executionTestcases").store.add(allTCs);
me.down("#totalNotRun").setRawValue(allTCs.length);
me.down("#totalTestCases").setRawValue(allTCs.length);
}
}
},
{
xtype:"displayfield",
fieldLabel: "State",
//labelStyle: "font-weight: bold",
itemId:"status",
anchor:'90%',
renderer: function(value,meta){
if (value == "Ready To Run"){
return "<p style='font-weight:bold;color:#ffb013'>"+value+"</p>";
}
else{
return "<p style='font-weight:bold;color:green'>"+value+"</p>";
}
}
},
{
xtype: 'button',
cls: 'x-btn-text-icon',
icon: 'images/lock_open.png',
itemId: "locked",
text: 'Lock',
iconAlign: "right",
handler: function(btn) {
if(btn.getText() == "Lock"){
btn.setText("Unlock");
btn.setIcon("images/lock_ok.png")
}
else{
btn.setText("Lock");
btn.setIcon("images/lock_open.png")
}
if (me.loadingData === false){
me.markDirty();
}
}
}
]
},
{
xtype: 'fieldset',
title: 'Email Notification',
flex: 1,
collapsed: false,
collapsible: true,
layout:"hbox",
defaults: {
margin: '0 10 0 5',
labelWidth: "100px"
},
items:[
{
xtype: "checkbox",
fieldLabel: "Send Email",
itemId:"sendEmail",
labelWidth: 70,
anchor:'90%',
listeners:{
afterrender: function(me,eOpt){
Ext.tip.QuickTipManager.register({
target: me.getEl(),
//title: 'My Tooltip',
text: 'Send E-Mail notification.',
//width: 100,
dismissDelay: 10000 // Hide after 10 seconds hover
});
},
change: function(){
if (me.loadingData === false){
//me.markDirty();
}
}
}
},
{
xtype:"combofieldbox",
typeAhead:true,
fieldLabel: "E-Mails",
displayField:"name",
descField:"name",
height:24,
width: 800,
anchor:'90%',
labelWidth: 50,
forceSelection:false,
createNewOnEnter:true,
encodeSubmitValue:true,
autoSelect: true,
createNewOnBlur: true,
store:me.usersStore,
valueField:"email",
queryMode: 'local',
removeOnDblClick:true,
itemId:"emails",
listeners:{
afterrender: function(field,eOpt){
},
change: function(){
if (me.loadingData === false){
me.markDirty();
}
}
}
}
]
},
{
xtype: 'fieldset',
title: 'Settings',
flex: 1,
collapsed: true,
collapsible: true,
layout:"hbox",
defaults: {
margin: '0 10 0 5',
labelWidth: "100px",
labelPad: 0
},
items:[
{
xtype: 'numberfield',
width: 150,
labelWidth: "70px",
//anchor: "90%",
itemId: "retryCount",
fieldLabel: 'Retry Count',
value: 0,
maxValue: 99,
minValue: 0,
listeners:{
afterrender: function(me,eOpt){
Ext.tip.QuickTipManager.register({
target: me.getEl(),
text: 'Number of times to re-run failed test cases.',
dismissDelay: 10000 // Hide after 10 seconds hover
});
},
blur: function(me){
if (me.getValue() === null){
me.setValue(0)
}
}
}
},
{
xtype: "checkbox",
fieldLabel: "Ignore Status",
itemId:"ignoreStatus",
labelWidth: "75px",
anchor:'90%',
listeners:{
afterrender: function(me,eOpt){
Ext.tip.QuickTipManager.register({
target: me.getEl(),
//title: 'My Tooltip',
text: 'Run Test Cases even if Test Case or Action status is Not Automated or Needs Maintanence.',
//width: 100,
dismissDelay: 10000 // Hide after 10 seconds hover
});
},
change: function(){
if (me.loadingData === false){
me.markDirty();
}
}
}
},
{
xtype: "checkbox",
fieldLabel: "No Screen Shots",
itemId:"ignoreScreenshots",
labelWidth: "92px",
anchor:'90%',
listeners:{
afterrender: function(me,eOpt){
Ext.tip.QuickTipManager.register({
target: me.getEl(),
//title: 'My Tooltip',
text: "Don't take any screen shot during the test.",
//width: 100,
dismissDelay: 10000 // Hide after 10 seconds hover
});
},
change: function(){
if (me.loadingData === false){
me.markDirty();
}
}
}
},
{
xtype: "checkbox",
fieldLabel: "UI Snapshots",
itemId:"allScreenshots",
labelWidth: "75px",
anchor:'90%',
listeners:{
afterrender: function(me,eOpt){
Ext.tip.QuickTipManager.register({
target: me.getEl(),
//title: 'My Tooltip',
text: "Take a screen shot for every action.",
//width: 100,
dismissDelay: 10000 // Hide after 10 seconds hover
});
},
change: function(){
if (me.loadingData === false){
me.markDirty();
}
}
}
},
{
xtype: "checkbox",
fieldLabel: "No After State",
itemId:"ignoreAfterState",
labelWidth: "80px",
anchor:'90%',
listeners:{
afterrender: function(me,eOpt){
Ext.tip.QuickTipManager.register({
target: me.getEl(),
//title: 'My Tooltip',
text: "Don't run after state.",
//width: 100,
dismissDelay: 10000 // Hide after 10 seconds hover
});
},
change: function(){
if (me.loadingData === false){
me.markDirty();
}
}
}
}
]
},
{
xtype: 'fieldset',
title: 'Set Variables',
flex: 1,
collapsed: true,
collapsible: true,
items:[
variablesGrid
]
},
{
xtype: 'fieldset',
title: 'Execution Totals',
flex: 1,
collapsed: true,
collapsible: true,
layout:"hbox",
defaults: {
margin: '0 10 0 5',
labelWidth: "80px",
labelStyle: "font-weight: bold"
},
items:[
{
xtype:"displayfield",
fieldLabel: "Total",
itemId:"totalTestCases",
value: "0",
renderer: function(value,meta){
return "<p style='font-weight:bold;color:blue'>"+value+"</p>";
}
},
{
xtype:"displayfield",
fieldLabel: "Passed",
itemId:"totalPassed",
value: "0",
renderer: function(value,meta){
if (value == "0"){
return value
}
else{
return "<p style='font-weight:bold;color:green'>"+value+"</p>";
}
}
},
{
xtype:"displayfield",
fieldLabel: "Failed",
itemId:"totalFailed",
value: "0",
renderer: function(value,meta){
if (value == "0"){
return value;
}
else{
return "<p style='font-weight:bold;color:red'>"+value+"</p>";
}
}
},
{
xtype:"displayfield",
fieldLabel: "Not Run",
itemId:"totalNotRun",
value: "0",
renderer: function(value,meta){
if (value == "0"){
return value;
}
else{
return "<p style='font-weight:bold;color:#ffb013'>"+value+"</p>";
}
}
},
{
xtype:"displayfield",
fieldLabel: "Run Time Sum",
itemId:"runtime",
value: "0",
renderer: function(value,meta){
var hours = Math.floor(parseInt(value,10) / 36e5),
mins = Math.floor((parseInt(value,10) % 36e5) / 6e4),
secs = Math.floor((parseInt(value,10) % 6e4) / 1000);
return "<p style='font-weight:bold;color:#blue'>"+hours+"h:"+mins+"m:"+secs+"s"+"</p>";
}
}
]
},
{
xtype: 'fieldset',
title: 'Execution Chart',
flex: 1,
collapsible: true,
collapsed: true,
layout:"fit",
defaults: {
margin: '0 10 0 5',
labelWidth: "60px",
labelStyle: "font-weight: bold"
},
items:[
{
xtype:"chart",
width: 500,
height: 350,
animate: false,
store: me.chartStore,
theme: 'Base:gradients',
series: [{
type: 'pie',
angleField: 'data',
showInLegend: true,
renderer: function(sprite, record, attr, index, store) {
var color = "green";
if(record.get("name") == "Passed") color = "green";
if(record.get("name") == "Failed") color = "red";
if(record.get("name") == "Not Run") color = "#ffb013";
return Ext.apply(attr, {
fill: color
});
},
tips: {
trackMouse: true,
width: 140,
height: 28,
renderer: function(storeItem, item,attr) {
// calculate and display percentage on hover
var total = 0;
//me.chartStore.each(function(rec) {
// total += rec.get('data');
//});
//this.setTitle(storeItem.get('name') + ': ' + Math.round(storeItem.get('data') / total * 100) + '%');
this.setTitle(storeItem.get('name') + ': ' + storeItem.get('data'));
}
},
/*
highlight: {
segment: {
margin: 10
}
},
*/
label: {
field: 'name',
//display: 'rotate',
display: 'outside',
//contrast: true,
//color:"#22EDFF",
font: '18px Arial'
}
}]
}
]
},
{
xtype: 'fieldset',
title: 'Cloud',
flex: 1,
collapsible: true,
hidden:true,
collapsed: false,
items:[
{
xtype:"displayfield",
fieldLabel: "Status",
itemId:"cloudStatus",
value: "",
renderer: function(value,meta){
if(value.indexOf("Error:") != -1){
return "<p style='font-weight:bold;color:red'>"+value+"</p>";
}
else{
return "<p style='font-weight:bold;color:green'>"+value+"</p>";
}
}
},
templatesGrid
]
},
{
xtype: 'fieldset',
title: 'Select Machines',
flex: 1,
collapsible: true,
items:[
machinesGrid
]
},
{
xtype: 'fieldset',
title: 'Test Cases',
flex: 1,
collapsible: true,
items:[
testcasesGrid
]
}
];
this.callParent(arguments);
me.loadingData = false;
},
listeners:{
afterrender: function(me){
me.loadingData = true;
if (me.dataRecord != null){
me.down("#name").setValue(me.dataRecord.get("name"));
me.down("#status").setValue(me.dataRecord.get("status"));
me.down("#tag").setValue(me.dataRecord.get("tag"));
me.down("#testset").setValue(me.dataRecord.get("testset"));
me.down("#testset").setDisabled(true);
me.down("#executionTestcases").store.removeAll();
me.down("#ignoreStatus").setValue(me.dataRecord.get("ignoreStatus"));
me.down("#ignoreScreenshots").setValue(me.dataRecord.get("ignoreScreenshots"));
me.down("#allScreenshots").setValue(me.dataRecord.get("allScreenshots"));
me.down("#ignoreAfterState").setValue(me.dataRecord.get("ignoreAfterState"));
me.down("#cloudStatus").setValue(me.dataRecord.get("cloudStatus"));
if (me.dataRecord.get("locked") == true){
me.down("#locked").setIcon("images/lock_ok.png");
me.down("#locked").setText("Unlock");
}
else{
me.down("#locked").setIcon("images/lock_open.png");
me.down("#locked").setText("Lock");
}
me.down("#emails").setValue(me.savedEmails);
var allTCs = [];
var loadTCs = function(){
me.dataRecord.get("testcases").forEach(function(testcase){
var originalTC = Ext.data.StoreManager.lookup('TestCases').query("_id",testcase.testcaseID).getAt(0);
if (originalTC){
if(testcase.tcData && testcase.tcData != ""){
testcase.name = originalTC.get("name")+"_"+testcase.rowIndex;
}
else{
testcase.name = originalTC.get("name");
}
testcase.tag = originalTC.get("tag");
allTCs.push(testcase);
}
});
me.down("#executionTestcases").store.add(allTCs);
me.down("#executionTestcases").store.filter("email", /\.com$/);
me.down("#executionTestcases").store.clearFilter();
};
if (Ext.data.StoreManager.lookup('TestCases').initialLoad == true){
loadTCs();
}
else{
Ext.data.StoreManager.lookup('TestCases').on("load",function(){
loadTCs();
})
}
}
else{
var record = me.down("#emails").store.findRecord("username",Ext.util.Cookies.get('username'));
if(record) me.down("#emails").setValue(record);
}
me.loadingData = false;
me.initialTotals();
this.down("#name").focus();
me.on("beforecontainermousedown",function(){
//if (me.getEl()){
//me.lastScrollPos = me.getEl().dom.children[0].scrollTop;
//console.log(me.lastScrollPos)
//}
});
me.down("#executionTestcases").getSelectionModel().on("selectionchange",function(){
//if(me.lastScrollPos != null){
// me.getEl().dom.children[0].scrollTop = me.lastScrollPos;
// me.lastScrollPos = null;
//}
})
},
beforedestroy: function(me){
Ext.data.StoreManager.lookup("Executions").removeListener("beforesync",me.statusListener);
Ext.data.StoreManager.lookup("Machines").removeListener("beforesync",me.machinesListener);
Ext.data.StoreManager.lookup("Variables").removeListener("beforesync",me.variablesListener);
Ext.data.StoreManager.remove(me.executionTCStore);
}
},
validate: function(store){
if (this.down("#name").validate() == false){
this.down("#name").focus();
return false;
}
if (this.down("#testset").validate() == false){
this.down("#testset").focus();
return false;
}
return true;
},
getStatus: function(){
return this.down("#status").getValue();
},
getSelectedTestCases: function(){
var testcases = [];
this.down("#executionTestcases").getSelectionModel().getSelection().forEach(function(testcase){
testcases.push({rowIndex:testcase.get("rowIndex"),tcData:testcase.get("tcData"),testcaseID:testcase.get("testcaseID"),_id:testcase.get("_id"),resultID:testcase.get("resultID"),startAction:testcase.get("startAction"),endAction:testcase.get("endAction")});
});
return testcases;
},
getSelectedMachines: function(){
var machines = [];
this.down("#executionMachines").getSelectionModel().getSelection().forEach(function(machine){
machines.push(machine.data);
});
return machines;
},
getSelectedTemplates: function(){
var templates = [];
this.down("#executionTemplates").getSelectionModel().getSelection().forEach(function(template){
templates.push(template.data);
});
return templates;
},
getExecutionData: function(){
var execution = {};
execution._id = this.itemId;
execution.name = this.down("#name").getValue();
execution.tag = this.down("#tag").getValue();
execution.testset = this.down("#testset").getValue();
execution.testsetname = this.down("#testset").getRawValue ();
execution.ignoreStatus = this.down("#ignoreStatus").getValue();
execution.ignoreAfterState = this.down("#ignoreAfterState").getValue();
execution.ignoreScreenshots = this.down("#ignoreScreenshots").getValue();
execution.allScreenshots = this.down("#allScreenshots").getValue();
execution.emails = this.down("#emails").getValue();
if (this.down("#locked").getText() == "Lock"){
execution.locked = false;
}
else{
execution.locked = true;
}
var variablesStore = this.down("#executionVars").store;
execution.variables = [];
variablesStore.each(function(item){
execution.variables.push(item.data);
});
var testcasesStore = this.down("#executionTestcases").store;
execution.testcases = [];
//testcasesStore.query("name",/.*/).each(function(item){
testcasesStore.query("_id",/.*/).each(function(item){
execution.testcases.push(item.data);
});
var machinesStore = this.down("#executionMachines").store;
execution.machines = [];
machinesStore.each(function(item){
execution.machines.push(item.data);
});
return execution;
}
}); | chenc4/RedwoodHQ | public/view/ExecutionView.js | JavaScript | gpl-3.0 | 84,657 |
var searchData=
[
['left',['left',['../struct__bst__node.html#ac33950f6c4a6e2bbe1674d0c7436b30f',1,'_bst_node']]]
];
| Richard-Degenne/bst | doc/html/search/variables_3.js | JavaScript | gpl-3.0 | 119 |
/**
* Template Name: Daily Shop
* Version: 1.1
* Template Scripts
* Author: MarkUps
* Author URI: http://www.markups.io/
Custom JS
1. CARTBOX
2. TOOLTIP
3. PRODUCT VIEW SLIDER
4. POPULAR PRODUCT SLIDER (SLICK SLIDER)
5. FEATURED PRODUCT SLIDER (SLICK SLIDER)
6. LATEST PRODUCT SLIDER (SLICK SLIDER)
7. TESTIMONIAL SLIDER (SLICK SLIDER)
8. CLIENT BRAND SLIDER (SLICK SLIDER)
9. PRICE SLIDER (noUiSlider SLIDER)
10. SCROLL TOP BUTTON
11. PRELOADER
12. GRID AND LIST LAYOUT CHANGER
13. RELATED ITEM SLIDER (SLICK SLIDER)
14. TOP SLIDER (SLICK SLIDER)
**/
jQuery(function($){
/* ----------------------------------------------------------- */
/* 1. CARTBOX
/* ----------------------------------------------------------- */
jQuery(".aa-cartbox").hover(function(){
jQuery(this).find(".aa-cartbox-summary").fadeIn(500);
}
,function(){
jQuery(this).find(".aa-cartbox-summary").fadeOut(500);
}
);
/* ----------------------------------------------------------- */
/* 2. TOOLTIP
/* ----------------------------------------------------------- */
jQuery('[data-toggle="tooltip"]').tooltip();
jQuery('[data-toggle2="tooltip"]').tooltip();
/* ----------------------------------------------------------- */
/* 3. PRODUCT VIEW SLIDER
/* ----------------------------------------------------------- */
jQuery('#demo-1 .simpleLens-thumbnails-container img').simpleGallery({
loading_image: 'img/view-slider/loading.gif'
});
jQuery('#demo-1 .simpleLens-big-image').simpleLens({
loading_image: 'img/view-slider/loading.gif'
});
/* ----------------------------------------------------------- */
/* 4. POPULAR PRODUCT SLIDER (SLICK SLIDER)
/* ----------------------------------------------------------- */
jQuery('.aa-popular-slider').slick({
dots: false,
infinite: false,
speed: 300,
slidesToShow: 4,
slidesToScroll: 4,
responsive: [
{
breakpoint: 1024,
settings: {
slidesToShow: 3,
slidesToScroll: 3,
infinite: true,
dots: true
}
},
{
breakpoint: 600,
settings: {
slidesToShow: 2,
slidesToScroll: 2
}
},
{
breakpoint: 480,
settings: {
slidesToShow: 1,
slidesToScroll: 1
}
}
// You can unslick at a given breakpoint now by adding:
// settings: "unslick"
// instead of a settings object
]
});
/* ----------------------------------------------------------- */
/* 5. FEATURED PRODUCT SLIDER (SLICK SLIDER)
/* ----------------------------------------------------------- */
jQuery('.aa-featured-slider').slick({
dots: false,
infinite: false,
speed: 300,
slidesToShow: 4,
slidesToScroll: 4,
responsive: [
{
breakpoint: 1024,
settings: {
slidesToShow: 3,
slidesToScroll: 3,
infinite: true,
dots: true
}
},
{
breakpoint: 600,
settings: {
slidesToShow: 2,
slidesToScroll: 2
}
},
{
breakpoint: 480,
settings: {
slidesToShow: 1,
slidesToScroll: 1
}
}
// You can unslick at a given breakpoint now by adding:
// settings: "unslick"
// instead of a settings object
]
});
/* ----------------------------------------------------------- */
/* 6. LATEST PRODUCT SLIDER (SLICK SLIDER)
/* ----------------------------------------------------------- */
jQuery('.aa-latest-slider').slick({
dots: false,
infinite: false,
speed: 300,
slidesToShow: 4,
slidesToScroll: 4,
responsive: [
{
breakpoint: 1024,
settings: {
slidesToShow: 3,
slidesToScroll: 3,
infinite: true,
dots: true
}
},
{
breakpoint: 600,
settings: {
slidesToShow: 2,
slidesToScroll: 2
}
},
{
breakpoint: 480,
settings: {
slidesToShow: 1,
slidesToScroll: 1
}
}
// You can unslick at a given breakpoint now by adding:
// settings: "unslick"
// instead of a settings object
]
});
/* ----------------------------------------------------------- */
/* 7. TESTIMONIAL SLIDER (SLICK SLIDER)
/* ----------------------------------------------------------- */
jQuery('.aa-testimonial-slider').slick({
dots: true,
infinite: true,
arrows: false,
speed: 300,
slidesToShow: 1,
adaptiveHeight: true
});
/* ----------------------------------------------------------- */
/* 8. CLIENT BRAND SLIDER (SLICK SLIDER)
/* ----------------------------------------------------------- */
jQuery('.aa-client-brand-slider').slick({
dots: false,
infinite: false,
speed: 300,
autoplay: true,
autoplaySpeed: 2000,
slidesToShow: 5,
slidesToScroll: 1,
responsive: [
{
breakpoint: 1024,
settings: {
slidesToShow: 4,
slidesToScroll: 4,
infinite: true,
dots: true
}
},
{
breakpoint: 600,
settings: {
slidesToShow: 2,
slidesToScroll: 2
}
},
{
breakpoint: 480,
settings: {
slidesToShow: 1,
slidesToScroll: 1
}
}
// You can unslick at a given breakpoint now by adding:
// settings: "unslick"
// instead of a settings object
]
});
/* ----------------------------------------------------------- */
/* 9. PRICE SLIDER (noUiSlider SLIDER)
/* ----------------------------------------------------------- */
jQuery(function(){
if($('body').is('.productPage')){
var skipSlider = document.getElementById('skipstep');
noUiSlider.create(skipSlider, {
range: {
'min': 0,
'10%': 10,
'20%': 20,
'30%': 30,
'40%': 40,
'50%': 50,
'60%': 60,
'70%': 70,
'80%': 80,
'90%': 90,
'max': 100
},
snap: true,
connect: true,
start: [20, 70]
});
// for value print
var skipValues = [
document.getElementById('skip-value-lower'),
document.getElementById('skip-value-upper')
];
skipSlider.noUiSlider.on('update', function( values, handle ) {
skipValues[handle].innerHTML = values[handle];
});
}
});
/* ----------------------------------------------------------- */
/* 10. SCROLL TOP BUTTON
/* ----------------------------------------------------------- */
//Check to see if the window is top if not then display button
jQuery(window).scroll(function(){
if ($(this).scrollTop() > 300) {
$('.scrollToTop').fadeIn();
} else {
$('.scrollToTop').fadeOut();
}
});
//Click event to scroll to top
jQuery('.scrollToTop').click(function(){
$('html, body').animate({scrollTop : 0},800);
return false;
});
/* ----------------------------------------------------------- */
/* 11. PRELOADER
/* ----------------------------------------------------------- */
jQuery(window).load(function() { // makes sure the whole site is loaded
jQuery('#wpf-loader-two').delay(200).fadeOut('slow'); // will fade out
})
/* ----------------------------------------------------------- */
/* 12. GRID AND LIST LAYOUT CHANGER
/* ----------------------------------------------------------- */
jQuery("#list-catg").click(function(e){
e.preventDefault(e);
jQuery(".aa-product-catg").addClass("list");
});
jQuery("#grid-catg").click(function(e){
e.preventDefault(e);
jQuery(".aa-product-catg").removeClass("list");
});
/* ----------------------------------------------------------- */
/* 13. RELATED ITEM SLIDER (SLICK SLIDER)
/* ----------------------------------------------------------- */
jQuery('.aa-related-item-slider').slick({
dots: false,
infinite: false,
speed: 300,
slidesToShow: 4,
slidesToScroll: 4,
responsive: [
{
breakpoint: 1024,
settings: {
slidesToShow: 3,
slidesToScroll: 3,
infinite: true,
dots: true
}
},
{
breakpoint: 600,
settings: {
slidesToShow: 2,
slidesToScroll: 2
}
},
{
breakpoint: 480,
settings: {
slidesToShow: 1,
slidesToScroll: 1
}
}
// You can unslick at a given breakpoint now by adding:
// settings: "unslick"
// instead of a settings object
]
});
/* ----------------------------------------------------------- */
/* 14. TOP SLIDER (SLICK SLIDER)
/* ----------------------------------------------------------- */
jQuery('.seq-canvas').slick({
dots: false,
infinite: true,
speed: 500,
fade: true,
cssEase: 'linear'
});
});
| aquinotgr00/lc-app | public/js/d-shop/custom.js | JavaScript | gpl-3.0 | 10,027 |
// ** I18N
// Calendar pt-BR language
// Author: Fernando Dourado, <fernando.dourado@ig.com.br>
// Encoding: any
// Distributed under the same terms as the calendar itself.
// For translators: please use UTF-8 if possible. We strongly believe that
// Unicode is the answer to a real internationalized world. Also please
// include your contact information in the header, as can be seen above.
// full day names
Calendar._DN = new Array
("Domingo",
"Segunda",
"Terça",
"Quarta",
"Quinta",
"Sexta",
"Sabádo",
"Domingo");
// Please note that the following array of short day names (and the same goes
// for short month names, _SMN) isn't absolutely necessary. We give it here
// for exemplification on how one can customize the short day names, but if
// they are simply the first N letters of the full name you can simply say:
//
// Calendar._SDN_len = N; // short day name length
// Calendar._SMN_len = N; // short month name length
//
// If N = 3 then this is not needed either since we assume a value of 3 if not
// present, to be compatible with translation files that were written before
// this feature.
// short day names
// [No changes using default values]
// full month names
Calendar._MN = new Array
("Janeiro",
"Fevereiro",
"Março",
"Abril",
"Maio",
"Junho",
"Julho",
"Agosto",
"Setembro",
"Outubro",
"Novembro",
"Dezembro");
// short month names
// [No changes using default values]
// First day of the week. "0" means display Sunday first, "1" means display
// Monday first, etc.
Calendar._FD = 1;
// tooltips
Calendar._TT = {};
Calendar._TT["INFO"] = "Sobre o calendário";
Calendar._TT["ABOUT"] =
"DHTML Date/Time Selector\n" +
"(c) dynarch.com 2002-2005 / Author: Mihai Bazon\n" + // don't translate this this ;-)
"For latest version visit: http://www.dynarch.com/projects/calendar/\n" +
"Distributed under GNU LGPL. See http://gnu.org/licenses/lgpl.html for details." +
"\n\n" +
"Translate to portuguese Brazil (pt-BR) by Fernando Dourado (fernando.dourado@ig.com.br)\n" +
"Tradução para o português Brasil (pt-BR) por Fernando Dourado (fernando.dourado@ig.com.br)" +
"\n\n" +
"Selecionar data:\n" +
"- Use as teclas \xab, \xbb para selecionar o ano\n" +
"- Use as teclas " + String.fromCharCode(0x2039) + ", " + String.fromCharCode(0x203a) + " para selecionar o mês\n" +
"- Clique e segure com o mouse em qualquer botão para selecionar rapidamente.";
Calendar._TT["ABOUT_TIME"] = "\n\n" +
"Selecionar hora:\n" +
"- Clique em qualquer uma das partes da hora para aumentar\n" +
"- ou Shift-clique para diminuir\n" +
"- ou clique e arraste para selecionar rapidamente.";
Calendar._TT["PREV_YEAR"] = "Ano anterior (clique e segure para menu)";
Calendar._TT["PREV_MONTH"] = "Mês anterior (clique e segure para menu)";
Calendar._TT["GO_TODAY"] = "Ir para a data atual";
Calendar._TT["NEXT_MONTH"] = "Próximo mês (clique e segure para menu)";
Calendar._TT["NEXT_YEAR"] = "Próximo ano (clique e segure para menu)";
Calendar._TT["SEL_DATE"] = "Selecione uma data";
Calendar._TT["DRAG_TO_MOVE"] = "Clique e segure para mover";
Calendar._TT["PART_TODAY"] = " (hoje)";
// the following is to inform that "%s" is to be the first day of week
// %s will be replaced with the day name.
Calendar._TT["DAY_FIRST"] = "Exibir %s primeiro";
// This may be locale-dependent. It specifies the week-end days, as an array
// of comma-separated numbers. The numbers are from 0 to 6: 0 means Sunday, 1
// means Monday, etc.
Calendar._TT["WEEKEND"] = "0,6";
Calendar._TT["CLOSE"] = "Fechar";
Calendar._TT["TODAY"] = "Hoje";
Calendar._TT["TIME_PART"] = "(Shift-)Clique ou arraste para mudar o valor";
// date formats
Calendar._TT["DEF_DATE_FORMAT"] = "%d/%m/%Y";
Calendar._TT["TT_DATE_FORMAT"] = "%d de %B de %Y";
Calendar._TT["WK"] = "sem";
Calendar._TT["TIME"] = "Hora:";
| projectestac/intraweb | intranet/javascript/jscalendar/lang/calendar-pt_BR.utf8.js | JavaScript | gpl-3.0 | 3,823 |
var searchData=
[
['wizard_2ec',['wizard.c',['../wizard_8c.html',1,'']]],
['wrapper_2ecpp',['wrapper.cpp',['../wrapper_8cpp.html',1,'']]],
['wxforms_2ec',['wxforms.c',['../wxforms_8c.html',1,'']]]
];
| gregnietsky/dtsguiapp | doxygen/html/search/files_77.js | JavaScript | gpl-3.0 | 206 |
// in development
// getsimple tree expansion
// written for editpages, but can probably be expanded to support any
// list of elements with depth data in proper parent child order
//
var treeprefix = 'tree-';
var treeparentclass = treeprefix + 'parent'; // class for expander handles
var treeindentclass = treeprefix + 'indent'; // class for expander handles
var treeexpanderclass = treeprefix + 'expander'; // class for expander handles
var treeexpandedclass = treeprefix + 'expander-expanded'; // class for expander when expanded
var treecollapsedclass = treeprefix + 'expander-collapsed'; // class for expanded when collapsed
var nodecollapsedclass = treeprefix + 'collapsed'; // class to control node visibility and data flag as collapsed
var nodeparentcollapsedclass = treeprefix + 'parentcollapsed'; // class to control children visibility while retaining collapse data
var depthprefix = 'depth-'; // class prefix for depth information
var datadepthattr = 'depth'; // data attribute name for depth information
function toggleRow(){
var row = $(this).closest('.'+treeparentclass);
// Debugger.log("toggle row " + $(row));
var depth = getNodeDepth(row);
if(depth < 0 ) return toggleTopAncestors(); // special handler to collapse all top level
if($(row).hasClass(nodecollapsedclass)) expandRow(row);
else collapseRow(row);
$("table.striped").zebraStripe();
}
function setExpander(elem){
var expander = $(elem).find('.'+treeexpanderclass);
$(expander).toggleClass(treecollapsedclass,$(elem).hasClass(nodecollapsedclass));
$(expander).toggleClass(treeexpandedclass,!$(elem).hasClass(nodecollapsedclass));
}
function collapseRow(elem){
$(elem).addClass(nodecollapsedclass);
hideChildRows(elem);
setExpander(elem);
}
function expandRow(elem){
$(elem).removeClass(nodecollapsedclass);
showChildRows(elem);
setExpander(elem);
}
function hideChildRows(elem){
var children = getChildrenByDepth(elem);
children.each(function(i,elem){
hideChildRow(elem);
});
}
function hideChildRow(elem){
$(elem).addClass(nodeparentcollapsedclass);
// $(elem).animate({opacity: 0.1} , 100, function(){ $(this).addClass(nodeparentcollapsedclass);} ); // @todo custom callout
}
// not using recursion or tree walking here, this is likely faster
// obtains children by getting all siblings up until the first sibling of equal depth
// retains collapse states on parents
function showChildRows(elem){
var children = getChildrenByDepth(elem);
var startDepth = getNodeDepth(elem);
children.each(function(i,elem){
thisDepth = getNodeDepth(elem);
immediateChild = thisDepth == (startDepth + 1);
// if immediate child just show it
if(immediateChild){
showChildRow(elem);
return true;
}
// get actual parent of this child
thisParent = getParentByDepth(elem);
// if(!thisParent[0]) Debugger.log('parent not found');
parentCollapsed = $(thisParent).hasClass(nodecollapsedclass);
parentHidden = $(thisParent).hasClass(nodeparentcollapsedclass);
// Debugger.log(elem.id + ' | ' + $(thisParent).attr('id') + ' | ' + parentCollapsed + ' | ' + parentHidden);
// show child only if parent is not hidden AND parent is not collapsed
if(!parentHidden && !parentCollapsed){
showChildRow(elem);
}
});
}
function showChildRow(elem){
$(elem).removeClass(nodeparentcollapsedclass);
// $(elem).animate({opacity: 1}, 300); // todo: custom callout
}
function getNodeDepth(elem){
return parseInt($(elem).data(datadepthattr),10);
}
function getChildrenByDepth(elem){
// children are all nodes until nextsibling of equal OR LOWER depth
var nextsibling = getNextSiblingByDepth(elem);
var children = elem.nextUntil(nextsibling);
return children;
}
/**
* get the first previous parentclass with lower depth
*/
function getParentByDepth(elem){
var depth = getNodeDepth(elem) - 1;
return $(elem).prevAll("."+treeparentclass+"[data-"+datadepthattr+"='" + (depth) + "']").first();
}
/**
* get the next parent of equal or less depth
*/
function getNextSiblingByDepth(elem){
var tagname = getTagName(elem);
var depth = getNodeDepth(elem);
var nextsiblings = elem.nextAll(tagname).filter(function(index){
return getNodeDepth(this) <= depth;
});
return nextsiblings.first();
}
function addExpanders(elems,expander){
if(expander === undefined) expander = '<span class="'+ treeexpanderclass + ' ' + treeexpandedclass +'"></span>';
$(elems).each(function(i,elem){
// Debugger.log($(elem));
$(elem).removeClass("tree-indent").removeClass("indent-last").html(''); // remove any indentation here, now an expander
$(expander).on('click',toggleRow).bind('selectstart dragstart', function(evt)
{ evt.preventDefault(); return false; }).prependTo($(elem));
});
}
function addIndents(elems){
$(elems).each(function(i,elem){
$('<span class="'+treeindentclass+'"></span>').prependTo($(elem));
});
}
function toggleTopAncestors(){
// @todo possible optimizations
// could use a table css rule to hide all trs, unless classes depth-0 or something with specificty to override
// would skip all iterations needed here, but would also require special css to toggle expanders
// could also use a cache table for these using tr ids
var rootcollapsed = $("#roottoggle").hasClass("rootcollapsed");
// if(rootcollapsed) console.profile('expand all');
// else console.profile('collapse all');
// toggle label text
var langstr = !rootcollapsed ? i18n('EXPAND_TOP') : i18n('COLLAPSE_TOP');
$('#roottoggle .label').html(langstr);
// hide all depth 0 children, do not change collpase data
var depth = 0;
$("#editpages tr[data-depth='" + depth + "']").each(function(i,elem){
if(rootcollapsed) expandRow($(elem));
else collapseRow($(elem));
});
$("#roottoggle").toggleClass("rootcollapsed");
$('#roottoggle').toggleClass(nodecollapsedclass,!rootcollapsed);
setExpander($('#roottoggle'));
$("table.striped").zebraStripe();
// console.profileEnd();
}
// add tree to editpages table
function addExpanderTableHeader(elem,expander,colspan){
// Debugger.log($(elem));
var rootcollapsed = $("#roottoggle").hasClass("rootcollapsed");
var langstr = rootcollapsed ? i18n('EXPAND_TOP') : i18n('COLLAPSE_TOP');
$('<tr id="roottoggle" class="tree-roottoggle nohighlight" data-depth="-1"><td colspan="'+colspan+'">'+expander+'<span class="label">'+ langstr +'</span></td></tr>').insertAfter(elem);
// init expander
$('#roottoggle').toggleClass("collapsed",rootcollapsed);
setExpander($('#roottoggle'));
$('#roottoggle .'+treeexpanderclass).on('click',toggleTopAncestors).bind('selectstart dragstart', function(evt)
{ evt.preventDefault(); return false; });
$('#roottoggle .label').on('click',toggleTopAncestors).bind('selectstart dragstart', function(evt)
{ evt.preventDefault(); return false; });
}
$.fn.zebraStripe = function(){
$("tbody tr:not(.tree-parentcollapsed)",$(this)).each(function(i,elem){
if(i%2!=1) $(elem).addClass('odd').removeClass('even');
else $(elem).addClass('even').removeClass('odd');
});
};
/**
* addTabletree
*
* add gstree to tree ready table with data-depths and parent,indent classes
*
* @param int minrows minumum rows needed to apply tree, else will skip tree creation
* @param int mindepth minimum depth required to apply tree, else wil skip
* @param int headerdepth minimum depth required to add the header expander controls
*/
$.fn.addTableTree = function(minrows,mindepth,headerdepth){
// console.profile();
// @todo for slide animations, temporarily insert tbody at start end of collapse range and animate it, use display:block on tbody
// minrows = 10;
// mindepth = 3;
// headerdepth = 3;
var elem = this;
if(!elem[0]){
Debugger.log("gstree: table does not exist, skipping");
return;
}
// table is small if table has less rows that minrows
var small = minrows !== undefined && $("tbody tr",elem).length < minrows;
// table is shallow if table has depths less than mindepth
var shallow = $("tbody tr[data-depth="+mindepth+"]",elem).length <= 0;
// skip if no children
if(!$("."+treeparentclass,elem)[0] || small || shallow){
if(!small || !shallow) Debugger.log("gstree: insufficient depth, skipping");
else Debugger.log("gstree: table too small, skipping");
return;
}
// custom overrides for fontawesome icons for expander and collapse classes
treeexpandedclass = 'fa-rotate-90';
treecollapsedclass = '';
var customexpander = '<i class="'+treeexpanderclass+' '+treeexpandedclass+' fa fa-play fa-fw"></i>';
addIndents($('tr td:first-child',elem)); // preload indents for roots and childless
addExpanders($('tr.tree-parent td:first-child .tree-indent:last-of-type',elem),customexpander); // add expanders to last indent
$('tr td:first-child .tree-indent:last-of-type').html(''); // remove extra indentation
// add the header expander controls
var deep = headerdepth === undefined || $("tbody tr[data-depth="+headerdepth+"]",elem).length > 0;
if(deep) addExpanderTableHeader($('thead > tr:first',elem),customexpander,4);
$("table.striped").zebraStripe();
// console.profileEnd();
};
| dgleba/getsimplecms1 | admin/template/js/jquery-gstree.js | JavaScript | gpl-3.0 | 9,301 |
module.exports = function (str) {
var bytes = [];
for (var i = 0; i < str.length; i++) {
var c = str.charCodeAt(i);
if (c >= 0xd800 && c <= 0xdbff && i + 1 < str.length) {
var cn = str.charCodeAt(i + 1);
if (cn >= 0xdc00 && cn <= 0xdfff) {
var pt = (c - 0xd800) * 0x400 + cn - 0xdc00 + 0x10000;
bytes.push(
0xf0 + Math.floor(pt / 64 / 64 / 64),
0x80 + Math.floor(pt / 64 / 64) % 64,
0x80 + Math.floor(pt / 64) % 64,
0x80 + pt % 64
);
i += 1;
continue;
}
}
if (c >= 2048) {
bytes.push(
0xe0 + Math.floor(c / 64 / 64),
0x80 + Math.floor(c / 64) % 64,
0x80 + c % 64
);
}
else if (c >= 128) {
bytes.push(0xc0 + Math.floor(c / 64), 0x80 + c % 64);
}
else bytes.push(c);
}
return bytes;
};
| kura52/sushi-browser | resource/tui-editor/node_modules/utf8-bytes/index.js | JavaScript | gpl-3.0 | 1,061 |
/*
Base.js, version 1.1a
Copyright 2006-2010, Dean Edwards
License: http://www.opensource.org/licenses/mit-license.php
*/
var Base = function() {
// dummy
};
Base.extend = function(_instance, _static) { // subclass
"use strict";
var extend = Base.prototype.extend;
// build the prototype
Base._prototyping = true;
var proto = new this();
extend.call(proto, _instance);
proto.base = function() {
// call this method from any other method to invoke that method's ancestor
};
delete Base._prototyping;
// create the wrapper for the constructor function
//var constructor = proto.constructor.valueOf(); //-dean
var constructor = proto.constructor;
var klass = proto.constructor = function() {
if (!Base._prototyping) {
if (this._constructing || this.constructor == klass) { // instantiation
this._constructing = true;
constructor.apply(this, arguments);
delete this._constructing;
} else if (arguments[0] !== null) { // casting
return (arguments[0].extend || extend).call(arguments[0], proto);
}
}
};
// build the class interface
klass.ancestor = this;
klass.extend = this.extend;
klass.forEach = this.forEach;
klass.implement = this.implement;
klass.prototype = proto;
klass.toString = this.toString;
klass.valueOf = function(type) {
//return (type == "object") ? klass : constructor; //-dean
return (type == "object") ? klass : constructor.valueOf();
};
extend.call(klass, _static);
// class initialisation
if (typeof klass.init == "function") klass.init();
return klass;
};
Base.prototype = {
extend: function(source, value) {
if (arguments.length > 1) { // extending with a name/value pair
var ancestor = this[source];
if (ancestor && (typeof value == "function") && // overriding a method?
// the valueOf() comparison is to avoid circular references
(!ancestor.valueOf || ancestor.valueOf() != value.valueOf()) &&
/\bbase\b/.test(value)) {
// get the underlying method
var method = value.valueOf();
// override
value = function() {
var previous = this.base || Base.prototype.base;
this.base = ancestor;
var returnValue = method.apply(this, arguments);
this.base = previous;
return returnValue;
};
// point to the underlying method
value.valueOf = function(type) {
return (type == "object") ? value : method;
};
value.toString = Base.toString;
}
this[source] = value;
} else if (source) { // extending with an object literal
var extend = Base.prototype.extend;
// if this object has a customised extend method then use it
if (!Base._prototyping && typeof this != "function") {
extend = this.extend || extend;
}
var proto = {toSource: null};
// do the "toString" and other methods manually
var hidden = ["constructor", "toString", "valueOf"];
// if we are prototyping then include the constructor
var i = Base._prototyping ? 0 : 1;
while (key = hidden[i++]) {
if (source[key] != proto[key]) {
extend.call(this, key, source[key]);
}
}
// copy each of the source object's properties to this object
for (var key in source) {
if (!proto[key]) extend.call(this, key, source[key]);
}
}
return this;
}
};
// initialise
Base = Base.extend({
constructor: function() {
this.extend(arguments[0]);
}
}, {
ancestor: Object,
version: "1.1",
forEach: function(object, block, context) {
for (var key in object) {
if (this.prototype[key] === undefined) {
block.call(context, object[key], key, object);
}
}
},
implement: function() {
for (var i = 0; i < arguments.length; i++) {
if (typeof arguments[i] == "function") {
// if it's a function, call it
arguments[i](this.prototype);
} else {
// add the interface using the extend method
this.prototype.extend(arguments[i]);
}
}
return this;
},
toString: function() {
return String(this.valueOf());
}
});
/*jshint smarttabs:true */
var FlipClock;
/**
* FlipClock.js
*
* @author Justin Kimbrell
* @copyright 2013 - Objective HTML, LLC
* @licesnse http://www.opensource.org/licenses/mit-license.php
*/
(function($) {
"use strict";
/**
* FlipFlock Helper
*
* @param object A jQuery object or CSS select
* @param int An integer used to start the clock (no. seconds)
* @param object An object of properties to override the default
*/
FlipClock = function(obj, digit, options) {
if(digit instanceof Object && digit instanceof Date === false) {
options = digit;
digit = 0;
}
return new FlipClock.Factory(obj, digit, options);
};
/**
* The global FlipClock.Lang object
*/
FlipClock.Lang = {};
/**
* The Base FlipClock class is used to extend all other FlipFlock
* classes. It handles the callbacks and the basic setters/getters
*
* @param object An object of the default properties
* @param object An object of properties to override the default
*/
FlipClock.Base = Base.extend({
/**
* Build Date
*/
buildDate: '2014-12-12',
/**
* Version
*/
version: '0.7.7',
/**
* Sets the default options
*
* @param object The default options
* @param object The override options
*/
constructor: function(_default, options) {
if(typeof _default !== "object") {
_default = {};
}
if(typeof options !== "object") {
options = {};
}
this.setOptions($.extend(true, {}, _default, options));
},
/**
* Delegates the callback to the defined method
*
* @param object The default options
* @param object The override options
*/
callback: function(method) {
if(typeof method === "function") {
var args = [];
for(var x = 1; x <= arguments.length; x++) {
if(arguments[x]) {
args.push(arguments[x]);
}
}
method.apply(this, args);
}
},
/**
* Log a string into the console if it exists
*
* @param string The name of the option
* @return mixed
*/
log: function(str) {
if(window.console && console.log) {
console.log(str);
}
},
/**
* Get an single option value. Returns false if option does not exist
*
* @param string The name of the option
* @return mixed
*/
getOption: function(index) {
if(this[index]) {
return this[index];
}
return false;
},
/**
* Get all options
*
* @return bool
*/
getOptions: function() {
return this;
},
/**
* Set a single option value
*
* @param string The name of the option
* @param mixed The value of the option
*/
setOption: function(index, value) {
this[index] = value;
},
/**
* Set a multiple options by passing a JSON object
*
* @param object The object with the options
* @param mixed The value of the option
*/
setOptions: function(options) {
for(var key in options) {
if(typeof options[key] !== "undefined") {
this.setOption(key, options[key]);
}
}
}
});
}(jQuery));
/*jshint smarttabs:true */
/**
* FlipClock.js
*
* @author Justin Kimbrell
* @copyright 2013 - Objective HTML, LLC
* @licesnse http://www.opensource.org/licenses/mit-license.php
*/
(function($) {
"use strict";
/**
* The FlipClock Face class is the base class in which to extend
* all other FlockClock.Face classes.
*
* @param object The parent FlipClock.Factory object
* @param object An object of properties to override the default
*/
FlipClock.Face = FlipClock.Base.extend({
/**
* Sets whether or not the clock should start upon instantiation
*/
autoStart: true,
/**
* An array of jQuery objects used for the dividers (the colons)
*/
dividers: [],
/**
* An array of FlipClock.List objects
*/
factory: false,
/**
* An array of FlipClock.List objects
*/
lists: [],
/**
* Constructor
*
* @param object The parent FlipClock.Factory object
* @param object An object of properties to override the default
*/
constructor: function(factory, options) {
this.dividers = [];
this.lists = [];
this.base(options);
this.factory = factory;
},
/**
* Build the clock face
*/
build: function() {
if(this.autoStart) {
this.start();
}
},
/**
* Creates a jQuery object used for the digit divider
*
* @param mixed The divider label text
* @param mixed Set true to exclude the dots in the divider.
* If not set, is false.
*/
createDivider: function(label, css, excludeDots) {
if(typeof css == "boolean" || !css) {
excludeDots = css;
css = label;
}
var dots = [
'<span class="'+this.factory.classes.dot+' top"></span>',
'<span class="'+this.factory.classes.dot+' bottom"></span>'
].join('');
if(excludeDots) {
dots = '';
}
label = this.factory.localize(label);
var html = [
'<span class="'+this.factory.classes.divider+' '+(css ? css : '').toLowerCase()+'">',
'<span class="'+this.factory.classes.label+'">'+(label ? label : '')+'</span>',
dots,
'</span>'
];
var $html = $(html.join(''));
this.dividers.push($html);
return $html;
},
/**
* Creates a FlipClock.List object and appends it to the DOM
*
* @param mixed The digit to select in the list
* @param object An object to override the default properties
*/
createList: function(digit, options) {
if(typeof digit === "object") {
options = digit;
digit = 0;
}
var obj = new FlipClock.List(this.factory, digit, options);
this.lists.push(obj);
return obj;
},
/**
* Triggers when the clock is reset
*/
reset: function() {
this.factory.time = new FlipClock.Time(
this.factory,
this.factory.original ? Math.round(this.factory.original) : 0,
{
minimumDigits: this.factory.minimumDigits
}
);
this.flip(this.factory.original, false);
},
/**
* Append a newly created list to the clock
*/
appendDigitToClock: function(obj) {
obj.$el.append(false);
},
/**
* Add a digit to the clock face
*/
addDigit: function(digit) {
var obj = this.createList(digit, {
classes: {
active: this.factory.classes.active,
before: this.factory.classes.before,
flip: this.factory.classes.flip
}
});
this.appendDigitToClock(obj);
},
/**
* Triggers when the clock is started
*/
start: function() {},
/**
* Triggers when the time on the clock stops
*/
stop: function() {},
/**
* Auto increments/decrements the value of the clock face
*/
autoIncrement: function() {
if(!this.factory.countdown) {
this.increment();
}
else {
this.decrement();
}
},
/**
* Increments the value of the clock face
*/
increment: function() {
this.factory.time.addSecond();
},
/**
* Decrements the value of the clock face
*/
decrement: function() {
if(this.factory.time.getTimeSeconds() == 0) {
this.factory.stop()
}
else {
this.factory.time.subSecond();
}
},
/**
* Triggers when the numbers on the clock flip
*/
flip: function(time, doNotAddPlayClass) {
var t = this;
$.each(time, function(i, digit) {
var list = t.lists[i];
if(list) {
if(!doNotAddPlayClass && digit != list.digit) {
list.play();
}
list.select(digit);
}
else {
t.addDigit(digit);
}
});
}
});
}(jQuery));
/*jshint smarttabs:true */
/**
* FlipClock.js
*
* @author Justin Kimbrell
* @copyright 2013 - Objective HTML, LLC
* @licesnse http://www.opensource.org/licenses/mit-license.php
*/
(function($) {
"use strict";
/**
* The FlipClock Factory class is used to build the clock and manage
* all the public methods.
*
* @param object A jQuery object or CSS selector used to fetch
the wrapping DOM nodes
* @param mixed This is the digit used to set the clock. If an
object is passed, 0 will be used.
* @param object An object of properties to override the default
*/
FlipClock.Factory = FlipClock.Base.extend({
/**
* The clock's animation rate.
*
* Note, currently this property doesn't do anything.
* This property is here to be used in the future to
* programmaticaly set the clock's animation speed
*/
animationRate: 1000,
/**
* Auto start the clock on page load (True|False)
*/
autoStart: true,
/**
* The callback methods
*/
callbacks: {
destroy: false,
create: false,
init: false,
interval: false,
start: false,
stop: false,
reset: false
},
/**
* The CSS classes
*/
classes: {
active: 'flip-clock-active',
before: 'flip-clock-before',
divider: 'flip-clock-divider',
dot: 'flip-clock-dot',
label: 'flip-clock-label',
flip: 'flip',
play: 'play',
wrapper: 'flip-clock-wrapper'
},
/**
* The name of the clock face class in use
*/
clockFace: 'HourlyCounter',
/**
* The name of the clock face class in use
*/
countdown: false,
/**
* The name of the default clock face class to use if the defined
* clockFace variable is not a valid FlipClock.Face object
*/
defaultClockFace: 'HourlyCounter',
/**
* The default language
*/
defaultLanguage: 'english',
/**
* The jQuery object
*/
$el: false,
/**
* The FlipClock.Face object
*/
face: true,
/**
* The language object after it has been loaded
*/
lang: false,
/**
* The language being used to display labels (string)
*/
language: 'english',
/**
* The minimum digits the clock must have
*/
minimumDigits: 0,
/**
* The original starting value of the clock. Used for the reset method.
*/
original: false,
/**
* Is the clock running? (True|False)
*/
running: false,
/**
* The FlipClock.Time object
*/
time: false,
/**
* The FlipClock.Timer object
*/
timer: false,
/**
* The jQuery object (depcrecated)
*/
$wrapper: false,
/**
* Constructor
*
* @param object The wrapping jQuery object
* @param object Number of seconds used to start the clock
* @param object An object override options
*/
constructor: function(obj, digit, options) {
if(!options) {
options = {};
}
this.lists = [];
this.running = false;
this.base(options);
this.$el = $(obj).addClass(this.classes.wrapper);
// Depcrated support of the $wrapper property.
this.$wrapper = this.$el;
this.original = (digit instanceof Date) ? digit : (digit ? Math.round(digit) : 0);
this.time = new FlipClock.Time(this, this.original, {
minimumDigits: this.minimumDigits,
animationRate: this.animationRate
});
this.timer = new FlipClock.Timer(this, options);
this.loadLanguage(this.language);
this.loadClockFace(this.clockFace, options);
if(this.autoStart) {
this.start();
}
},
/**
* Load the FlipClock.Face object
*
* @param object The name of the FlickClock.Face class
* @param object An object override options
*/
loadClockFace: function(name, options) {
var face, suffix = 'Face', hasStopped = false;
name = name.ucfirst()+suffix;
if(this.face.stop) {
this.stop();
hasStopped = true;
}
this.$el.html('');
this.time.minimumDigits = this.minimumDigits;
if(FlipClock[name]) {
face = new FlipClock[name](this, options);
}
else {
face = new FlipClock[this.defaultClockFace+suffix](this, options);
}
face.build();
this.face = face
if(hasStopped) {
this.start();
}
return this.face;
},
/**
* Load the FlipClock.Lang object
*
* @param object The name of the language to load
*/
loadLanguage: function(name) {
var lang;
if(FlipClock.Lang[name.ucfirst()]) {
lang = FlipClock.Lang[name.ucfirst()];
}
else if(FlipClock.Lang[name]) {
lang = FlipClock.Lang[name];
}
else {
lang = FlipClock.Lang[this.defaultLanguage];
}
return this.lang = lang;
},
/**
* Localize strings into various languages
*
* @param string The index of the localized string
* @param object Optionally pass a lang object
*/
localize: function(index, obj) {
var lang = this.lang;
if(!index) {
return null;
}
var lindex = index.toLowerCase();
if(typeof obj == "object") {
lang = obj;
}
if(lang && lang[lindex]) {
return lang[lindex];
}
return index;
},
/**
* Starts the clock
*/
start: function(callback) {
var t = this;
if(!t.running && (!t.countdown || t.countdown && t.time.time > 0)) {
t.face.start(t.time);
t.timer.start(function() {
t.flip();
if(typeof callback === "function") {
callback();
}
});
}
else {
t.log('Trying to start timer when countdown already at 0');
}
},
/**
* Stops the clock
*/
stop: function(callback) {
this.face.stop();
this.timer.stop(callback);
for(var x in this.lists) {
if (this.lists.hasOwnProperty(x)) {
this.lists[x].stop();
}
}
},
/**
* Reset the clock
*/
reset: function(callback) {
this.timer.reset(callback);
this.face.reset();
},
/**
* Sets the clock time
*/
setTime: function(time) {
this.time.time = time;
this.flip(true);
},
/**
* Get the clock time
*
* @return object Returns a FlipClock.Time object
*/
getTime: function(time) {
return this.time;
},
/**
* Changes the increment of time to up or down (add/sub)
*/
setCountdown: function(value) {
var running = this.running;
this.countdown = value ? true : false;
if(running) {
this.stop();
this.start();
}
},
/**
* Flip the digits on the clock
*
* @param array An array of digits
*/
flip: function(doNotAddPlayClass) {
this.face.flip(false, doNotAddPlayClass);
}
});
}(jQuery));
/*jshint smarttabs:true */
/**
* FlipClock.js
*
* @author Justin Kimbrell
* @copyright 2013 - Objective HTML, LLC
* @licesnse http://www.opensource.org/licenses/mit-license.php
*/
(function($) {
"use strict";
/**
* The FlipClock List class is used to build the list used to create
* the card flip effect. This object fascilates selecting the correct
* node by passing a specific digit.
*
* @param object A FlipClock.Factory object
* @param mixed This is the digit used to set the clock. If an
* object is passed, 0 will be used.
* @param object An object of properties to override the default
*/
FlipClock.List = FlipClock.Base.extend({
/**
* The digit (0-9)
*/
digit: 0,
/**
* The CSS classes
*/
classes: {
active: 'flip-clock-active',
before: 'flip-clock-before',
flip: 'flip'
},
/**
* The parent FlipClock.Factory object
*/
factory: false,
/**
* The jQuery object
*/
$el: false,
/**
* The jQuery object (deprecated)
*/
$obj: false,
/**
* The items in the list
*/
items: [],
/**
* The last digit
*/
lastDigit: 0,
/**
* Constructor
*
* @param object A FlipClock.Factory object
* @param int An integer use to select the correct digit
* @param object An object to override the default properties
*/
constructor: function(factory, digit, options) {
this.factory = factory;
this.digit = digit;
this.lastDigit = digit;
this.$el = this.createList();
// Depcrated support of the $obj property.
this.$obj = this.$el;
if(digit > 0) {
this.select(digit);
}
this.factory.$el.append(this.$el);
},
/**
* Select the digit in the list
*
* @param int A digit 0-9
*/
select: function(digit) {
if(typeof digit === "undefined") {
digit = this.digit;
}
else {
this.digit = digit;
}
if(this.digit != this.lastDigit) {
var $delete = this.$el.find('.'+this.classes.before).removeClass(this.classes.before);
this.$el.find('.'+this.classes.active).removeClass(this.classes.active)
.addClass(this.classes.before);
this.appendListItem(this.classes.active, this.digit);
$delete.remove();
this.lastDigit = this.digit;
}
},
/**
* Adds the play class to the DOM object
*/
play: function() {
this.$el.addClass(this.factory.classes.play);
},
/**
* Removes the play class to the DOM object
*/
stop: function() {
var t = this;
setTimeout(function() {
t.$el.removeClass(t.factory.classes.play);
}, this.factory.timer.interval);
},
/**
* Creates the list item HTML and returns as a string
*/
createListItem: function(css, value) {
return [
'<li class="'+(css ? css : '')+'">',
'<a href="#">',
'<div class="up">',
'<div class="shadow"></div>',
'<div class="inn">'+(value ? value : '')+'</div>',
'</div>',
'<div class="down">',
'<div class="shadow"></div>',
'<div class="inn">'+(value ? value : '')+'</div>',
'</div>',
'</a>',
'</li>'
].join('');
},
/**
* Append the list item to the parent DOM node
*/
appendListItem: function(css, value) {
var html = this.createListItem(css, value);
this.$el.append(html);
},
/**
* Create the list of digits and appends it to the DOM object
*/
createList: function() {
var lastDigit = this.getPrevDigit() ? this.getPrevDigit() : this.digit;
var html = $([
'<ul class="'+this.classes.flip+' '+(this.factory.running ? this.factory.classes.play : '')+'">',
this.createListItem(this.classes.before, lastDigit),
this.createListItem(this.classes.active, this.digit),
'</ul>'
].join(''));
return html;
},
getNextDigit: function() {
return this.digit == 9 ? 0 : this.digit + 1;
},
getPrevDigit: function() {
return this.digit == 0 ? 9 : this.digit - 1;
}
});
}(jQuery));
/*jshint smarttabs:true */
/**
* FlipClock.js
*
* @author Justin Kimbrell
* @copyright 2013 - Objective HTML, LLC
* @licesnse http://www.opensource.org/licenses/mit-license.php
*/
(function($) {
"use strict";
/**
* Capitalize the first letter in a string
*
* @return string
*/
String.prototype.ucfirst = function() {
return this.substr(0, 1).toUpperCase() + this.substr(1);
};
/**
* jQuery helper method
*
* @param int An integer used to start the clock (no. seconds)
* @param object An object of properties to override the default
*/
$.fn.FlipClock = function(digit, options) {
return new FlipClock($(this), digit, options);
};
/**
* jQuery helper method
*
* @param int An integer used to start the clock (no. seconds)
* @param object An object of properties to override the default
*/
$.fn.flipClock = function(digit, options) {
return $.fn.FlipClock(digit, options);
};
}(jQuery));
/*jshint smarttabs:true */
/**
* FlipClock.js
*
* @author Justin Kimbrell
* @copyright 2013 - Objective HTML, LLC
* @licesnse http://www.opensource.org/licenses/mit-license.php
*/
(function($) {
"use strict";
/**
* The FlipClock Time class is used to manage all the time
* calculations.
*
* @param object A FlipClock.Factory object
* @param mixed This is the digit used to set the clock. If an
* object is passed, 0 will be used.
* @param object An object of properties to override the default
*/
FlipClock.Time = FlipClock.Base.extend({
/**
* The time (in seconds) or a date object
*/
time: 0,
/**
* The parent FlipClock.Factory object
*/
factory: false,
/**
* The minimum number of digits the clock face must have
*/
minimumDigits: 0,
/**
* Constructor
*
* @param object A FlipClock.Factory object
* @param int An integer use to select the correct digit
* @param object An object to override the default properties
*/
constructor: function(factory, time, options) {
if(typeof options != "object") {
options = {};
}
if(!options.minimumDigits) {
options.minimumDigits = factory.minimumDigits;
}
this.base(options);
this.factory = factory;
if(time) {
this.time = time;
}
},
/**
* Convert a string or integer to an array of digits
*
* @param mixed String or Integer of digits
* @return array An array of digits
*/
convertDigitsToArray: function(str) {
var data = [];
str = str.toString();
for(var x = 0;x < str.length; x++) {
if(str[x].match(/^\d*$/g)) {
data.push(str[x]);
}
}
return data;
},
/**
* Get a specific digit from the time integer
*
* @param int The specific digit to select from the time
* @return mixed Returns FALSE if no digit is found, otherwise
* the method returns the defined digit
*/
digit: function(i) {
var timeStr = this.toString();
var length = timeStr.length;
if(timeStr[length - i]) {
return timeStr[length - i];
}
return false;
},
/**
* Formats any array of digits into a valid array of digits
*
* @param mixed An array of digits
* @return array An array of digits
*/
digitize: function(obj) {
var data = [];
$.each(obj, function(i, value) {
value = value.toString();
if(value.length == 1) {
value = '0'+value;
}
for(var x = 0; x < value.length; x++) {
data.push(value.charAt(x));
}
});
if(data.length > this.minimumDigits) {
this.minimumDigits = data.length;
}
if(this.minimumDigits > data.length) {
for(var x = data.length; x < this.minimumDigits; x++) {
data.unshift('0');
}
}
return data;
},
/**
* Gets a new Date object for the current time
*
* @return array Returns a Date object
*/
getDateObject: function() {
if(this.time instanceof Date) {
return this.time;
}
return new Date((new Date()).getTime() + this.getTimeSeconds() * 1000);
},
/**
* Gets a digitized daily counter
*
* @return object Returns a digitized object
*/
getDayCounter: function(includeSeconds) {
var digits = [
this.getDays(),
this.getHours(true),
this.getMinutes(true)
];
if(includeSeconds) {
digits.push(this.getSeconds(true));
}
return this.digitize(digits);
},
/**
* Gets number of days
*
* @param bool Should perform a modulus? If not sent, then no.
* @return int Retuns a floored integer
*/
getDays: function(mod) {
var days = this.getTimeSeconds() / 60 / 60 / 24;
if(mod) {
days = days % 7;
}
return Math.floor(days);
},
/**
* Gets an hourly breakdown
*
* @return object Returns a digitized object
*/
getHourCounter: function() {
var obj = this.digitize([
this.getHours(),
this.getMinutes(true),
this.getSeconds(true)
]);
return obj;
},
/**
* Gets an hourly breakdown
*
* @return object Returns a digitized object
*/
getHourly: function() {
return this.getHourCounter();
},
/**
* Gets number of hours
*
* @param bool Should perform a modulus? If not sent, then no.
* @return int Retuns a floored integer
*/
getHours: function(mod) {
var hours = this.getTimeSeconds() / 60 / 60;
if(mod) {
hours = hours % 24;
}
return Math.floor(hours);
},
/**
* Gets the twenty-four hour time
*
* @return object returns a digitized object
*/
getMilitaryTime: function(date, showSeconds) {
if(typeof showSeconds === "undefined") {
showSeconds = true;
}
if(!date) {
date = this.getDateObject();
}
var data = [
date.getHours(),
date.getMinutes()
];
if(showSeconds === true) {
data.push(date.getSeconds());
}
return this.digitize(data);
},
/**
* Gets number of minutes
*
* @param bool Should perform a modulus? If not sent, then no.
* @return int Retuns a floored integer
*/
getMinutes: function(mod) {
var minutes = this.getTimeSeconds() / 60;
if(mod) {
minutes = minutes % 60;
}
return Math.floor(minutes);
},
/**
* Gets a minute breakdown
*/
getMinuteCounter: function() {
var obj = this.digitize([
this.getMinutes(),
this.getSeconds(true)
]);
return obj;
},
/**
* Gets time count in seconds regardless of if targetting date or not.
*
* @return int Returns a floored integer
*/
getTimeSeconds: function(date) {
if(!date) {
date = new Date();
}
if (this.time instanceof Date) {
if (this.factory.countdown) {
return Math.max(this.time.getTime()/1000 - date.getTime()/1000,0);
} else {
return date.getTime()/1000 - this.time.getTime()/1000 ;
}
} else {
return this.time;
}
},
/**
* Gets the current twelve hour time
*
* @return object Returns a digitized object
*/
getTime: function(date, showSeconds) {
if(typeof showSeconds === "undefined") {
showSeconds = true;
}
if(!date) {
date = this.getDateObject();
}
console.log(date);
var hours = date.getHours();
var merid = hours > 12 ? 'PM' : 'AM';
var data = [
hours > 12 ? hours - 12 : (hours === 0 ? 12 : hours),
date.getMinutes()
];
if(showSeconds === true) {
data.push(date.getSeconds());
}
return this.digitize(data);
},
/**
* Gets number of seconds
*
* @param bool Should perform a modulus? If not sent, then no.
* @return int Retuns a ceiled integer
*/
getSeconds: function(mod) {
var seconds = this.getTimeSeconds();
if(mod) {
if(seconds == 60) {
seconds = 0;
}
else {
seconds = seconds % 60;
}
}
return Math.ceil(seconds);
},
/**
* Gets number of weeks
*
* @param bool Should perform a modulus? If not sent, then no.
* @return int Retuns a floored integer
*/
getWeeks: function(mod) {
var weeks = this.getTimeSeconds() / 60 / 60 / 24 / 7;
if(mod) {
weeks = weeks % 52;
}
return Math.floor(weeks);
},
/**
* Removes a specific number of leading zeros from the array.
* This method prevents you from removing too many digits, even
* if you try.
*
* @param int Total number of digits to remove
* @return array An array of digits
*/
removeLeadingZeros: function(totalDigits, digits) {
var total = 0;
var newArray = [];
$.each(digits, function(i, digit) {
if(i < totalDigits) {
total += parseInt(digits[i], 10);
}
else {
newArray.push(digits[i]);
}
});
if(total === 0) {
return newArray;
}
return digits;
},
/**
* Adds X second to the current time
*/
addSeconds: function(x) {
if(this.time instanceof Date) {
this.time.setSeconds(this.time.getSeconds() + x);
}
else {
this.time += x;
}
},
/**
* Adds 1 second to the current time
*/
addSecond: function() {
this.addSeconds(1);
},
/**
* Substracts X seconds from the current time
*/
subSeconds: function(x) {
if(this.time instanceof Date) {
this.time.setSeconds(this.time.getSeconds() - x);
}
else {
this.time -= x;
}
},
/**
* Substracts 1 second from the current time
*/
subSecond: function() {
this.subSeconds(1);
},
/**
* Converts the object to a human readable string
*/
toString: function() {
return this.getTimeSeconds().toString();
}
/*
getYears: function() {
return Math.floor(this.time / 60 / 60 / 24 / 7 / 52);
},
getDecades: function() {
return Math.floor(this.getWeeks() / 10);
}*/
});
}(jQuery));
/*jshint smarttabs:true */
/**
* FlipClock.js
*
* @author Justin Kimbrell
* @copyright 2013 - Objective HTML, LLC
* @licesnse http://www.opensource.org/licenses/mit-license.php
*/
(function($) {
"use strict";
/**
* The FlipClock.Timer object managers the JS timers
*
* @param object The parent FlipClock.Factory object
* @param object Override the default options
*/
FlipClock.Timer = FlipClock.Base.extend({
/**
* Callbacks
*/
callbacks: {
destroy: false,
create: false,
init: false,
interval: false,
start: false,
stop: false,
reset: false
},
/**
* FlipClock timer count (how many intervals have passed)
*/
count: 0,
/**
* The parent FlipClock.Factory object
*/
factory: false,
/**
* Timer interval (1 second by default)
*/
interval: 1000,
/**
* The rate of the animation in milliseconds (not currently in use)
*/
animationRate: 1000,
/**
* Constructor
*
* @return void
*/
constructor: function(factory, options) {
this.base(options);
this.factory = factory;
this.callback(this.callbacks.init);
this.callback(this.callbacks.create);
},
/**
* This method gets the elapsed the time as an interger
*
* @return void
*/
getElapsed: function() {
return this.count * this.interval;
},
/**
* This method gets the elapsed the time as a Date object
*
* @return void
*/
getElapsedTime: function() {
return new Date(this.time + this.getElapsed());
},
/**
* This method is resets the timer
*
* @param callback This method resets the timer back to 0
* @return void
*/
reset: function(callback) {
clearInterval(this.timer);
this.count = 0;
this._setInterval(callback);
this.callback(this.callbacks.reset);
},
/**
* This method is starts the timer
*
* @param callback A function that is called once the timer is destroyed
* @return void
*/
start: function(callback) {
this.factory.running = true;
this._createTimer(callback);
this.callback(this.callbacks.start);
},
/**
* This method is stops the timer
*
* @param callback A function that is called once the timer is destroyed
* @return void
*/
stop: function(callback) {
this.factory.running = false;
this._clearInterval(callback);
this.callback(this.callbacks.stop);
this.callback(callback);
},
/**
* Clear the timer interval
*
* @return void
*/
_clearInterval: function() {
clearInterval(this.timer);
},
/**
* Create the timer object
*
* @param callback A function that is called once the timer is created
* @return void
*/
_createTimer: function(callback) {
this._setInterval(callback);
},
/**
* Destroy the timer object
*
* @param callback A function that is called once the timer is destroyed
* @return void
*/
_destroyTimer: function(callback) {
this._clearInterval();
this.timer = false;
this.callback(callback);
this.callback(this.callbacks.destroy);
},
/**
* This method is called each time the timer interval is ran
*
* @param callback A function that is called once the timer is destroyed
* @return void
*/
_interval: function(callback) {
this.callback(this.callbacks.interval);
this.callback(callback);
this.count++;
},
/**
* This sets the timer interval
*
* @param callback A function that is called once the timer is destroyed
* @return void
*/
_setInterval: function(callback) {
var t = this;
t._interval(callback);
t.timer = setInterval(function() {
t._interval(callback);
}, this.interval);
}
});
}(jQuery));
(function($) {
/**
* Twenty-Four Hour Clock Face
*
* This class will generate a twenty-four our clock for FlipClock.js
*
* @param object The parent FlipClock.Factory object
* @param object An object of properties to override the default
*/
FlipClock.TwentyFourHourClockFace = FlipClock.Face.extend({
/**
* Constructor
*
* @param object The parent FlipClock.Factory object
* @param object An object of properties to override the default
*/
constructor: function(factory, options) {
this.base(factory, options);
},
/**
* Build the clock face
*
* @param object Pass the time that should be used to display on the clock.
*/
build: function(time) {
var t = this;
var children = this.factory.$el.find('ul');
if(!this.factory.time.time) {
this.factory.original = new Date();
this.factory.time = new FlipClock.Time(this.factory, this.factory.original);
}
var time = time ? time : this.factory.time.getMilitaryTime(false, this.showSeconds);
if(time.length > children.length) {
$.each(time, function(i, digit) {
t.createList(digit);
});
}
this.createDivider();
this.createDivider();
$(this.dividers[0]).insertBefore(this.lists[this.lists.length - 2].$el);
$(this.dividers[1]).insertBefore(this.lists[this.lists.length - 4].$el);
this.base();
},
/**
* Flip the clock face
*/
flip: function(time, doNotAddPlayClass) {
this.autoIncrement();
time = time ? time : this.factory.time.getMilitaryTime(false, this.showSeconds);
this.base(time, doNotAddPlayClass);
}
});
}(jQuery));
(function($) {
/**
* Counter Clock Face
*
* This class will generate a generice flip counter. The timer has been
* disabled. clock.increment() and clock.decrement() have been added.
*
* @param object The parent FlipClock.Factory object
* @param object An object of properties to override the default
*/
FlipClock.CounterFace = FlipClock.Face.extend({
/**
* Tells the counter clock face if it should auto-increment
*/
shouldAutoIncrement: false,
/**
* Constructor
*
* @param object The parent FlipClock.Factory object
* @param object An object of properties to override the default
*/
constructor: function(factory, options) {
if(typeof options != "object") {
options = {};
}
factory.autoStart = options.autoStart ? true : false;
if(options.autoStart) {
this.shouldAutoIncrement = true;
}
factory.increment = function() {
factory.countdown = false;
factory.setTime(factory.getTime().getTimeSeconds() + 1);
};
factory.decrement = function() {
factory.countdown = true;
var time = factory.getTime().getTimeSeconds();
if(time > 0) {
factory.setTime(time - 1);
}
};
factory.setValue = function(digits) {
factory.setTime(digits);
};
factory.setCounter = function(digits) {
factory.setTime(digits);
};
this.base(factory, options);
},
/**
* Build the clock face
*/
build: function() {
var t = this;
var children = this.factory.$el.find('ul');
var time = this.factory.getTime().digitize([this.factory.getTime().time]);
if(time.length > children.length) {
$.each(time, function(i, digit) {
var list = t.createList(digit);
list.select(digit);
});
}
$.each(this.lists, function(i, list) {
list.play();
});
this.base();
},
/**
* Flip the clock face
*/
flip: function(time, doNotAddPlayClass) {
if(this.shouldAutoIncrement) {
this.autoIncrement();
}
if(!time) {
time = this.factory.getTime().digitize([this.factory.getTime().time]);
}
this.base(time, doNotAddPlayClass);
},
/**
* Reset the clock face
*/
reset: function() {
this.factory.time = new FlipClock.Time(
this.factory,
this.factory.original ? Math.round(this.factory.original) : 0
);
this.flip();
}
});
}(jQuery));
(function($) {
/**
* Daily Counter Clock Face
*
* This class will generate a daily counter for FlipClock.js. A
* daily counter will track days, hours, minutes, and seconds. If
* the number of available digits is exceeded in the count, a new
* digit will be created.
*
* @param object The parent FlipClock.Factory object
* @param object An object of properties to override the default
*/
FlipClock.DailyCounterFace = FlipClock.Face.extend({
showSeconds: true,
/**
* Constructor
*
* @param object The parent FlipClock.Factory object
* @param object An object of properties to override the default
*/
constructor: function(factory, options) {
this.base(factory, options);
},
/**
* Build the clock face
*/
build: function(time) {
var t = this;
var children = this.factory.$el.find('ul');
var offset = 0;
time = time ? time : this.factory.time.getDayCounter(this.showSeconds);
if(time.length > children.length) {
$.each(time, function(i, digit) {
t.createList(digit);
});
}
if(this.showSeconds) {
$(this.createDivider('Segundos')).insertBefore(this.lists[this.lists.length - 2].$el);
}
else
{
offset = 2;
}
$(this.createDivider('Minutos')).insertBefore(this.lists[this.lists.length - 4 + offset].$el);
$(this.createDivider('Horas')).insertBefore(this.lists[this.lists.length - 6 + offset].$el);
$(this.createDivider('Dias', true)).insertBefore(this.lists[0].$el);
this.base();
},
/**
* Flip the clock face
*/
flip: function(time, doNotAddPlayClass) {
if(!time) {
time = this.factory.time.getDayCounter(this.showSeconds);
}
this.autoIncrement();
this.base(time, doNotAddPlayClass);
}
});
}(jQuery));
(function($) {
/**
* Hourly Counter Clock Face
*
* This class will generate an hourly counter for FlipClock.js. An
* hour counter will track hours, minutes, and seconds. If number of
* available digits is exceeded in the count, a new digit will be
* created.
*
* @param object The parent FlipClock.Factory object
* @param object An object of properties to override the default
*/
FlipClock.HourlyCounterFace = FlipClock.Face.extend({
// clearExcessDigits: true,
/**
* Constructor
*
* @param object The parent FlipClock.Factory object
* @param object An object of properties to override the default
*/
constructor: function(factory, options) {
this.base(factory, options);
},
/**
* Build the clock face
*/
build: function(excludeHours, time) {
var t = this;
var children = this.factory.$el.find('ul');
time = time ? time : this.factory.time.getHourCounter();
if(time.length > children.length) {
$.each(time, function(i, digit) {
t.createList(digit);
});
}
$(this.createDivider('Segundos')).insertBefore(this.lists[this.lists.length - 2].$el);
$(this.createDivider('Minutos')).insertBefore(this.lists[this.lists.length - 4].$el);
if(!excludeHours) {
$(this.createDivider('Horas', true)).insertBefore(this.lists[0].$el);
}
this.base();
},
/**
* Flip the clock face
*/
flip: function(time, doNotAddPlayClass) {
if(!time) {
time = this.factory.time.getHourCounter();
}
this.autoIncrement();
this.base(time, doNotAddPlayClass);
},
/**
* Append a newly created list to the clock
*/
appendDigitToClock: function(obj) {
this.base(obj);
this.dividers[0].insertAfter(this.dividers[0].next());
}
});
}(jQuery));
(function($) {
/**
* Minute Counter Clock Face
*
* This class will generate a minute counter for FlipClock.js. A
* minute counter will track minutes and seconds. If an hour is
* reached, the counter will reset back to 0. (4 digits max)
*
* @param object The parent FlipClock.Factory object
* @param object An object of properties to override the default
*/
FlipClock.MinuteCounterFace = FlipClock.HourlyCounterFace.extend({
clearExcessDigits: false,
/**
* Constructor
*
* @param object The parent FlipClock.Factory object
* @param object An object of properties to override the default
*/
constructor: function(factory, options) {
this.base(factory, options);
},
/**
* Build the clock face
*/
build: function() {
this.base(true, this.factory.time.getMinuteCounter());
},
/**
* Flip the clock face
*/
flip: function(time, doNotAddPlayClass) {
if(!time) {
time = this.factory.time.getMinuteCounter();
}
this.base(time, doNotAddPlayClass);
}
});
}(jQuery));
(function($) {
/**
* Twelve Hour Clock Face
*
* This class will generate a twelve hour clock for FlipClock.js
*
* @param object The parent FlipClock.Factory object
* @param object An object of properties to override the default
*/
FlipClock.TwelveHourClockFace = FlipClock.TwentyFourHourClockFace.extend({
/**
* The meridium jQuery DOM object
*/
meridium: false,
/**
* The meridium text as string for easy access
*/
meridiumText: 'AM',
/**
* Build the clock face
*
* @param object Pass the time that should be used to display on the clock.
*/
build: function() {
var t = this;
var time = this.factory.time.getTime(false, this.showSeconds);
this.base(time);
this.meridiumText = this.getMeridium();
this.meridium = $([
'<ul class="flip-clock-meridium">',
'<li>',
'<a href="#">'+this.meridiumText+'</a>',
'</li>',
'</ul>'
].join(''));
this.meridium.insertAfter(this.lists[this.lists.length-1].$el);
},
/**
* Flip the clock face
*/
flip: function(time, doNotAddPlayClass) {
if(this.meridiumText != this.getMeridium()) {
this.meridiumText = this.getMeridium();
this.meridium.find('a').html(this.meridiumText);
}
this.base(this.factory.time.getTime(false, this.showSeconds), doNotAddPlayClass);
},
/**
* Get the current meridium
*
* @return string Returns the meridium (AM|PM)
*/
getMeridium: function() {
return new Date().getHours() >= 12 ? 'PM' : 'AM';
},
/**
* Is it currently in the post-medirium?
*
* @return bool Returns true or false
*/
isPM: function() {
return this.getMeridium() == 'PM' ? true : false;
},
/**
* Is it currently before the post-medirium?
*
* @return bool Returns true or false
*/
isAM: function() {
return this.getMeridium() == 'AM' ? true : false;
}
});
}(jQuery));
(function($) {
/**
* FlipClock Arabic Language Pack
*
* This class will be used to translate tokens into the Arabic language.
*
*/
FlipClock.Lang.Arabic = {
'years' : 'سنوات',
'months' : 'شهور',
'days' : 'أيام',
'hours' : 'ساعات',
'minutes' : 'دقائق',
'seconds' : 'ثواني'
};
/* Create various aliases for convenience */
FlipClock.Lang['ar'] = FlipClock.Lang.Arabic;
FlipClock.Lang['ar-ar'] = FlipClock.Lang.Arabic;
FlipClock.Lang['arabic'] = FlipClock.Lang.Arabic;
}(jQuery));
(function($) {
/**
* FlipClock Danish Language Pack
*
* This class will used to translate tokens into the Danish language.
*
*/
FlipClock.Lang.Danish = {
'years' : 'År',
'months' : 'Måneder',
'days' : 'Dage',
'hours' : 'Timer',
'minutes' : 'Minutter',
'seconds' : 'Sekunder'
};
/* Create various aliases for convenience */
FlipClock.Lang['da'] = FlipClock.Lang.Danish;
FlipClock.Lang['da-dk'] = FlipClock.Lang.Danish;
FlipClock.Lang['danish'] = FlipClock.Lang.Danish;
}(jQuery));
(function($) {
/**
* FlipClock German Language Pack
*
* This class will used to translate tokens into the German language.
*
*/
FlipClock.Lang.German = {
'years' : 'Jahre',
'months' : 'Monate',
'days' : 'Tage',
'hours' : 'Stunden',
'minutes' : 'Minuten',
'seconds' : 'Sekunden'
};
/* Create various aliases for convenience */
FlipClock.Lang['de'] = FlipClock.Lang.German;
FlipClock.Lang['de-de'] = FlipClock.Lang.German;
FlipClock.Lang['german'] = FlipClock.Lang.German;
}(jQuery));
(function($) {
/**
* FlipClock English Language Pack
*
* This class will used to translate tokens into the English language.
*
*/
FlipClock.Lang.English = {
'years' : 'Years',
'months' : 'Months',
'days' : 'Days',
'hours' : 'Hours',
'minutes' : 'Minutos',
'seconds' : 'Segundos'
};
/* Create various aliases for convenience */
FlipClock.Lang['en'] = FlipClock.Lang.English;
FlipClock.Lang['en-us'] = FlipClock.Lang.English;
FlipClock.Lang['english'] = FlipClock.Lang.English;
}(jQuery));
(function($) {
/**
* FlipClock Spanish Language Pack
*
* This class will used to translate tokens into the Spanish language.
*
*/
FlipClock.Lang.Spanish = {
'years' : 'Años',
'months' : 'Meses',
'days' : 'Días',
'hours' : 'Horas',
'minutes' : 'Minutos',
'seconds' : 'Segundos'
};
/* Create various aliases for convenience */
FlipClock.Lang['es'] = FlipClock.Lang.Spanish;
FlipClock.Lang['es-es'] = FlipClock.Lang.Spanish;
FlipClock.Lang['spanish'] = FlipClock.Lang.Spanish;
}(jQuery));
(function($) {
/**
* FlipClock Finnish Language Pack
*
* This class will used to translate tokens into the Finnish language.
*
*/
FlipClock.Lang.Finnish = {
'years' : 'Vuotta',
'months' : 'Kuukautta',
'days' : 'Päivää',
'hours' : 'Tuntia',
'minutes' : 'Minuuttia',
'seconds' : 'Sekuntia'
};
/* Create various aliases for convenience */
FlipClock.Lang['fi'] = FlipClock.Lang.Finnish;
FlipClock.Lang['fi-fi'] = FlipClock.Lang.Finnish;
FlipClock.Lang['finnish'] = FlipClock.Lang.Finnish;
}(jQuery));
(function($) {
/**
* FlipClock Canadian French Language Pack
*
* This class will used to translate tokens into the Canadian French language.
*
*/
FlipClock.Lang.French = {
'years' : 'Ans',
'months' : 'Mois',
'days' : 'Jours',
'hours' : 'Heures',
'minutes' : 'Minutes',
'seconds' : 'Secondes'
};
/* Create various aliases for convenience */
FlipClock.Lang['fr'] = FlipClock.Lang.French;
FlipClock.Lang['fr-ca'] = FlipClock.Lang.French;
FlipClock.Lang['french'] = FlipClock.Lang.French;
}(jQuery));
(function($) {
/**
* FlipClock Italian Language Pack
*
* This class will used to translate tokens into the Italian language.
*
*/
FlipClock.Lang.Italian = {
'years' : 'Anni',
'months' : 'Mesi',
'days' : 'Giorni',
'hours' : 'Ore',
'minutes' : 'Minuti',
'seconds' : 'Secondi'
};
/* Create various aliases for convenience */
FlipClock.Lang['it'] = FlipClock.Lang.Italian;
FlipClock.Lang['it-it'] = FlipClock.Lang.Italian;
FlipClock.Lang['italian'] = FlipClock.Lang.Italian;
}(jQuery));
(function($) {
/**
* FlipClock Latvian Language Pack
*
* This class will used to translate tokens into the Latvian language.
*
*/
FlipClock.Lang.Latvian = {
'years' : 'Gadi',
'months' : 'Mēneši',
'days' : 'Dienas',
'hours' : 'Stundas',
'minutes' : 'Minūtes',
'seconds' : 'Sekundes'
};
/* Create various aliases for convenience */
FlipClock.Lang['lv'] = FlipClock.Lang.Latvian;
FlipClock.Lang['lv-lv'] = FlipClock.Lang.Latvian;
FlipClock.Lang['latvian'] = FlipClock.Lang.Latvian;
}(jQuery));
(function($) {
/**
* FlipClock Dutch Language Pack
*
* This class will used to translate tokens into the Dutch language.
*/
FlipClock.Lang.Dutch = {
'years' : 'Jaren',
'months' : 'Maanden',
'days' : 'Dagen',
'hours' : 'Uren',
'minutes' : 'Minuten',
'seconds' : 'Seconden'
};
/* Create various aliases for convenience */
FlipClock.Lang['nl'] = FlipClock.Lang.Dutch;
FlipClock.Lang['nl-be'] = FlipClock.Lang.Dutch;
FlipClock.Lang['dutch'] = FlipClock.Lang.Dutch;
}(jQuery));
(function($) {
/**
* FlipClock Norwegian-Bokmål Language Pack
*
* This class will used to translate tokens into the Norwegian language.
*
*/
FlipClock.Lang.Norwegian = {
'years' : 'År',
'months' : 'Måneder',
'days' : 'Dager',
'hours' : 'Timer',
'minutes' : 'Minutter',
'seconds' : 'Sekunder'
};
/* Create various aliases for convenience */
FlipClock.Lang['no'] = FlipClock.Lang.Norwegian;
FlipClock.Lang['nb'] = FlipClock.Lang.Norwegian;
FlipClock.Lang['no-nb'] = FlipClock.Lang.Norwegian;
FlipClock.Lang['norwegian'] = FlipClock.Lang.Norwegian;
}(jQuery));
(function($) {
/**
* FlipClock Portuguese Language Pack
*
* This class will used to translate tokens into the Portuguese language.
*
*/
FlipClock.Lang.Portuguese = {
'years' : 'Anos',
'months' : 'Meses',
'days' : 'Dias',
'hours' : 'Horas',
'minutes' : 'Minutos',
'seconds' : 'Segundos'
};
/* Create various aliases for convenience */
FlipClock.Lang['pt'] = FlipClock.Lang.Portuguese;
FlipClock.Lang['pt-br'] = FlipClock.Lang.Portuguese;
FlipClock.Lang['portuguese'] = FlipClock.Lang.Portuguese;
}(jQuery));
(function($) {
/**
* FlipClock Russian Language Pack
*
* This class will used to translate tokens into the Russian language.
*
*/
FlipClock.Lang.Russian = {
'years' : 'лет',
'months' : 'месяцев',
'days' : 'дней',
'hours' : 'часов',
'minutes' : 'минут',
'seconds' : 'секунд'
};
/* Create various aliases for convenience */
FlipClock.Lang['ru'] = FlipClock.Lang.Russian;
FlipClock.Lang['ru-ru'] = FlipClock.Lang.Russian;
FlipClock.Lang['russian'] = FlipClock.Lang.Russian;
}(jQuery));
(function($) {
/**
* FlipClock Swedish Language Pack
*
* This class will used to translate tokens into the Swedish language.
*
*/
FlipClock.Lang.Swedish = {
'years' : 'År',
'months' : 'Månader',
'days' : 'Dagar',
'hours' : 'Timmar',
'minutes' : 'Minuter',
'seconds' : 'Sekunder'
};
/* Create various aliases for convenience */
FlipClock.Lang['sv'] = FlipClock.Lang.Swedish;
FlipClock.Lang['sv-se'] = FlipClock.Lang.Swedish;
FlipClock.Lang['swedish'] = FlipClock.Lang.Swedish;
}(jQuery));
(function($) {
/**
* FlipClock Chinese Language Pack
*
* This class will used to translate tokens into the Chinese language.
*
*/
FlipClock.Lang.Chinese = {
'years' : '年',
'months' : '月',
'days' : '日',
'hours' : '时',
'minutes' : '分',
'seconds' : '秒'
};
/* Create various aliases for convenience */
FlipClock.Lang['zh'] = FlipClock.Lang.Chinese;
FlipClock.Lang['zh-cn'] = FlipClock.Lang.Chinese;
FlipClock.Lang['chinese'] = FlipClock.Lang.Chinese;
}(jQuery)); | manuelsousa7/ipm-site | interface/clock/flipclock2.js | JavaScript | gpl-3.0 | 55,561 |
const _ = require('lodash')
const handleText = (event, next, botfmk) => {
if (event.platform !== 'botfmk' || event.type !== 'text') {
return next()
}
// TODO DEBUG
console.log('REPLIED', event.raw)
const session = event.session
const replied = event.raw
if (_.isArray(replied)) {
replied.forEach(r => session.send(r))
} else {
session.send(replied)
}
return next()
}
module.exports = {
'text': handleText
}
| Okazari/mystery-bot | botpress-botbuilder/outgoing.js | JavaScript | gpl-3.0 | 447 |
import { isArray } from '@ember/array';
import { module, test } from 'qunit';
import RollingArray from 'nomad-ui/utils/classes/rolling-array';
module('Unit | Util | RollingArray', function() {
test('has a maxLength property that gets set in the constructor', function(assert) {
const array = RollingArray(10, 'a', 'b', 'c');
assert.equal(array.maxLength, 10, 'maxLength is set in the constructor');
assert.deepEqual(
array,
['a', 'b', 'c'],
'additional arguments to the constructor become elements'
);
});
test('push works like Array#push', function(assert) {
const array = RollingArray(10);
const pushReturn = array.push('a');
assert.equal(
pushReturn,
array.length,
'the return value from push is equal to the return value of Array#push'
);
assert.equal(array[0], 'a', 'the arguments passed to push are appended to the array');
array.push('b', 'c', 'd');
assert.deepEqual(
array,
['a', 'b', 'c', 'd'],
'the elements already in the array are left in tact and new elements are appended'
);
});
test('when pushing past maxLength, items are removed from the head of the array', function(assert) {
const array = RollingArray(3);
const pushReturn = array.push(1, 2, 3, 4);
assert.deepEqual(
array,
[2, 3, 4],
'The first argument to push is not in the array, but the following three are'
);
assert.equal(
pushReturn,
array.length,
'The return value of push is still the array length despite more arguments than possible were provided to push'
);
});
test('when splicing past maxLength, items are removed from the head of the array', function(assert) {
const array = RollingArray(3, 'a', 'b', 'c');
array.splice(1, 0, 'z');
assert.deepEqual(
array,
['z', 'b', 'c'],
'The new element is inserted as the second element in the array and the first element is removed due to maxLength restrictions'
);
array.splice(0, 0, 'pickme');
assert.deepEqual(
array,
['z', 'b', 'c'],
'The new element never makes it into the array since it was added at the head of the array and immediately removed'
);
array.splice(0, 1, 'pickme');
assert.deepEqual(
array,
['pickme', 'b', 'c'],
'The new element makes it into the array since the previous element at the head of the array is first removed due to the second argument to splice'
);
});
test('unshift throws instead of prepending elements', function(assert) {
const array = RollingArray(5);
assert.throws(
() => {
array.unshift(1);
},
/Cannot unshift/,
'unshift is not supported, but is not undefined'
);
});
test('RollingArray is an instance of Array', function(assert) {
const array = RollingArray(5);
assert.ok(array.constructor === Array, 'The constructor is Array');
assert.ok(array instanceof Array, 'The instanceof check is true');
assert.ok(isArray(array), 'The ember isArray helper works');
});
});
| dvusboy/nomad | ui/tests/unit/utils/rolling-array-test.js | JavaScript | mpl-2.0 | 3,086 |
initSidebarItems({"mod":[["big5","Big5 and HKSCS."]]}); | susaing/doc.servo.org | encoding_index_tradchinese/sidebar-items.js | JavaScript | mpl-2.0 | 55 |
module.exports = { domain:"messages",
locale_data:{ messages:{ "":{ domain:"messages",
plural_forms:"nplurals=2; plural=(n!=1);",
lang:"mk" },
"%(addonName)s %(startSpan)sby %(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":[ "" ],
"How are you enjoying your experience with %(addonName)s?":[ "" ],
"screenshot %(imageNumber)s of %(totalImages)s":[ "" ],
"Average rating: %(rating)s out of 5":[ "" ],
"No ratings":[ "" ],
"%(users)s user":[ "",
"%(users)s users" ],
"Log out":[ "" ],
"Log in/Sign up":[ "" ],
"Add-ons for Firefox":[ "" ],
"What do you want Firefox to do?":[ "" ],
"Block ads":[ "" ],
Screenshot:[ "" ],
"Save stuff":[ "" ],
"Shop online":[ "" ],
"Be social":[ "" ],
"Share stuff":[ "" ],
"Browse all extensions":[ "" ],
"How do you want Firefox to look?":[ "" ],
Wild:[ "" ],
Abstract:[ "" ],
Fashionable:[ "" ],
Scenic:[ "" ],
Sporty:[ "" ],
Mystical:[ "" ],
"Browse all themes":[ "" ],
"Downloading %(name)s.":[ "" ],
"Installing %(name)s.":[ "" ],
"%(name)s is installed and enabled. Click to uninstall.":[ "" ],
"%(name)s is disabled. Click to enable.":[ "" ],
"Uninstalling %(name)s.":[ "" ],
"%(name)s is uninstalled. Click to install.":[ "" ],
"Install state for %(name)s is unknown.":[ "" ],
Previous:[ "" ],
Next:[ "" ],
"Page %(currentPage)s of %(totalPages)s":[ "" ],
"Your search for \"%(query)s\" returned %(count)s result.":[ "",
"Your search for \"%(query)s\" returned %(count)s results." ],
"Searching...":[ "" ],
"No results were found for \"%(query)s\".":[ "" ],
"Please supply a valid search":[ "" ] } },
_momentDefineLocale:function anonymous() {
//! moment.js locale configuration
//! locale : Macedonian [mk]
//! author : Borislav Mickov : https://github.com/B0k0
;(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';
var mk = moment.defineLocale('mk', {
months : 'јануари_февруари_март_април_мај_јуни_јули_август_септември_октомври_ноември_декември'.split('_'),
monthsShort : 'јан_фев_мар_апр_мај_јун_јул_авг_сеп_окт_ное_дек'.split('_'),
weekdays : 'недела_понеделник_вторник_среда_четврток_петок_сабота'.split('_'),
weekdaysShort : 'нед_пон_вто_сре_чет_пет_саб'.split('_'),
weekdaysMin : 'нe_пo_вт_ср_че_пе_сa'.split('_'),
longDateFormat : {
LT : 'H:mm',
LTS : 'H:mm:ss',
L : 'D.MM.YYYY',
LL : 'D MMMM YYYY',
LLL : 'D MMMM YYYY H:mm',
LLLL : 'dddd, D MMMM YYYY H:mm'
},
calendar : {
sameDay : '[Денес во] LT',
nextDay : '[Утре во] LT',
nextWeek : '[Во] dddd [во] LT',
lastDay : '[Вчера во] LT',
lastWeek : function () {
switch (this.day()) {
case 0:
case 3:
case 6:
return '[Изминатата] dddd [во] LT';
case 1:
case 2:
case 4:
case 5:
return '[Изминатиот] dddd [во] LT';
}
},
sameElse : 'L'
},
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 : function (number) {
var lastDigit = number % 10,
last2Digits = number % 100;
if (number === 0) {
return number + '-ев';
} else if (last2Digits === 0) {
return number + '-ен';
} else if (last2Digits > 10 && last2Digits < 20) {
return number + '-ти';
} else if (lastDigit === 1) {
return number + '-ви';
} else if (lastDigit === 2) {
return number + '-ри';
} else if (lastDigit === 7 || lastDigit === 8) {
return number + '-ми';
} else {
return number + '-ти';
}
},
week : {
dow : 1, // Monday is the first day of the week.
doy : 7 // The week that contains Jan 1st is the first week of the year.
}
});
return mk;
})));
} } | jasonthomas/addons-frontend | src/locale/mk/amo.js | JavaScript | mpl-2.0 | 5,582 |
import { run } from '@ember/runloop';
import Helper from '@ember/component/helper';
export default Helper.extend({
disableInterval: false,
compute(value, { interval }) {
if (this.disableInterval) {
return;
}
this.clearTimer();
if (interval) {
/*
* NOTE: intentionally a setTimeout so tests do not block on it
* as the run loop queue is never clear so tests will stay locked waiting
* for queue to clear.
*/
this.intervalTimer = setTimeout(() => {
run(() => this.recompute());
}, parseInt(interval, 10));
}
},
clearTimer() {
clearTimeout(this.intervalTimer);
},
destroy() {
this.clearTimer();
this._super(...arguments);
},
});
| hashicorp/vault | ui/app/helpers/-date-base.js | JavaScript | mpl-2.0 | 738 |
var cred = require('./cred');
module.exports = {
'db': {
'host': 'pub-redis-10769.us-east-1-2.4.ec2.garantiadata.com',
'port': 10769,
'auth': cred.auth
}
};
| sinkingshriek/gotoline | config/env/production.js | JavaScript | mpl-2.0 | 173 |
// |jit-test| error: StopIteration
// Returning {throw:} from an onPop handler when yielding works and
// does closes the generator-iterator.
load(libdir + "asserts.js");
var g = newGlobal();
var dbg = new Debugger;
var gw = dbg.addDebuggee(g);
dbg.onDebuggerStatement = function handleDebugger(frame) {
frame.onPop = function (c) {
return {throw: "fit"};
};
};
g.eval("function g() { for (var i = 0; i < 10; i++) { debugger; yield i; } }");
g.eval("var it = g();");
var rv = gw.executeInGlobal("it.next();");
assertEq(rv.throw, "fit");
dbg.enabled = false;
g.it.next();
| cstipkovic/spidermonkey-research | js/src/jit-test/tests/debug/Frame-onPop-generators-01.js | JavaScript | mpl-2.0 | 590 |
var Quest = require('../quest'),
Messages = require('../../../../../../network/messages'),
Packets = require('../../../../../../network/packets'),
Utils = require('../../../../../../util/utils');
module.exports = Introduction = Quest.extend({
init: function(player, data) {
var self = this;
self.player = player;
self.data = data;
self.lastNPC = null;
self._super(data.id, data.name, data.description);
self.loadCallbacks();
},
load: function(stage) {
var self = this;
if (!stage)
self.update();
else
self.stage = stage;
if (self.finishedCallback)
self.finishedCallback();
},
loadCallbacks: function() {
var self = this;
self.onFinishedLoading(function() {
if (self.stage > 9999)
return;
if (self.stage < 10)
self.toggleChat();
});
self.player.onReady(function() {
self.updatePointers();
});
self.onNPCTalk(function(npc) {
var conversation = self.getConversation(npc.id);
if (!conversation)
return;
self.lastNPC = npc;
npc.talk(conversation);
self.player.send(new Messages.NPC(Packets.NPCOpcode.Talk, {
id: npc.instance,
text: conversation
}));
if (npc.talkIndex > conversation.length)
self.progress('talk');
});
},
progress: function(type) {
var self = this,
task = self.data.task[self.stage];
if (!task || task !== type)
return;
switch (type) {
case 'talk':
break;
case 'click':
if (self.stage === 1)
self.forceTalk(self.lastNPC, ['Great job! This is your character menu.']);
break;
}
self.stage++;
self.clearPointers();
self.update();
self.updatePointers();
},
update: function() {
this.player.save();
},
updatePointers: function() {
var self = this,
pointer = self.data.pointers[self.stage];
if (!pointer)
return;
var opcode = pointer[0],
x = pointer[1],
y = pointer[2];
self.player.send(new Messages.Pointer(opcode, {
id: Utils.generateRandomId(),
x: x,
y: y
}));
},
clearPointers: function() {
this.player.send(new Messages.Pointer(Packets.PointerOpcode.Remove, {}));
},
toggleChat: function() {
this.player.canTalk = !this.player.canTalk;
},
getConversation: function(id) {
var self = this,
conversation = self.data.conversations[id];
if (!conversation || !conversation[self.stage])
return [''];
var message = conversation[self.stage];
if (self.stage === 3)
message[0] += self.player.username;
return message;
},
setStage: function(stage) {
var self = this;
self._super(stage);
self.update();
self.clearPointers();
},
finish: function() {
var self = this;
self.setStage(9999);
},
forceTalk: function(npc, message) {
var self = this;
/**
* The message must be in an array format.
*/
npc.talkIndex = 0;
self.player.send(new Messages.NPC(Packets.NPCOpcode.Talk, {
id: npc.instance,
text: message
}));
},
hasNPC: function(id) {
var self = this;
for (var i = 0; i < self.data.npcs.length; i++)
if (self.data.npcs[i] === id)
return true;
return false;
},
onFinishedLoading: function(callback) {
this.finishedCallback = callback;
}
}); | udeva/Kaetram | server/js/game/entity/character/player/quest/misc/introduction.js | JavaScript | mpl-2.0 | 4,001 |
/* 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/>. */
// @flow
const { applyMiddleware, createStore, compose } = require("redux");
const { thunk } = require("../shared/redux/middleware/thunk");
const {
waitUntilService
} = require("../shared/redux/middleware/waitUntilService");
const reducer = require("./reducer");
import type { Props, State } from "./types";
function createInitialState(overrides: Object): State {
return {
actors: new Set(),
expandedPaths: new Set(),
focusedItem: null,
loadedProperties: new Map(),
forceUpdated: false,
...overrides
};
}
function enableStateReinitializer(props) {
return next => (innerReducer, initialState, enhancer) => {
function reinitializerEnhancer(state, action) {
if (action.type !== "ROOTS_CHANGED") {
return innerReducer(state, action);
}
if (props.releaseActor && initialState.actors) {
initialState.actors.forEach(props.releaseActor);
}
return {
...action.data,
actors: new Set(),
expandedPaths: new Set(),
loadedProperties: new Map(),
// Indicates to the component that we do want to render on the next
// render cycle.
forceUpdate: true
};
}
return next(reinitializerEnhancer, initialState, enhancer);
};
}
module.exports = (props: Props) => {
const middlewares = [thunk];
if (props.injectWaitService) {
middlewares.push(waitUntilService);
}
return createStore(
reducer,
createInitialState(props),
compose(
applyMiddleware(...middlewares),
enableStateReinitializer(props)
)
);
};
| jasonLaster/debugger.html | packages/devtools-reps/src/object-inspector/store.js | JavaScript | mpl-2.0 | 1,789 |
'use strict';
import TyphonLoggedEvents from './TyphonLoggedEvents.js';
const eventbus = new TyphonLoggedEvents();
eventbus.setEventbusName('mainEventbus');
/**
* Exports an instance of `TyphonLoggedEvents` which adds asynchronous capabilities to `Backbone.Events` which is used
* as a main eventbus. Note that an instance of `TyphonLoggedEvents` is exported and is also associated to a mapped
* path, `mainEventbus` in the SystemJS extra configuration data loaded by all TyphonJS repos in
* `./config/config-app-paths.js`. By using a mapped path any other module may import the main eventbus via:
* `import eventbus from 'mainEventbus';`
*
* Note the above creation of `const eventbus` is a workaround for an ESDoc bug:
* https://github.com/esdoc/esdoc/issues/166
*
* Normally we can write `export default new TyphonLoggedEvents();`, but this currently breaks ESDoc.
*/
export default eventbus; | typhonjs-backbone/typhonjs-core-backbone-events-logged | src/mainEventbus.js | JavaScript | mpl-2.0 | 911 |
/**
* Created by leow on 2/12/17.
*/
"use strict";
// Stdlib
const util = require("util")
// Constants
const NON_FATAL_INCONSISTENT = "Inconsistent state - retry!"
const FATAL_CONTENT = "Page does not exist!"
const FATAL_UNKNOWN = "Unknown Error!"
// Libs
const cheerio = require('cheerio')
const tableParser = require('cheerio-tableparser')
function recognize_page_type(page_parsed) {
// console.error("TYPE: " + typeof(page_parsed))
// DEBUG:
// console.error("TITLE IS " + pageParsed('head title').text())
// If title is "PublicViewStatus"; is OK; otherwise ERROR out!!
if (page_parsed('head title').text() == "PublicViewStatus") {
// Aduan Information
// id="dlAduan"
// DEBUG:
// console.error("ADUAN: " + pageParsed('#Table9'))
/*
console.error("====== ADUAN_DATA: =====\n" + util.inspect(
pageParsed('#Table9').parsetable(false, false, true).reduce(
(p, n) => n.map((item, i) => [...(p[i] || []), n[i]]), []
)))
*/
/* NO NEED TRANSPOSE!! :P
const aduanData = pageParsed('#Table9').parsetable(false, false, true).reduce(
(p, n) => n.map((item, i) => [...(p[i] || []), n[i]]), []
)
*/
const aduan_data = page_parsed('#Table9').parsetable(false, false, true)
// DEBUG:
/*
console.error("SIZE: " + aduan_data.length)
aduanData[0].every((element, index, array) => {
console.error("EL: " + util.inspect(element) + " ID: " + index )
})
*/
// Choose the column number; then we can get out the key/value
// aduanData[0] for the label
// aduanData[1] for the value
// DEBUG:
/*
aduan_data[1].forEach((element, index) => {
console.error('a[' + index + '] = ' + element)
})
*/
// console.error("ADUANID: " + aduan_data[1][0])
// Tindakan Table
// id="dsTindakan"
// DEBUG:
// console.error("TINDAKAN: " + pageParsed('#dsTindakan'))
// References:
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array
// Transpose assumes matrix (same size both end); not suitable
// const transpose = a => a.map((_, c) => a.map(r => r[c]))
// Last solution by @tatomyr works!!
const tindakan_data = page_parsed('#dsTindakan').parsetable(false, false, true).reduce(
(p, n) => n.map((item, i) => [...(p[i] || []), n[i]]), []
)
// DEBUG:
/*
console.error("TINDAKAN_DATA:" + util.inspect(tindakan_data))
console.error("TINDAKAN_LENGTH: " + tindakan_data.length)
*/
if (tindakan_data.length == 1) {
return {
"page_type": "empty",
"aduan_id": aduan_data[1][0]
}
} else {
return {
"page_type": "good",
"aduan_id": aduan_data[1][0]
}
}
} else {
return {
"page_type": "error"
}
}
// Should not get here .. is bad!
return {
"page_type": "unknown"
}
}
function extract_table(loaded_raw_content) {
if (loaded_raw_content === null || loaded_raw_content === undefined) {
return {
"error": FATAL_CONTENT
}
}
const page_parsed = cheerio.load(loaded_raw_content)
// Setup cheerio-tableparser
tableParser(page_parsed)
// Extract out page type and other goodies?
const res = recognize_page_type(page_parsed)
if (res.page_type == "error") {
// Assumes Error Page; but it is loaded correctly ..
return {
"error": null,
"type": "error"
}
} else if (res.page_type == "unknown") {
return {
"error": FATAL_UNKNOWN,
"type": "error"
}
}
// Type: "good" or "empty"
return {
"error": null,
"type": res.page_type,
"aduan_id": res.aduan_id
}
}
module.exports = {
execute: extract_table
} | leowmjw/playground-es6 | NATIVE_ES6_TAP/libs/recognize-page-type.js | JavaScript | agpl-3.0 | 4,125 |