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
|
---|---|---|---|---|---|
import _extends from "@babel/runtime/helpers/extends";
import _inheritsLoose from "@babel/runtime/helpers/inheritsLoose";
import _assertThisInitialized from "@babel/runtime/helpers/assertThisInitialized";
import _defineProperty from "@babel/runtime/helpers/defineProperty";
import * as React from 'react';
import createContext from 'create-react-context';
export var ManagerContext = createContext({
setReferenceNode: undefined,
referenceNode: undefined
});
var Manager =
/*#__PURE__*/
function (_React$Component) {
_inheritsLoose(Manager, _React$Component);
function Manager() {
var _this;
_this = _React$Component.call(this) || this;
_defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "setReferenceNode", function (referenceNode) {
if (!referenceNode || _this.state.context.referenceNode === referenceNode) {
return;
}
_this.setState(function (_ref) {
var context = _ref.context;
return {
context: _extends({}, context, {
referenceNode: referenceNode
})
};
});
});
_this.state = {
context: {
setReferenceNode: _this.setReferenceNode,
referenceNode: undefined
}
};
return _this;
}
var _proto = Manager.prototype;
_proto.render = function render() {
return React.createElement(ManagerContext.Provider, {
value: this.state.context
}, this.props.children);
};
return Manager;
}(React.Component);
export { Manager as default }; | brett-harvey/Smart-Contracts | Ethereum-based-Roll4Win/node_modules/react-popper/lib/esm/Manager.js | JavaScript | mit | 1,530 |
import React from 'react'
const NotFoundPage = () => (
<div>
<h1>Apologies, the page you are looking for aint here :/</h1>
<p>You just hit a route that doesn't exist... the sadness.</p>
</div>
)
export default NotFoundPage
| mccannsean421/mccannsean421.github.io | src/pages/404.js | JavaScript | mit | 241 |
import React, {PropTypes} from 'react'
import {connect} from 'dva'
import UserSearch from '../components/operation/search'
import UserList from '../components/operation/mypaperlist'
import AddModal from '../components/operation/addpapermodal'
import EditModal from '../components/operation/editpapermodal'
function MyPaper({search,dispatch}) {
const {
loading, _examinepaperlist, modalVisible, modalType,
} = search;
const userListProps = {
dataSource: _examinepaperlist,
loading,
onDeleteItem(item){
dispatch({
type: 'search/delPaper',
payload: {paper_id:item.paper_id},
})
},
onEditItem(item){
dispatch({type: 'search/showeditModal',payload:item,});
}
};
const userSearchProps = {
onAdd()
{
dispatch({type: 'search/showModal',});
},
onSearch(fieldsValue) {
dispatch({
type: 'search/getmyPaper',
payload: fieldsValue.keyword,
})
},
};
return (
<div className="content-inner">
<UserSearch {...userSearchProps} />
<UserList {...userListProps} />
<AddModal/>
<EditModal/>
</div>
)
}
export default connect(search => search)(MyPaper) | shihaoran/PaperDataBase | src/routes/papers.js | JavaScript | mit | 1,199 |
import controller from './ngbOrthoParaTable.controller';
export default {
bindings: {
changeState: '&'
},
controller: controller.UID,
restrict: 'E',
template: require('./ngbOrthoParaTable.tpl.html'),
};
| epam/NGB | client/client/app/components/ngbHomologsPanel/ngbOrthoParaTable/ngbOrthoParaTable.component.js | JavaScript | mit | 232 |
const assert = require('assert');
const esTokenizer = require('../../lib/compile/es-tokenizer');
module.exports = {
'parser': {
'basic': () => {
const test = (code, result) => {
assert.deepEqual(result, esTokenizer(code));
};
test('var', [{
type: 'keyword',
value: 'var'
}]);
test('0.99', [{
type: 'number',
value: '0.99'
}]);
test('"value"', [{
type: 'string',
value: '"value"',
closed: true
}]);
test('/*value*/', [{
type: 'comment',
value: '/*value*/',
closed: true
}]);
test('=>', [{
type: 'punctuator',
value: '=>'
}]);
test('#', [{
type: 'invalid',
value: '#'
}]);
test('@', [{
type: 'invalid',
value: '@'
}]);
test('a.b.c+d', [{
type: 'name',
value: 'a'
}, {
type: 'punctuator',
value: '.'
}, {
type: 'name',
value: 'b'
}, {
type: 'punctuator',
value: '.'
}, {
type: 'name',
value: 'c'
}, {
type: 'punctuator',
value: '+'
}, {
type: 'name',
value: 'd'
}]);
test('@if a + b === 0', [{
type: 'invalid',
value: '@'
}, {
type: 'keyword',
value: 'if'
}, {
type: 'whitespace',
value: ' '
}, {
type: 'name',
value: 'a'
}, {
type: 'whitespace',
value: ' '
}, {
type: 'punctuator',
value: '+'
}, {
type: 'whitespace',
value: ' '
}, {
type: 'name',
value: 'b'
}, {
type: 'whitespace',
value: ' '
}, {
type: 'punctuator',
value: '==='
}, {
type: 'whitespace',
value: ' '
}, {
type: 'number',
value: '0'
}]);
}
}
}; | HazelZ/proj-essential | ARTTEMPLATE/art-template-master/test/compile/es-tokenizer.js | JavaScript | mit | 2,669 |
function PartialProjectList()
{
return [
'<div class="container-fluid">\n',
' <div class="row">\n',
' <div class="col-md-2">\n',
' <!--Sidebar content-->\n',
' <h1>My Bio</h1>\n',
' <div class="bio">\n',
' <img class="photo" ng-src="{{user.photoUrl}}"/>\n',
' <div class="name">{{user.name}}</div>\n',
' <ul class="degrees">\n',
' <li ng-repeat="degree in user.degree"\n',
' class="degree">\n',
' <img class="country-icon" ng-src="{{degree.icon}}"/>\n',
' {{degree.title}}\n',
' </li>\n',
' </ul>\n',
' <br/>\n',
' <div class="cv">\n',
' <a target="_blank" ng-href="{{user.cv}}">\n',
' <img class="ref-icon" ng-src="img/core/pdf.png"/>\n',
' </a>\n',
' <a target="_blank" ng-href="{{user.cv}}">\n',
' CV (Résumé)\n',
' </a>\n',
' </div> \n',
' <div class="linkedIn">\n',
' <a target="_blank" target="_blank" ng-href="{{user.labUrl}}">\n',
' <img class="ref-icon" ng-src="img/core/linkedin.png"/>\n',
' </a>\n',
' <a target="_blank" target="_blank" ng-href="{{user.linkedInUrl}}">LinkedIn Profile</a>\n',
' </div>\n',
' <div class="labUrl">\n',
' <a target="_blank" ng-href="{{user.labUrl}}">\n',
' <img class="ref-icon" ng-src="img/core/gsdlab.png"/>\n',
' </a>\n',
' <a target="_blank" ng-href="{{user.labUrl}}">\n',
' Laboratory Homepage\n',
' </a>\n',
' </div> \n',
' <br/>\n',
' <div class="status-title">Current status:</div> \n',
' <div class="status">{{user.status}}</div> \n',
' </div>\n',
' <h1>Contact Me</h1>\n',
' <div class="contact">\n',
' <div class="email">\n',
' <a target="_blank" href="mailto:{{user.email}}">\n',
' <img class="ref-icon" ng-src="img/core/email.png"/>\n',
' </a> \n',
' <a target="_blank" class="email" href="mailto:{{user.email}}">{{user.email}}</a>\n',
' </div>\n',
' <div class="call">\n',
' <img class="ref-icon" ng-src="img/core/call.png"/>\n',
' <span class="call">{{user.phone}}</span>\n',
' </div>\n',
' </div>\n',
' </div>\n',
' <div class="col-md-10">\n',
' <!--Body content-->\n',
' <h1>My Top Projects</h1>\n',
' Search: <input ng-model="query">\n',
' Sort by:\n',
' <select ng-model="orderProp">\n',
' <option value="name">Alphabet</option>\n',
' <option value="weight">Coolness</option>\n',
' </select>\n',
' <br/>\n',
' <br/>\n',
' <ul class="projects">\n',
' <li ng-repeat="project in projects | filter:query | orderBy:orderProp"\n',
' class="thumbnail project-listing">\n',
' <a href="index.html#show/project/{{project.id}}" class="thumb"><img ng-src="{{project.imageUrl}}"></a>\n',
' <a href="index.html#show/project/{{project.id}}">{{project.name}}</a>\n',
' <p>{{project.snippet}}</p>\n',
' </li>\n',
' </ul>\n',
'\n',
' </div>\n',
' </div>\n',
'</div>'
].join("");
} | AMurashkin/Portfolio | app/partials/project-list.js | JavaScript | mit | 3,224 |
bpm = (function ($) {
"use strict";
var socket;
var url = function (){
return $.url().param();
};
var init = function(){
$('#status').removeClass('connected').addClass('disconnected').text('not connected');
socket = io.connect('http://' + document.location.hostname + ':8081');
socket.on('connect', function (data) {
$('#status').removeClass('disconnected').addClass('connected').text('connected');
socket.emit('subscribe', { room: 'webNodes' });
});
socket.on('disconnect', function (data){
$('#status').removeClass('connected').addClass('disconnected').text('not connected');
});
socket.on('connect_failed', function (data) {
console.log('socket connect failed');
console.log(data);
});
socket.on('error', function (data) {
console.log('socket error');
console.log(data);
});
socket.on('roomChange', function(data){
roomUpdate(data);
});
socket.on('update', function (data) {
displayUpdate(data);
});
socket.on('topFiveResponse', function(data){
displayUpdate(data);
});
console.log('fsb.init...');
socket.emit('topFive');
socket.emit('roomStatusInit');
};
var roomUpdate = function(data){
console.log(data);
$('#roomActivity').empty();
$('#roomActivity').append('<table>');
$.each(data, function(i,v){
$('#roomActivity').append('<tr><td>' + v.ip + ':' + v.port + '</td><td>' + v.id + '</td></tr>');
});
$('#roomActivity').append('</table>');
}
var displayUpdate = function(data){
$.each(data, function(i,v){
$('#recentActivity').prepend('<div>' + v.ipAddr + ' -- ' + v.tagAddr + ' -- ' + v.temp + '</div>');
$('#recentActivity div').each(
function(i,v){
if (i >= 5) {
$(v).remove()
}
});
});
};
// Public
return {
socket: function(){ return socket },
url: url,
init: init
};
} (jQuery));
| HammerDuJour/blepimesh | static/js/main.js | JavaScript | mit | 2,052 |
import React from 'react';
import { withStyles } from 'material-ui/styles';
import { RaisedButton } from '../../../components';
import Typography from 'material-ui/Typography';
import TextField from 'material-ui/TextField';
import Input, { InputLabel } from 'material-ui/Input';
import { MenuItem } from 'material-ui/Menu';
import { FormControl, FormHelperText } from 'material-ui/Form';
import Select from 'material-ui/Select';
const styles = theme => ({
title: {
fontSize: 18,
marginBottom: 16,
fontWeight: 600
},
input: {
marginBottom: 20
},
button: {
textAlign: 'right'
},
helperText: {
fontSize: 10
}
});
class ProfileStep extends React.Component {
state = {
email: '',
age: '',
gender: '',
educationLevel: ''
}
handleChange (field, value) {
this.setState({ [field]: value });
}
handleChangeAge (value) {
value = parseInt(value, 10);
if (!value) return this.handleChange('age', '');
if (value > 100 || value < 0) return;
this.handleChange('age', value);
}
handleSubmit (event) {
event.preventDefault();
let { email, age, gender, educationLevel } = this.state;
this.props.onSubmit({
email: email,
age: age !== '' ? age : null,
gender: gender !== '' ? gender : null,
educationLevel: educationLevel !== '' ? educationLevel : null
});
}
render () {
let { classes, isFetching } = this.props;
return (
<form onSubmit={ this.handleSubmit.bind(this) }>
<Typography type="title" className={ classes.title }>
Complete la siguiente información
</Typography>
<TextField fullWidth required className={ classes.input }
label="Email"
type="email"
name="email"
value={ this.state.email }
onChange={ e => this.handleChange('email', e.target.value) }
/>
<TextField fullWidth className={ classes.input }
label="Edad"
type="number"
name="age"
helperText="Opcional"
value={ this.state.age }
onChange={ e => this.handleChangeAge(e.target.value) }
FormHelperTextProps={{
classes: { root: classes.helperText }
}}
/>
<FormControl fullWidth className={ classes.input }>
<InputLabel htmlFor="gender">Género</InputLabel>
<Select
input={ <Input id="gender" /> }
value={ this.state.gender }
onChange={ e => this.handleChange('gender', e.target.value) }
>
<MenuItem value="female">Mujer</MenuItem>
<MenuItem value="male">Varón</MenuItem>
<MenuItem value="other">Otro</MenuItem>
</Select>
<FormHelperText classes={{ root: classes.helperText }}>Opcional</FormHelperText>
</FormControl>
<FormControl fullWidth className={ classes.input }>
<InputLabel htmlFor="education-level">Nivel de educación</InputLabel>
<Select
input={ <Input id="education-level" /> }
value={ this.state.educationLevel }
onChange={ e => this.handleChange('educationLevel', e.target.value) }
>
<MenuItem value="none">Ninguno</MenuItem>
<MenuItem value="primary">Primario</MenuItem>
<MenuItem value="high-school">Secundario</MenuItem>
<MenuItem value="academic">Terciario / Universitario</MenuItem>
<MenuItem value="postgraduate">Posgrado</MenuItem>
</Select>
<FormHelperText classes={{ root: classes.helperText }}>Opcional</FormHelperText>
</FormControl>
<div className={ classes.button }>
<RaisedButton label="Siguiente" type="submit" style={{ minWidth: '160px' }} disabled={ isFetching } />
</div>
</form>
);
}
}
export default withStyles(styles)(ProfileStep);
| EehMauro/dyscalculia-web | src/pages/DataEntry/components/ProfileStep.js | JavaScript | mit | 3,920 |
/* eslint import/no-extraneous-dependencies:0 */
/* eslint no-param-reassign:0 */
import test from 'ava';
import Bundler from '../src/Bundler';
test.beforeEach((t) => {
t.context.bundlerInstance = new Bundler();
});
test('returns bundled javascript', async (t) => {
t.plan(1);
const res = await t.context.bundlerInstance.bundle(
'console.log(\'foo\');'
);
t.regex(res, /console\.log\('foo'\)/);
});
test.cb('returns error if bundle fails', (t) => {
t.plan(1);
const bundler = new Bundler();
bundler.bundle(
'invalid js code'
).catch((err) => {
t.regex(
err.message,
/Unexpected token/
);
t.end();
});
});
| JiriChara/krtek | spec/Bundler.bundle.spec.js | JavaScript | mit | 665 |
(function () {
'use strict';
angular
.module('app.web')
.controller('app.views.dashboard.index', DashboardController);
DashboardController.$inject = ["abp.services.app.auditLogService", "$uibModal", '$interval', 'WebConst'];
function DashboardController(_auditLogService, modal, $interval, webConst) {
var vm = this;
var serieCount = 0;
vm.chartConfigs = {
updateInterval: 3000,
selectedOptionValue: vm.selectVal
}
vm.myChartOptions = {
series: {
lines: {
show: true,
lineWidth: 1,
fill: true,
fillColor: {
colors: [{
opacity: 0.1
}, {
opacity: 0.15
}]
}
},
points: {
show: true
},
shadowSize: 0
},
xaxis: {
mode: "categories"
},
grid: {
hoverable: true,
clickable: true
},
};
vm.toolTips = [];
var tenantId;
var requestModel = {
Count: vm.chartConfigs.selectedOptionValue,
Code: 2,
TenantId: tenantId
}
vm.changeLogType = function (option) {
requestModel.Code = option;
vm.update();
}
vm.selectVal = 50;
activate(vm.chartConfigs.selectedOptionValue);
////////////////
vm.chartData = {
auditLogTimeOutputDtos: [],
avgExecutionTime: "",
totalRequestsReceived: 0
};
vm.update = function () {
requestModel.Count = vm.selectVal;
activate();
}
vm.chartDataFormatedDtos = [[]];
vm.labels = [];
var openModal = function (id) {
var modalInstance = modal.open({
templateUrl: webConst.contentFolder + 'dashboard/logDetails.cshtml',
controller: 'app.views.dashboard.logDetails as vm',
resolve: {
items: function () {
return id;
}
}
});
}
vm.liveUpdate = false;
vm.liveUpdateText = "Toggle live update";
vm.toggleLiveUpdate = function () {
if (vm.liveUpdate == false) vm.liveUpdate = true;
else vm.liveUpdate = false;
liveUpdate(vm.selectVal);
}
vm.flotData = [];
function activate() {
vm.flotData = [];
if (!tenantId) tenantId = null;
getChartData(function (data, labels) {
var text = App.localize("Success");
if (requestModel.Code != 2) {
text = App.localize("Error");
}
vm.toolTips = labels;
vm.flotData.push({
data: data,
label: text
});
});
}
vm.hoveredItem = {};
$("<div id='tooltip'></div>").css({
position: "absolute",
display: "none",
border: "1px solid #fdd",
padding: "2px",
"background-color": "#fee",
opacity: 0.80
}).appendTo("body");
var $toolTip = $("#tooltip");
vm.onHover = function (event, pos, item) {
if (item) {
var toolTip = vm.toolTips[item.dataIndex];
if (toolTip) {
var txt = toolTip.MethodName;
var value = item.datapoint[1];
var color = "";
if (value > 500) {
color = "#ffca28";
}
if (value <= 500) {
color = "#827717";
}
if (value > 1000) {
color = "#e53935";
}
var message = "Method name: " + txt + ", Execution time: <a style='color:" + color + "'> " + value + " ms<a>";
$toolTip
.html(message)
.css({ top: item.pageY + 5, left: item.pageX + 5 })
.fadeIn(200);
}
} else {
$toolTip.hide();
}
}
vm.onClick = function (event, pos, item) {
if (item) {
console.log(vm.toolTips);
vm.hoveredItem = getCorrectToolTipIndex(vm.toolTips, item);
openModal(vm.hoveredItem.Id);
}
}
function getCorrectToolTipIndex(toolTips, item) {
//toolTips[item.dataIndex]
var seriesIndex = item.seriesIndex;
var dataIndex = item.dataIndex;
for (var i = 0; i < toolTips.length; i++) {
if (i == dataIndex) {
for (var j = 0; j < toolTips.length; j++) {
if (toolTips[j].SerieId == seriesIndex) {
return toolTips[i];
}
}
}
}
return undefined;
}
function getChartData(callback) {
var florSeriesData = [];
var toolTips = [];
_auditLogService.getAuditLogTimes(requestModel).then(function (response) {
vm.chartData = response.data;
var count = 1;
for (var i = 0; i < vm.chartData.auditLogTimeOutputDtos.length; i++) {
var elm = vm.chartData.auditLogTimeOutputDtos[i];
//Flot chart
florSeriesData.push([count, elm.executionDuration]);
toolTips.push({
MethodName: elm.methodName,
Id: elm.id,
SerieId: serieCount
});
count = count + 1;
}
//Number of series available
// serieCount = serieCount + 1;
//Flot chart
callback(florSeriesData, toolTips);
});
}
}
})(); | periface/AbpCinotamZero-SmartAdmin | Cinotam.AbpModuleZero.Web/App/SysAdmin/Main/modules/web/dashboard/index.js | JavaScript | mit | 6,418 |
import React from 'react';
import Grid from 'react-bootstrap/lib/Grid';
export default class Footer extends React.Component {
render() {
return (
<Grid>
<hr />
<footer className="taco-footer">
<p>Taco Radar 2016</p>
</footer>
</Grid>
);
}
} | SaraChicaD/TacoRadarReact | src/components/Footer.js | JavaScript | mit | 299 |
export function nextAnimationFrame() {
return new Promise(resolve => requestAnimationFrame(resolve));
}
export function isScrollable(element, style) {
if (
element.scrollHeight - element.clientHeight > 10 &&
["auto", "scroll"].includes(style.overflowY)
)
return true;
if (
element.scrollWidth - element.clientWidth > 10 &&
["auto", "scroll"].includes(style.overflowX)
)
return true;
return false;
}
export function isEditable(elem) {
if (!(elem instanceof Element)) return false;
// No-selectable <input> throws an error when "selectionStart" are referred.
let selectionStart;
try {
selectionStart = elem.selectionStart;
} catch (e) {
return false;
}
return selectionStart != null || elem.contentEditable === "true";
}
export class ArrayMap extends Map {
add(k, v) {
let vs = this.get(k);
if (vs == null) {
vs = [];
this.set(k, vs);
}
vs.push(v);
return vs;
}
delete(k, v) {
if (v == null) return super.delete(k);
const vs = this.get(k);
if (vs == null) return false;
const idx = vs.indexOf(v);
if (idx < 0) return false;
vs.splice(idx, 1);
if (vs.length === 0) super.delete(k);
return true;
}
}
export class SetMap extends Map {
add(k, v) {
let vs = this.get(k);
if (vs == null) {
vs = new Set();
this.set(k, vs);
}
return vs.add(v);
}
has(k, v) {
if (v == null) {
return this.has(k);
}
const vs = this.get(k);
if (vs == null) return false;
return vs.has(v);
}
delete(k, v) {
if (v == null) return super.delete(k);
const vs = this.get(k);
if (vs == null) return false;
const b = vs.delete(v);
if (vs.size === 0) super.delete(k);
return b;
}
}
export async function waitUntil(predicate) {
while (!predicate()) {
await nextAnimationFrame();
}
}
| kui/KNavi | src/lib/utils.js | JavaScript | mit | 1,884 |
import WaypointListContainer from './WaypointListContainer'
export default WaypointListContainer
| eunvanz/handpokemon2 | src/components/WaypointListContainer/index.js | JavaScript | mit | 98 |
function findMaxSequence(value){
var element = 0;
var maxSeq = 0;
var currSeq = 0;
var sorted = value;
for (var i = 0; i < sorted.length; i++)
{
currSeq = 1;
for (var j = i + 1; j < sorted.length - 1; j++) {
if (sorted[i] == sorted[j])
currSeq++;
else
break;
}
if (currSeq >= maxSeq)
{
maxSeq = currSeq;
element = sorted[i];
}
}
var arr = [];
for (var i = 0; i < maxSeq; i++){
arr.push(element);
}
console.log(arr);
}
findMaxSequence([2, 1, 1, 2, 3, 3, 2, 2, 2, 1]);
findMaxSequence(['happy']);
findMaxSequence([2, 'qwe', 'qwe', 3, 3, '3']);
| pan196/softuni_tasks | javascript-basics/JS-Loops&Arrays-myHomework/6. MaximalSequence/sequenceFinder.js | JavaScript | mit | 723 |
import angular from 'angular';
import _ from 'lodash';
import expect from 'expect.js';
import ngMock from 'ng_mock';
import VislibComponentsLabelsLabelsProvider from 'ui/vislib/components/labels/labels';
import VislibComponentsLabelsDataArrayProvider from 'ui/vislib/components/labels/data_array';
import VislibComponentsLabelsUniqLabelsProvider from 'ui/vislib/components/labels/uniq_labels';
import VislibComponentsLabelsFlattenSeriesProvider from 'ui/vislib/components/labels/flatten_series';
let getLabels;
let seriesLabels;
let rowsLabels;
let seriesArr;
let rowsArr;
let uniqLabels;
let error;
const seriesData = {
'label': '',
'series': [
{
'label': '100',
'values': [{ x: 0, y: 1 }, { x: 1, y: 2 }, { x: 2, y: 3 }]
}
]
};
const rowsData = {
'rows': [
{
'label': 'a',
'series': [
{
'label': '100',
'values': [{ x: 0, y: 1 }, { x: 1, y: 2 }, { x: 2, y: 3 }]
}
]
},
{
'label': 'b',
'series': [
{
'label': '300',
'values': [{ x: 0, y: 1 }, { x: 1, y: 2 }, { x: 2, y: 3 }]
}
]
},
{
'label': 'c',
'series': [
{
'label': '100',
'values': [{ x: 0, y: 1 }, { x: 1, y: 2 }, { x: 2, y: 3 }]
}
]
},
{
'label': 'd',
'series': [
{
'label': '200',
'values': [{ x: 0, y: 1 }, { x: 1, y: 2 }, { x: 2, y: 3 }]
}
]
}
]
};
const columnsData = {
'columns': [
{
'label': 'a',
'series': [
{
'label': '100',
'values': [{ x: 0, y: 1 }, { x: 1, y: 2 }, { x: 2, y: 3 }]
}
]
},
{
'label': 'b',
'series': [
{
'label': '300',
'values': [{ x: 0, y: 1 }, { x: 1, y: 2 }, { x: 2, y: 3 }]
}
]
},
{
'label': 'c',
'series': [
{
'label': '100',
'values': [{ x: 0, y: 1 }, { x: 1, y: 2 }, { x: 2, y: 3 }]
}
]
},
{
'label': 'd',
'series': [
{
'label': '200',
'values': [{ x: 0, y: 1 }, { x: 1, y: 2 }, { x: 2, y: 3 }]
}
]
}
]
};
describe('Vislib Labels Module Test Suite', function () {
describe('Labels (main)', function () {
beforeEach(ngMock.module('kibana'));
beforeEach(ngMock.inject(function (Private) {
getLabels = Private(VislibComponentsLabelsLabelsProvider);
seriesLabels = getLabels(seriesData);
rowsLabels = getLabels(rowsData);
seriesArr = _.isArray(seriesLabels);
rowsArr = _.isArray(rowsLabels);
uniqLabels = _.chain(rowsData.rows)
.pluck('series')
.flattenDeep()
.pluck('label')
.uniq()
.value();
}));
it('should be a function', function () {
expect(typeof getLabels).to.be('function');
});
it('should return an array if input is data.series', function () {
expect(seriesArr).to.be(true);
});
it('should return an array if input is data.rows', function () {
expect(rowsArr).to.be(true);
});
it('should throw an error if input is not an object', function () {
expect(function () {
getLabels('string not object');
}).to.throwError();
});
it('should return unique label values', function () {
expect(rowsLabels[0]).to.equal(uniqLabels[0]);
expect(rowsLabels[1]).to.equal(uniqLabels[1]);
expect(rowsLabels[2]).to.equal(uniqLabels[2]);
});
});
describe('Data array', function () {
const childrenObject = {
children: []
};
const seriesObject = {
series: []
};
const rowsObject = {
rows: []
};
const columnsObject = {
columns: []
};
const string = 'string';
const number = 23;
const boolean = false;
const emptyArray = [];
const nullValue = null;
let notAValue;
let dataArray;
let testSeries;
let testRows;
beforeEach(ngMock.module('kibana'));
beforeEach(ngMock.inject(function (Private) {
dataArray = Private(VislibComponentsLabelsDataArrayProvider);
seriesLabels = dataArray(seriesData);
rowsLabels = dataArray(rowsData);
testSeries = _.isArray(seriesLabels);
testRows = _.isArray(rowsLabels);
}));
it('should throw an error if the input is not an object', function () {
expect(function () {
dataArray(string);
}).to.throwError();
expect(function () {
dataArray(number);
}).to.throwError();
expect(function () {
dataArray(boolean);
}).to.throwError();
expect(function () {
dataArray(emptyArray);
}).to.throwError();
expect(function () {
dataArray(nullValue);
}).to.throwError();
expect(function () {
dataArray(notAValue);
}).to.throwError();
});
it(
'should throw an error if property series, rows, or ' +
'columns is not present',
function () {
expect(function () {
dataArray(childrenObject);
}).to.throwError();
}
);
it(
'should not throw an error if object has property series, rows, or ' +
'columns',
function () {
expect(function () {
dataArray(seriesObject);
}).to.not.throwError();
expect(function () {
dataArray(rowsObject);
}).to.not.throwError();
expect(function () {
dataArray(columnsObject);
}).to.not.throwError();
}
);
it('should be a function', function () {
expect(typeof dataArray).to.equal('function');
});
it('should return an array of objects if input is data.series', function () {
expect(testSeries).to.equal(true);
});
it('should return an array of objects if input is data.rows', function () {
expect(testRows).to.equal(true);
});
it('should return an array of same length as input data.series', function () {
expect(seriesLabels.length).to.equal(seriesData.series.length);
});
it('should return an array of same length as input data.rows', function () {
expect(rowsLabels.length).to.equal(rowsData.rows.length);
});
it('should return an array of objects with obj.labels and obj.values', function () {
expect(seriesLabels[0].label).to.equal('100');
expect(seriesLabels[0].values[0].x).to.equal(0);
expect(seriesLabels[0].values[0].y).to.equal(1);
});
});
describe('Unique labels', function () {
let uniqLabels;
const arrObj = [
{ 'label': 'a' },
{ 'label': 'b' },
{ 'label': 'b' },
{ 'label': 'c' },
{ 'label': 'c' },
{ 'label': 'd' },
{ 'label': 'f' }
];
const string = 'string';
const number = 24;
const boolean = false;
const nullValue = null;
const emptyObject = {};
const emptyArray = [];
let notAValue;
let uniq;
let testArr;
beforeEach(ngMock.module('kibana'));
beforeEach(ngMock.inject(function (Private) {
uniqLabels = Private(VislibComponentsLabelsUniqLabelsProvider);
uniq = uniqLabels(arrObj, function (d) { return d; });
testArr = _.isArray(uniq);
}));
it('should throw an error if input is not an array', function () {
expect(function () {
uniqLabels(string);
}).to.throwError();
expect(function () {
uniqLabels(number);
}).to.throwError();
expect(function () {
uniqLabels(boolean);
}).to.throwError();
expect(function () {
uniqLabels(nullValue);
}).to.throwError();
expect(function () {
uniqLabels(emptyObject);
}).to.throwError();
expect(function () {
uniqLabels(notAValue);
}).to.throwError();
});
it('should not throw an error if the input is an array', function () {
expect(function () {
uniqLabels(emptyArray);
}).to.not.throwError();
});
it('should be a function', function () {
expect(typeof uniqLabels).to.be('function');
});
it('should return an array', function () {
expect(testArr).to.be(true);
});
it('should return array of 5 unique values', function () {
expect(uniq.length).to.be(5);
});
});
describe('Get series', function () {
const string = 'string';
const number = 24;
const boolean = false;
const nullValue = null;
const rowsObject = {
rows: []
};
const columnsObject = {
columns: []
};
const emptyObject = {};
const emptyArray = [];
let notAValue;
let getSeries;
let columnsLabels;
let rowsLabels;
let columnsArr;
let rowsArr;
beforeEach(ngMock.module('kibana'));
beforeEach(ngMock.inject(function (Private) {
getSeries = Private(VislibComponentsLabelsFlattenSeriesProvider);
columnsLabels = getSeries(columnsData);
rowsLabels = getSeries(rowsData);
columnsArr = _.isArray(columnsLabels);
rowsArr = _.isArray(rowsLabels);
}));
it('should throw an error if input is not an object', function () {
expect(function () {
getSeries(string);
}).to.throwError();
expect(function () {
getSeries(number);
}).to.throwError();
expect(function () {
getSeries(boolean);
}).to.throwError();
expect(function () {
getSeries(nullValue);
}).to.throwError();
expect(function () {
getSeries(emptyArray);
}).to.throwError();
expect(function () {
getSeries(notAValue);
}).to.throwError();
});
it('should throw an if property rows or columns is not set on the object', function () {
expect(function () {
getSeries(emptyObject);
}).to.throwError();
});
it('should not throw an error if rows or columns set on object', function () {
expect(function () {
getSeries(rowsObject);
}).to.not.throwError();
expect(function () {
getSeries(columnsObject);
}).to.not.throwError();
});
it('should be a function', function () {
expect(typeof getSeries).to.be('function');
});
it('should return an array if input is data.columns', function () {
expect(columnsArr).to.be(true);
});
it('should return an array if input is data.rows', function () {
expect(rowsArr).to.be(true);
});
it('should return an array of the same length as as input data.columns', function () {
expect(columnsLabels.length).to.be(columnsData.columns.length);
});
it('should return an array of the same length as as input data.rows', function () {
expect(rowsLabels.length).to.be(rowsData.rows.length);
});
});
});
| istresearch/PulseTheme | kibana/src/ui/public/vislib/__tests__/components/labels.js | JavaScript | mit | 10,815 |
/*!
* Bootstrap v3.3.6 (http://getbootstrap.com)
* Copyright 2011-2015 Twitter, Inc.
* Licensed under the MIT license
*/
if (typeof jQuery === 'undefined') {
throw new Error('Bootstrap\'s JavaScript requires jQuery')
} + function($) {
'use strict';
var version = $.fn.jquery.split(' ')[0].split('.')
if ((version[0] < 2 && version[1] < 9) || (version[0] == 1 && version[1] == 9 && version[2] < 1) || (version[0] > 2)) {
throw new Error('Bootstrap\'s JavaScript requires jQuery version 1.9.1 or higher, but lower than version 3')
}
}(jQuery);
/* ========================================================================
* Bootstrap: transition.js v3.3.6
* http://getbootstrap.com/javascript/#transitions
* ========================================================================
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+ function($) {
'use strict';
function transitionEnd() {
var el = document.createElement('bootstrap')
var transEndEventNames = {
WebkitTransition: 'webkitTransitionEnd',
MozTransition: 'transitionend',
OTransition: 'oTransitionEnd otransitionend',
transition: 'transitionend'
}
for (var name in transEndEventNames) {
if (el.style[name] !== undefined) {
return {
end: transEndEventNames[name]
}
}
}
return false // explicit for ie8 ( ._.)
}
// http://blog.alexmaccaw.com/css-transitions
$.fn.emulateTransitionEnd = function(duration) {
var called = false
var $el = this
$(this).one('bsTransitionEnd', function() {
called = true
})
var callback = function() {
if (!called) $($el).trigger($.support.transition.end)
}
setTimeout(callback, duration)
return this
}
$(function() {
$.support.transition = transitionEnd()
if (!$.support.transition) return
$.event.special.bsTransitionEnd = {
bindType: $.support.transition.end,
delegateType: $.support.transition.end,
handle: function(e) {
if ($(e.target).is(this)) return e.handleObj.handler.apply(this, arguments)
}
}
})
}(jQuery);
/* ========================================================================
* Bootstrap: alert.js v3.3.6
* http://getbootstrap.com/javascript/#alerts
* ========================================================================
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+ function($) {
'use strict';
// ALERT CLASS DEFINITION
// ======================
var dismiss = '[data-dismiss="alert"]'
var Alert = function(el) {
$(el).on('click', dismiss, this.close)
}
Alert.VERSION = '3.3.6'
Alert.TRANSITION_DURATION = 150
Alert.prototype.close = function(e) {
var $this = $(this)
var selector = $this.attr('data-target')
if (!selector) {
selector = $this.attr('href')
selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7
}
var $parent = $(selector)
if (e) e.preventDefault()
if (!$parent.length) {
$parent = $this.closest('.alert')
}
$parent.trigger(e = $.Event('close.bs.alert'))
if (e.isDefaultPrevented()) return
$parent.removeClass('in')
function removeElement() {
// detach from parent, fire event then clean up data
$parent.detach().trigger('closed.bs.alert').remove()
}
$.support.transition && $parent.hasClass('fade') ? $parent.one('bsTransitionEnd', removeElement).emulateTransitionEnd(Alert.TRANSITION_DURATION) : removeElement()
}
// ALERT PLUGIN DEFINITION
// =======================
function Plugin(option) {
return this.each(function() {
var $this = $(this)
var data = $this.data('bs.alert')
if (!data) $this.data('bs.alert', (data = new Alert(this)))
if (typeof option == 'string') data[option].call($this)
})
}
var old = $.fn.alert
$.fn.alert = Plugin
$.fn.alert.Constructor = Alert
// ALERT NO CONFLICT
// =================
$.fn.alert.noConflict = function() {
$.fn.alert = old
return this
}
// ALERT DATA-API
// ==============
$(document).on('click.bs.alert.data-api', dismiss, Alert.prototype.close)
}(jQuery);
/* ========================================================================
* Bootstrap: button.js v3.3.6
* http://getbootstrap.com/javascript/#buttons
* ========================================================================
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+ function($) {
'use strict';
// BUTTON PUBLIC CLASS DEFINITION
// ==============================
var Button = function(element, options) {
this.$element = $(element)
this.options = $.extend({}, Button.DEFAULTS, options)
this.isLoading = false
}
Button.VERSION = '3.3.6'
Button.DEFAULTS = {
loadingText: 'loading...'
}
Button.prototype.setState = function(state) {
var d = 'disabled'
var $el = this.$element
var val = $el.is('input') ? 'val' : 'html'
var data = $el.data()
state += 'Text'
if (data.resetText == null) $el.data('resetText', $el[val]())
// push to event loop to allow forms to submit
setTimeout($.proxy(function() {
$el[val](data[state] == null ? this.options[state] : data[state])
if (state == 'loadingText') {
this.isLoading = true
$el.addClass(d).attr(d, d)
} else if (this.isLoading) {
this.isLoading = false
$el.removeClass(d).removeAttr(d)
}
}, this), 0)
}
Button.prototype.toggle = function() {
var changed = true
var $parent = this.$element.closest('[data-toggle="buttons"]')
if ($parent.length) {
var $input = this.$element.find('input')
if ($input.prop('type') == 'radio') {
if ($input.prop('checked')) changed = false
$parent.find('.active').removeClass('active')
this.$element.addClass('active')
} else if ($input.prop('type') == 'checkbox') {
if (($input.prop('checked')) !== this.$element.hasClass('active')) changed = false
this.$element.toggleClass('active')
}
$input.prop('checked', this.$element.hasClass('active'))
if (changed) $input.trigger('change')
} else {
this.$element.attr('aria-pressed', !this.$element.hasClass('active'))
this.$element.toggleClass('active')
}
}
// BUTTON PLUGIN DEFINITION
// ========================
function Plugin(option) {
return this.each(function() {
var $this = $(this)
var data = $this.data('bs.button')
var options = typeof option == 'object' && option
if (!data) $this.data('bs.button', (data = new Button(this, options)))
if (option == 'toggle') data.toggle()
else if (option) data.setState(option)
})
}
var old = $.fn.button
$.fn.button = Plugin
$.fn.button.Constructor = Button
// BUTTON NO CONFLICT
// ==================
$.fn.button.noConflict = function() {
$.fn.button = old
return this
}
// BUTTON DATA-API
// ===============
$(document).on('click.bs.button.data-api', '[data-toggle^="button"]', function(e) {
var $btn = $(e.target)
if (!$btn.hasClass('btn')) $btn = $btn.closest('.btn')
Plugin.call($btn, 'toggle')
if (!($(e.target).is('input[type="radio"]') || $(e.target).is('input[type="checkbox"]'))) e.preventDefault()
}).on('focus.bs.button.data-api blur.bs.button.data-api', '[data-toggle^="button"]', function(e) {
$(e.target).closest('.btn').toggleClass('focus', /^focus(in)?$/.test(e.type))
})
}(jQuery);
/* ========================================================================
* Bootstrap: carousel.js v3.3.6
* http://getbootstrap.com/javascript/#carousel
* ========================================================================
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+ function($) {
'use strict';
// CAROUSEL CLASS DEFINITION
// =========================
var Carousel = function(element, options) {
this.$element = $(element)
this.$indicators = this.$element.find('.carousel-indicators')
this.options = options
this.paused = null
this.sliding = null
this.interval = null
this.$active = null
this.$items = null
this.options.keyboard && this.$element.on('keydown.bs.carousel', $.proxy(this.keydown, this))
this.options.pause == 'hover' && !('ontouchstart' in document.documentElement) && this.$element.on('mouseenter.bs.carousel', $.proxy(this.pause, this)).on('mouseleave.bs.carousel', $.proxy(this.cycle, this))
}
Carousel.VERSION = '3.3.6'
Carousel.TRANSITION_DURATION = 600
Carousel.DEFAULTS = {
interval: 5000,
pause: 'hover',
wrap: true,
keyboard: true
}
Carousel.prototype.keydown = function(e) {
if (/input|textarea/i.test(e.target.tagName)) return
switch (e.which) {
case 37:
this.prev();
break
case 39:
this.next();
break
default:
return
}
e.preventDefault()
}
Carousel.prototype.cycle = function(e) {
e || (this.paused = false)
this.interval && clearInterval(this.interval)
this.options.interval && !this.paused && (this.interval = setInterval($.proxy(this.next, this), this.options.interval))
return this
}
Carousel.prototype.getItemIndex = function(item) {
this.$items = item.parent().children('.item')
return this.$items.index(item || this.$active)
}
Carousel.prototype.getItemForDirection = function(direction, active) {
var activeIndex = this.getItemIndex(active)
var willWrap = (direction == 'prev' && activeIndex === 0) || (direction == 'next' && activeIndex == (this.$items.length - 1))
if (willWrap && !this.options.wrap) return active
var delta = direction == 'prev' ? -1 : 1
var itemIndex = (activeIndex + delta) % this.$items.length
return this.$items.eq(itemIndex)
}
Carousel.prototype.to = function(pos) {
var that = this
var activeIndex = this.getItemIndex(this.$active = this.$element.find('.item.active'))
if (pos > (this.$items.length - 1) || pos < 0) return
if (this.sliding) return this.$element.one('slid.bs.carousel', function() {
that.to(pos)
}) // yes, "slid"
if (activeIndex == pos) return this.pause().cycle()
return this.slide(pos > activeIndex ? 'next' : 'prev', this.$items.eq(pos))
}
Carousel.prototype.pause = function(e) {
e || (this.paused = true)
if (this.$element.find('.next, .prev').length && $.support.transition) {
this.$element.trigger($.support.transition.end)
this.cycle(true)
}
this.interval = clearInterval(this.interval)
return this
}
Carousel.prototype.next = function() {
if (this.sliding) return
return this.slide('next')
}
Carousel.prototype.prev = function() {
if (this.sliding) return
return this.slide('prev')
}
Carousel.prototype.slide = function(type, next) {
var $active = this.$element.find('.item.active')
var $next = next || this.getItemForDirection(type, $active)
var isCycling = this.interval
var direction = type == 'next' ? 'left' : 'right'
var that = this
if ($next.hasClass('active')) return (this.sliding = false)
var relatedTarget = $next[0]
var slideEvent = $.Event('slide.bs.carousel', {
relatedTarget: relatedTarget,
direction: direction
})
this.$element.trigger(slideEvent)
if (slideEvent.isDefaultPrevented()) return
this.sliding = true
isCycling && this.pause()
if (this.$indicators.length) {
this.$indicators.find('.active').removeClass('active')
var $nextIndicator = $(this.$indicators.children()[this.getItemIndex($next)])
$nextIndicator && $nextIndicator.addClass('active')
}
var slidEvent = $.Event('slid.bs.carousel', {
relatedTarget: relatedTarget,
direction: direction
}) // yes, "slid"
if ($.support.transition && this.$element.hasClass('slide')) {
$next.addClass(type)
$next[0].offsetWidth // force reflow
$active.addClass(direction)
$next.addClass(direction)
$active.one('bsTransitionEnd', function() {
$next.removeClass([type, direction].join(' ')).addClass('active')
$active.removeClass(['active', direction].join(' '))
that.sliding = false
setTimeout(function() {
that.$element.trigger(slidEvent)
}, 0)
}).emulateTransitionEnd(Carousel.TRANSITION_DURATION)
} else {
$active.removeClass('active')
$next.addClass('active')
this.sliding = false
this.$element.trigger(slidEvent)
}
isCycling && this.cycle()
return this
}
// CAROUSEL PLUGIN DEFINITION
// ==========================
function Plugin(option) {
return this.each(function() {
var $this = $(this)
var data = $this.data('bs.carousel')
var options = $.extend({}, Carousel.DEFAULTS, $this.data(), typeof option == 'object' && option)
var action = typeof option == 'string' ? option : options.slide
if (!data) $this.data('bs.carousel', (data = new Carousel(this, options)))
if (typeof option == 'number') data.to(option)
else if (action) data[action]()
else if (options.interval) data.pause().cycle()
})
}
var old = $.fn.carousel
$.fn.carousel = Plugin
$.fn.carousel.Constructor = Carousel
// CAROUSEL NO CONFLICT
// ====================
$.fn.carousel.noConflict = function() {
$.fn.carousel = old
return this
}
// CAROUSEL DATA-API
// =================
var clickHandler = function(e) {
var href
var $this = $(this)
var $target = $($this.attr('data-target') || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) // strip for ie7
if (!$target.hasClass('carousel')) return
var options = $.extend({}, $target.data(), $this.data())
var slideIndex = $this.attr('data-slide-to')
if (slideIndex) options.interval = false
Plugin.call($target, options)
if (slideIndex) {
$target.data('bs.carousel').to(slideIndex)
}
e.preventDefault()
}
$(document).on('click.bs.carousel.data-api', '[data-slide]', clickHandler).on('click.bs.carousel.data-api', '[data-slide-to]', clickHandler)
$(window).on('load', function() {
$('[data-ride="carousel"]').each(function() {
var $carousel = $(this)
Plugin.call($carousel, $carousel.data())
})
})
}(jQuery);
/* ========================================================================
* Bootstrap: collapse.js v3.3.6
* http://getbootstrap.com/javascript/#collapse
* ========================================================================
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+ function($) {
'use strict';
// COLLAPSE PUBLIC CLASS DEFINITION
// ================================
var Collapse = function(element, options) {
this.$element = $(element)
this.options = $.extend({}, Collapse.DEFAULTS, options)
this.$trigger = $('[data-toggle="collapse"][href="#' + element.id + '"],' + '[data-toggle="collapse"][data-target="#' + element.id + '"]')
this.transitioning = null
if (this.options.parent) {
this.$parent = this.getParent()
} else {
this.addAriaAndCollapsedClass(this.$element, this.$trigger)
}
if (this.options.toggle) this.toggle()
}
Collapse.VERSION = '3.3.6'
Collapse.TRANSITION_DURATION = 350
Collapse.DEFAULTS = {
toggle: true
}
Collapse.prototype.dimension = function() {
var hasWidth = this.$element.hasClass('width')
return hasWidth ? 'width' : 'height'
}
Collapse.prototype.show = function() {
if (this.transitioning || this.$element.hasClass('in')) return
var activesData
var actives = this.$parent && this.$parent.children('.panel').children('.in, .collapsing')
if (actives && actives.length) {
activesData = actives.data('bs.collapse')
if (activesData && activesData.transitioning) return
}
var startEvent = $.Event('show.bs.collapse')
this.$element.trigger(startEvent)
if (startEvent.isDefaultPrevented()) return
if (actives && actives.length) {
Plugin.call(actives, 'hide')
activesData || actives.data('bs.collapse', null)
}
var dimension = this.dimension()
this.$element.removeClass('collapse').addClass('collapsing')[dimension](0).attr('aria-expanded', true)
this.$trigger.removeClass('collapsed').attr('aria-expanded', true)
this.transitioning = 1
var complete = function() {
this.$element.removeClass('collapsing').addClass('collapse in')[dimension]('')
this.transitioning = 0
this.$element.trigger('shown.bs.collapse')
}
if (!$.support.transition) return complete.call(this)
var scrollSize = $.camelCase(['scroll', dimension].join('-'))
this.$element.one('bsTransitionEnd', $.proxy(complete, this)).emulateTransitionEnd(Collapse.TRANSITION_DURATION)[dimension](this.$element[0][scrollSize])
}
Collapse.prototype.hide = function() {
if (this.transitioning || !this.$element.hasClass('in')) return
var startEvent = $.Event('hide.bs.collapse')
this.$element.trigger(startEvent)
if (startEvent.isDefaultPrevented()) return
var dimension = this.dimension()
this.$element[dimension](this.$element[dimension]())[0].offsetHeight
this.$element.addClass('collapsing').removeClass('collapse in').attr('aria-expanded', false)
this.$trigger.addClass('collapsed').attr('aria-expanded', false)
this.transitioning = 1
var complete = function() {
this.transitioning = 0
this.$element.removeClass('collapsing').addClass('collapse').trigger('hidden.bs.collapse')
}
if (!$.support.transition) return complete.call(this)
this.$element[dimension](0).one('bsTransitionEnd', $.proxy(complete, this)).emulateTransitionEnd(Collapse.TRANSITION_DURATION)
}
Collapse.prototype.toggle = function() {
this[this.$element.hasClass('in') ? 'hide' : 'show']()
}
Collapse.prototype.getParent = function() {
return $(this.options.parent).find('[data-toggle="collapse"][data-parent="' + this.options.parent + '"]').each($.proxy(function(i, element) {
var $element = $(element)
this.addAriaAndCollapsedClass(getTargetFromTrigger($element), $element)
}, this)).end()
}
Collapse.prototype.addAriaAndCollapsedClass = function($element, $trigger) {
var isOpen = $element.hasClass('in')
$element.attr('aria-expanded', isOpen)
$trigger.toggleClass('collapsed', !isOpen).attr('aria-expanded', isOpen)
}
function getTargetFromTrigger($trigger) {
var href
var target = $trigger.attr('data-target') || (href = $trigger.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '') // strip for ie7
return $(target)
}
// COLLAPSE PLUGIN DEFINITION
// ==========================
function Plugin(option) {
return this.each(function() {
var $this = $(this)
var data = $this.data('bs.collapse')
var options = $.extend({}, Collapse.DEFAULTS, $this.data(), typeof option == 'object' && option)
if (!data && options.toggle && /show|hide/.test(option)) options.toggle = false
if (!data) $this.data('bs.collapse', (data = new Collapse(this, options)))
if (typeof option == 'string') data[option]()
})
}
var old = $.fn.collapse
$.fn.collapse = Plugin
$.fn.collapse.Constructor = Collapse
// COLLAPSE NO CONFLICT
// ====================
$.fn.collapse.noConflict = function() {
$.fn.collapse = old
return this
}
// COLLAPSE DATA-API
// =================
$(document).on('click.bs.collapse.data-api', '[data-toggle="collapse"]', function(e) {
var $this = $(this)
if (!$this.attr('data-target')) e.preventDefault()
var $target = getTargetFromTrigger($this)
var data = $target.data('bs.collapse')
var option = data ? 'toggle' : $this.data()
Plugin.call($target, option)
})
}(jQuery);
/* ========================================================================
* Bootstrap: dropdown.js v3.3.6
* http://getbootstrap.com/javascript/#dropdowns
* ========================================================================
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+ function($) {
'use strict';
// DROPDOWN CLASS DEFINITION
// =========================
var backdrop = '.dropdown-backdrop'
var toggle = '[data-toggle="dropdown"]'
var Dropdown = function(element) {
$(element).on('click.bs.dropdown', this.toggle)
}
Dropdown.VERSION = '3.3.6'
function getParent($this) {
var selector = $this.attr('data-target')
if (!selector) {
selector = $this.attr('href')
selector = selector && /#[A-Za-z]/.test(selector) && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7
}
var $parent = selector && $(selector)
return $parent && $parent.length ? $parent : $this.parent()
}
function clearMenus(e) {
if (e && e.which === 3) return
$(backdrop).remove()
$(toggle).each(function() {
var $this = $(this)
var $parent = getParent($this)
var relatedTarget = {
relatedTarget: this
}
if (!$parent.hasClass('open')) return
if (e && e.type == 'click' && /input|textarea/i.test(e.target.tagName) && $.contains($parent[0], e.target)) return
$parent.trigger(e = $.Event('hide.bs.dropdown', relatedTarget))
if (e.isDefaultPrevented()) return
$this.attr('aria-expanded', 'false')
$parent.removeClass('open').trigger($.Event('hidden.bs.dropdown', relatedTarget))
})
}
Dropdown.prototype.toggle = function(e) {
var $this = $(this)
if ($this.is('.disabled, :disabled')) return
var $parent = getParent($this)
var isActive = $parent.hasClass('open')
clearMenus()
if (!isActive) {
if ('ontouchstart' in document.documentElement && !$parent.closest('.navbar-nav').length) {
// if mobile we use a backdrop because click events don't delegate
$(document.createElement('div')).addClass('dropdown-backdrop').insertAfter($(this)).on('click', clearMenus)
}
var relatedTarget = {
relatedTarget: this
}
$parent.trigger(e = $.Event('show.bs.dropdown', relatedTarget))
if (e.isDefaultPrevented()) return
$this.trigger('focus').attr('aria-expanded', 'true')
$parent.toggleClass('open').trigger($.Event('shown.bs.dropdown', relatedTarget))
}
return false
}
Dropdown.prototype.keydown = function(e) {
if (!/(38|40|27|32)/.test(e.which) || /input|textarea/i.test(e.target.tagName)) return
var $this = $(this)
e.preventDefault()
e.stopPropagation()
if ($this.is('.disabled, :disabled')) return
var $parent = getParent($this)
var isActive = $parent.hasClass('open')
if (!isActive && e.which != 27 || isActive && e.which == 27) {
if (e.which == 27) $parent.find(toggle).trigger('focus')
return $this.trigger('click')
}
var desc = ' li:not(.disabled):visible a'
var $items = $parent.find('.dropdown-menu' + desc)
if (!$items.length) return
var index = $items.index(e.target)
if (e.which == 38 && index > 0) index-- // up
if (e.which == 40 && index < $items.length - 1) index++ // down
if (!~index) index = 0
$items.eq(index).trigger('focus')
}
// DROPDOWN PLUGIN DEFINITION
// ==========================
function Plugin(option) {
return this.each(function() {
var $this = $(this)
var data = $this.data('bs.dropdown')
if (!data) $this.data('bs.dropdown', (data = new Dropdown(this)))
if (typeof option == 'string') data[option].call($this)
})
}
var old = $.fn.dropdown
$.fn.dropdown = Plugin
$.fn.dropdown.Constructor = Dropdown
// DROPDOWN NO CONFLICT
// ====================
$.fn.dropdown.noConflict = function() {
$.fn.dropdown = old
return this
}
// APPLY TO STANDARD DROPDOWN ELEMENTS
// ===================================
$(document).on('click.bs.dropdown.data-api', clearMenus).on('click.bs.dropdown.data-api', '.dropdown form', function(e) {
e.stopPropagation()
}).on('click.bs.dropdown.data-api', toggle, Dropdown.prototype.toggle).on('keydown.bs.dropdown.data-api', toggle, Dropdown.prototype.keydown).on('keydown.bs.dropdown.data-api', '.dropdown-menu', Dropdown.prototype.keydown)
}(jQuery);
/* ========================================================================
* Bootstrap: modal.js v3.3.6
* http://getbootstrap.com/javascript/#modals
* ========================================================================
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+ function($) {
'use strict';
// MODAL CLASS DEFINITION
// ======================
var Modal = function(element, options) {
this.options = options
this.$body = $(document.body)
this.$element = $(element)
this.$dialog = this.$element.find('.modal-dialog')
this.$backdrop = null
this.isShown = null
this.originalBodyPad = null
this.scrollbarWidth = 0
this.ignoreBackdropClick = false
if (this.options.remote) {
this.$element.find('.modal-content').load(this.options.remote, $.proxy(function() {
this.$element.trigger('loaded.bs.modal')
}, this))
}
}
Modal.VERSION = '3.3.6'
Modal.TRANSITION_DURATION = 300
Modal.BACKDROP_TRANSITION_DURATION = 150
Modal.DEFAULTS = {
backdrop: true,
keyboard: true,
show: true
}
Modal.prototype.toggle = function(_relatedTarget) {
return this.isShown ? this.hide() : this.show(_relatedTarget)
}
Modal.prototype.show = function(_relatedTarget) {
var that = this
var e = $.Event('show.bs.modal', {
relatedTarget: _relatedTarget
})
this.$element.trigger(e)
if (this.isShown || e.isDefaultPrevented()) return
this.isShown = true
this.checkScrollbar()
this.setScrollbar()
this.$body.addClass('modal-open')
this.escape()
this.resize()
this.$element.on('click.dismiss.bs.modal', '[data-dismiss="modal"]', $.proxy(this.hide, this))
this.$dialog.on('mousedown.dismiss.bs.modal', function() {
that.$element.one('mouseup.dismiss.bs.modal', function(e) {
if ($(e.target).is(that.$element)) that.ignoreBackdropClick = true
})
})
this.backdrop(function() {
var transition = $.support.transition && that.$element.hasClass('fade')
if (!that.$element.parent().length) {
that.$element.appendTo(that.$body) // don't move modals dom position
}
that.$element.show().scrollTop(0)
that.adjustDialog()
if (transition) {
that.$element[0].offsetWidth // force reflow
}
that.$element.addClass('in')
that.enforceFocus()
var e = $.Event('shown.bs.modal', {
relatedTarget: _relatedTarget
})
transition ? that.$dialog // wait for modal to slide in
.one('bsTransitionEnd', function() {
that.$element.trigger('focus').trigger(e)
}).emulateTransitionEnd(Modal.TRANSITION_DURATION) : that.$element.trigger('focus').trigger(e)
})
}
Modal.prototype.hide = function(e) {
if (e) e.preventDefault()
e = $.Event('hide.bs.modal')
this.$element.trigger(e)
if (!this.isShown || e.isDefaultPrevented()) return
this.isShown = false
this.escape()
this.resize()
$(document).off('focusin.bs.modal')
this.$element.removeClass('in').off('click.dismiss.bs.modal').off('mouseup.dismiss.bs.modal')
this.$dialog.off('mousedown.dismiss.bs.modal')
$.support.transition && this.$element.hasClass('fade') ? this.$element.one('bsTransitionEnd', $.proxy(this.hideModal, this)).emulateTransitionEnd(Modal.TRANSITION_DURATION) : this.hideModal()
}
Modal.prototype.enforceFocus = function() {
$(document).off('focusin.bs.modal') // guard against infinite focus loop
.on('focusin.bs.modal', $.proxy(function(e) {
if (this.$element[0] !== e.target && !this.$element.has(e.target).length) {
this.$element.trigger('focus')
}
}, this))
}
Modal.prototype.escape = function() {
if (this.isShown && this.options.keyboard) {
this.$element.on('keydown.dismiss.bs.modal', $.proxy(function(e) {
e.which == 27 && this.hide()
}, this))
} else if (!this.isShown) {
this.$element.off('keydown.dismiss.bs.modal')
}
}
Modal.prototype.resize = function() {
if (this.isShown) {
$(window).on('resize.bs.modal', $.proxy(this.handleUpdate, this))
} else {
$(window).off('resize.bs.modal')
}
}
Modal.prototype.hideModal = function() {
var that = this
this.$element.hide()
this.backdrop(function() {
that.$body.removeClass('modal-open')
that.resetAdjustments()
that.resetScrollbar()
that.$element.trigger('hidden.bs.modal')
})
}
Modal.prototype.removeBackdrop = function() {
this.$backdrop && this.$backdrop.remove()
this.$backdrop = null
}
Modal.prototype.backdrop = function(callback) {
var that = this
var animate = this.$element.hasClass('fade') ? 'fade' : ''
if (this.isShown && this.options.backdrop) {
var doAnimate = $.support.transition && animate
this.$backdrop = $(document.createElement('div')).addClass('modal-backdrop ' + animate).appendTo(this.$body)
this.$element.on('click.dismiss.bs.modal', $.proxy(function(e) {
if (this.ignoreBackdropClick) {
this.ignoreBackdropClick = false
return
}
if (e.target !== e.currentTarget) return
this.options.backdrop == 'static' ? this.$element[0].focus() : this.hide()
}, this))
if (doAnimate) this.$backdrop[0].offsetWidth // force reflow
this.$backdrop.addClass('in')
if (!callback) return
doAnimate ? this.$backdrop.one('bsTransitionEnd', callback).emulateTransitionEnd(Modal.BACKDROP_TRANSITION_DURATION) : callback()
} else if (!this.isShown && this.$backdrop) {
this.$backdrop.removeClass('in')
var callbackRemove = function() {
that.removeBackdrop()
callback && callback()
}
$.support.transition && this.$element.hasClass('fade') ? this.$backdrop.one('bsTransitionEnd', callbackRemove).emulateTransitionEnd(Modal.BACKDROP_TRANSITION_DURATION) : callbackRemove()
} else if (callback) {
callback()
}
}
// these following methods are used to handle overflowing modals
Modal.prototype.handleUpdate = function() {
this.adjustDialog()
}
Modal.prototype.adjustDialog = function() {
var modalIsOverflowing = this.$element[0].scrollHeight > document.documentElement.clientHeight
this.$element.css({
paddingLeft: !this.bodyIsOverflowing && modalIsOverflowing ? this.scrollbarWidth : '',
paddingRight: this.bodyIsOverflowing && !modalIsOverflowing ? this.scrollbarWidth : ''
})
}
Modal.prototype.resetAdjustments = function() {
this.$element.css({
paddingLeft: '',
paddingRight: ''
})
}
Modal.prototype.checkScrollbar = function() {
var fullWindowWidth = window.innerWidth
if (!fullWindowWidth) { // workaround for missing window.innerWidth in IE8
var documentElementRect = document.documentElement.getBoundingClientRect()
fullWindowWidth = documentElementRect.right - Math.abs(documentElementRect.left)
}
this.bodyIsOverflowing = document.body.clientWidth < fullWindowWidth
this.scrollbarWidth = this.measureScrollbar()
}
Modal.prototype.setScrollbar = function() {
var bodyPad = parseInt((this.$body.css('padding-right') || 0), 10)
this.originalBodyPad = document.body.style.paddingRight || ''
if (this.bodyIsOverflowing) this.$body.css('padding-right', bodyPad + this.scrollbarWidth)
}
Modal.prototype.resetScrollbar = function() {
this.$body.css('padding-right', this.originalBodyPad)
}
Modal.prototype.measureScrollbar = function() { // thx walsh
var scrollDiv = document.createElement('div')
scrollDiv.className = 'modal-scrollbar-measure'
this.$body.append(scrollDiv)
var scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth
this.$body[0].removeChild(scrollDiv)
return scrollbarWidth
}
// MODAL PLUGIN DEFINITION
// =======================
function Plugin(option, _relatedTarget) {
return this.each(function() {
var $this = $(this)
var data = $this.data('bs.modal')
var options = $.extend({}, Modal.DEFAULTS, $this.data(), typeof option == 'object' && option)
if (!data) $this.data('bs.modal', (data = new Modal(this, options)))
if (typeof option == 'string') data[option](_relatedTarget)
else if (options.show) data.show(_relatedTarget)
})
}
var old = $.fn.modal
$.fn.modal = Plugin
$.fn.modal.Constructor = Modal
// MODAL NO CONFLICT
// =================
$.fn.modal.noConflict = function() {
$.fn.modal = old
return this
}
// MODAL DATA-API
// ==============
$(document).on('click.bs.modal.data-api', '[data-toggle="modal"]', function(e) {
var $this = $(this)
var href = $this.attr('href')
var $target = $($this.attr('data-target') || (href && href.replace(/.*(?=#[^\s]+$)/, ''))) // strip for ie7
var option = $target.data('bs.modal') ? 'toggle' : $.extend({
remote: !/#/.test(href) && href
}, $target.data(), $this.data())
if ($this.is('a')) e.preventDefault()
$target.one('show.bs.modal', function(showEvent) {
if (showEvent.isDefaultPrevented()) return // only register focus restorer if modal will actually get shown
$target.one('hidden.bs.modal', function() {
$this.is(':visible') && $this.trigger('focus')
})
})
Plugin.call($target, option, this)
})
}(jQuery);
/* ========================================================================
* Bootstrap: tooltip.js v3.3.6
* http://getbootstrap.com/javascript/#tooltip
* Inspired by the original jQuery.tipsy by Jason Frame
* ========================================================================
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+ function($) {
'use strict';
// TOOLTIP PUBLIC CLASS DEFINITION
// ===============================
var Tooltip = function(element, options) {
this.type = null
this.options = null
this.enabled = null
this.timeout = null
this.hoverState = null
this.$element = null
this.inState = null
this.init('tooltip', element, options)
}
Tooltip.VERSION = '3.3.6'
Tooltip.TRANSITION_DURATION = 150
Tooltip.DEFAULTS = {
animation: true,
placement: 'top',
selector: false,
template: '<div class="tooltip" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>',
trigger: 'hover focus',
title: '',
delay: 0,
html: false,
container: false,
viewport: {
selector: 'body',
padding: 0
}
}
Tooltip.prototype.init = function(type, element, options) {
this.enabled = true
this.type = type
this.$element = $(element)
this.options = this.getOptions(options)
this.$viewport = this.options.viewport && $($.isFunction(this.options.viewport) ? this.options.viewport.call(this, this.$element) : (this.options.viewport.selector || this.options.viewport))
this.inState = {
click: false,
hover: false,
focus: false
}
if (this.$element[0] instanceof document.constructor && !this.options.selector) {
throw new Error('`selector` option must be specified when initializing ' + this.type + ' on the window.document object!')
}
var triggers = this.options.trigger.split(' ')
for (var i = triggers.length; i--;) {
var trigger = triggers[i]
if (trigger == 'click') {
this.$element.on('click.' + this.type, this.options.selector, $.proxy(this.toggle, this))
} else if (trigger != 'manual') {
var eventIn = trigger == 'hover' ? 'mouseenter' : 'focusin'
var eventOut = trigger == 'hover' ? 'mouseleave' : 'focusout'
this.$element.on(eventIn + '.' + this.type, this.options.selector, $.proxy(this.enter, this))
this.$element.on(eventOut + '.' + this.type, this.options.selector, $.proxy(this.leave, this))
}
}
this.options.selector ? (this._options = $.extend({}, this.options, {
trigger: 'manual',
selector: ''
})) : this.fixTitle()
}
Tooltip.prototype.getDefaults = function() {
return Tooltip.DEFAULTS
}
Tooltip.prototype.getOptions = function(options) {
options = $.extend({}, this.getDefaults(), this.$element.data(), options)
if (options.delay && typeof options.delay == 'number') {
options.delay = {
show: options.delay,
hide: options.delay
}
}
return options
}
Tooltip.prototype.getDelegateOptions = function() {
var options = {}
var defaults = this.getDefaults()
this._options && $.each(this._options, function(key, value) {
if (defaults[key] != value) options[key] = value
})
return options
}
Tooltip.prototype.enter = function(obj) {
var self = obj instanceof this.constructor ? obj : $(obj.currentTarget).data('bs.' + this.type)
if (!self) {
self = new this.constructor(obj.currentTarget, this.getDelegateOptions())
$(obj.currentTarget).data('bs.' + this.type, self)
}
if (obj instanceof $.Event) {
self.inState[obj.type == 'focusin' ? 'focus' : 'hover'] = true
}
if (self.tip().hasClass('in') || self.hoverState == 'in') {
self.hoverState = 'in'
return
}
clearTimeout(self.timeout)
self.hoverState = 'in'
if (!self.options.delay || !self.options.delay.show) return self.show()
self.timeout = setTimeout(function() {
if (self.hoverState == 'in') self.show()
}, self.options.delay.show)
}
Tooltip.prototype.isInStateTrue = function() {
for (var key in this.inState) {
if (this.inState[key]) return true
}
return false
}
Tooltip.prototype.leave = function(obj) {
var self = obj instanceof this.constructor ? obj : $(obj.currentTarget).data('bs.' + this.type)
if (!self) {
self = new this.constructor(obj.currentTarget, this.getDelegateOptions())
$(obj.currentTarget).data('bs.' + this.type, self)
}
if (obj instanceof $.Event) {
self.inState[obj.type == 'focusout' ? 'focus' : 'hover'] = false
}
if (self.isInStateTrue()) return
clearTimeout(self.timeout)
self.hoverState = 'out'
if (!self.options.delay || !self.options.delay.hide) return self.hide()
self.timeout = setTimeout(function() {
if (self.hoverState == 'out') self.hide()
}, self.options.delay.hide)
}
Tooltip.prototype.show = function() {
var e = $.Event('show.bs.' + this.type)
if (this.hasContent() && this.enabled) {
this.$element.trigger(e)
var inDom = $.contains(this.$element[0].ownerDocument.documentElement, this.$element[0])
if (e.isDefaultPrevented() || !inDom) return
var that = this
var $tip = this.tip()
var tipId = this.getUID(this.type)
this.setContent()
$tip.attr('id', tipId)
this.$element.attr('aria-describedby', tipId)
if (this.options.animation) $tip.addClass('fade')
var placement = typeof this.options.placement == 'function' ? this.options.placement.call(this, $tip[0], this.$element[0]) : this.options.placement
var autoToken = /\s?auto?\s?/i
var autoPlace = autoToken.test(placement)
if (autoPlace) placement = placement.replace(autoToken, '') || 'top'
$tip.detach().css({
top: 0,
left: 0,
display: 'block'
}).addClass(placement).data('bs.' + this.type, this)
this.options.container ? $tip.appendTo(this.options.container) : $tip.insertAfter(this.$element)
this.$element.trigger('inserted.bs.' + this.type)
var pos = this.getPosition()
var actualWidth = $tip[0].offsetWidth
var actualHeight = $tip[0].offsetHeight
if (autoPlace) {
var orgPlacement = placement
var viewportDim = this.getPosition(this.$viewport)
placement = placement == 'bottom' && pos.bottom + actualHeight > viewportDim.bottom ? 'top' : placement == 'top' && pos.top - actualHeight < viewportDim.top ? 'bottom' : placement == 'right' && pos.right + actualWidth > viewportDim.width ? 'left' : placement == 'left' && pos.left - actualWidth < viewportDim.left ? 'right' : placement
$tip.removeClass(orgPlacement).addClass(placement)
}
var calculatedOffset = this.getCalculatedOffset(placement, pos, actualWidth, actualHeight)
this.applyPlacement(calculatedOffset, placement)
var complete = function() {
var prevHoverState = that.hoverState
that.$element.trigger('shown.bs.' + that.type)
that.hoverState = null
if (prevHoverState == 'out') that.leave(that)
}
$.support.transition && this.$tip.hasClass('fade') ? $tip.one('bsTransitionEnd', complete).emulateTransitionEnd(Tooltip.TRANSITION_DURATION) : complete()
}
}
Tooltip.prototype.applyPlacement = function(offset, placement) {
var $tip = this.tip()
var width = $tip[0].offsetWidth
var height = $tip[0].offsetHeight
// manually read margins because getBoundingClientRect includes difference
var marginTop = parseInt($tip.css('margin-top'), 10)
var marginLeft = parseInt($tip.css('margin-left'), 10)
// we must check for NaN for ie 8/9
if (isNaN(marginTop)) marginTop = 0
if (isNaN(marginLeft)) marginLeft = 0
offset.top += marginTop
offset.left += marginLeft
// $.fn.offset doesn't round pixel values
// so we use setOffset directly with our own function B-0
$.offset.setOffset($tip[0], $.extend({
using: function(props) {
$tip.css({
top: Math.round(props.top),
left: Math.round(props.left)
})
}
}, offset), 0)
$tip.addClass('in')
// check to see if placing tip in new offset caused the tip to resize itself
var actualWidth = $tip[0].offsetWidth
var actualHeight = $tip[0].offsetHeight
if (placement == 'top' && actualHeight != height) {
offset.top = offset.top + height - actualHeight
}
var delta = this.getViewportAdjustedDelta(placement, offset, actualWidth, actualHeight)
if (delta.left) offset.left += delta.left
else offset.top += delta.top
var isVertical = /top|bottom/.test(placement)
var arrowDelta = isVertical ? delta.left * 2 - width + actualWidth : delta.top * 2 - height + actualHeight
var arrowOffsetPosition = isVertical ? 'offsetWidth' : 'offsetHeight'
$tip.offset(offset)
this.replaceArrow(arrowDelta, $tip[0][arrowOffsetPosition], isVertical)
}
Tooltip.prototype.replaceArrow = function(delta, dimension, isVertical) {
this.arrow().css(isVertical ? 'left' : 'top', 50 * (1 - delta / dimension) + '%').css(isVertical ? 'top' : 'left', '')
}
Tooltip.prototype.setContent = function() {
var $tip = this.tip()
var title = this.getTitle()
$tip.find('.tooltip-inner')[this.options.html ? 'html' : 'text'](title)
$tip.removeClass('fade in top bottom left right')
}
Tooltip.prototype.hide = function(callback) {
var that = this
var $tip = $(this.$tip)
var e = $.Event('hide.bs.' + this.type)
function complete() {
if (that.hoverState != 'in') $tip.detach()
that.$element.removeAttr('aria-describedby').trigger('hidden.bs.' + that.type)
callback && callback()
}
this.$element.trigger(e)
if (e.isDefaultPrevented()) return
$tip.removeClass('in')
$.support.transition && $tip.hasClass('fade') ? $tip.one('bsTransitionEnd', complete).emulateTransitionEnd(Tooltip.TRANSITION_DURATION) : complete()
this.hoverState = null
return this
}
Tooltip.prototype.fixTitle = function() {
var $e = this.$element
if ($e.attr('title') || typeof $e.attr('data-original-title') != 'string') {
$e.attr('data-original-title', $e.attr('title') || '').attr('title', '')
}
}
Tooltip.prototype.hasContent = function() {
return this.getTitle()
}
Tooltip.prototype.getPosition = function($element) {
$element = $element || this.$element
var el = $element[0]
var isBody = el.tagName == 'BODY'
var elRect = el.getBoundingClientRect()
if (elRect.width == null) {
// width and height are missing in IE8, so compute them manually; see https://github.com/twbs/bootstrap/issues/14093
elRect = $.extend({}, elRect, {
width: elRect.right - elRect.left,
height: elRect.bottom - elRect.top
})
}
var elOffset = isBody ? {
top: 0,
left: 0
} : $element.offset()
var scroll = {
scroll: isBody ? document.documentElement.scrollTop || document.body.scrollTop : $element.scrollTop()
}
var outerDims = isBody ? {
width: $(window).width(),
height: $(window).height()
} : null
return $.extend({}, elRect, scroll, outerDims, elOffset)
}
Tooltip.prototype.getCalculatedOffset = function(placement, pos, actualWidth, actualHeight) {
return placement == 'bottom' ? {
top: pos.top + pos.height,
left: pos.left + pos.width / 2 - actualWidth / 2
} : placement == 'top' ? {
top: pos.top - actualHeight,
left: pos.left + pos.width / 2 - actualWidth / 2
} : placement == 'left' ? {
top: pos.top + pos.height / 2 - actualHeight / 2,
left: pos.left - actualWidth
} :
/* placement == 'right' */
{
top: pos.top + pos.height / 2 - actualHeight / 2,
left: pos.left + pos.width
}
}
Tooltip.prototype.getViewportAdjustedDelta = function(placement, pos, actualWidth, actualHeight) {
var delta = {
top: 0,
left: 0
}
if (!this.$viewport) return delta
var viewportPadding = this.options.viewport && this.options.viewport.padding || 0
var viewportDimensions = this.getPosition(this.$viewport)
if (/right|left/.test(placement)) {
var topEdgeOffset = pos.top - viewportPadding - viewportDimensions.scroll
var bottomEdgeOffset = pos.top + viewportPadding - viewportDimensions.scroll + actualHeight
if (topEdgeOffset < viewportDimensions.top) { // top overflow
delta.top = viewportDimensions.top - topEdgeOffset
} else if (bottomEdgeOffset > viewportDimensions.top + viewportDimensions.height) { // bottom overflow
delta.top = viewportDimensions.top + viewportDimensions.height - bottomEdgeOffset
}
} else {
var leftEdgeOffset = pos.left - viewportPadding
var rightEdgeOffset = pos.left + viewportPadding + actualWidth
if (leftEdgeOffset < viewportDimensions.left) { // left overflow
delta.left = viewportDimensions.left - leftEdgeOffset
} else if (rightEdgeOffset > viewportDimensions.right) { // right overflow
delta.left = viewportDimensions.left + viewportDimensions.width - rightEdgeOffset
}
}
return delta
}
Tooltip.prototype.getTitle = function() {
var title
var $e = this.$element
var o = this.options
title = $e.attr('data-original-title') || (typeof o.title == 'function' ? o.title.call($e[0]) : o.title)
return title
}
Tooltip.prototype.getUID = function(prefix) {
do prefix += ~~(Math.random() * 1000000)
while (document.getElementById(prefix))
return prefix
}
Tooltip.prototype.tip = function() {
if (!this.$tip) {
this.$tip = $(this.options.template)
if (this.$tip.length != 1) {
throw new Error(this.type + ' `template` option must consist of exactly 1 top-level element!')
}
}
return this.$tip
}
Tooltip.prototype.arrow = function() {
return (this.$arrow = this.$arrow || this.tip().find('.tooltip-arrow'))
}
Tooltip.prototype.enable = function() {
this.enabled = true
}
Tooltip.prototype.disable = function() {
this.enabled = false
}
Tooltip.prototype.toggleEnabled = function() {
this.enabled = !this.enabled
}
Tooltip.prototype.toggle = function(e) {
var self = this
if (e) {
self = $(e.currentTarget).data('bs.' + this.type)
if (!self) {
self = new this.constructor(e.currentTarget, this.getDelegateOptions())
$(e.currentTarget).data('bs.' + this.type, self)
}
}
if (e) {
self.inState.click = !self.inState.click
if (self.isInStateTrue()) self.enter(self)
else self.leave(self)
} else {
self.tip().hasClass('in') ? self.leave(self) : self.enter(self)
}
}
Tooltip.prototype.destroy = function() {
var that = this
clearTimeout(this.timeout)
this.hide(function() {
that.$element.off('.' + that.type).removeData('bs.' + that.type)
if (that.$tip) {
that.$tip.detach()
}
that.$tip = null
that.$arrow = null
that.$viewport = null
})
}
// TOOLTIP PLUGIN DEFINITION
// =========================
function Plugin(option) {
return this.each(function() {
var $this = $(this)
var data = $this.data('bs.tooltip')
var options = typeof option == 'object' && option
if (!data && /destroy|hide/.test(option)) return
if (!data) $this.data('bs.tooltip', (data = new Tooltip(this, options)))
if (typeof option == 'string') data[option]()
})
}
var old = $.fn.tooltip
$.fn.tooltip = Plugin
$.fn.tooltip.Constructor = Tooltip
// TOOLTIP NO CONFLICT
// ===================
$.fn.tooltip.noConflict = function() {
$.fn.tooltip = old
return this
}
}(jQuery);
/* ========================================================================
* Bootstrap: popover.js v3.3.6
* http://getbootstrap.com/javascript/#popovers
* ========================================================================
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+ function($) {
'use strict';
// POPOVER PUBLIC CLASS DEFINITION
// ===============================
var Popover = function(element, options) {
this.init('popover', element, options)
}
if (!$.fn.tooltip) throw new Error('Popover requires tooltip.js')
Popover.VERSION = '3.3.6'
Popover.DEFAULTS = $.extend({}, $.fn.tooltip.Constructor.DEFAULTS, {
placement: 'right',
trigger: 'click',
content: '',
template: '<div class="popover" role="tooltip"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>'
})
// NOTE: POPOVER EXTENDS tooltip.js
// ================================
Popover.prototype = $.extend({}, $.fn.tooltip.Constructor.prototype)
Popover.prototype.constructor = Popover
Popover.prototype.getDefaults = function() {
return Popover.DEFAULTS
}
Popover.prototype.setContent = function() {
var $tip = this.tip()
var title = this.getTitle()
var content = this.getContent()
$tip.find('.popover-title')[this.options.html ? 'html' : 'text'](title)
$tip.find('.popover-content').children().detach().end()[ // we use append for html objects to maintain js events
this.options.html ? (typeof content == 'string' ? 'html' : 'append') : 'text'](content)
$tip.removeClass('fade top bottom left right in')
// IE8 doesn't accept hiding via the `:empty` pseudo selector, we have to do
// this manually by checking the contents.
if (!$tip.find('.popover-title').html()) $tip.find('.popover-title').hide()
}
Popover.prototype.hasContent = function() {
return this.getTitle() || this.getContent()
}
Popover.prototype.getContent = function() {
var $e = this.$element
var o = this.options
return $e.attr('data-content') || (typeof o.content == 'function' ? o.content.call($e[0]) : o.content)
}
Popover.prototype.arrow = function() {
return (this.$arrow = this.$arrow || this.tip().find('.arrow'))
}
// POPOVER PLUGIN DEFINITION
// =========================
function Plugin(option) {
return this.each(function() {
var $this = $(this)
var data = $this.data('bs.popover')
var options = typeof option == 'object' && option
if (!data && /destroy|hide/.test(option)) return
if (!data) $this.data('bs.popover', (data = new Popover(this, options)))
if (typeof option == 'string') data[option]()
})
}
var old = $.fn.popover
$.fn.popover = Plugin
$.fn.popover.Constructor = Popover
// POPOVER NO CONFLICT
// ===================
$.fn.popover.noConflict = function() {
$.fn.popover = old
return this
}
}(jQuery);
/* ========================================================================
* Bootstrap: scrollspy.js v3.3.6
* http://getbootstrap.com/javascript/#scrollspy
* ========================================================================
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+ function($) {
'use strict';
// SCROLLSPY CLASS DEFINITION
// ==========================
function ScrollSpy(element, options) {
this.$body = $(document.body)
this.$scrollElement = $(element).is(document.body) ? $(window) : $(element)
this.options = $.extend({}, ScrollSpy.DEFAULTS, options)
this.selector = (this.options.target || '') + ' .nav li > a'
this.offsets = []
this.targets = []
this.activeTarget = null
this.scrollHeight = 0
this.$scrollElement.on('scroll.bs.scrollspy', $.proxy(this.process, this))
this.refresh()
this.process()
}
ScrollSpy.VERSION = '3.3.6'
ScrollSpy.DEFAULTS = {
offset: 10
}
ScrollSpy.prototype.getScrollHeight = function() {
return this.$scrollElement[0].scrollHeight || Math.max(this.$body[0].scrollHeight, document.documentElement.scrollHeight)
}
ScrollSpy.prototype.refresh = function() {
var that = this
var offsetMethod = 'offset'
var offsetBase = 0
this.offsets = []
this.targets = []
this.scrollHeight = this.getScrollHeight()
if (!$.isWindow(this.$scrollElement[0])) {
offsetMethod = 'position'
offsetBase = this.$scrollElement.scrollTop()
}
this.$body.find(this.selector).map(function() {
var $el = $(this)
var href = $el.data('target') || $el.attr('href')
var $href = /^#./.test(href) && $(href)
return ($href && $href.length && $href.is(':visible') && [
[$href[offsetMethod]().top + offsetBase, href]
]) || null
}).sort(function(a, b) {
return a[0] - b[0]
}).each(function() {
that.offsets.push(this[0])
that.targets.push(this[1])
})
}
ScrollSpy.prototype.process = function() {
var scrollTop = this.$scrollElement.scrollTop() + this.options.offset
var scrollHeight = this.getScrollHeight()
var maxScroll = this.options.offset + scrollHeight - this.$scrollElement.height()
var offsets = this.offsets
var targets = this.targets
var activeTarget = this.activeTarget
var i
if (this.scrollHeight != scrollHeight) {
this.refresh()
}
if (scrollTop >= maxScroll) {
return activeTarget != (i = targets[targets.length - 1]) && this.activate(i)
}
if (activeTarget && scrollTop < offsets[0]) {
this.activeTarget = null
return this.clear()
}
for (i = offsets.length; i--;) {
activeTarget != targets[i] && scrollTop >= offsets[i] && (offsets[i + 1] === undefined || scrollTop < offsets[i + 1]) && this.activate(targets[i])
}
}
ScrollSpy.prototype.activate = function(target) {
this.activeTarget = target
this.clear()
var selector = this.selector + '[data-target="' + target + '"],' + this.selector + '[href="' + target + '"]'
var active = $(selector).parents('li').addClass('active')
if (active.parent('.dropdown-menu').length) {
active = active.closest('li.dropdown').addClass('active')
}
active.trigger('activate.bs.scrollspy')
}
ScrollSpy.prototype.clear = function() {
$(this.selector).parentsUntil(this.options.target, '.active').removeClass('active')
}
// SCROLLSPY PLUGIN DEFINITION
// ===========================
function Plugin(option) {
return this.each(function() {
var $this = $(this)
var data = $this.data('bs.scrollspy')
var options = typeof option == 'object' && option
if (!data) $this.data('bs.scrollspy', (data = new ScrollSpy(this, options)))
if (typeof option == 'string') data[option]()
})
}
var old = $.fn.scrollspy
$.fn.scrollspy = Plugin
$.fn.scrollspy.Constructor = ScrollSpy
// SCROLLSPY NO CONFLICT
// =====================
$.fn.scrollspy.noConflict = function() {
$.fn.scrollspy = old
return this
}
// SCROLLSPY DATA-API
// ==================
$(window).on('load.bs.scrollspy.data-api', function() {
$('[data-spy="scroll"]').each(function() {
var $spy = $(this)
Plugin.call($spy, $spy.data())
})
})
}(jQuery);
/* ========================================================================
* Bootstrap: tab.js v3.3.6
* http://getbootstrap.com/javascript/#tabs
* ========================================================================
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+ function($) {
'use strict';
// TAB CLASS DEFINITION
// ====================
var Tab = function(element) {
// jscs:disable requireDollarBeforejQueryAssignment
this.element = $(element)
// jscs:enable requireDollarBeforejQueryAssignment
}
Tab.VERSION = '3.3.6'
Tab.TRANSITION_DURATION = 150
Tab.prototype.show = function() {
var $this = this.element
var $ul = $this.closest('ul:not(.dropdown-menu)')
var selector = $this.data('target')
if (!selector) {
selector = $this.attr('href')
selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7
}
if ($this.parent('li').hasClass('active')) return
var $previous = $ul.find('.active:last a')
var hideEvent = $.Event('hide.bs.tab', {
relatedTarget: $this[0]
})
var showEvent = $.Event('show.bs.tab', {
relatedTarget: $previous[0]
})
$previous.trigger(hideEvent)
$this.trigger(showEvent)
if (showEvent.isDefaultPrevented() || hideEvent.isDefaultPrevented()) return
var $target = $(selector)
this.activate($this.closest('li'), $ul)
this.activate($target, $target.parent(), function() {
$previous.trigger({
type: 'hidden.bs.tab',
relatedTarget: $this[0]
})
$this.trigger({
type: 'shown.bs.tab',
relatedTarget: $previous[0]
})
})
}
Tab.prototype.activate = function(element, container, callback) {
var $active = container.find('> .active')
var transition = callback && $.support.transition && ($active.length && $active.hasClass('fade') || !!container.find('> .fade').length)
function next() {
$active.removeClass('active').find('> .dropdown-menu > .active').removeClass('active').end().find('[data-toggle="tab"]').attr('aria-expanded', false)
element.addClass('active').find('[data-toggle="tab"]').attr('aria-expanded', true)
if (transition) {
element[0].offsetWidth // reflow for transition
element.addClass('in')
} else {
element.removeClass('fade')
}
if (element.parent('.dropdown-menu').length) {
element.closest('li.dropdown').addClass('active').end().find('[data-toggle="tab"]').attr('aria-expanded', true)
}
callback && callback()
}
$active.length && transition ? $active.one('bsTransitionEnd', next).emulateTransitionEnd(Tab.TRANSITION_DURATION) : next()
$active.removeClass('in')
}
// TAB PLUGIN DEFINITION
// =====================
function Plugin(option) {
return this.each(function() {
var $this = $(this)
var data = $this.data('bs.tab')
if (!data) $this.data('bs.tab', (data = new Tab(this)))
if (typeof option == 'string') data[option]()
})
}
var old = $.fn.tab
$.fn.tab = Plugin
$.fn.tab.Constructor = Tab
// TAB NO CONFLICT
// ===============
$.fn.tab.noConflict = function() {
$.fn.tab = old
return this
}
// TAB DATA-API
// ============
var clickHandler = function(e) {
e.preventDefault()
Plugin.call($(this), 'show')
}
$(document).on('click.bs.tab.data-api', '[data-toggle="tab"]', clickHandler).on('click.bs.tab.data-api', '[data-toggle="pill"]', clickHandler)
}(jQuery);
/* ========================================================================
* Bootstrap: affix.js v3.3.6
* http://getbootstrap.com/javascript/#affix
* ========================================================================
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+ function($) {
'use strict';
// AFFIX CLASS DEFINITION
// ======================
var Affix = function(element, options) {
this.options = $.extend({}, Affix.DEFAULTS, options)
this.$target = $(this.options.target).on('scroll.bs.affix.data-api', $.proxy(this.checkPosition, this)).on('click.bs.affix.data-api', $.proxy(this.checkPositionWithEventLoop, this))
this.$element = $(element)
this.affixed = null
this.unpin = null
this.pinnedOffset = null
this.checkPosition()
}
Affix.VERSION = '3.3.6'
Affix.RESET = 'affix affix-top affix-bottom'
Affix.DEFAULTS = {
offset: 0,
target: window
}
Affix.prototype.getState = function(scrollHeight, height, offsetTop, offsetBottom) {
var scrollTop = this.$target.scrollTop()
var position = this.$element.offset()
var targetHeight = this.$target.height()
if (offsetTop != null && this.affixed == 'top') return scrollTop < offsetTop ? 'top' : false
if (this.affixed == 'bottom') {
if (offsetTop != null) return (scrollTop + this.unpin <= position.top) ? false : 'bottom'
return (scrollTop + targetHeight <= scrollHeight - offsetBottom) ? false : 'bottom'
}
var initializing = this.affixed == null
var colliderTop = initializing ? scrollTop : position.top
var colliderHeight = initializing ? targetHeight : height
if (offsetTop != null && scrollTop <= offsetTop) return 'top'
if (offsetBottom != null && (colliderTop + colliderHeight >= scrollHeight - offsetBottom)) return 'bottom'
return false
}
Affix.prototype.getPinnedOffset = function() {
if (this.pinnedOffset) return this.pinnedOffset
this.$element.removeClass(Affix.RESET).addClass('affix')
var scrollTop = this.$target.scrollTop()
var position = this.$element.offset()
return (this.pinnedOffset = position.top - scrollTop)
}
Affix.prototype.checkPositionWithEventLoop = function() {
setTimeout($.proxy(this.checkPosition, this), 1)
}
Affix.prototype.checkPosition = function() {
if (!this.$element.is(':visible')) return
var height = this.$element.height()
var offset = this.options.offset
var offsetTop = offset.top
var offsetBottom = offset.bottom
var scrollHeight = Math.max($(document).height(), $(document.body).height())
if (typeof offset != 'object') offsetBottom = offsetTop = offset
if (typeof offsetTop == 'function') offsetTop = offset.top(this.$element)
if (typeof offsetBottom == 'function') offsetBottom = offset.bottom(this.$element)
var affix = this.getState(scrollHeight, height, offsetTop, offsetBottom)
if (this.affixed != affix) {
if (this.unpin != null) this.$element.css('top', '')
var affixType = 'affix' + (affix ? '-' + affix : '')
var e = $.Event(affixType + '.bs.affix')
this.$element.trigger(e)
if (e.isDefaultPrevented()) return
this.affixed = affix
this.unpin = affix == 'bottom' ? this.getPinnedOffset() : null
this.$element.removeClass(Affix.RESET).addClass(affixType).trigger(affixType.replace('affix', 'affixed') + '.bs.affix')
}
if (affix == 'bottom') {
this.$element.offset({
top: scrollHeight - height - offsetBottom
})
}
}
// AFFIX PLUGIN DEFINITION
// =======================
function Plugin(option) {
return this.each(function() {
var $this = $(this)
var data = $this.data('bs.affix')
var options = typeof option == 'object' && option
if (!data) $this.data('bs.affix', (data = new Affix(this, options)))
if (typeof option == 'string') data[option]()
})
}
var old = $.fn.affix
$.fn.affix = Plugin
$.fn.affix.Constructor = Affix
// AFFIX NO CONFLICT
// =================
$.fn.affix.noConflict = function() {
$.fn.affix = old
return this
}
// AFFIX DATA-API
// ==============
$(window).on('load', function() {
$('[data-spy="affix"]').each(function() {
var $spy = $(this)
var data = $spy.data()
data.offset = data.offset || {}
if (data.offsetBottom != null) data.offset.bottom = data.offsetBottom
if (data.offsetTop != null) data.offset.top = data.offsetTop
Plugin.call($spy, data)
})
})
}(jQuery); | ApolloZhu/Biology-Final-Project | js/bootstrap.js | JavaScript | mit | 74,094 |
function whoisIpUtils() {
let ipDictionary = {};
this.getIpInfo = (ip, cb) => {
if (ipDictionary[ip])
return cb(ipDictionary[ip]);
GM.xmlHttpRequest({
method: "GET",
url: `http://ipinfo.io/${ip}/json`,
onload: function (res) {
var resObj = JSON.parse(res.responseText);
if (res.status === 200 || res.status === 304) {
if (/^AS[0-9]+ /.test(resObj.org)) {
resObj.org = resObj.org.replace(/^AS[0-9]+ /, '');
}
if (SET.ipInfoDefaultOrg != 'ipinfo.io') {
getIpWhois(ip, function (whoisRes) {
if (!whoisRes.success || whoisRes.raw) {
ipDictionary[ip] = resObj;
cb(resObj);
return;
}
var koreanISP = null,
koreanUser = null;
if (whoisRes.result.korean && whoisRes.result.korean.ISP && whoisRes.result.korean.ISP.netinfo && whoisRes.result.korean.ISP.netinfo.orgName) {
koreanISP = whoisRes.result.korean.ISP.netinfo.orgName;
} else if (whoisRes.result.korean && whoisRes.result.korean.user && whoisRes.result.korean.user.netinfo && whoisRes.result.korean.user.netinfo.orgName) {
koreanUser = whoisRes.result.korean.user.netinfo.orgName;
}
if (SET.ipInfoDefaultOrg === 'KISAuser' && koreanUser !== null) {
resObj.org = koreanUser;
} else if (SET.ipInfoDefaultOrg === 'KISAISP' && koreanISP !== null) {
resObj.org = koreanISP;
} else if (SET.ipInfoDefaultOrg === 'KISAuserOrISP' && (koreanUser !== null || koreanISP !== null)) {
resObj.org = koreanUser !== null ? koreanUser : koreanISP;
}
ipDictionary[ip] = resObj;
cb(resObj);
return;
});
} else {
ipDictionary[ip] = resObj;
cb(resObj);
}
} else {
cb(null);
}
}
});
}
let whoisDictionary = {};
this.getIpWhois = (ip, cb) => {
if (whoisDictionary[ip])
return cb(whoisDictionary[ip]);
GM.xmlHttpRequest({
method: "GET",
url: `http://namufix.wikimasonry.org/whois/ip/${ip}`,
onload: function (res) {
var resObj = JSON.parse(res.responseText);
whoisDictionary[ip] = resObj;
cb(resObj);
}
});
}
let vpngateCache = [],
vpngateCrawlledAt = -1;
this.getVPNGateIPList = () => {
return new Promise((resolve, reject) => {
GM.xmlHttpRequest({
method: "GET",
url: "https://namufix.wikimasonry.org/vpngate/list",
onload: function (res) {
let resObj = JSON.parse(res.responseText);
if (resObj.success)
resolve(resObj.result);
else
reject(resObj.message);
}
});
});
};
this.whoisPopup = (ip) => {
if (ip === null || ip === "")
return alert('ip주소를 입력해주세요');
var win = TooSimplePopup();
win.title('IP WHOIS 조회');
win.button('다른 IP 조회', function () {
var newip = prompt('IP 주소를 입력하세요.');
win.close();
whoisPopup(newip);
})
win.button('닫기', win.close);
win.content(function (container) {
container.innerHTML = '조회중입니다. 잠시만 기다려주세요...';
getIpWhois(ip, function (result) {
if (result.success && !result.raw) {
var whoisObj = result.result;
var currentView = 'table';
container.innerHTML = '<p>NamuFix 서버를 통해 KISA WHOIS를 조회했습니다. 결과는 다음과 같습니다.(<a href="#" class="switchViewType">JSON 형식으로 보기</a>)</p><div class="whois-content"><table></table></div>';
var resultContainer = container.querySelector('.whois-content');
var switchViewLink = container.querySelector('a.switchViewType');
function useTableView() {
function writeSubInfoTable(subInfoObj, caption) {
var table = document.createElement('table');
table.className = "whois";
table.innerHTML += '<caption>' + encodeHTMLComponent(caption) + '</caption>';
table.innerHTML += '<thead><tr><th>이름</th><th>내용</th></tr></thead>';
var tableHtml = '<tbody>';
var koreanContactNames = {
techContact: '네트워크 담당자 정보',
adminContact: 'IP주소 관리자 정보',
abuseContact: '네트워크 abuse 담당자 정보'
};
var koreanNetInfoNames = {
// 주소범위(range), 프리픽스(prefix), 네트워크이름(servName), 기관명(orgname), 주소(addr), 우편번호(zipCode), 할당내역 등록일(regDate) 필드 포함
addr: '주소',
netType: '네트워크 구분',
orgName: '기관명',
orgID: '기관 ID',
prefix: 'IP prefix',
range: 'IP 범위',
regDate: '등록일',
servName: '네트워크 이름',
zipCode: '우편번호'
};
for (var i in subInfoObj) {
if (i == 'techContact' || i == 'adminContact' || i == 'abuseContact') {
tableHtml += '<tr><td colspan="2" class="whois-subheader">' + koreanContactNames[i] + '</td></tr>';
if (subInfoObj[i].name)
tableHtml += '<tr><td>이름</td><td>' + encodeHTMLComponent(subInfoObj[i].name) + '</td></tr>';
if (subInfoObj[i].phone)
tableHtml += '<tr><td>전화번호</td><td>' + encodeHTMLComponent(subInfoObj[i].phone) + '</td></tr>';
if (subInfoObj[i].email)
tableHtml += '<tr><td>연락처</td><td>' + encodeHTMLComponent(subInfoObj[i].email) + '</td></tr>';
} else if (i == 'netinfo') {
// KISA 씨발놈들.... API 설명서에 다 적어두지...
tableHtml += '<tr><td colspan="2" class="whois-subheader">네트워크 정보</td></tr>';
for (var na in subInfoObj[i]) {
tableHtml += '<tr><td>' + (koreanNetInfoNames[na] ? koreanNetInfoNames[na] : na) + '</td><td>' + encodeHTMLComponent(subInfoObj[i][na]) + '</td></tr>';
}
}
}
tableHtml += '</tbody>';
table.innerHTML += tableHtml;
return table;
}
switchViewLink.innerText = '(진행중입니다)';
currentView = 'progress';
resultContainer.innerHTML = '<p>(진행중입니다.)</p>'
function writeRest() {
if (whoisObj.korean && whoisObj.korean.ISP)
resultContainer.appendChild(writeSubInfoTable(whoisObj.korean.ISP, "IP 주소 보유기관 정보 (국문)"));
if (whoisObj.korean && whoisObj.korean.user)
resultContainer.appendChild(writeSubInfoTable(whoisObj.korean.user, "IP 주소 이용기관 정보 (국문)"));
if (whoisObj.english && whoisObj.english.ISP)
resultContainer.appendChild(writeSubInfoTable(whoisObj.english.ISP, "IP 주소 보유기관 정보 (영문)"));
if (whoisObj.english && whoisObj.english.user)
resultContainer.appendChild(writeSubInfoTable(whoisObj.english.user, "IP 주소 이용기관 정보 (영문)"));
switchViewLink.innerText = 'JSON 형식으로 보기';
currentView = 'table';
}
if (whoisObj.countryCode == 'none') {
resultContainer.innerHTML = '<style>.whois-subheader {background: #9D75D9; color: white; text-align: center;} table.whois tr, table.whois td{border: 1px #9D75D9 solid; border-collapse: collapse;} table.whois td {padding: 5px;} table.whois caption { caption-side: top; }</style>' +
'<table class="whois"><caption>쿼리 정보</caption>' +
'<thead><th>이름</th><th>내용</th></tr></thead>' +
'<tbody>' +
'<tr><td>쿼리</td><td>' + whoisObj.query + '</td></tr>' +
'<tr><td>쿼리 유형</td><td>' + whoisObj.queryType + '</td></tr>' +
'<tr><td>레지스트리</td><td>' + whoisObj.registry + '</td></tr>' +
'<tr><td>등록 국가</td><td><span class="icon ion-android-star"></span> 없음 (루프백같이 특수한 경우)</td></tr>' +
'</tbody></table>';
writeRest();
} else {
getFlagIcon(whoisObj.countryCode.toLowerCase(), function (flagIconData) {
resultContainer.innerHTML = '<style>.whois-subheader {background: #9D75D9; color: white; text-align: center;} table.whois tr, table.whois td{border: 1px #9D75D9 solid; border-collapse: collapse;} table.whois td {padding: 5px;} table.whois caption { caption-side: top; }</style>' +
'<table class="whois"><caption>쿼리 정보</caption>' +
'<thead><th>이름</th><th>내용</th></tr></thead>' +
'<tbody>' +
'<tr><td>쿼리</td><td>' + whoisObj.query + '</td></tr>' +
'<tr><td>쿼리 유형</td><td>' + whoisObj.queryType + '</td></tr>' +
'<tr><td>레지스트리</td><td>' + whoisObj.registry + '</td></tr>' +
'<tr><td>등록 국가</td><td><img style="height: 1em;" src="' + flagIconData + '">' + korCountryNames[whoisObj.countryCode.toUpperCase()] + '</td></tr>' +
'</tbody></table>';
writeRest();
});
}
}
function useJsonView() {
switchViewLink.innerText = '표 형식으로 보기';
currentView = 'json';
resultContainer.innerHTML = '<textarea readonly style="width: 50vw; height: 600px; max-height: 90vh;"></textarea>';
resultContainer.querySelector('textarea').value = JSON.stringify(whoisObj);
}
switchViewLink.addEventListener('click', function (evt) {
evt.preventDefault();
if (currentView == 'json') {
useTableView();
} else if (currentView == 'table') {
useJsonView();
} else if (currentView == 'progress') {
alert('잠시만 기다려주세요.');
}
})
useTableView();
} else if (result.success && result.raw) {
container.innerHTML = '<p>NamuFix 서버에서 다음과 같은 WHOIS 결과를 얻었습니다.</p><textarea readonly style="width: 50vw; height: 600px; max-height: 80vh;"></textarea>';
container.querySelector('textarea').value = result.result;
} else if (result.error.namufix) {
alert('NamuFix 서버측에서 오류가 발생했습니다.\n\n메세지 : ' + result.error.message + '\n오류 코드 : ' + result.error.code);
win.close();
} else if (result.error.kisa) {
container.innerHTML = '<p>KISA WHOIS 조회결과 다음과 같은 오류가 반환됐습니다.</p><p><em>' + result.error.message + '</em></p><p>오류 코드는 ' + result.error.code + '입니다.</p>';
}
});
});
}
this.checkVPNGateIP = async (ip) => {
return new Promise((resolve, reject) => {
GM.xmlHttpRequest({
method: "GET",
url: "https://namufix.wikimasonry.org/vpngate/check/" + encodeURIComponent(ip),
onload: function (res) {
let resObj = JSON.parse(res.responseText);
if (resObj.success)
resolve(resObj.result);
else
reject(resObj.message);
}
});
});
}
} | revi/NamuFix | src/whoisIpUtils.js | JavaScript | mit | 12,113 |
game.Player3Entity = me.Entity.extend({
init: function(x, y, settings){
this.setSuper(x, y);
this.setPlayerTimers();
this.setAttributes();
//sets type to PlayerEntity
this.type = "Player3Entity";
this.setFlags();
me.game.viewport.follow(this.pos, me.game.viewport.AXIS.BOTH);
this.addAnimation();
this.renderable.setCurrentAnimation("idle");
},
setSuper: function(x, y){
this._super(me.Entity, 'init', [x, y, {
//loads the image for the sprite
image: "player3",
width:64,
height: 64,
spritewidth: "64",
spriteheight: "64",
getShape: function(){
return(new me.Rect(0, 0, 64, 64)).toPolygon();
}
}]);
},
setPlayerTimers: function(){
//sets the player timer for attacks
this.now = new Date().getTime();
this.lastHit = this.now;
this.lastFireball = this.now;
this.lastMagic = this.now;
this.lastAttack = new Date().getTime();
},
setAttributes: function(){
//sets the health and attack that was loaded in game.js
this.health = game.data.playerHealth;
this.body.setVelocity(game.data.playerMoveSpeed, 20);
this.attack = game.data.playerAttack;
},
setFlags: function(){
//starting direction
this.facing = "right";
this.dead = false;
},
addAnimation: function(){
//sets and add animations for the player
this.renderable.addAnimation("idle", [26]);
this.renderable.addAnimation("walk", [143, 144, 145, 146, 147, 148, 149, 150, 151], 80);
this.renderable.addAnimation("attack", [195, 196, 197, 198, 199, 200], 80);
},
update: function(delta){
//checks and update functions that supports the player
this.now = new Date().getTime();
this.dead = this.checkIfDead();
this.checkKeyPressesAndMove();
this.checkAbilityKeys();
this.setAnimation();
me.collision.check(this, true, this.collideHandler.bind(this), true);
this.body.update(delta);
this._super(me.Entity, "update", [delta]);
return true;
},
checkIfDead: function(){
//checks if the player is dead
if(this.health <= 0){
return true;
}
return false;
},
checkKeyPressesAndMove: function(){
//checks if the player inputs a KeyPress function and triggers when so.
if(me.input.isKeyPressed("right")){
//sets the charater to move right
this.moveRight();
}else if(me.input.isKeyPressed("left")){
//sets the character to jump
this.moveLeft();
}else{
//set the speed to any direction to 0
this.body.vel.x = 0;
}
if(me.input.isKeyPressed("jump") && !this.body.jumping && !this.body.falling){
//checks if the body isnt jumping nor falling so the charater cant double jump or fly
this.jump();
}
//sets this key to attack
this.attacking = me.input.isKeyPressed("attack");
},
moveRight: function(){
//sets it so when the right key is pressed, the character faces right and walk
this.body.vel.x += this.body.accel.x * me.timer.tick;
this.facing = "right";
this.flipX(false);
},
moveLeft: function(){
//just like the one for moving right, this does it for the left instead.
this.body.vel.x -= this.body.accel.x * me.timer.tick;
this.facing = "left";
this.flipX(true);
},
jump: function(){
//sets the charater to be able to jump
this.body.jumping = true;
this.body.vel.y -= this.body.accel.y * me.timer.tick;
},
checkAbilityKeys: function(){
//checks if any skill is pressed
if(me.input.isKeyPressed("skill1")){
}else if(me.input.isKeyPressed("skill2")){
this.magic();
}else if(me.input.isKeyPressed("skill3")){
this.shootFireball();
this.renderable.setCurrentAnimation("attack", "idle");
}
},
shootFireball: function(){
//checks the timer to launch fireball
if(this.now-this.lastFireball >= game.data.fireballTimer && game.data.ability3 > 0){
this.lastFireball = this.now;
var fireball = me.pool.pull("fireball", this.pos.x, this.pos.y, {}, this.facing);
me.game.world.addChild(fireball, 10);
}
},
magic: function(){
//checks the timer to launch fireball
if(this.now-this.lastMagic >= game.data.magicTimer && game.data.ability2 > 0){
this.lastMagic = this.now;
var magic = me.pool.pull("magic", this.pos.x, this.pos.y, {}, this.facing);
me.game.world.addChild(magic, 10);
}
},
setAnimation: function(){
//sets the animation based on the keys pressed
if(this.attacking){
if(!this.renderable.isCurrentAnimation("attack")){
this.renderable.setCurrentAnimation("attack", "idle");
this.renderable.setAnimationFrame();
}
}else if(this.body.vel.x !==0 && !this.renderable.isCurrentAnimation("attack")){
if(!this.renderable.isCurrentAnimation("walk")){
this.renderable.setCurrentAnimation("walk");
}
}else if(!this.renderable.isCurrentAnimation("attack")){
this.renderable.setCurrentAnimation("idle");
}
},
loseHealth: function(damage){
//sets so the plpayer could lose health
this.health = this.health - damage;
},
collideHandler: function(response){
//checks if the player collide with any of the following entities
if(response.b.type==='EnemyBaseEntity'){
this.collideWithEnemyBase(response);
}else if(response.b.type==='EnemyCreep'){
this.collideWithEnemyCreep(response);
}
},
collideWithEnemyBase: function(response){
//checks the cordinate so if wont look ugly when it attacks
var ydif = this.pos.y - response.b.pos.y;
var xdif = this.pos.x - response.b.pos.x;
//checks to make sure they are facing the right way
if(ydif<-40 && xdif<70 && xdif>-39){
this.body.falling = false;
this.body.vel.y = -1;
}else if(xdif>-35 && this.facing==='right' && xdif<0){
this.body.vel.x = 0;
}else if(xdif<70 && this.facing==='left' && xdif>0){
this.body.vel.x = 0;
}
//set the animation to attack wheen the attack key is pressed
if(this.renderable.isCurrentAnimation("attack") && this.now-this.lastHit >= game.data.playerAttackTimer){
this.lastHit = this.now;
response.b.loseHealth(game.data.playerAttack);
}
},
collideWithEnemyCreep: function(response){
//checks for the collision with the enemy creep the same way with the base.
var xdif = this.pos.x - response.b.pos.x;
var ydif = this.pos.y - response.b.pos.y;
this.stopMovement(xdif);
if(this.checkAttack(xdif, ydif)){
this.hitCreep(response);
};
},
stopMovement: function(xdif){
//set the player to stop moving
if(xdif>0){
if(this.facing==="left"){
this.body.vel.x = 0;
}
}else{
if(this.facing==="right"){
this.body.vel.x = 0;
}
}
},
checkAttack: function(xdif, ydif){
//sets the animation for attack and the damage for the attack.
if(this.renderable.isCurrentAnimation("attack") && this.now-this.lastHit >= game.data.playerAttackTimer
&& (Math.abs(ydif) <40) &&
(((xdif>0 ) && this.facing==="left") || ((xdif<0) && this.facing==="right"))
){
this.lastHit = this.now;
return true;
}
return false;
},
hitCreep: function(response){
//checks for the responce from the enemy creep
if(response.b.health <= game.data.playerAttack){
game.data.gold += 100;
}
response.b.loseHealth(game.data.playerAttack);
}
});
| KentZacatelco/Awesomenauts | js/entities/Player/wizard.js | JavaScript | mit | 8,492 |
module.exports = ({
comandaEstado
}) => {
return Promise.all(
comandaEstado.upsert({
id: 1,
descripcion: 'Pendiente'
}),
comandaEstado.upsert({
id: 2,
descripcion: 'Lista para entrega'
}),
comandaEstado.upsert({
id: 3,
descripcion: 'Entregada'
})
);
};
| ungs-pp1g2/delix | api/db/defaults/comanda_estado.js | JavaScript | mit | 385 |
import {
ARRAY_INSERT,
ARRAY_MOVE,
ARRAY_POP,
ARRAY_PUSH,
ARRAY_REMOVE,
ARRAY_REMOVE_ALL,
ARRAY_SHIFT,
ARRAY_SPLICE,
ARRAY_SWAP,
ARRAY_UNSHIFT,
BLUR,
CHANGE,
CLEAR_SUBMIT,
CLEAR_SUBMIT_ERRORS,
CLEAR_FIELDS,
DESTROY,
FOCUS,
INITIALIZE,
REGISTER_FIELD,
RESET,
RESET_SECTION,
SET_SUBMIT_FAILED,
SET_SUBMIT_SUCCEEDED,
START_ASYNC_VALIDATION,
START_SUBMIT,
STOP_ASYNC_VALIDATION,
STOP_SUBMIT,
SUBMIT,
TOUCH,
UNREGISTER_FIELD,
UNTOUCH,
UPDATE_SYNC_ERRORS,
UPDATE_SYNC_WARNINGS,
CLEAR_ASYNC_ERROR
} from '../actionTypes'
import actions from '../actions'
import { isFSA } from 'flux-standard-action'
const {
arrayInsert,
arrayMove,
arrayPop,
arrayPush,
arrayRemove,
arrayRemoveAll,
arrayShift,
arraySplice,
arraySwap,
arrayUnshift,
blur,
change,
clearSubmit,
clearSubmitErrors,
clearFields,
destroy,
focus,
initialize,
registerField,
reset,
resetSection,
setSubmitFailed,
setSubmitSucceeded,
startAsyncValidation,
startSubmit,
stopAsyncValidation,
stopSubmit,
submit,
touch,
unregisterField,
untouch,
updateSyncErrors,
updateSyncWarnings,
clearAsyncError
} = actions
describe('actions', () => {
it('should create array insert action', () => {
expect(arrayInsert('myForm', 'myField', 0, 'foo')).toEqual({
type: ARRAY_INSERT,
meta: {
form: 'myForm',
field: 'myField',
index: 0
},
payload: 'foo'
})
expect(isFSA(arrayInsert('myForm', 'myField', 0, 'foo'))).toBe(true)
})
it('should create array move action', () => {
expect(arrayMove('myForm', 'myField', 2, 4)).toEqual({
type: ARRAY_MOVE,
meta: {
form: 'myForm',
field: 'myField',
from: 2,
to: 4
}
})
expect(isFSA(arrayMove('myForm', 'myField', 2, 4))).toBe(true)
})
it('should create array pop action', () => {
expect(arrayPop('myForm', 'myField')).toEqual({
type: ARRAY_POP,
meta: {
form: 'myForm',
field: 'myField'
}
})
expect(isFSA(arrayPop('myForm', 'myField'))).toBe(true)
})
it('should create array push action', () => {
expect(arrayPush('myForm', 'myField', 'foo')).toEqual({
type: ARRAY_PUSH,
meta: {
form: 'myForm',
field: 'myField'
},
payload: 'foo'
})
expect(isFSA(arrayPush('myForm', 'myField', 'foo'))).toBe(true)
expect(arrayPush('myForm', 'myField')).toEqual({
type: ARRAY_PUSH,
meta: {
form: 'myForm',
field: 'myField'
},
payload: undefined
})
expect(isFSA(arrayPush('myForm', 'myField'))).toBe(true)
})
it('should create array remove action', () => {
expect(arrayRemove('myForm', 'myField', 3)).toEqual({
type: ARRAY_REMOVE,
meta: {
form: 'myForm',
field: 'myField',
index: 3
}
})
expect(isFSA(arrayRemove('myForm', 'myField', 3))).toBe(true)
})
it('should create array removeAll action', () => {
expect(arrayRemoveAll('myForm', 'myField')).toEqual({
type: ARRAY_REMOVE_ALL,
meta: {
form: 'myForm',
field: 'myField'
}
})
expect(isFSA(arrayRemoveAll('myForm', 'myField'))).toBe(true)
})
it('should create array shift action', () => {
expect(arrayShift('myForm', 'myField')).toEqual({
type: ARRAY_SHIFT,
meta: {
form: 'myForm',
field: 'myField'
}
})
expect(isFSA(arrayShift('myForm', 'myField'))).toBe(true)
})
it('should create array splice action', () => {
expect(arraySplice('myForm', 'myField', 1, 1)).toEqual({
type: ARRAY_SPLICE,
meta: {
form: 'myForm',
field: 'myField',
index: 1,
removeNum: 1
}
})
expect(isFSA(arraySplice('myForm', 'myField', 1, 1))).toBe(true)
expect(arraySplice('myForm', 'myField', 2, 1)).toEqual({
type: ARRAY_SPLICE,
meta: {
form: 'myForm',
field: 'myField',
index: 2,
removeNum: 1
}
})
expect(isFSA(arraySplice('myForm', 'myField', 2, 1))).toBe(true)
expect(arraySplice('myForm', 'myField', 2, 0, 'foo')).toEqual({
type: ARRAY_SPLICE,
meta: {
form: 'myForm',
field: 'myField',
index: 2,
removeNum: 0
},
payload: 'foo'
})
expect(isFSA(arraySplice('myForm', 'myField', 2, 0, 'foo'))).toBe(true)
expect(arraySplice('myForm', 'myField', 3, 2, { foo: 'bar' })).toEqual({
type: ARRAY_SPLICE,
meta: {
form: 'myForm',
field: 'myField',
index: 3,
removeNum: 2
},
payload: {
foo: 'bar'
}
})
expect(isFSA(arraySplice('myForm', 'myField', 3, 2, { foo: 'bar' }))).toBe(
true
)
})
it('should create array unshift action', () => {
expect(arrayUnshift('myForm', 'myField', 'foo')).toEqual({
type: ARRAY_UNSHIFT,
meta: {
form: 'myForm',
field: 'myField'
},
payload: 'foo'
})
expect(isFSA(arrayUnshift('myForm', 'myField', 'foo'))).toBe(true)
})
it('should create array swap action', () => {
expect(arraySwap('myForm', 'myField', 0, 8)).toEqual({
type: ARRAY_SWAP,
meta: {
form: 'myForm',
field: 'myField',
indexA: 0,
indexB: 8
}
})
expect(isFSA(arraySwap('myForm', 'myField', 0, 8))).toBe(true)
})
it('should throw an exception with illegal array swap indices', () => {
expect(() => arraySwap('myForm', 'myField', 2, 2)).toThrow(
'Swap indices cannot be equal'
)
expect(() => arraySwap('myForm', 'myField', -2, 2)).toThrow(
'Swap indices cannot be negative'
)
expect(() => arraySwap('myForm', 'myField', 2, -2)).toThrow(
'Swap indices cannot be negative'
)
})
it('should create blur action', () => {
expect(blur('myForm', 'myField', 'bar', false)).toEqual({
type: BLUR,
meta: {
form: 'myForm',
field: 'myField',
touch: false
},
payload: 'bar'
})
expect(isFSA(blur('myForm', 'myField', 'bar', false))).toBe(true)
expect(blur('myForm', 'myField', 7, true)).toEqual({
type: BLUR,
meta: {
form: 'myForm',
field: 'myField',
touch: true
},
payload: 7
})
expect(isFSA(blur('myForm', 'myField', 7, true))).toBe(true)
})
it('should create change action', () => {
expect(change('myForm', 'myField', 'bar', false, true)).toEqual({
type: CHANGE,
meta: {
form: 'myForm',
field: 'myField',
touch: false,
persistentSubmitErrors: true
},
payload: 'bar'
})
expect(isFSA(change('myForm', 'myField', 'bar', false, true))).toBe(true)
expect(change('myForm', 'myField', 7, true, false)).toEqual({
type: CHANGE,
meta: {
form: 'myForm',
field: 'myField',
touch: true,
persistentSubmitErrors: false
},
payload: 7
})
expect(isFSA(change('myForm', 'myField', 7, true, false))).toBe(true)
})
it('should create focus action', () => {
expect(focus('myForm', 'myField')).toEqual({
type: FOCUS,
meta: {
form: 'myForm',
field: 'myField'
}
})
expect(isFSA(focus('myForm', 'myField'))).toBe(true)
})
it('should create clear submit action', () => {
expect(clearSubmit('myForm')).toEqual({
type: CLEAR_SUBMIT,
meta: {
form: 'myForm'
}
})
expect(isFSA(clearSubmit('myForm'))).toBe(true)
})
it('should create clear submit errors action', () => {
expect(clearSubmitErrors('myForm')).toEqual({
type: CLEAR_SUBMIT_ERRORS,
meta: {
form: 'myForm'
}
})
expect(isFSA(clearSubmitErrors('myForm'))).toBe(true)
})
it('should create clear fields action', () => {
expect(clearFields('myForm', true, true, 'a', 'b')).toEqual({
type: CLEAR_FIELDS,
meta: {
form: 'myForm',
keepTouched: true,
persistentSubmitErrors: true,
fields: ['a', 'b']
}
})
expect(isFSA(clearSubmitErrors('myForm'))).toBe(true)
})
it('should create initialize action', () => {
const data = { a: 8, c: 9 }
expect(initialize('myForm', data)).toEqual({
type: INITIALIZE,
meta: {
form: 'myForm',
keepDirty: undefined
},
payload: data
})
expect(isFSA(initialize('myForm', data))).toBe(true)
})
it('should create initialize action with a keepDirty value', () => {
const data = { a: 8, c: 9 }
expect(initialize('myForm', data, true)).toEqual({
type: INITIALIZE,
meta: {
form: 'myForm',
keepDirty: true
},
payload: data
})
expect(isFSA(initialize('myForm', data, true))).toBe(true)
})
it('should create registerField action', () => {
expect(registerField('myForm', 'foo', 'Field')).toEqual({
type: REGISTER_FIELD,
meta: {
form: 'myForm'
},
payload: {
name: 'foo',
type: 'Field'
}
})
expect(isFSA(registerField('myForm', 'foo', 'Field'))).toBe(true)
})
it('should create reset action', () => {
expect(reset('myForm')).toEqual({
type: RESET,
meta: {
form: 'myForm'
}
})
expect(isFSA(reset('myForm'))).toBe(true)
})
it('should create resetSection action', () => {
expect(resetSection('myForm', 'mySection')).toEqual({
type: RESET_SECTION,
meta: {
form: 'myForm',
sections: ['mySection']
}
})
expect(isFSA(resetSection('myForm', 'mySection'))).toBe(true)
})
it('should create destroy action', () => {
expect(destroy('myForm')).toEqual({
type: DESTROY,
meta: {
form: ['myForm']
}
})
expect(isFSA(destroy('myForm'))).toBe(true)
expect(destroy('myForm1', 'myForm2')).toEqual({
type: DESTROY,
meta: {
form: ['myForm1', 'myForm2']
}
})
expect(isFSA(destroy('myForm1', 'myForm2'))).toBe(true)
})
it('should create startAsyncValidation action', () => {
expect(startAsyncValidation('myForm', 'myField')).toEqual({
type: START_ASYNC_VALIDATION,
meta: {
form: 'myForm',
field: 'myField'
}
})
expect(isFSA(startAsyncValidation('myForm', 'myField'))).toBe(true)
})
it('should create startSubmit action', () => {
expect(startSubmit('myForm')).toEqual({
type: START_SUBMIT,
meta: {
form: 'myForm'
}
})
expect(isFSA(startSubmit('myForm'))).toBe(true)
})
it('should create startSubmit action', () => {
expect(startSubmit('myForm')).toEqual({
type: START_SUBMIT,
meta: {
form: 'myForm'
}
})
expect(isFSA(startSubmit('myForm'))).toBe(true)
})
it('should create stopAsyncValidation action', () => {
const errors = {
foo: 'Foo error',
bar: 'Error for bar'
}
expect(stopAsyncValidation('myForm', errors)).toEqual({
type: STOP_ASYNC_VALIDATION,
meta: {
form: 'myForm'
},
payload: errors,
error: true
})
expect(isFSA(stopAsyncValidation('myForm', errors))).toBe(true)
})
it('should create stopSubmit action', () => {
expect(stopSubmit('myForm')).toEqual({
type: STOP_SUBMIT,
meta: {
form: 'myForm'
},
payload: undefined,
error: false
})
expect(isFSA(stopSubmit('myForm'))).toBe(true)
const errors = {
foo: 'Foo error',
bar: 'Error for bar'
}
expect(stopSubmit('myForm', errors)).toEqual({
type: STOP_SUBMIT,
meta: {
form: 'myForm'
},
payload: errors,
error: true
})
expect(isFSA(stopSubmit('myForm', errors))).toBe(true)
})
it('should create submit action', () => {
expect(submit('myForm')).toEqual({
type: SUBMIT,
meta: {
form: 'myForm'
}
})
expect(isFSA(submit('myForm'))).toBe(true)
})
it('should create setSubmitFailed action', () => {
expect(setSubmitFailed('myForm')).toEqual({
type: SET_SUBMIT_FAILED,
meta: {
form: 'myForm',
fields: []
},
error: true
})
expect(isFSA(setSubmitFailed('myForm'))).toBe(true)
expect(setSubmitFailed('myForm', 'a', 'b', 'c')).toEqual({
type: SET_SUBMIT_FAILED,
meta: {
form: 'myForm',
fields: ['a', 'b', 'c']
},
error: true
})
expect(isFSA(setSubmitFailed('myForm', 'a', 'b', 'c'))).toBe(true)
})
it('should create setSubmitSucceeded action', () => {
expect(setSubmitSucceeded('myForm')).toEqual({
type: SET_SUBMIT_SUCCEEDED,
meta: {
form: 'myForm',
fields: []
},
error: false
})
expect(isFSA(setSubmitSucceeded('myForm'))).toBe(true)
expect(setSubmitSucceeded('myForm', 'a', 'b', 'c')).toEqual({
type: SET_SUBMIT_SUCCEEDED,
meta: {
form: 'myForm',
fields: ['a', 'b', 'c']
},
error: false
})
expect(isFSA(setSubmitSucceeded('myForm', 'a', 'b', 'c'))).toBe(true)
})
it('should create touch action', () => {
expect(touch('myForm', 'foo', 'bar')).toEqual({
type: TOUCH,
meta: {
form: 'myForm',
fields: ['foo', 'bar']
}
})
expect(isFSA(touch('myForm', 'foo', 'bar'))).toBe(true)
expect(touch('myForm', 'cat', 'dog', 'pig')).toEqual({
type: TOUCH,
meta: {
form: 'myForm',
fields: ['cat', 'dog', 'pig']
}
})
expect(isFSA(touch('myForm', 'cat', 'dog', 'pig'))).toBe(true)
})
it('should create unregisterField action', () => {
expect(unregisterField('myForm', 'foo')).toEqual({
type: UNREGISTER_FIELD,
meta: {
form: 'myForm'
},
payload: {
name: 'foo',
destroyOnUnmount: true
}
})
expect(isFSA(unregisterField('myForm', 'foo'))).toBe(true)
})
it('should create untouch action', () => {
expect(untouch('myForm', 'foo', 'bar')).toEqual({
type: UNTOUCH,
meta: {
form: 'myForm',
fields: ['foo', 'bar']
}
})
expect(isFSA(untouch('myForm', 'foo', 'bar'))).toBe(true)
expect(untouch('myForm', 'cat', 'dog', 'pig')).toEqual({
type: UNTOUCH,
meta: {
form: 'myForm',
fields: ['cat', 'dog', 'pig']
}
})
expect(isFSA(untouch('myForm', 'cat', 'dog', 'pig'))).toBe(true)
})
it('should create updateSyncErrors action', () => {
expect(updateSyncErrors('myForm', { foo: 'foo error' })).toEqual({
type: UPDATE_SYNC_ERRORS,
meta: {
form: 'myForm'
},
payload: {
error: undefined,
syncErrors: {
foo: 'foo error'
}
}
})
expect(isFSA(updateSyncErrors('myForm', { foo: 'foo error' }))).toBe(true)
})
it('should create updateSyncErrors action with no errors if none given', () => {
expect(updateSyncErrors('myForm')).toEqual({
type: UPDATE_SYNC_ERRORS,
meta: {
form: 'myForm'
},
payload: {
error: undefined,
syncErrors: {}
}
})
expect(isFSA(updateSyncErrors('myForm'))).toBe(true)
})
it('should create updateSyncWarnings action', () => {
expect(updateSyncWarnings('myForm', { foo: 'foo warning' })).toEqual({
type: UPDATE_SYNC_WARNINGS,
meta: {
form: 'myForm'
},
payload: {
warning: undefined,
syncWarnings: {
foo: 'foo warning'
}
}
})
expect(isFSA(updateSyncWarnings('myForm', { foo: 'foo warning' }))).toBe(
true
)
})
it('should create updateSyncWarnings action with no warnings if none given', () => {
expect(updateSyncWarnings('myForm')).toEqual({
type: UPDATE_SYNC_WARNINGS,
meta: {
form: 'myForm'
},
payload: {
warning: undefined,
syncWarnings: {}
}
})
expect(isFSA(updateSyncWarnings('myForm'))).toBe(true)
})
it('should create clearAsyncError action', () => {
expect(clearAsyncError('myForm', 'foo')).toEqual({
type: CLEAR_ASYNC_ERROR,
meta: {
form: 'myForm',
field: 'foo'
}
})
expect(isFSA(clearAsyncError('myForm', 'foo'))).toBe(true)
})
})
| erikras/redux-form | src/__tests__/actions.spec.js | JavaScript | mit | 16,583 |
/**
* Server side app.js file for my web dev project.
* Author: Matthew Murphy
*/
var connectionString = 'mongodb://127.0.0.1:27017/webdev_summer1_assignment_2017';
if(process.env.MLAB_USERNAME) {
connectionString = process.env.MLAB_USERNAME + ":" +
process.env.MLAB_PASSWORD + "@" +
process.env.MLAB_HOST + ':' +
process.env.MLAB_PORT + '/' +
process.env.MLAB_APP_NAME;
}
var mongoose = require("mongoose");
var db = mongoose.connect(connectionString);
require('./modules/authenticator.service.server.js');
require('./services/admin.service.server.js');
require('./services/user.service.server.js');
require('./services/image.service.server.js');
require('./services/feed.service.server.js');
require('./services/rep.service.server.js');
require('./services/proPublica.service.server.js');
| Murphy-matth/murphy-matthew-webdev | project/app.js | JavaScript | mit | 834 |
console.log("Hello from index.js");
| drouhard/github-pages-test | docs/index.js | JavaScript | mit | 36 |
'use strict';
/**
* @fileoverview log4js is a library to log in JavaScript in similar manner
* than in log4j for Java (but not really).
*
* <h3>Example:</h3>
* <pre>
* const logging = require('log4js');
* const log = logging.getLogger('some-category');
*
* //call the log
* log.trace('trace me' );
* </pre>
*
* NOTE: the authors below are the original browser-based log4js authors
* don't try to contact them about bugs in this version :)
* @author Stephan Strittmatter - http://jroller.com/page/stritti
* @author Seth Chisamore - http://www.chisamore.com
* @since 2005-05-20
* Website: http://log4js.berlios.de
*/
const debug = require('debug')('log4js:main');
const fs = require('fs');
const deepClone = require('rfdc')({ proto: true });
const configuration = require('./configuration');
const layouts = require('./layouts');
const levels = require('./levels');
const appenders = require('./appenders');
const categories = require('./categories');
const Logger = require('./logger');
const clustering = require('./clustering');
const connectLogger = require('./connect-logger');
let enabled = false;
function sendLogEventToAppender(logEvent) {
if (!enabled) return;
debug('Received log event ', logEvent);
const categoryAppenders = categories.appendersForCategory(logEvent.categoryName);
categoryAppenders.forEach((appender) => {
appender(logEvent);
});
}
function loadConfigurationFile(filename) {
if (filename) {
debug(`Loading configuration from ${filename}`);
return JSON.parse(fs.readFileSync(filename, 'utf8'));
}
return filename;
}
function configure(configurationFileOrObject) {
let configObject = configurationFileOrObject;
if (typeof configObject === 'string') {
configObject = loadConfigurationFile(configurationFileOrObject);
}
debug(`Configuration is ${configObject}`);
configuration.configure(deepClone(configObject));
clustering.onMessage(sendLogEventToAppender);
enabled = true;
// eslint-disable-next-line no-use-before-define
return log4js;
}
/**
* Shutdown all log appenders. This will first disable all writing to appenders
* and then call the shutdown function each appender.
*
* @params {Function} cb - The callback to be invoked once all appenders have
* shutdown. If an error occurs, the callback will be given the error object
* as the first argument.
*/
function shutdown(cb) {
debug('Shutdown called. Disabling all log writing.');
// First, disable all writing to appenders. This prevents appenders from
// not being able to be drained because of run-away log writes.
enabled = false;
// Call each of the shutdown functions in parallel
const appendersToCheck = Array.from(appenders.values());
const shutdownFunctions = appendersToCheck.reduceRight((accum, next) => (next.shutdown ? accum + 1 : accum), 0);
let completed = 0;
let error;
debug(`Found ${shutdownFunctions} appenders with shutdown functions.`);
function complete(err) {
error = error || err;
completed += 1;
debug(`Appender shutdowns complete: ${completed} / ${shutdownFunctions}`);
if (completed >= shutdownFunctions) {
debug('All shutdown functions completed.');
cb(error);
}
}
if (shutdownFunctions === 0) {
debug('No appenders with shutdown functions found.');
return cb();
}
appendersToCheck.filter(a => a.shutdown).forEach(a => a.shutdown(complete));
return null;
}
/**
* Get a logger instance.
* @static
* @param loggerCategoryName
* @return {Logger} instance of logger for the category
*/
function getLogger(category) {
if (!enabled) {
configure(process.env.LOG4JS_CONFIG || {
appenders: { out: { type: 'stdout' } },
categories: { default: { appenders: ['out'], level: 'OFF' } }
});
}
return new Logger(category || 'default');
}
/**
* @name log4js
* @namespace Log4js
* @property getLogger
* @property configure
* @property shutdown
*/
const log4js = {
getLogger,
configure,
shutdown,
connectLogger,
levels,
addLayout: layouts.addLayout
};
module.exports = log4js;
| AxelSparkster/axelsparkster.github.io | node_modules/log4js/lib/log4js.js | JavaScript | mit | 4,088 |
/**
* @author mrdoob / http://mrdoob.com/
* @author *kile / http://kile.stravaganza.org/
* @author philogb / http://blog.thejit.org/
* @author mikael emtinger / http://gomo.se/
* @author egraether / http://egraether.com/
* @author WestLangley / http://github.com/WestLangley
*/
THREE.Vector3 = function ( x, y, z ) {
this.x = x || 0;
this.y = y || 0;
this.z = z || 0;
};
THREE.Vector3.prototype = {
constructor: THREE.Vector3,
set: function ( x, y, z ) {
this.x = x;
this.y = y;
this.z = z;
return this;
},
setX: function ( x ) {
this.x = x;
return this;
},
setY: function ( y ) {
this.y = y;
return this;
},
setZ: function ( z ) {
this.z = z;
return this;
},
setComponent: function ( index, value ) {
switch ( index ) {
case 0: this.x = value; break;
case 1: this.y = value; break;
case 2: this.z = value; break;
default: throw new Error( 'index is out of range: ' + index );
}
},
getComponent: function ( index ) {
switch ( index ) {
case 0: return this.x;
case 1: return this.y;
case 2: return this.z;
default: throw new Error( 'index is out of range: ' + index );
}
},
clone: function () {
return new this.constructor( this.x, this.y, this.z );
},
copy: function ( v ) {
this.x = v.x;
this.y = v.y;
this.z = v.z;
return this;
},
add: function ( v, w ) {
if ( w !== undefined ) {
console.warn( 'THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
return this.addVectors( v, w );
}
this.x += v.x;
this.y += v.y;
this.z += v.z;
return this;
},
addScalar: function ( s ) {
this.x += s;
this.y += s;
this.z += s;
return this;
},
addVectors: function ( a, b ) {
this.x = a.x + b.x;
this.y = a.y + b.y;
this.z = a.z + b.z;
return this;
},
addScaledVector: function ( v, s ) {
this.x += v.x * s;
this.y += v.y * s;
this.z += v.z * s;
return this;
},
sub: function ( v, w ) {
if ( w !== undefined ) {
console.warn( 'THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
return this.subVectors( v, w );
}
this.x -= v.x;
this.y -= v.y;
this.z -= v.z;
return this;
},
subScalar: function ( s ) {
this.x -= s;
this.y -= s;
this.z -= s;
return this;
},
subVectors: function ( a, b ) {
this.x = a.x - b.x;
this.y = a.y - b.y;
this.z = a.z - b.z;
return this;
},
multiply: function ( v, w ) {
if ( w !== undefined ) {
console.warn( 'THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' );
return this.multiplyVectors( v, w );
}
this.x *= v.x;
this.y *= v.y;
this.z *= v.z;
return this;
},
multiplyScalar: function ( scalar ) {
if ( isFinite( scalar ) ) {
this.x *= scalar;
this.y *= scalar;
this.z *= scalar;
} else {
this.x = 0;
this.y = 0;
this.z = 0;
}
return this;
},
multiplyVectors: function ( a, b ) {
this.x = a.x * b.x;
this.y = a.y * b.y;
this.z = a.z * b.z;
return this;
},
applyEuler: function () {
var quaternion;
return function applyEuler( euler ) {
if ( euler instanceof THREE.Euler === false ) {
console.error( 'THREE.Vector3: .applyEuler() now expects a Euler rotation rather than a Vector3 and order.' );
}
if ( quaternion === undefined ) quaternion = new THREE.Quaternion();
this.applyQuaternion( quaternion.setFromEuler( euler ) );
return this;
};
}(),
applyAxisAngle: function () {
var quaternion;
return function applyAxisAngle( axis, angle ) {
if ( quaternion === undefined ) quaternion = new THREE.Quaternion();
this.applyQuaternion( quaternion.setFromAxisAngle( axis, angle ) );
return this;
};
}(),
applyMatrix3: function ( m ) {
var x = this.x;
var y = this.y;
var z = this.z;
var e = m.elements;
this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
return this;
},
applyMatrix4: function ( m ) {
// input: THREE.Matrix4 affine matrix
var x = this.x, y = this.y, z = this.z;
var e = m.elements;
this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ];
this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ];
this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ];
return this;
},
applyProjection: function ( m ) {
// input: THREE.Matrix4 projection matrix
var x = this.x, y = this.y, z = this.z;
var e = m.elements;
var d = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] ); // perspective divide
this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * d;
this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * d;
this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * d;
return this;
},
applyQuaternion: function ( q ) {
var x = this.x;
var y = this.y;
var z = this.z;
var qx = q.x;
var qy = q.y;
var qz = q.z;
var qw = q.w;
// calculate quat * vector
var ix = qw * x + qy * z - qz * y;
var iy = qw * y + qz * x - qx * z;
var iz = qw * z + qx * y - qy * x;
var iw = - qx * x - qy * y - qz * z;
// calculate result * inverse quat
this.x = ix * qw + iw * - qx + iy * - qz - iz * - qy;
this.y = iy * qw + iw * - qy + iz * - qx - ix * - qz;
this.z = iz * qw + iw * - qz + ix * - qy - iy * - qx;
return this;
},
project: function () {
var matrix;
return function project( camera ) {
if ( matrix === undefined ) matrix = new THREE.Matrix4();
matrix.multiplyMatrices( camera.projectionMatrix, matrix.getInverse( camera.matrixWorld ) );
return this.applyProjection( matrix );
};
}(),
unproject: function () {
var matrix;
return function unproject( camera ) {
if ( matrix === undefined ) matrix = new THREE.Matrix4();
matrix.multiplyMatrices( camera.matrixWorld, matrix.getInverse( camera.projectionMatrix ) );
return this.applyProjection( matrix );
};
}(),
transformDirection: function ( m ) {
// input: THREE.Matrix4 affine matrix
// vector interpreted as a direction
var x = this.x, y = this.y, z = this.z;
var e = m.elements;
this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
this.normalize();
return this;
},
divide: function ( v ) {
this.x /= v.x;
this.y /= v.y;
this.z /= v.z;
return this;
},
divideScalar: function ( scalar ) {
return this.multiplyScalar( 1 / scalar );
},
min: function ( v ) {
this.x = Math.min( this.x, v.x );
this.y = Math.min( this.y, v.y );
this.z = Math.min( this.z, v.z );
return this;
},
max: function ( v ) {
this.x = Math.max( this.x, v.x );
this.y = Math.max( this.y, v.y );
this.z = Math.max( this.z, v.z );
return this;
},
clamp: function ( min, max ) {
// This function assumes min < max, if this assumption isn't true it will not operate correctly
this.x = Math.max( min.x, Math.min( max.x, this.x ) );
this.y = Math.max( min.y, Math.min( max.y, this.y ) );
this.z = Math.max( min.z, Math.min( max.z, this.z ) );
return this;
},
clampScalar: function () {
var min, max;
return function clampScalar( minVal, maxVal ) {
if ( min === undefined ) {
min = new THREE.Vector3();
max = new THREE.Vector3();
}
min.set( minVal, minVal, minVal );
max.set( maxVal, maxVal, maxVal );
return this.clamp( min, max );
};
}(),
clampLength: function ( min, max ) {
var length = this.length();
this.multiplyScalar( Math.max( min, Math.min( max, length ) ) / length );
return this;
},
floor: function () {
this.x = Math.floor( this.x );
this.y = Math.floor( this.y );
this.z = Math.floor( this.z );
return this;
},
ceil: function () {
this.x = Math.ceil( this.x );
this.y = Math.ceil( this.y );
this.z = Math.ceil( this.z );
return this;
},
round: function () {
this.x = Math.round( this.x );
this.y = Math.round( this.y );
this.z = Math.round( this.z );
return this;
},
roundToZero: function () {
this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
return this;
},
negate: function () {
this.x = - this.x;
this.y = - this.y;
this.z = - this.z;
return this;
},
dot: function ( v ) {
return this.x * v.x + this.y * v.y + this.z * v.z;
},
lengthSq: function () {
return this.x * this.x + this.y * this.y + this.z * this.z;
},
length: function () {
return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
},
lengthManhattan: function () {
return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
},
normalize: function () {
return this.divideScalar( this.length() );
},
setLength: function ( length ) {
return this.multiplyScalar( length / this.length() );
},
lerp: function ( v, alpha ) {
this.x += ( v.x - this.x ) * alpha;
this.y += ( v.y - this.y ) * alpha;
this.z += ( v.z - this.z ) * alpha;
return this;
},
lerpVectors: function ( v1, v2, alpha ) {
this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
return this;
},
cross: function ( v, w ) {
if ( w !== undefined ) {
console.warn( 'THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' );
return this.crossVectors( v, w );
}
var x = this.x, y = this.y, z = this.z;
this.x = y * v.z - z * v.y;
this.y = z * v.x - x * v.z;
this.z = x * v.y - y * v.x;
return this;
},
crossVectors: function ( a, b ) {
var ax = a.x, ay = a.y, az = a.z;
var bx = b.x, by = b.y, bz = b.z;
this.x = ay * bz - az * by;
this.y = az * bx - ax * bz;
this.z = ax * by - ay * bx;
return this;
},
projectOnVector: function () {
var v1, dot;
return function projectOnVector( vector ) {
if ( v1 === undefined ) v1 = new THREE.Vector3();
v1.copy( vector ).normalize();
dot = this.dot( v1 );
return this.copy( v1 ).multiplyScalar( dot );
};
}(),
projectOnPlane: function () {
var v1;
return function projectOnPlane( planeNormal ) {
if ( v1 === undefined ) v1 = new THREE.Vector3();
v1.copy( this ).projectOnVector( planeNormal );
return this.sub( v1 );
}
}(),
reflect: function () {
// reflect incident vector off plane orthogonal to normal
// normal is assumed to have unit length
var v1;
return function reflect( normal ) {
if ( v1 === undefined ) v1 = new THREE.Vector3();
return this.sub( v1.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
}
}(),
angleTo: function ( v ) {
var theta = this.dot( v ) / ( Math.sqrt( this.lengthSq() * v.lengthSq() ) );
// clamp, to handle numerical problems
return Math.acos( THREE.Math.clamp( theta, - 1, 1 ) );
},
distanceTo: function ( v ) {
return Math.sqrt( this.distanceToSquared( v ) );
},
distanceToSquared: function ( v ) {
var dx = this.x - v.x;
var dy = this.y - v.y;
var dz = this.z - v.z;
return dx * dx + dy * dy + dz * dz;
},
setFromMatrixPosition: function ( m ) {
this.x = m.elements[ 12 ];
this.y = m.elements[ 13 ];
this.z = m.elements[ 14 ];
return this;
},
setFromMatrixScale: function ( m ) {
var sx = this.set( m.elements[ 0 ], m.elements[ 1 ], m.elements[ 2 ] ).length();
var sy = this.set( m.elements[ 4 ], m.elements[ 5 ], m.elements[ 6 ] ).length();
var sz = this.set( m.elements[ 8 ], m.elements[ 9 ], m.elements[ 10 ] ).length();
this.x = sx;
this.y = sy;
this.z = sz;
return this;
},
setFromMatrixColumn: function ( index, matrix ) {
var offset = index * 4;
var me = matrix.elements;
this.x = me[ offset ];
this.y = me[ offset + 1 ];
this.z = me[ offset + 2 ];
return this;
},
equals: function ( v ) {
return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
},
fromArray: function ( array, offset ) {
if ( offset === undefined ) offset = 0;
this.x = array[ offset ];
this.y = array[ offset + 1 ];
this.z = array[ offset + 2 ];
return this;
},
toArray: function ( array, offset ) {
if ( array === undefined ) array = [];
if ( offset === undefined ) offset = 0;
array[ offset ] = this.x;
array[ offset + 1 ] = this.y;
array[ offset + 2 ] = this.z;
return array;
},
fromAttribute: function ( attribute, index, offset ) {
if ( offset === undefined ) offset = 0;
index = index * attribute.itemSize + offset;
this.x = attribute.array[ index ];
this.y = attribute.array[ index + 1 ];
this.z = attribute.array[ index + 2 ];
return this;
}
};
| pletzer/three.js | src/math/Vector3.js | JavaScript | mit | 12,867 |
import React from 'react';
import Link from '../Link';
import { html } from './index.md';
function Footer() {
return (
<footer className="mdl-mini-footer" style={{ backgroundColor: '#000000' }}>
<div className="mdl-mini-footer__left-section">
<div dangerouslySetInnerHTML={{ __html: html }} />
</div>
<div className="mdl-mini-footer__right-section">
<ul className="mdl-mini-footer__link-list">
<li className="mdl-mini-footer--social-btn" style={{ backgroundColor: 'transparent' }}>
<a href="https://github.com/andeemarks/conf-gen-div" role="button" title="GitHub">
<svg width="36" height="36" viewBox="0 0 24 24">
<path
fill="#fff" d="M12,2A10,10 0 0,0 2,12C2,16.42 4.87,20.17 8.84,21.5C9.34,21.58
9.5,21.27 9.5,21C9.5,20.77 9.5,20.14 9.5,19.31C6.73,19.91 6.14,17.97 6.14,
17.97C5.68,16.81 5.03,16.5 5.03,16.5C4.12,15.88 5.1,15.9 5.1,15.9C6.1,15.97 6.63,
16.93 6.63,16.93C7.5,18.45 8.97,18 9.54,17.76C9.63,17.11 9.89,16.67 10.17,
16.42C7.95,16.17 5.62,15.31 5.62,11.5C5.62,10.39 6,9.5 6.65,8.79C6.55,8.54 6.2,
7.5 6.75,6.15C6.75,6.15 7.59,5.88 9.5,7.17C10.29,6.95 11.15,6.84 12,6.84C12.85,
6.84 13.71,6.95 14.5,7.17C16.41,5.88 17.25,6.15 17.25,6.15C17.8,7.5 17.45,8.54
17.35,8.79C18,9.5 18.38,10.39 18.38,11.5C18.38,15.32 16.04,16.16 13.81,
16.41C14.17,16.72 14.5,17.33 14.5,18.26C14.5,19.6 14.5,20.68 14.5,21C14.5,21.27
14.66,21.59 15.17,21.5C19.14,20.16 22,16.42 22,12A10,10 0 0,0 12,2Z"
/>
</svg>
</a>
</li>
<li className="mdl-mini-footer--social-btn" style={{ backgroundColor: 'transparent' }}>
<a href="https://twitter.com/XXatTechConfs" role="button" title="Twitter">
<svg width="36" height="36" viewBox="0 0 24 24">
<path
fill="#fff" d="M17.71,9.33C18.19,8.93 18.75,8.45 19,7.92C18.59,8.13 18.1,8.26
17.56,8.33C18.06,7.97 18.47,7.5 18.68,6.86C18.16,7.14 17.63,7.38 16.97,
7.5C15.42,5.63 11.71,7.15 12.37,9.95C9.76,9.79 8.17,8.61 6.85,7.16C6.1,8.38
6.75,10.23 7.64,10.74C7.18,10.71 6.83,10.57 6.5,10.41C6.54,11.95 7.39,12.69
8.58,13.09C8.22,13.16 7.82,13.18 7.44,13.12C7.81,14.19 8.58,14.86 9.9,15C9,15.76
7.34,16.29 6,16.08C7.15,16.81 8.46,17.39 10.28,17.31C14.69,17.11 17.64,13.95
17.71,9.33M12,2A10,10 0 0,1 22,12A10,10 0 0,1 12,22A10,10 0 0,1 2,12A10,10 0 0,1
12,2Z"
/>
</svg>
</a>
</li>
</ul>
</div>
</footer>
);
}
export default Footer;
| andeemarks/conf-gen-div-react | components/Footer/Footer.js | JavaScript | mit | 2,845 |
var expect = require('expect.js');
var path = require('path');
var fs = require('../../../lib/util/fs');
var path = require('path');
var rimraf = require('../../../lib/util/rimraf');
var Logger = require('bower-logger');
var cmd = require('../../../lib/util/cmd');
var copy = require('../../../lib/util/copy');
var GitFsResolver = require('../../../lib/core/resolvers/GitFsResolver');
var defaultConfig = require('../../../lib/config');
describe('GitFsResolver', function() {
var tempSource;
var testPackage = path.resolve(__dirname, '../../assets/package-a');
var logger;
before(function() {
logger = new Logger();
});
afterEach(function(next) {
logger.removeAllListeners();
if (tempSource) {
rimraf(tempSource, next);
tempSource = null;
} else {
next();
}
});
function clearResolverRuntimeCache() {
GitFsResolver.clearRuntimeCache();
}
function create(decEndpoint) {
if (typeof decEndpoint === 'string') {
decEndpoint = { source: decEndpoint };
}
return new GitFsResolver(decEndpoint, defaultConfig(), logger);
}
describe('.constructor', function() {
it('should guess the name from the path', function() {
var resolver = create(testPackage);
expect(resolver.getName()).to.equal('package-a');
});
it('should not guess the name from the path if the name was specified', function() {
var resolver = create({ source: testPackage, name: 'foo' });
expect(resolver.getName()).to.equal('foo');
});
it('should make paths absolute and normalized', function() {
var resolver;
resolver = create(path.relative(process.cwd(), testPackage));
expect(resolver.getSource()).to.equal(testPackage);
resolver = create(testPackage + '/something/..');
expect(resolver.getSource()).to.equal(testPackage);
});
it.skip('should use config.cwd for resolving relative paths');
});
describe('.resolve', function() {
it('should checkout correctly if resolution is a branch', function(next) {
var resolver = create({
source: testPackage,
target: 'some-branch'
});
resolver
.resolve()
.then(function(dir) {
expect(dir).to.be.a('string');
var files = fs.readdirSync(dir);
var fooContents;
expect(files).to.contain('foo');
expect(files).to.contain('baz');
expect(files).to.contain('baz');
fooContents = fs
.readFileSync(path.join(dir, 'foo'))
.toString();
expect(fooContents).to.equal('foo foo');
next();
})
.done();
});
it('should checkout correctly if resolution is a tag', function(next) {
var resolver = create({ source: testPackage, target: '~0.0.1' });
resolver
.resolve()
.then(function(dir) {
expect(dir).to.be.a('string');
var files = fs.readdirSync(dir);
expect(files).to.contain('foo');
expect(files).to.contain('bar');
expect(files).to.not.contain('baz');
next();
})
.done();
});
it('should checkout correctly if resolution is a commit', function(next) {
var resolver = create({
source: testPackage,
target: 'bdf51ece75e20cf404e49286727b7e92d33e9ad0'
});
resolver
.resolve()
.then(function(dir) {
expect(dir).to.be.a('string');
var files = fs.readdirSync(dir);
expect(files).to.not.contain('foo');
expect(files).to.not.contain('bar');
expect(files).to.not.contain('baz');
expect(files).to.contain('.master');
next();
})
.done();
});
it('should remove any untracked files and directories', function(next) {
var resolver = create({
source: testPackage,
target: 'bdf51ece75e20cf404e49286727b7e92d33e9ad0'
});
var file = path.join(testPackage, 'new-file');
var dir = path.join(testPackage, 'new-dir');
fs.writeFileSync(file, 'foo');
fs.mkdirSync(dir);
function cleanup(err) {
fs.unlinkSync(file);
fs.rmdirSync(dir);
if (err) {
throw err;
}
}
resolver
.resolve()
.then(function(dir) {
expect(dir).to.be.a('string');
var files = fs.readdirSync(dir);
expect(files).to.not.contain('new-file');
expect(files).to.not.contain('new-dir');
cleanup();
next();
})
.fail(cleanup)
.done();
});
it('should leave the original repository untouched', function(next) {
// Switch to master
cmd('git', ['checkout', 'master'], { cwd: testPackage })
// Resolve to some-branch
.then(function() {
var resolver = create({
source: testPackage,
target: 'some-branch'
});
return resolver.resolve();
})
// Check if the original branch is still the master one
.then(function() {
return cmd('git', ['branch', '--color=never'], {
cwd: testPackage
}).spread(function(stdout) {
expect(stdout).to.contain('* master');
});
})
// Check if git status is empty
.then(function() {
return cmd('git', ['status', '--porcelain'], {
cwd: testPackage
}).spread(function(stdout) {
stdout = stdout.trim();
expect(stdout).to.equal('');
next();
});
})
.done();
});
it('should copy source folder permissions', function(next) {
var mode0777;
var resolver;
tempSource = path.resolve(__dirname, '../../assets/package-a-copy');
resolver = create({ source: tempSource, target: 'some-branch' });
copy.copyDir(testPackage, tempSource)
.then(function() {
// Change tempSource dir to 0777
fs.chmodSync(tempSource, 0777);
// Get the mode to a variable
mode0777 = fs.statSync(tempSource).mode;
})
.then(resolver.resolve.bind(resolver))
.then(function(dir) {
// Check if temporary dir is 0777 instead of default 0777 & ~process.umask()
var stat = fs.statSync(dir);
expect(stat.mode).to.equal(mode0777);
next();
})
.done();
});
});
describe('#refs', function() {
afterEach(clearResolverRuntimeCache);
it('should resolve to the references of the local repository', function(next) {
GitFsResolver.refs(testPackage)
.then(function(refs) {
// Remove master and test only for the first 7 refs
refs = refs.slice(1, 8);
expect(refs).to.eql([
'e4655d250f2a3f64ef2d712f25dafa60652bb93e refs/heads/some-branch',
'0a7daf646d4fd743b6ef701d63bdbe20eee422de refs/tags/0.0.1',
'0791865e6f4b88f69fc35167a09a6f0626627765 refs/tags/0.0.2',
'2af02ac6ddeaac1c2f4bead8d6287ce54269c039 refs/tags/0.1.0',
'6ab264f1ba5bafa80fb0198183493e4d5b20804a refs/tags/0.1.1',
'c91ed7facbb695510e3e1ab86bac8b5ac159f4f3 refs/tags/0.2.0',
'8556e55c65722a351ca5fdce4f1ebe83ec3f2365 refs/tags/0.2.1'
]);
next();
})
.done();
});
it('should cache the results', function(next) {
GitFsResolver.refs(testPackage)
.then(function() {
// Manipulate the cache and check if it resolves for the cached ones
GitFsResolver._cache.refs.get(testPackage).splice(0, 1);
// Check if it resolver to the same array
return GitFsResolver.refs(testPackage);
})
.then(function(refs) {
// Test only for the first 6 refs
refs = refs.slice(0, 7);
expect(refs).to.eql([
'e4655d250f2a3f64ef2d712f25dafa60652bb93e refs/heads/some-branch',
'0a7daf646d4fd743b6ef701d63bdbe20eee422de refs/tags/0.0.1',
'0791865e6f4b88f69fc35167a09a6f0626627765 refs/tags/0.0.2',
'2af02ac6ddeaac1c2f4bead8d6287ce54269c039 refs/tags/0.1.0',
'6ab264f1ba5bafa80fb0198183493e4d5b20804a refs/tags/0.1.1',
'c91ed7facbb695510e3e1ab86bac8b5ac159f4f3 refs/tags/0.2.0',
'8556e55c65722a351ca5fdce4f1ebe83ec3f2365 refs/tags/0.2.1'
]);
next();
})
.done();
});
});
});
| bower/bower | test/core/resolvers/gitFsResolver.js | JavaScript | mit | 10,216 |
var gtest_internal__8h_8js =
[
[ "gtest_internal_8h", "gtest-internal__8h_8js.html#aeab4ea100449ddbdc209043769290de4", null ]
]; | bhargavipatel/808X_VO | docs/html/gtest-internal__8h_8js.js | JavaScript | mit | 132 |
import ContentScript from './ContentScript';
import Messenger from './Messenger';
import DocumentScanner from './DocumentScanner';
import Highlighter from './Highlighter';
import TooltipsterWrapper from './TooltipsterWrapper';
// console.log('entering content index.js');
const messenger = new Messenger(chrome);
const documentScanner = new DocumentScanner(document);
const highlighter = new Highlighter();
const tooltipsterWrapper = new TooltipsterWrapper();
const contentScript = new ContentScript(
messenger,
documentScanner,
highlighter,
tooltipsterWrapper
);
contentScript.runInTab(document);
// console.log('exiting content index.js')
| getcahoots/extension | src/content/index.js | JavaScript | mit | 660 |
'use strict'
var test = require('tape')
var component = require('./')
test('component directive', function (t) {
var ddo = component.directive()
t.plan(6)
t.equal('function', typeof component.directive, 'directive is of type function')
t.equal('object', typeof ddo, 'directive function returns object')
t.equal('object', typeof ddo.scope, 'directive has isolate scope')
t.ok(ddo.controller, 'directive has controller')
t.ok(ddo.controllerAs, 'directive has controllerAs')
t.ok(ddo.template, 'directive has template')
})
test('component controller', function (t) {
var ctrl = component.controller
t.plan(1)
t.equal('function', typeof component.directive, 'controller is of type function')
})
| excellenteasy/boilerplate-angular-component | test.js | JavaScript | mit | 715 |
function SystemUser(){
this.login = "";
this.password = "";
this.firstName = "";
this.lastName = "";
this.nickname = "";
this.linkedin = "";
this.twitter = "";
this.clientIdGoogle = "";
this.tags = [];
this.items = [];
this.avatar = {};
}
| RafaelBruno/todoQuest | TodoQuestClient/app/src/models/user.js | JavaScript | mit | 261 |
// Note: See http://blog.garstasio.com/you-dont-need-jquery/ and http://youmightnotneedjquery.com/ for JS commands that don't require jQuery
// $(document).ready( function() {
// $("span").click( function() {
// $(":nth-child(1)", this).css('display', 'block');
// $(":nth-child(2)", this).css('display', 'block');
// });
// $('.modal').click( function() {
// $(this).fadeOut("fast");
// $(this).css('display', 'none');
// });
// });
// $("#example-one").on("click", function() {
// var el = $(this);
// el.text() == el.data("text-swap")
// ? el.text(el.data("text-original"))
// : el.text(el.data("text-swap"));
// });
$(document).ready(function() {
// navigation click actions
$('.scroll-link').on('click', function(event){
event.preventDefault();
var sectionID = $(this).attr("data-id");
scrollToID('#' + sectionID, 750);
});
// scroll to top action
$('.scroll-top').on('click', function(event) {
event.preventDefault();
$('html, body').animate({scrollTop:0}, 'slow');
});
// mobile nav toggle
$('#nav-toggle').on('click', function (event) {
event.preventDefault();
$('#main-nav').toggleClass("open");
});
});
// scroll function
function scrollToID(id, speed){
var offSet = 50;
var targetOffset = $(id).offset().top - offSet;
var mainNav = $('#main-nav');
$('html,body').animate({scrollTop:targetOffset}, speed);
if (mainNav.hasClass("open")) {
mainNav.css("height", "1px").removeClass("in").addClass("collapse");
mainNav.removeClass("open");
}
}
if (typeof console === "undefined") {
console = {
log: function() { }
};
} | juliazxu/juliaxume | js/main.js | JavaScript | mit | 1,613 |
import React from 'react'
import AdminToolResponses from './AdminToolResponses'
import Layout from '../../components/Layout'
async function action({ path }) {
return {
chunks: ['adminToolResponses'],
title: 'Tool Responses',
path,
description: 'Tools responses',
component: (
<Layout path={path}>
<AdminToolResponses path={path} />
</Layout>
),
}
}
export default action
| goldylucks/adamgoldman.me | src/routes/adminToolResponses/index.js | JavaScript | mit | 423 |
import { Command } from '../Command.js';
/**
* @param editor Editor
* @param object THREE.Object3D
* @param script javascript object
* @constructor
*/
function AddScriptCommand( editor, object, script ) {
Command.call( this, editor );
this.type = 'AddScriptCommand';
this.name = 'Add Script';
this.object = object;
this.script = script;
}
AddScriptCommand.prototype = {
execute: function () {
if ( this.editor.scripts[ this.object.uuid ] === undefined ) {
this.editor.scripts[ this.object.uuid ] = [];
}
this.editor.scripts[ this.object.uuid ].push( this.script );
this.editor.signals.scriptAdded.dispatch( this.script );
},
undo: function () {
if ( this.editor.scripts[ this.object.uuid ] === undefined ) return;
var index = this.editor.scripts[ this.object.uuid ].indexOf( this.script );
if ( index !== - 1 ) {
this.editor.scripts[ this.object.uuid ].splice( index, 1 );
}
this.editor.signals.scriptRemoved.dispatch( this.script );
},
toJSON: function () {
var output = Command.prototype.toJSON.call( this );
output.objectUuid = this.object.uuid;
output.script = this.script;
return output;
},
fromJSON: function ( json ) {
Command.prototype.fromJSON.call( this, json );
this.script = json.script;
this.object = this.editor.objectByUuid( json.objectUuid );
}
};
export { AddScriptCommand };
| fraguada/three.js | editor/js/commands/AddScriptCommand.js | JavaScript | mit | 1,381 |
String.prototype.strip = function() {
return String(this).replace(/\s/g, '');
};
exports.generateSessionId = function () {
var characters = '012345abcdefghijklmnopqrstuvwxyz',
sessionId = '';
for (var count = 0; count < 24; count++) {
sessionId += characters.charAt(Math.floor(
Math.random() * characters.length));;
}
return sessionId;
};
exports.parseArchives = function ($table) {
var archives = {};
$table.find('tr').each(function (i) {
var td = $table.find('tr').eq(i).find('td');
for (var i = 0; i < td.length; i += 2) {
var key = td.eq(i).text().strip(),
value = td.eq(i + 1).text().strip();
if (key && value) {
archives[key] = value;
}
}
});
return archives;
};
| xshwz/node-kingo | lib/utils.js | JavaScript | mit | 758 |
var assert = require('assert');
var swf = require('../index');
var ActivityPoller = swf.ActivityPoller;
var pollForActivityTaskCallCount = 0;
var swfClientMock = {
pollForActivityTask: function(p, cb) {
pollForActivityTaskCallCount += 1;
setTimeout(function() {
cb(null, {
taskToken: (pollForActivityTaskCallCount == 2) ? '12345' : undefined
});
}, 10);
}
};
var nullLogger = { info: function() {} };
describe('ActivityPoller', function(){
it('should check domain and taskList', function() {
var error_raised = false;
try {
var activityPoller = new ActivityPoller({
}, swfClientMock);
}
catch(ex) {
error_raised = true;
}
assert.equal(true, error_raised);
});
it('should start, emit ActivityTask, and stop', function(done) {
var activityPoller = new ActivityPoller({
domain: 'test-domain',
taskList: {
name: 'test-taskList'
},
logger: nullLogger
}, swfClientMock);
activityPoller.on('activityTask', function(activityTask) {
activityPoller.stop();
done();
});
activityPoller.start();
});
it('should insntaiate without swfClient', function() {
var activityPoller = new ActivityPoller({
domain: 'test-domain',
taskList: {
name: 'test-taskList'
}
});
});
});
| neyric/aws-swf | test/test_ActivityPoller.js | JavaScript | mit | 1,470 |
var myApp = angular.module('myApp', ['infinite-scroll'])
.config( [
'$compileProvider',
function( $compileProvider )
{
$compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|ftp|mailto|chrome-extension|magnet):/);
// Angular before v1.2 uses $compileProvider.urlSanitizationWhitelist(...)
}
]);
myApp.controller('DemoController', function($scope, Playflix) {
$scope.playflix = new Playflix();
});
// Playflix constructor function to encapsulate HTTP and pagination logic
myApp.factory('Playflix', function($http) {
var page = 1;
var Playflix = function() {
this.items = [];
this.busy = false;
};
Playflix.prototype.nextPage = function() {
if (this.busy) return;
this.busy = true;
$http.get("https://yts.ag/api/v2/list_movies.jsonp?sort_by=year&quality=720p&limit=24&page="+page).success(function(data) {
var items = data.data.movies;
var i = 0;
for (var i = 0; i < items.length; i++) {
this.items.push(items[i]);
}
this.busy = false;
}.bind(this));
page = page + 1;
};
return Playflix;
}); | hydraflix-dev/hydraflix-dev.github.io | playflix-v3/js/app.js | JavaScript | mit | 1,143 |
/**
* This module monitors angularFire's authentication and performs actions based on authentication state.
*
* See usage examples here: https://gist.github.com/katowulf/7328023
*/
angular.module('waitForAuth', [])
/**
* A service that returns a promise object, which is resolved once $firebaseSimpleLogin
* is initialized (i.e. it returns login, logout, or error)
*/
.service('waitForAuth', function($rootScope, $q, $timeout) {
var def = $q.defer(), subs = [];
subs.push($rootScope.$on('$firebaseSimpleLogin:login', fn));
subs.push($rootScope.$on('$firebaseSimpleLogin:logout', fn));
subs.push($rootScope.$on('$firebaseSimpleLogin:error', fn));
function fn(err) {
if( $rootScope.auth ) {
$rootScope.auth.error = err instanceof Error? err.toString() : null;
}
for(var i=0; i < subs.length; i++) { subs[i](); }
$timeout(function() {
// force $scope.$apply to be re-run after login resolves
def.resolve();
});
}
return def.promise;
})
/**
* A directive that hides the element from view until waitForAuth resolves
*/
.directive('ngCloakAuth', function(waitForAuth) {
return {
restrict: 'A',
compile: function(el) {
el.addClass('hide');
waitForAuth.then(function() {
el.removeClass('hide');
})
}
}
})
/**
* A directive that shows elements only when the given authentication state is in effect
*/
.directive('ngShowAuth', function($rootScope) {
var loginState;
var loginRole;
$rootScope.$on("$firebaseSimpleLogin:login", function() { loginState = 'login' });
$rootScope.$on("$firebaseSimpleLogin:logout", function() { loginState = 'logout' });
$rootScope.$on("$firebaseSimpleLogin:error", function() { loginState = 'error' });
function inList(needle, list) {
var res = false;
angular.forEach(list, function(x) {
if( x === needle ) {
res = true;
return true;
}
return false;
});
return res;
}
function assertValidState(state) {
if( !state ) {
throw new Error('ng-show-auth directive must be login, logout, or error (you may use a comma-separated list)');
}
var states = (state||'').split(',');
angular.forEach(states, function(s) {
if( !inList(s, ['login', 'logout', 'error']) ) {
throw new Error('Invalid state "'+s+'" for ng-show-auth directive, must be one of login, logout, or error');
}
});
return true;
}
return {
restrict: 'A',
compile: function(el, attr) {
assertValidState(attr.ngShowAuth);
var expState = (attr.ngShowAuth||'').split(',');
function fn(newState) {
loginState = newState;
var hide = !inList(newState, expState);
if('role' in attr)
{
hide = (loginRole !== attr.role)
}
el.toggleClass('hide', hide );
}
fn(loginState);
$rootScope.$on("$firebaseSimpleLogin:login", function() { fn('login') });
$rootScope.$on("$firebaseSimpleLogin:logout", function() { fn('logout') });
$rootScope.$on("$firebaseSimpleLogin:error", function() { fn('error') });
$rootScope.$on("loginService:role", function(event, role) {
loginRole = role;
fn(loginState);
});
}
}
}); | anandthakker/yawpcow | src/common/waitForAuth/waitForAuth.js | JavaScript | mit | 3,675 |
// Get WebApiClient core
var WebApiClient = require("./WebApiClient.Core.js");
/* @preserve
* The Bluebird license is included below as Terser keeps removing it (https://github.com/terser/terser/issues/575)
*/
/* @preserve
* The MIT License (MIT)
*
* Copyright (c) 2013-2018 Petka Antonov
*
* 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.
*
*/
/**
* This is the bundled version of bluebird for usage as polyfill in browsers that don't support promises natively
* @class
* @see https://github.com/petkaantonov/bluebird
* @memberof module:WebApiClient
* @alias WebApiClient.Promise
*/
WebApiClient.Promise = require("bluebird").noConflict();
// Attach requests to core
WebApiClient.Requests = require("./WebApiClient.Requests.js");
// Attach batch to core
WebApiClient.Batch = require("./WebApiClient.Batch.js");
// Attach changeSet to core
WebApiClient.ChangeSet = require("./WebApiClient.ChangeSet.js");
// Attach batchRequest to core
WebApiClient.BatchRequest = require("./WebApiClient.BatchRequest.js");
// Attach batchResponse to core
WebApiClient.BatchResponse = require("./WebApiClient.BatchResponse.js");
// Attach response to core
WebApiClient.Response = require("./WebApiClient.Response.js");
// Export complete WebApiClient
module.exports = WebApiClient; | DigitalFlow/Xrm-WebApi-Client | src/js/WebApiClient.js | JavaScript | mit | 2,316 |
'use strict';
module.exports = function(app) {
var users = require('../../app/controllers/users.server.controller');
var allowanceEntries = require('../../app/controllers/allowance-entries.server.controller');
// Allowance entries Routes
app.route('/allowance-entries')
.get(allowanceEntries.list)
.post(users.requiresLogin, allowanceEntries.create);
app.route('/allowance-entries/:allowanceEntryId')
.get(allowanceEntries.read)
.put(users.requiresLogin, allowanceEntries.hasAuthorization, allowanceEntries.update)
.delete(users.requiresLogin, allowanceEntries.hasAuthorization, allowanceEntries.delete);
// Finish by binding the Allowance entry middleware
app.param('allowanceEntryId', allowanceEntries.allowanceEntryByID);
};
| niranjan21/skt | app/routes/allowance-entries.server.routes.js | JavaScript | mit | 749 |
// Page.js (c) 2012 Loren West and other contributors
// May be freely distributed under the MIT license.
// For further details and documentation:
// http://lorenwest.github.com/node_monitor
(function(root){
// Module loading
var Monitor = root.Monitor || require('monitor'),
UI = Monitor.UI,
Component = UI.Component,
Backbone = Monitor.Backbone, _ = Monitor._;
/**
* A page on the node_monitor site
*
* All pages on the node_monitor site are dynamically defined, and represented
* by an instance of this class.
*
* @class Page
* @extends Backbone.Model
* @constructor
* @param model - Initial data model. Can be a JS object or another Model.
* @param model.id {String} The page url within the site
* @param [model.title] {String} The page title
* @param [model.description] {String} Description of the page
* @param [model.notes] {String} Page notes
* @param model.onInit {String} - JavaScript to run when the Page model and PageView have been initialized and rendered.
* The JS has access to two local variables: pageModel and pageView.
* @param [model.css] {Object} - Key/value map of CSS selector to CSS overrides to apply to the entire page
* @param [model.components] {Component.List} - List of components on the page
*/
var Page = UI.Page = Backbone.Model.extend({
defaults: {
id:'',
title:'',
description:'',
notes:'',
onInit:'',
css:{},
components:[]
},
sync: new Monitor.Sync('Page'),
initialize: function(params, options) {
var t = this;
UI.containedModel(t, 'components', Component.List);
},
/**
* Add a new component to the Page model by component class
*
* This uses the default component attributes
*
* @method addComponent
* @param viewClass - Class name for the main view in the component
* @return component - The newly instantiated component
*/
addComponent: function(viewClass) {
var t = this,
newIdNum = 1,
components = t.get('components'),
classParts = viewClass.split('.'),
appName = classParts[0],
appView = classParts[1];
// Instantiate and add the component
var component = new Component({
id: Monitor.generateUniqueCollectionId(components, 'c'),
viewClass: viewClass,
viewOptions: UI.app[appName][appView].prototype.defaultOptions,
css: {
'.nm-cv': 'top:10px;'
}
});
components.add(component);
return component;
},
// Overridden to override some options
toJSON: function(options) {
var t = this,
opts = _.extend({trim:true, deep:true}, options),
raw = Backbone.Model.prototype.toJSON.call(t, opts);
return raw;
}
});
/**
* Constructor for a list of Page objects
*
* var myList = new Page.List(initialElements);
*
* @static
* @method List
* @param [items] {Array} Initial list items. These can be raw JS objects or Page data model objects.
* @return {Backbone.Collection} Collection of Page data model objects
*/
Page.List = Backbone.Collection.extend({model: Page});
}(this));
| chiehwen/node_monitor | lib/js/Page.js | JavaScript | mit | 3,240 |
import { ChartInternal } from './core';
import { isValue, isUndefined, isDefined, notEmpty, isArray } from './util';
ChartInternal.prototype.convertUrlToData = function (url, mimeType, headers, keys, done) {
var $$ = this, type = mimeType ? mimeType : 'csv', f, converter;
if (type === 'json') {
f = $$.d3.json;
converter = $$.convertJsonToData;
} else if (type === 'tsv') {
f = $$.d3.tsv;
converter = $$.convertXsvToData;
} else {
f = $$.d3.csv;
converter = $$.convertXsvToData;
}
f(url, headers).then(function (data) {
done.call($$, converter.call($$, data, keys));
}).catch(function (error) {
throw error;
});
};
ChartInternal.prototype.convertXsvToData = function (xsv) {
var keys = xsv.columns, rows = xsv;
if (rows.length === 0) {
return { keys, rows: [ keys.reduce((row, key) => Object.assign(row, { [key]: null }), {}) ] };
} else {
// [].concat() is to convert result into a plain array otherwise
// test is not happy because rows have properties.
return { keys, rows: [].concat(xsv) };
}
};
ChartInternal.prototype.convertJsonToData = function (json, keys) {
var $$ = this,
new_rows = [], targetKeys, data;
if (keys) { // when keys specified, json would be an array that includes objects
if (keys.x) {
targetKeys = keys.value.concat(keys.x);
$$.config.data_x = keys.x;
} else {
targetKeys = keys.value;
}
new_rows.push(targetKeys);
json.forEach(function (o) {
var new_row = [];
targetKeys.forEach(function (key) {
// convert undefined to null because undefined data will be removed in convertDataToTargets()
var v = $$.findValueInJson(o, key);
if (isUndefined(v)) {
v = null;
}
new_row.push(v);
});
new_rows.push(new_row);
});
data = $$.convertRowsToData(new_rows);
} else {
Object.keys(json).forEach(function (key) {
new_rows.push([key].concat(json[key]));
});
data = $$.convertColumnsToData(new_rows);
}
return data;
};
ChartInternal.prototype.findValueInJson = function (object, path) {
path = path.replace(/\[(\w+)\]/g, '.$1'); // convert indexes to properties (replace [] with .)
path = path.replace(/^\./, ''); // strip a leading dot
var pathArray = path.split('.');
for (var i = 0; i < pathArray.length; ++i) {
var k = pathArray[i];
if (k in object) {
object = object[k];
} else {
return;
}
}
return object;
};
/**
* Converts the rows to normalized data.
* @param {any[][]} rows The row data
* @return {Object}
*/
ChartInternal.prototype.convertRowsToData = (rows) => {
const newRows = [];
const keys = rows[0];
for (let i = 1; i < rows.length; i++) {
const newRow = {};
for (let j = 0; j < rows[i].length; j++) {
if (isUndefined(rows[i][j])) {
throw new Error("Source data is missing a component at (" + i + "," + j + ")!");
}
newRow[keys[j]] = rows[i][j];
}
newRows.push(newRow);
}
return { keys, rows: newRows };
};
/**
* Converts the columns to normalized data.
* @param {any[][]} columns The column data
* @return {Object}
*/
ChartInternal.prototype.convertColumnsToData = (columns) => {
const newRows = [];
const keys = [];
for (let i = 0; i < columns.length; i++) {
const key = columns[i][0];
for (let j = 1; j < columns[i].length; j++) {
if (isUndefined(newRows[j - 1])) {
newRows[j - 1] = {};
}
if (isUndefined(columns[i][j])) {
throw new Error("Source data is missing a component at (" + i + "," + j + ")!");
}
newRows[j - 1][key] = columns[i][j];
}
keys.push(key);
}
return { keys, rows: newRows };
};
/**
* Converts the data format into the target format.
* @param {!Object} data
* @param {!Array} data.keys Ordered list of target IDs.
* @param {!Array} data.rows Rows of data to convert.
* @param {boolean} appendXs True to append to $$.data.xs, False to replace.
* @return {!Array}
*/
ChartInternal.prototype.convertDataToTargets = function (data, appendXs) {
var $$ = this, config = $$.config, targets, ids, xs, keys, epochs;
// handles format where keys are not orderly provided
if (isArray(data)) {
keys = Object.keys(data[ 0 ]);
} else {
keys = data.keys;
data = data.rows;
}
xs = keys.filter($$.isX, $$);
if(!$$.isStanfordGraphType()) {
ids = keys.filter($$.isNotX, $$);
} else {
epochs = keys.filter($$.isEpochs, $$);
ids = keys.filter($$.isNotXAndNotEpochs, $$);
if(xs.length !== 1 || epochs.length !== 1 || ids.length !== 1) {
throw new Error('You must define the \'x\' key name and the \'epochs\' for Stanford Diagrams');
}
}
// save x for update data by load when custom x and c3.x API
ids.forEach(function (id) {
var xKey = $$.getXKey(id);
if ($$.isCustomX() || $$.isTimeSeries()) {
// if included in input data
if (xs.indexOf(xKey) >= 0) {
$$.data.xs[id] = (appendXs && $$.data.xs[id] ? $$.data.xs[id] : []).concat(
data.map(function (d) { return d[xKey]; })
.filter(isValue)
.map(function (rawX, i) { return $$.generateTargetX(rawX, id, i); })
);
}
// if not included in input data, find from preloaded data of other id's x
else if (config.data_x) {
$$.data.xs[id] = $$.getOtherTargetXs();
}
// if not included in input data, find from preloaded data
else if (notEmpty(config.data_xs)) {
$$.data.xs[id] = $$.getXValuesOfXKey(xKey, $$.data.targets);
}
// MEMO: if no x included, use same x of current will be used
} else {
$$.data.xs[id] = data.map(function (d, i) { return i; });
}
});
// check x is defined
ids.forEach(function (id) {
if (!$$.data.xs[id]) {
throw new Error('x is not defined for id = "' + id + '".');
}
});
// convert to target
targets = ids.map(function (id, index) {
var convertedId = config.data_idConverter(id);
return {
id: convertedId,
id_org: id,
values: data.map(function (d, i) {
var xKey = $$.getXKey(id), rawX = d[xKey],
value = d[id] !== null && !isNaN(d[id]) ? +d[id] : null, x, returnData;
// use x as categories if custom x and categorized
if ($$.isCustomX() && $$.isCategorized() && !isUndefined(rawX)) {
if (index === 0 && i === 0) {
config.axis_x_categories = [];
}
x = config.axis_x_categories.indexOf(rawX);
if (x === -1) {
x = config.axis_x_categories.length;
config.axis_x_categories.push(rawX);
}
} else {
x = $$.generateTargetX(rawX, id, i);
}
// mark as x = undefined if value is undefined and filter to remove after mapped
if (isUndefined(d[id]) || $$.data.xs[id].length <= i) {
x = undefined;
}
returnData = {x: x, value: value, id: convertedId};
if($$.isStanfordGraphType()) {
returnData.epochs = d[epochs];
}
return returnData;
}).filter(function (v) { return isDefined(v.x); })
};
});
// finish targets
targets.forEach(function (t) {
var i;
// sort values by its x
if (config.data_xSort) {
t.values = t.values.sort(function (v1, v2) {
var x1 = v1.x || v1.x === 0 ? v1.x : Infinity,
x2 = v2.x || v2.x === 0 ? v2.x : Infinity;
return x1 - x2;
});
}
// indexing each value
i = 0;
t.values.forEach(function (v) {
v.index = i++;
});
// this needs to be sorted because its index and value.index is identical
$$.data.xs[t.id].sort(function (v1, v2) {
return v1 - v2;
});
});
// cache information about values
$$.hasNegativeValue = $$.hasNegativeValueInTargets(targets);
$$.hasPositiveValue = $$.hasPositiveValueInTargets(targets);
// set target types
if (config.data_type) {
$$.setTargetType($$.mapToIds(targets).filter(function (id) { return ! (id in config.data_types); }), config.data_type);
}
// cache as original id keyed
targets.forEach(function (d) {
$$.addCache(d.id_org, d);
});
return targets;
};
| TeamSPoon/logicmoo_workspace | packs_web/swish/web/node_modules/c3/src/data.convert.js | JavaScript | mit | 9,263 |
/* Gorgias
* demo
*/
var gorgiasDemo = (function () {
var KEY_TAB = 9;
var KEY_UP = 38;
var KEY_DOWN = 40;
var KEY_ENTER = 13;
var KEY_SPACE = 32;
var KEY_ESC = 27;
var $editor;
var $container;
var $focusNode;
var quicktexts = [
{
shortcut: 'h',
title: 'Say Hello',
body: "Hello <span class='h'>Gorgias Team</span>,<br><br><br>"
},
/*{
shortcut: 'nice',
title: 'Nice talking',
body: 'It was nice talking to you!'
},*/
{
shortcut: 'use',
title: 'Glad to use Gorgias',
body: "I'm glad to use Gorgias for the first time. Keyboard completion is great!"
},
{
shortcut: 'kr',
title: 'Kind regards,',
body: 'Kind Regards, <br>Me'
}
];
var getQuicktext = function (shortcut) {
var q;
shortcut = shortcut.toLowerCase();
// find quicktext by shortcut
quicktexts.some(function (quicktext) {
if (quicktext.shortcut === shortcut) {
q = quicktext;
return true;
}
return false;
});
return q;
};
var filterQuicktexts = function (word) {
var add;
var filtered = [];
quicktexts.forEach(function (qt) {
add = false;
if (qt.shortcut.indexOf(word) !== -1) {
add = true;
}
if (!add && qt.title.indexOf(word) !== -1) {
add = true;
}
if (!add && qt.body.indexOf(word) !== -1) {
add = true;
}
if (add === true) {
filtered.push(qt);
}
});
return filtered;
};
var getCursorPosition = function (e, params) {
params = params || {};
var position = {
element: e && e.target ? e.target : null,
offset: 0,
absolute: {
left: 0,
top: 0
},
word: null
};
var getRanges = function (sel) {
if (sel.rangeCount) {
var ranges = [];
for (var i = 0; i < sel.rangeCount; i++) {
ranges.push(sel.getRangeAt(i));
}
return ranges;
}
return [];
};
var restoreRanges = function (sel, ranges) {
for (var i in ranges) {
sel.addRange(ranges[i]);
}
};
// Working with editable div
// Insert a virtual cursor, find its position
// http://stackoverflow.com/questions/16580841/insert-text-at-caret-in-contenteditable-div
var selection = window.getSelection();
// get the element that we are focused + plus the offset
// Read more about this here: https://developer.mozilla.org/en-US/docs/Web/API/Selection.focusNode
position.element = params.focusNode || selection.focusNode;
position.offset = selection.focusOffset;
if (typeof params.focusOffset !== 'undefined') {
position.offset = params.focusOffset;
}
// First we get all ranges (most likely just 1 range)
var ranges = getRanges(selection);
if (!ranges.length) {
Raven.captureMessage('A selection without any ranges!');
return;
}
// remove any previous ranges
selection.removeAllRanges();
// Added a new range to place the caret at the focus point of the cursor
var range = new Range();
var caretText = '<span id="gdemo-caret"></span>';
range.setStart(position.element, position.offset);
range.setEnd(position.element, position.offset);
range.insertNode(range.createContextualFragment(caretText));
selection.addRange(range);
selection.removeAllRanges();
// finally we restore all the ranges that we had before
restoreRanges(selection, ranges);
// Virtual caret
var $caret = $('#gdemo-caret');
if ($caret.length) {
position.absolute = $caret.offset();
position.absolute.width = $caret.width();
position.absolute.height = $caret.height();
// Remove virtual caret
$caret.remove();
}
return position;
};
var getSelectedWord = function (params) {
var word = {
start: 0,
end: 0,
text: ''
};
var beforeSelection = "";
var selection = window.getSelection();
var focusNode = params.focusNode || selection.focusNode;
if (focusNode) {
switch (focusNode.nodeType) {
// In most cases, the focusNode property refers to a Text Node.
case (document.TEXT_NODE): // for text nodes it's easy. Just take the text and find the closest word
beforeSelection = focusNode.textContent;
break;
// However, in some cases it may refer to an Element Node
case (document.ELEMENT_NODE):
// In that case, the focusOffset property returns the index in the childNodes collection of the focus node where the selection ends.
beforeNode = focusNode.childNodes[selection.focusOffset];
if (beforeNode) {
beforeSelection = beforeNode.textContent;
}
break;
}
}
// Replace all with normal spaces
beforeSelection = beforeSelection.replace('\xa0', ' ').trim();
word.start = Math.max(beforeSelection.lastIndexOf(" "), beforeSelection.lastIndexOf("\n"), beforeSelection.lastIndexOf("<br>")) + 1;
word.text = beforeSelection.substr(word.start);
word.end = word.start + word.text.length;
return word;
};
var getData = function (params, callback) {
var data = {
from: [{
name: '',
first_name: '',
last_name: '',
email: ''
}],
to: [{
name: '',
first_name: '',
last_name: '',
email: ''
}],
cc: [{
name: '',
first_name: '',
last_name: '',
email: ''
}],
bcc: [{
name: '',
first_name: '',
last_name: '',
email: ''
}],
subject: ''
};
return callback(null, data);
};
var replaceWith = function (params) {
var replacement = '';
var word = params.word;
getData({
element: params.element
}, function (err, response) {
var parsedTemplate = params.quicktext.body;
var selection = window.getSelection();
var range = document.createRange();
replacement = parsedTemplate.replace(/\n/g, '<br>');
// setStart/setEnd work differently based on
// the type of node
// https://developer.mozilla.org/en-US/docs/Web/API/range.setStart
var focusNode = params.focusNode;
// we need to have a text node in the end
while (focusNode.nodeType === document.ELEMENT_NODE) {
if (focusNode.childNodes.length > 0) {
focusNode = focusNode.childNodes[selection.focusOffset]; // select a text node
} else {
// create an empty text node and attach it before the node
var tnode = document.createTextNode('');
focusNode.parentNode.insertBefore(tnode, focusNode);
focusNode = tnode;
}
}
// clear whitespace in the focused textnode
if (focusNode.nodeValue) {
focusNode.nodeValue = focusNode.nodeValue.trim();
}
// remove the shorcut text
range.setStart(focusNode, word.start);
range.setEnd(focusNode, word.end);
range.deleteContents();
var qtNode = range.createContextualFragment(replacement);
var lastQtChild = qtNode.lastChild;
range.insertNode(qtNode);
var caretRange = document.createRange();
caretRange.setStartAfter(lastQtChild);
caretRange.collapse(true);
selection.removeAllRanges();
selection.addRange(caretRange);
});
};
var triggerKey = function (e) {
if (e.keyCode === KEY_TAB) {
var element = e.target;
var focusNode = window.getSelection().focusNode;
var word = getSelectedWord({
focusNode: focusNode
});
var quicktext = getQuicktext(word.text);
if (quicktext) {
var params = {
element: element,
quicktext: quicktext,
focusNode: focusNode,
word: word
};
replaceWith(params);
$('body').trigger("template-inserted", params);
}
}
};
var dialogSelectItem = function (index) {
var content = $(contentSelector);
var $element = content.children().eq(index);
content.children()
.removeClass('active')
.eq(index);
$element.addClass('active');
};
var dialogPopulate = function (params) {
var quicktexts = filterQuicktexts(params.word.text);
// clone the elements
// so we can safely highlight the matched text
// without breaking the generated handlebars markup
var clonedElements = jQuery.extend(true, [], quicktexts);
// highlight found string in element title, body and shortcut
var searchRe = new RegExp(params.word.text, 'gi');
var highlightMatch = function (match) {
if (!params.word.text) {
return match;
}
return '<span class="gdemo-search-highlight">' + match + '</span>';
};
clonedElements.forEach(function (elem) {
elem.title = elem.title.replace(searchRe, highlightMatch);
elem.originalBody = elem.body;
elem.body = elem.body.replace(searchRe, highlightMatch);
elem.shortcut = elem.shortcut.replace(searchRe, highlightMatch);
});
$(contentSelector).empty();
clonedElements.forEach(function (elem) {
var body = elem.body.replace(/<br>/g, "\n");
$(contentSelector).append('<li class="gdemo-item active">' +
'<span class="gdemo-title">' + elem.title + '</span>' +
'<span class="gdemo-shortcut">' + elem.shortcut + '</span>' +
'<span class="gdemo-body">' + body + '</span>' +
'</li>');
});
/*
var content = Handlebars.compile(dialogLiTemplate)({
elements: clonedElements
});
$(contentSelector).html(content);
*/
// Set first element active
dialogSelectItem(0);
};
var dialogSelector = '.gdemo-dropdown';
var contentSelector = '.gdemo-dropdown-content';
var searchSelector = '.gdemo-dropdown-search';
var dialogChangeSelection = function (direction) {
var index_diff = direction === 'prev' ? -1 : 1,
content = $(contentSelector),
elements_count = content.children().length,
index_active = content.find('.active').index(),
index_new = Math.max(0, Math.min(elements_count - 1, index_active + index_diff));
dialogSelectItem(index_new);
};
var dialogCreate = function () {
// Create only once in the root of the document
var container = $('body');
// Add loading dropdown
var dialog = $(dialogSelector);
//HACK: set z-index to auto to a parent, otherwise the autocomplete
// dropdown will not be displayed with the correct stacking
dialog.parents('.qz').css('z-index', 'auto');
// Handle mouse hover and click
dialog.on('mouseover mousedown', 'li.gdemo-item', function (e) {
e.preventDefault();
e.stopPropagation();
dialogSelectItem($(this).index());
if (e.type === 'mousedown') {
dialogSelectActive();
}
});
dialog.on('keyup', searchSelector, function (e) {
e.preventDefault();
e.stopPropagation();
if (e.keyCode === KEY_UP) {
dialogChangeSelection('prev');
return;
}
if (e.keyCode === KEY_DOWN) {
dialogChangeSelection('next');
return;
}
if (e.keyCode === KEY_ENTER) {
dialogSelectActive();
dialogHide();
return;
}
if (e.keyCode === KEY_ESC) {
dialogHide();
return;
}
var text = $(this).val();
dialogPopulate({
word: {
text: text
}
});
});
};
var dialogSelectActive = function () {
var activeShortcut = $(contentSelector).find('.active .gdemo-shortcut').text();
var quicktext = getQuicktext(activeShortcut);
var word = getSelectedWord({
focusNode: $focusNode
});
if (typeof $focusNode !== 'undefined') {
var params = {
element: $editor,
quicktext: quicktext,
focusNode: $focusNode,
word: word
};
$($editor).append(quicktext.body);
$('body').trigger('dialog-used', params);
mixpanel.track("Tutorial Dialog Insert", {
shortcut: quicktext.shortcut
});
setTimeout(function(){
$('.gorgias-demo-hint>*').addClass('hidden');
$('.gorgias-demo-hint .new-template').removeClass('hidden').addClass('fadein');
$('.g-template-arrow').removeClass('hidden');
}, 1000);
}
};
var dialogShow = function (e, params) {
params = params || {};
e.preventDefault();
e.stopPropagation();
// make sure we have at least one space in the editor
// so we can use it as a textnode.
// otherwise, if the focusNode is the $editor
// the quicktext is appended before it in the dom, not in it.
if (!$editor.innerHTML) {
$editor.innerHTML = ' ';
}
var element = e.target;
var cursorPosition = getCursorPosition(e, params);
dialogPopulate({
word: {text: ''}
});
var topPos = $('.gorgias-demo-editor').offset().top;
var leftPos = $('.gorgias-demo-editor').offset().left + parseInt($('.gorgias-demo-editor').css('width'), 10) - parseInt($('.gdemo-dropdown').width(), 10);
$(dialogSelector).css({
top: topPos + 25 + 'px',
left: leftPos + 'px'
});
$(dialogSelector).addClass('gdemo-dropdown-show');
$(contentSelector).scrollTop();
// when manually triggering the dialog shortcut
// (not in animation frame)
if (!params.focusNode) {
$focusNode = window.getSelection().focusNode;
$(searchSelector).focus();
}
};
var dialogHide = function (e) {
$(dialogSelector).removeClass('gdemo-dropdown-show');
$(searchSelector).val('');
};
var isElementInViewport = function (el) {
//special bonus for those using jQuery
if (typeof jQuery === "function" && el instanceof jQuery) {
el = el[0];
}
var rect = el.getBoundingClientRect();
return (
rect.top >= 0 &&
rect.left >= 0 &&
rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
);
};
var animationStarted = false;
var visibilityChange = function () {
if (isElementInViewport($container) && !animationStarted) {
$($container).addClass('gorgias-demo-frame--' + name);
$(window).off('DOMContentLoaded load resize scroll', visibilityChange);
}
};
var preventShortcuts = function (e) {
// always prevent the default key action
// for a better experience.
// used just in the homepage demo, not in the extension.
if (e.keyCode === KEY_TAB) {
e.preventDefault();
e.stopImmediatePropagation();
}
};
var init = function () {
dialogCreate();
$editor = document.querySelector('.gorgias-demo-editor');
$container = document.querySelector('.gorgias-demo');
// only start the demo if we have the editor
if ($editor) {
$($editor).focus();
$($editor).on('keydown', triggerKey);
$editor.addEventListener('keyup', preventShortcuts, false);
$editor.addEventListener('keydown', preventShortcuts, false);
$editor.addEventListener('keypress', preventShortcuts, false);
// start the animation only when the container is in viewport
// so we don't miss it if we're scrolled,
// or get pushed back to top on focus().
$(window).on('DOMContentLoaded load resize scroll', visibilityChange);
}
$('body').on('template-inserted', function (e, params) {
mixpanel.track("Tutorial Shortcut", {
shortcut: params.quicktext.shortcut
});
if (params.quicktext.shortcut === 'h') {
$('.gorgias-editor-container .h').addClass('blink');
setTimeout(function () {
$('.gorgias-demo-hint>*').addClass('hidden');
$('.gorgias-demo-hint .use').removeClass('hidden').addClass('fadein');
}, 2000);
}
if (params.quicktext.shortcut === 'use') {
setTimeout(function () {
$('.gorgias-demo-hint>*').addClass('hidden');
$('.gorgias-demo-hint .search').removeClass('hidden').addClass('fadein');
$('.gorgias-qa-btn').css('visibility', 'visible');
}, 1000);
}
});
$('.gorgias-qa-btn').on('click', function(e){
mixpanel.track("Tutorial Button");
dialogShow(e);
setTimeout(function () {
$('.gorgias-demo-hint>*').addClass('hidden');
$('.gorgias-demo-hint .select').removeClass('hidden').addClass('fadein');
}, 1000);
});
// Removes 1st step and adds 2nd step
/*
$('body').on('dialog-used', function (e, params) {
mixpanel.track("Tutorial Dialog", {
shortcut: params.quicktext.shortcut
});
$('.gorgias-demo-hint .space').addClass('hidden');
$('.gorgias-demo-first-step-h2').addClass('hidden');
$('.browser-action').removeClass('hidden');
$('.gorgias-demo-last-step-h2').removeClass('hidden');
});
*/
};
return {
init: init
};
}());
| haveal/gorgias-chrome | src/background/js/utils/demo.js | JavaScript | mit | 19,903 |
/**
* values defined by fcs 3.1 standards
*/
module.exports = {
header:{
positions: {
title: [0, 5],
empty: [6, 9],
text: {
start: [10, 17],
end: [18, 25]
},
data: {
start: [26, 33],
end: [34, 41]
},
analysis: {
start: [42, 49],
end: [50, 57]
}
},
length: 58
}
};
| webduvet/fcsparser | config/standards.js | JavaScript | mit | 320 |
import { Platform, StyleSheet } from 'react-native'
const styles = StyleSheet.create({
mobileStyle: {
flex: 1,
},
switchOnStyle: {
...Platform.select({
android: {
elevation: 3,
},
}),
left: 160.0,
position: 'absolute',
shadowColor: 'rgba(0, 0, 0, 0.5)',
shadowOffset: {'height': 2, 'width': 0},
shadowOpacity: 1,
shadowRadius: 4,
top: 308.0,
},
})
export default styles
| ibhubs/sketch-components | tests/react_native_tests/test_data/native_code/Switch/app/components/Mobile/styles.js | JavaScript | mit | 442 |
/*
var mEvent = document.createEvent("MouseEvent");
mEvent.initMouseEvent("click", true, true, window, 0,
0, 0, 0, 0,
false, false, false, false,
0, null);
btn.dispatchEvent(mEvent);
* */
//on: ( function() {
// var docEl = document.documentElement;
// if (docEl.addEventListener) {
// return function(eventName, fn) {
// this.each(function(el) {
// el.addEventListener(eventName, fn, false);
// });
// };
// } else if (docEl.attachEvent) {
// return function(eventName, fn) {
// this.each(function(el) {
// el.attachEvent('on' + eventName, fn);
// });
// };
// } else {
// return function(eventName, fn) {
// this.each(function(el) {
// el['on' + eventName] = fn;
// });
// };
// }
//}() ),
//
//off: ( function() {
// var docEl = document.documentElement;
// if (docEl.removeEventListener) {
// return function(eventName, fn) {
// this.each(function(el) {
// el.removeEventListener(eventName, fn, false);
// });
// };
// } else if (docEl.detachEvent) {
// return function(eventName, fn) {
// this.each(function(el) {
// el.detachEvent('on' + eventName, fn);
// });
// };
// } else {
// return function(eventName) {
// this.each(function(el) {
// el['on' + eventName] = null;
// });
// };
// }
//}() ) | tomek-f/pln | test/src/js_back/_api.js | JavaScript | mit | 1,605 |
module.exports = {
input: ['src/app/**/*.{js,jsx,ts,tsx}', 'src/browsercheck.js'],
output: './',
options: {
debug: false,
removeUnusedKeys: true,
sort: true,
func: {
list: ['t', 'i18next.t', 'tl', 'DimError'],
extensions: ['.js', '.jsx', '.ts', '.tsx'],
},
lngs: ['en'],
ns: ['translation'],
defaultLng: 'en',
resource: {
loadPath: 'config/i18n.json',
savePath: 'src/locale/en.json',
jsonIndent: 2,
lineEnding: '\n',
},
context: true,
contextFallback: true,
contextDefaultValues: ['male', 'female'],
contextList: {
// contexts
compact: { list: ['compact'], fallback: false },
max: { list: ['Max'] },
// dynamic keys
buckets: {
list: ['General', 'Inventory', 'Postmaster', 'Progress', 'Unknown'],
fallback: false,
separator: false,
},
cooldowns: {
list: ['Grenade', 'Melee', 'Super'],
fallback: false,
separator: false,
},
difficulty: {
list: ['Normal', 'Hard'],
fallback: false,
separator: false,
},
minMax: {
list: ['Min', 'Max'],
fallback: false,
separator: false,
},
platforms: {
list: ['PlayStation', 'Stadia', 'Steam', 'Xbox'],
fallback: false,
separator: false,
},
progress: {
list: ['Bounties', 'Items', 'Quests'],
fallback: false,
separator: false,
},
sockets: {
list: [
'Mod',
'Ability',
'Shader',
'Ornament',
'Fragment',
'Aspect',
'Projection',
'Transmat',
'Super',
],
fallback: false,
separator: false,
},
},
},
};
| DestinyItemManager/DIM | i18next-scanner.config.js | JavaScript | mit | 1,804 |
H5.EntityServices = (function (Transition, changePath, changeCoords, Math) {
'use strict';
function duration(animation, duration) {
animation.duration = duration;
return animation;
}
function spacing(animation, spacing) {
animation.timingFn = spacing;
return animation;
}
function looping(animation, loop) {
animation.loop = loop;
return animation;
}
function callback(animation, callback, thisArg) {
animation.__callback = thisArg ? callback.bind(thisArg) : callback;
return animation;
}
function finish(animation) {
animation.duration = 0;
return animation;
}
function addServiceMethods(animation) {
animation.setDuration = duration.bind(undefined, animation);
animation.setSpacing = spacing.bind(undefined, animation);
animation.setLoop = looping.bind(undefined, animation);
animation.setCallback = callback.bind(undefined, animation);
animation.finish = finish.bind(undefined, animation);
return animation;
}
return {
moveTo: function (visuals, resizer, screen, drawable, xFn, yFn, resizeDependencies) {
var registerResizeAfterMove = function () {
resizer.removeKey('path', drawable);
resizer.add('position', drawable, function (width, height) {
changeCoords(drawable, Math.floor(xFn(width, height)), Math.floor(yFn(height, width)));
}, resizeDependencies);
};
var path = visuals.getPath(drawable.x, drawable.y, Math.floor(xFn(screen.width, screen.height)),
Math.floor(yFn(screen.height, screen.width)), 120, Transition.LINEAR, false);
var enhancedCallBack = function () {
registerResizeAfterMove();
if (path.__callback) {
path.__callback();
}
};
visuals.move(drawable, path, enhancedCallBack);
resizer.add('path', drawable, function (width, height) {
changePath(path, drawable.x, drawable.y, Math.floor(xFn(width, height)),
Math.floor(yFn(height, width)));
}, resizeDependencies);
return addServiceMethods(path);
},
moveQuadTo: function (visuals, resizer, screen, drawable, property, xFn, yFn, resizeDependencies) {
var registerResizeAfterMove = function () {
resizer.removeKey('path_' + property, drawable);
resizer.add('position_' + property, drawable, function (width, height) {
drawable.data[property + 'x'] = Math.floor(xFn(width, height));
drawable.data[property + 'y'] = Math.floor(yFn(height, width));
}, resizeDependencies);
};
var path = visuals.getPath(drawable.data[property + 'x'], drawable.data[property + 'y'],
Math.floor(xFn(screen.width, screen.height)), Math.floor(yFn(screen.height, screen.width)), 120,
Transition.LINEAR, false);
var enhancedCallBack = function () {
registerResizeAfterMove();
if (path.__callback) {
path.__callback();
}
};
visuals.moveQuad(property, drawable, path, enhancedCallBack);
resizer.add('path_' + property, drawable, function (width, height) {
changePath(path, drawable.data[property + 'x'], drawable.data[property + 'y'],
Math.floor(xFn(width, height)), Math.floor(yFn(height, width)));
}, resizeDependencies);
return addServiceMethods(path);
},
moveFrom: function (visuals, resizer, screen, drawable, xFn, yFn, resizeDependencies) {
var registerResizeAfterMove = function () {
resizer.removeKey('path', drawable);
};
var fromX = Math.floor(xFn(screen.width, screen.height));
var fromY = Math.floor(yFn(screen.height, screen.width));
var path = visuals.getPath(fromX, fromY, drawable.x, drawable.y, 120, Transition.LINEAR, false);
drawable.x = fromX;
drawable.y = fromY;
var enhancedCallBack = function () {
registerResizeAfterMove();
if (path.__callback) {
path.__callback();
}
};
visuals.move(drawable, path, enhancedCallBack);
resizer.add('path', drawable, function (width, height) {
changePath(path, Math.floor(xFn(width, height)), Math.floor(yFn(height, width)), drawable.x,
drawable.y);
}, resizeDependencies);
return addServiceMethods(path);
},
setShow: function (drawable, value) {
drawable.show = value;
return drawable;
},
show: function (visuals, drawable) {
visuals.draw(drawable);
return drawable;
},
hide: function (visuals, drawable) {
visuals.remove(drawable);
return drawable;
},
unmask: function (visuals, resizer, drawable) {
this.remove(visuals, resizer, drawable.mask);
},
remove: function (visuals, resizer, drawable) {
resizer.remove(drawable);
if (drawable.mask) {
this.remove(visuals, resizer, drawable.mask);
delete drawable.mask;
}
visuals.remove(drawable);
return drawable;
},
pause: function (visuals, drawable) {
visuals.pause(drawable);
return drawable;
},
play: function (visuals, drawable) {
visuals.play(drawable);
return drawable;
},
rotateTo: function (visuals, drawable, angle) {
var enhancedCallBack = function () {
if (animation.__callback) {
animation.__callback();
}
};
var animation = visuals.animateRotation(drawable, angle, 120, Transition.LINEAR, false, enhancedCallBack);
return addServiceMethods(animation);
},
rotationPattern: function (visuals, drawable, valuePairs, loop) {
visuals.animateRotationPattern(drawable, valuePairs, loop);
return drawable;
},
opacityTo: function (visuals, drawable, alpha) {
var enhancedCallBack = function () {
if (animation.__callback) {
animation.__callback();
}
};
var animation = visuals.animateAlpha(drawable, alpha, 120, Transition.LINEAR, false, enhancedCallBack);
return addServiceMethods(animation);
},
opacityPattern: function (visuals, drawable, valuePairs, loop) {
visuals.animateAlphaPattern(drawable, valuePairs, loop);
return drawable;
},
scaleTo: function (visuals, drawable, scale) {
var enhancedCallBack = function () {
if (animation.__callback) {
animation.__callback();
}
};
var animation = visuals.animateScale(drawable, scale, 120, Transition.LINEAR, false, enhancedCallBack);
return addServiceMethods(animation);
},
scalePattern: function (visuals, drawable, valuePairs, loop) {
visuals.animateScalePattern(drawable, valuePairs, loop);
return drawable;
},
sprite: function (visuals, drawable, imgPathName, numberOfFrames, loop) {
var sprite = visuals.getSprite(imgPathName, numberOfFrames, loop);
var enhancedCallBack = function () {
if (sprite.__callback) {
sprite.__callback();
}
};
visuals.animate(drawable, sprite, enhancedCallBack);
sprite.setLoop = looping.bind(undefined, sprite);
sprite.setCallback = callback.bind(undefined, sprite);
sprite.finish = function () {
// todo: fix api soon plz -> should be prefixed as private member
visuals.spriteAnimations.remove(drawable);
};
return sprite;
},
volumeTo: function (visuals, audio, volume) {
var enhancedCallBack = function () {
if (animation.__callback) {
animation.__callback();
}
};
var animation = visuals.animateVolume(audio, volume, 120, Transition.LINEAR, false, enhancedCallBack);
return addServiceMethods(animation);
}
};
})(H5.Transition, H5.changePath, H5.changeCoords, Math);
| raphaelstary/highfive.js | src/publicexposedinternals/render/internal/EntityServices.js | JavaScript | mit | 8,901 |
// generated on 2015-08-16 using generator-gulp-webapp 1.0.3
import gulp from 'gulp';
import gulpLoadPlugins from 'gulp-load-plugins';
import browserSync from 'browser-sync';
import del from 'del';
import {stream as wiredep} from 'wiredep';
const $ = gulpLoadPlugins();
const reload = browserSync.reload;
gulp.task('styles', () => {
return gulp.src('app/styles/*.scss')
.pipe($.plumber())
.pipe($.sourcemaps.init())
.pipe($.sass.sync({
outputStyle: 'expanded',
precision: 10,
includePaths: ['.']
}).on('error', $.sass.logError))
.pipe($.autoprefixer({browsers: ['last 1 version']}))
.pipe($.sourcemaps.write())
.pipe(gulp.dest('.tmp/styles'))
.pipe(reload({stream: true}));
});
function lint(files, options) {
return () => {
return gulp.src(files)
.pipe(reload({stream: true, once: true}))
.pipe($.eslint(options))
.pipe($.eslint.format())
.pipe($.if(!browserSync.active, $.eslint.failAfterError()));
};
}
const testLintOptions = {
env: {
mocha: true
}
};
gulp.task('lint', lint('app/scripts/**/*.js'));
gulp.task('lint:test', lint('test/spec/**/*.js', testLintOptions));
gulp.task('html', ['styles'], () => {
const assets = $.useref.assets({searchPath: ['.tmp', 'app', '.']});
return gulp.src('app/*.html')
.pipe(assets)
.pipe($.if('*.js', $.uglify()))
.pipe($.if('*.css', $.minifyCss({compatibility: '*'})))
.pipe(assets.restore())
.pipe($.useref())
.pipe($.if('*.html', $.minifyHtml({conditionals: true, loose: true})))
.pipe(gulp.dest('dist'));
});
gulp.task('images', () => {
return gulp.src('app/images/**/*')
.pipe($.if($.if.isFile, $.cache($.imagemin({
progressive: true,
interlaced: true,
// don't remove IDs from SVGs, they are often used
// as hooks for embedding and styling
svgoPlugins: [{cleanupIDs: false}]
}))
.on('error', function (err) {
console.log(err);
this.end();
})))
.pipe(gulp.dest('dist/images'));
});
gulp.task('fonts', () => {
return gulp.src(require('main-bower-files')({
filter: '**/*.{eot,svg,ttf,woff,woff2}'
}).concat('app/fonts/**/*'))
.pipe(gulp.dest('.tmp/fonts'))
.pipe(gulp.dest('dist/fonts'));
});
gulp.task('extras', () => {
return gulp.src([
'app/*.*',
'!app/*.html'
], {
dot: true
}).pipe(gulp.dest('dist'));
});
gulp.task('clean', del.bind(null, ['.tmp', 'dist']));
gulp.task('serve', ['styles', 'fonts'], () => {
browserSync({
notify: false,
port: 9000,
server: {
baseDir: ['.tmp', 'app'],
routes: {
'/bower_components': 'bower_components'
}
}
});
gulp.watch([
'app/*.html',
'app/scripts/**/*.js',
'app/images/**/*',
'.tmp/fonts/**/*'
]).on('change', reload);
gulp.watch('app/styles/**/*.scss', ['styles']);
gulp.watch('app/fonts/**/*', ['fonts']);
gulp.watch('bower.json', ['wiredep', 'fonts']);
});
gulp.task('serve:dist', () => {
browserSync({
notify: false,
port: 9000,
server: {
baseDir: ['dist']
}
});
});
gulp.task('serve:test', () => {
browserSync({
notify: false,
port: 9000,
ui: false,
server: {
baseDir: 'test',
routes: {
'/bower_components': 'bower_components'
}
}
});
gulp.watch('test/spec/**/*.js').on('change', reload);
gulp.watch('test/spec/**/*.js', ['lint:test']);
});
// inject bower components
gulp.task('wiredep', () => {
gulp.src('app/styles/*.scss')
.pipe(wiredep({
ignorePath: /^(\.\.\/)+/
}))
.pipe(gulp.dest('app/styles'));
gulp.src('app/*.html')
.pipe(wiredep({
exclude: ['bootstrap-sass'],
ignorePath: /^(\.\.\/)*\.\./
}))
.pipe(gulp.dest('app'));
});
gulp.task('build', ['lint', 'html', 'images', 'fonts', 'extras'], () => {
return gulp.src('dist/**/*').pipe($.size({title: 'build', gzip: true}));
});
gulp.task('default', ['clean'], () => {
gulp.start('build');
});
| shui91/frontend-nanodegree-map-webapp | gulpfile.babel.js | JavaScript | mit | 3,984 |
import THREE from 'three';
//TODO refactor HEAVILLY
class CircularLabeledGrid extends THREE.Object3D{
constructor ( diameter, step , upVector, color, opacity, text, textColor, textPosition) {
const DEFAULTS = {
diameter: 200,
step: 100,
color: 0xFFFFFF,
opacity: 0.1,
addText: true,
textColor: "#FFFFFF",
textLocation: "f",
rootAssembly: null
};
super();
this.diameter = diameter || 200;
this.step = step || 100;
this.color = color || 0x00baff;
this.opacity = opacity || 0.2;
this.text = text || true;
this.textColor = textColor || "#000000";
this.textPosition = "center";
this.upVector = upVector || new THREE.Vector3(0,1,0);
this.name = "grid";
//TODO: clean this up
this.marginSize =10;
this.stepSubDivisions = 10;
this._drawGrid();
//default grid orientation is z up, rotate if not the case
var upVector = this.upVector;
this.up = upVector;
this.lookAt(upVector);
}
_drawGrid() {
var gridGeometry, gridMaterial, mainGridZ, planeFragmentShader, planeGeometry, planeMaterial, subGridGeometry, subGridMaterial, subGridZ;
//offset to avoid z fighting
mainGridZ = -0.05;
gridGeometry = new THREE.Geometry();
gridMaterial = new THREE.LineBasicMaterial({
color: new THREE.Color().setHex(this.color),
opacity: this.opacity,
linewidth: 2,
transparent: true
});
subGridZ = -0.05;
subGridGeometry = new THREE.Geometry();
subGridMaterial = new THREE.LineBasicMaterial({
color: new THREE.Color().setHex(this.color),
opacity: this.opacity / 2,
transparent: true
});
var step = this.step;
var stepSubDivisions = this.stepSubDivisions;
var diameter = this.diameter;
var radius = diameter/2;
var width = this.diameter;
var length = this.diameter;
var centerBased = true
function getStart( offset ){
var angle = Math.asin( offset / radius );
var start = Math.cos( angle ) * radius;
return start
}
if(centerBased)
{
for (var i = 0; i <= width/2; i += step/stepSubDivisions)
{
var start = getStart( i );
subGridGeometry.vertices.push( new THREE.Vector3(-start, i, subGridZ) );
subGridGeometry.vertices.push( new THREE.Vector3(start, i, subGridZ) );
subGridGeometry.vertices.push( new THREE.Vector3(-start, -i, subGridZ) );
subGridGeometry.vertices.push( new THREE.Vector3(start, -i, subGridZ) );
if( i%step == 0 )
{
gridGeometry.vertices.push( new THREE.Vector3(-start, i, mainGridZ) );
gridGeometry.vertices.push( new THREE.Vector3(start, i, mainGridZ) );
gridGeometry.vertices.push( new THREE.Vector3(-start, -i, mainGridZ) );
gridGeometry.vertices.push( new THREE.Vector3(start, -i, mainGridZ) );
}
}
for (var i = 0; i <= length/2; i += step/stepSubDivisions)
{
var start = getStart( i );
subGridGeometry.vertices.push( new THREE.Vector3(i, -start, subGridZ) );
subGridGeometry.vertices.push( new THREE.Vector3(i, start, subGridZ) );
subGridGeometry.vertices.push( new THREE.Vector3(-i, -start, subGridZ) );
subGridGeometry.vertices.push( new THREE.Vector3(-i, start, subGridZ) );
if( i%step == 0 )
{
gridGeometry.vertices.push( new THREE.Vector3(i, -start, mainGridZ) );
gridGeometry.vertices.push( new THREE.Vector3(i, start, mainGridZ) );
gridGeometry.vertices.push( new THREE.Vector3(-i, -start, mainGridZ) );
gridGeometry.vertices.push( new THREE.Vector3(-i, start, mainGridZ) );
}
}
}
//create main & sub grid objects
this.mainGrid = new THREE.Line(gridGeometry, gridMaterial, THREE.LinePieces);
this.subGrid = new THREE.Line(subGridGeometry, subGridMaterial, THREE.LinePieces);
//create margin
var offsetWidth = width + this.marginSize;
var offsetLength = length + this.marginSize;
var segments = 128;
var marginGeometry = new THREE.CircleGeometry( diameter/2 + this.marginSize/2 , segments );
var marginGeometry2 = new THREE.CircleGeometry( diameter/2 , segments );
marginGeometry.vertices.shift();
marginGeometry2.vertices.shift();
marginGeometry.merge( marginGeometry2 );
var strongGridMaterial = new THREE.LineBasicMaterial({
color: new THREE.Color().setHex(this.color),
opacity: this.opacity*2,
linewidth: 2,
transparent: true
});
this.margin = new THREE.Line(marginGeometry, strongGridMaterial);
//add all grids, subgrids, margins etc
this.add( this.mainGrid );
this.add( this.subGrid );
this.add( this.margin );
//this._drawNumbering();
}
toggle(toggle) {
//apply visibility settings to all children
this.traverse( function( child ) {
child.visible = toggle;
});
}
setOpacity(opacity) {
this.opacity = opacity;
this.mainGrid.material.opacity = opacity;
this.subGrid.material.opacity = opacity/2;
this.margin.material.opacity = opacity*2;
}
setColor(color) {
this.color = color;
this.mainGrid.material.color = new THREE.Color().setHex(this.color);
this.subGrid.material.color = new THREE.Color().setHex(this.color);
this.margin.material.color = new THREE.Color().setHex(this.color);
}
toggleText(toggle) {
this.text = toggle;
var labels = this.labels.children;
for (var i = 0; i < this.labels.children.length; i++) {
var label = labels[i];
label.visible = toggle;
}
}
setTextColor(color) {
this.textColor = color;
this._drawNumbering();
}
setTextLocation(location) {
this.textLocation = location;
return this._drawNumbering();
}
setUp(upVector) {
this.upVector = upVector;
this.up = upVector;
this.lookAt(upVector);
}
resize( width, length ) {
if (width && length ) {
var width = Math.max(width,10);
this.diameter = width;
var length = Math.max(length,10);
this.length = length;
this.step = Math.max(this.step,5);
this.remove(this.mainGrid);
this.remove(this.subGrid);
this.remove( this.margin );
//this.remove(this.plane);
return this._drawGrid();
}
}
_drawNumbering() {
var label, sizeLabel, sizeLabel2, xLabelsLeft, xLabelsRight, yLabelsBack, yLabelsFront;
var step = this.step;
this._labelStore = {};
if (this.labels != null) {
this.mainGrid.remove(this.labels);
}
this.labels = new THREE.Object3D();
var width = this.width;
var length = this.length;
var numbering = this.numbering = "centerBased";
var labelsFront = new THREE.Object3D();
var labelsSideRight = new THREE.Object3D();
if(numbering == "centerBased" )
{
for (var i = 0 ; i <= width/2; i += step)
{
var sizeLabel = this.drawTextOnPlane("" + i, 32);
var sizeLabel2 = sizeLabel.clone();
sizeLabel.position.set(length/2, -i, 0.1);
sizeLabel.rotation.z = -Math.PI / 2;
labelsFront.add( sizeLabel );
sizeLabel2.position.set(length/2, i, 0.1);
sizeLabel2.rotation.z = -Math.PI / 2;
labelsFront.add( sizeLabel2 );
}
for (var i = 0 ; i <= length/2; i += step)
{
var sizeLabel = this.drawTextOnPlane("" + i, 32);
var sizeLabel2 = sizeLabel.clone();
sizeLabel.position.set(-i, width/2, 0.1);
//sizeLabel.rotation.z = -Math.PI / 2;
labelsSideRight.add( sizeLabel );
sizeLabel2.position.set(i, width/2, 0.1);
//sizeLabel2.rotation.z = -Math.PI / 2;
labelsSideRight.add( sizeLabel2 );
}
labelsSideLeft = labelsSideRight.clone();
labelsSideLeft.rotation.z = -Math.PI ;
//labelsSideLeft = labelsSideRight.clone().translateY(- width );
labelsBack = labelsFront.clone();
labelsBack.rotation.z = -Math.PI ;
}
/*if (this.textLocation === "center") {
yLabelsRight.translateY(- length/ 2);
xLabelsFront.translateX(- width / 2);
} else {
yLabelsLeft = yLabelsRight.clone().translateY( -width );
xLabelsBack = xLabelsFront.clone().translateX( -length );
this.labels.add( yLabelsLeft );
this.labels.add( xLabelsBack) ;
}*/
//this.labels.add( yLabelsRight );
this.labels.add( labelsFront );
this.labels.add( labelsBack );
this.labels.add( labelsSideRight );
this.labels.add( labelsSideLeft );
//apply visibility settings to all labels
var textVisible = this.text;
this.labels.traverse( function( child ) {
child.visible = textVisible;
});
this.mainGrid.add(this.labels);
}
drawTextOnPlane(text, size) {
var canvas, context, material, plane, texture;
if (size == null) {
size = 256;
}
canvas = document.createElement('canvas');
var size = 128;
canvas.width = size;
canvas.height = size;
context = canvas.getContext('2d');
context.font = "18px sans-serif";
context.textAlign = 'center';
context.fillStyle = this.textColor;
context.fillText(text, canvas.width / 2, canvas.height / 2);
context.strokeStyle = this.textColor;
context.strokeText(text, canvas.width / 2, canvas.height / 2);
texture = new THREE.Texture(canvas);
texture.needsUpdate = true;
texture.generateMipmaps = true;
texture.magFilter = THREE.LinearFilter;
texture.minFilter = THREE.LinearFilter;
material = new THREE.MeshBasicMaterial({
map: texture,
transparent: true,
color: 0xffffff,
alphaTest: 0.3
});
plane = new THREE.Mesh(new THREE.PlaneBufferGeometry(size / 8, size / 8), material);
plane.doubleSided = true
plane.overdraw = true
return plane;
}
}
//export {CircularLabeledGrid};
module.exports = CircularLabeledGrid;
//
//autoresize, disabled for now
/*
updateGridSize() {
var max, maxX, maxY, min, minX, minY, size, subchild, _getBounds, _i, _len, _ref,
_this = this;
minX = 99999;
maxX = -99999;
minY = 99999;
maxY = -99999;
_getBounds = function(mesh) {
var bBox, subchild, _i, _len, _ref, _results;
if (mesh instanceof THREE.Mesh) {
mesh.geometry.computeBoundingBox();
bBox = mesh.geometry.boundingBox;
minX = Math.min(minX, bBox.min.x);
maxX = Math.max(maxX, bBox.max.x);
minY = Math.min(minY, bBox.min.y);
maxY = Math.max(maxY, bBox.max.y);
_ref = mesh.children;
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
subchild = _ref[_i];
_results.push(_getBounds(subchild));
}
return _results;
}
};
if (this.rootAssembly != null) {
_ref = this.rootAssembly.children;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
subchild = _ref[_i];
if (subchild.name !== "renderSubs" && subchild.name !== "connectors") {
_getBounds(subchild);
}
}
}
max = Math.max(Math.max(maxX, maxY), 100);
min = Math.min(Math.min(minX, minY), -100);
size = (Math.max(max, Math.abs(min))) * 2;
size = Math.ceil(size / 10) * 10;
if (size >= 200) {
return this.resize(size);
}
};
*/
| usco/glView-helpers | src/grids/CircularLabeledGrid.js | JavaScript | mit | 12,223 |
/*
* /MathJax-v2/jax/output/CommonHTML/autoload/ms.js
*
* Copyright (c) 2009-2018 The MathJax Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
MathJax.Hub.Register.StartupHook("CommonHTML Jax Ready",function(){var c="2.7.8";var a=MathJax.ElementJax.mml,b=MathJax.OutputJax.CommonHTML;a.ms.Augment({toCommonHTML:function(e){e=this.CHTMLcreateNode(e);this.CHTMLhandleStyle(e);this.CHTMLgetVariant();this.CHTMLhandleScale(e);b.BBOX.empty(this.CHTML);var d=this.getValues("lquote","rquote","mathvariant");if(!this.hasValue("lquote")||d.lquote==='"'){d.lquote="\u201C"}if(!this.hasValue("rquote")||d.rquote==='"'){d.rquote="\u201D"}if(d.lquote==="\u201C"&&d.mathvariant==="monospace"){d.lquote='"'}if(d.rquote==="\u201D"&&d.mathvariant==="monospace"){d.rquote='"'}var f=d.lquote+this.data.join("")+d.rquote;this.CHTMLhandleText(e,f,this.CHTMLvariant);this.CHTML.clean();this.CHTMLhandleSpace(e);this.CHTMLhandleBBox(e);this.CHTMLhandleColor(e);return e}});MathJax.Hub.Startup.signal.Post("CommonHTML ms Ready");MathJax.Ajax.loadComplete(b.autoloadDir+"/ms.js")});
| sserrot/champion_relationships | venv/Lib/site-packages/notebook/static/components/MathJax/jax/output/CommonHTML/autoload/ms.js | JavaScript | mit | 1,598 |
/*
* Copyright AllSeen Alliance. All rights reserved.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
AsyncTestCase("BusAttachmentArgCountTest", {
_wrap: function(queue, test) {
queue.call(function(callbacks) {
bus = new org.alljoyn.bus.BusAttachment();
bus.create(false, callbacks.add(function(err) {
test(callbacks.add(function() {}));
}));
});
},
tearDown: function() {
bus.destroy();
delete bus;
bus = null;
},
testConstructor0: function(queue) {
this._wrap(queue, function(callback) {
assertNoError(function() {
var testbus = new org.alljoyn.bus.BusAttachment();
testbus.destroy();
delete testbus;
testbus = null;
});
callback();
});
},
testConnect0a: function(queue) {
this._wrap(queue, function(callback) {
assertError(function() { bus.connect(); });
callback();
});
},
testConnect0b: function(queue) {
this._wrap(queue, function(callback) {
assertNoError(function() { bus.connect(callback); });
});
},
testConnect1: function(queue) {
this._wrap(queue, function(callback) {
assertNoError(function() { bus.connect("connectSpec", callback); });
});
},
testDisconnect0a: function(queue) {
this._wrap(queue, function(callback) {
assertError(function() { bus.disconnect(); });
callback();
});
},
testDisconnect0b: function(queue) {
this._wrap(queue, function(callback) {
assertNoError(function() { bus.disconnect(callback); });
});
},
testRegisterSignalHandler0: function(queue) {
this._wrap(queue, function(callback) {
assertError(function() { bus.registerSignalHandler(); }, "TypeError");
callback();
});
},
testRegisterSignalHandler1: function(queue) {
this._wrap(queue, function(callback) {
assertError(function() { bus.registerSignalHandler(function() {}); }, "TypeError");
callback();
});
},
testRegisterSignalHandler2a: function(queue) {
this._wrap(queue, function(callback) {
assertError(function() { bus.registerSignalHandler(function() {}, "signalName"); });
callback();
});
},
testRegisterSignalHandler2b: function(queue) {
this._wrap(queue, function(callback) {
assertNoError(function() { bus.registerSignalHandler(function() {}, "signalName", callback); });
});
},
testRegisterSignalHandler3a: function(queue) {
this._wrap(queue, function(callback) {
assertError(function() { bus.registerSignalHandler(function() {}, "signalName", "sourcePath"); });
callback();
});
},
testRegisterSignalHandler3b: function(queue) {
this._wrap(queue, function(callback) {
assertNoError(function() { bus.registerSignalHandler(function() {}, "signalName", "sourcePath", callback); });
});
},
testUnregisterSignalHandler0: function(queue) {
this._wrap(queue, function(callback) {
assertError(function() { bus.unregisterSignalHandler(); }, "TypeError");
callback();
});
},
testUnregisterSignalHandler1: function(queue) {
this._wrap(queue, function(callback) {
assertError(function() { bus.unregisterSignalHandler(function() {}); }, "TypeError");
callback();
});
},
testUnregisterSignalHandler2a: function(queue) {
this._wrap(queue, function(callback) {
assertError(function() { bus.unregisterSignalHandler(function() {}, "signalName"); }, "TypeError");
callback();
});
},
testUnregisterSignalHandler2b: function(queue) {
this._wrap(queue, function(callback) {
assertNoError(function() { bus.unregisterSignalHandler(function() {}, "signalName", callback); });
});
},
testUnregisterSignalHandler3a: function(queue) {
this._wrap(queue, function(callback) {
assertError(function() { bus.unregisterSignalHandler(function() {}, "signalName", "sourcePath"); }, "TypeError");
callback();
});
},
testUnregisterSignalHandler3b: function(queue) {
this._wrap(queue, function(callback) {
assertNoError(function() { bus.unregisterSignalHandler(function() {}, "signalName", "sourcePath", callback); });
});
},
testRegisterBusListener0: function(queue) {
this._wrap(queue, function(callback) {
assertError(function() { bus.registerBusListener(); }, "TypeError");
callback();
});
},
testRegisterBusListener1a: function(queue) {
this._wrap(queue, function(callback) {
assertError(function() { bus.registerBusListener(function() {}); });
callback();
});
},
testRegisterBusListener1b: function(queue) {
this._wrap(queue, function(callback) {
assertNoError(function() { bus.registerBusListener(function() {}, callback); });
});
},
testUnregisterBusListener0: function(queue) {
this._wrap(queue, function(callback) {
assertError(function() { bus.unregisterBusListener(); }, "TypeError");
callback();
});
},
testUnregisterBusListener1a: function(queue) {
this._wrap(queue, function(callback) {
assertError(function() { bus.unregisterBusListener(function() {}); });
callback();
});
},
testUnregisterBusListener1b: function(queue) {
this._wrap(queue, function(callback) {
assertNoError(function() { bus.unregisterBusListener(function() {}, callback); });
});
},
testRequestName0: function(queue) {
this._wrap(queue, function(callback) {
assertError(function() { bus.requestName(); }, "TypeError");
callback();
});
},
testRequestName1a: function(queue) {
this._wrap(queue, function(callback) {
assertError(function() { bus.requestName("requestedName"); });
callback();
});
},
testRequestName1b: function(queue) {
this._wrap(queue, function(callback) {
assertNoError(function() { bus.requestName("requestedName", callback); });
});
},
testRequestName2a: function(queue) {
this._wrap(queue, function(callback) {
assertError(function() { bus.requestName("requestedName", 0); });
callback();
});
},
testRequestName2b: function(queue) {
this._wrap(queue, function(callback) {
assertNoError(function() { bus.requestName("requestedName", 0, callback); });
});
},
testReleaseName0: function(queue) {
this._wrap(queue, function(callback) {
assertError(function() { bus.releaseName(); }, "TypeError");
callback();
});
},
testReleaseName1a: function(queue) {
this._wrap(queue, function(callback) {
assertError(function() { bus.releaseName("name"); });
callback();
});
},
testReleaseName1b: function(queue) {
this._wrap(queue, function(callback) {
assertNoError(function() { bus.releaseName("name", callback); });
});
},
testAddMatch0: function(queue) {
this._wrap(queue, function(callback) {
assertError(function() { bus.addMatch(); }, "TypeError");
callback();
});
},
testAddMatch1a: function(queue) {
this._wrap(queue, function(callback) {
assertError(function() { bus.addMatch("rule"); });
callback();
});
},
testAddMatch1b: function(queue) {
this._wrap(queue, function(callback) {
assertNoError(function() { bus.addMatch("rule", callback); });
});
},
testRemoveMatch0: function(queue) {
this._wrap(queue, function(callback) {
assertError(function() { bus.removeMatch(); }, "TypeError");
callback();
});
},
testRemoveMatch1a: function(queue) {
this._wrap(queue, function(callback) {
assertError(function() { bus.removeMatch("rule"); });
callback();
});
},
testRemoveMatch1b: function(queue) {
this._wrap(queue, function(callback) {
assertNoError(function() { bus.removeMatch("rule", callback); });
});
},
testAdvertiseName0: function(queue) {
this._wrap(queue, function(callback) {
assertError(function() { bus.advertiseName(); }, "TypeError");
callback();
});
},
testAdvertiseName1: function(queue) {
this._wrap(queue, function(callback) {
assertError(function() { bus.advertiseName("name"); }, "TypeError");
callback();
});
},
testAdvertiseName2a: function(queue) {
this._wrap(queue, function(callback) {
assertError(function() { bus.advertiseName("name", 0); });
callback();
});
},
testAdvertiseName2b: function(queue) {
this._wrap(queue, function(callback) {
assertNoError(function() { bus.advertiseName("name", 0, callback); });
});
},
testCancelAdvertiseName0: function(queue) {
this._wrap(queue, function(callback) {
assertError(function() { bus.cancelAdvertiseName(); }, "TypeError");
callback();
});
},
testCancelAdvertiseName1: function(queue) {
this._wrap(queue, function(callback) {
assertError(function() { bus.cancelAdvertiseName("name"); }, "TypeError");
callback();
});
},
testCancelAdvertiseName2a: function(queue) {
this._wrap(queue, function(callback) {
assertError(function() { bus.cancelAdvertiseName("name", 0); });
callback();
});
},
testCancelAdvertiseName2b: function(queue) {
this._wrap(queue, function(callback) {
assertNoError(function() { bus.cancelAdvertiseName("name", 0, callback); });
});
},
testFindAdvertisedName0: function(queue) {
this._wrap(queue, function(callback) {
assertError(function() { bus.findAdvertisedName(); }, "TypeError");
callback();
});
},
testFindAdvertisedName1a: function(queue) {
this._wrap(queue, function(callback) {
assertError(function() { bus.findAdvertisedName("namePrefix"); });
callback();
});
},
testFindAdvertisedName1b: function(queue) {
this._wrap(queue, function(callback) {
assertNoError(function() { bus.findAdvertisedName("namePrefix", callback); });
});
},
testCancelFindAdvertisedName0: function(queue) {
this._wrap(queue, function(callback) {
assertError(function() { bus.cancelFindAdvertisedName(); }, "TypeError");
callback();
});
},
testCancelFindAdvertisedName1a: function(queue) {
this._wrap(queue, function(callback) {
assertError(function() { bus.cancelFindAdvertisedName("namePrefix"); });
callback();
});
},
testCancelFindAdvertisedName1b: function(queue) {
this._wrap(queue, function(callback) {
assertNoError(function() { bus.cancelFindAdvertisedName("namePrefix", callback); });
});
},
testBindSessionPort0: function(queue) {
this._wrap(queue, function(callback) {
assertError(function() { bus.bindSessionPort(); }, "TypeError");
callback();
});
},
testBindSessionPort1a: function(queue) {
this._wrap(queue, function(callback) {
assertError(function() { bus.bindSessionPort({}); });
callback();
});
},
testBindSessionPort1b: function(queue) {
this._wrap(queue, function(callback) {
assertNoError(function() { bus.bindSessionPort({}, callback); });
});
},
testUnbindSessionPort0: function(queue) {
this._wrap(queue, function(callback) {
assertError(function() { bus.unbindSessionPort(); }, "TypeError");
callback();
});
},
testUnbindSessionPort1a: function(queue) {
this._wrap(queue, function(callback) {
assertError(function() { bus.unbindSessionPort(0); });
callback();
});
},
testUnbindSessionPort1b: function(queue) {
this._wrap(queue, function(callback) {
assertNoError(function() { bus.unbindSessionPort(0, callback); });
});
},
testSetSessionListener0: function(queue) {
this._wrap(queue, function(callback) {
assertError(function() { bus.setSessionListener(); }, "TypeError");
callback();
});
},
testSetSessionListener1: function(queue) {
this._wrap(queue, function(callback) {
assertError(function() { bus.setSessionListener(0); }, "TypeError");
callback();
});
},
testSetSessionListener2a: function(queue) {
this._wrap(queue, function(callback) {
assertError(function() { bus.setSessionListener(0, function() {}); });
callback();
});
},
testSetSessionListener2b: function(queue) {
this._wrap(queue, function(callback) {
assertNoError(function() { bus.setSessionListener(0, function() {}, callback); });
});
},
testJoinSession0: function(queue) {
this._wrap(queue, function(callback) {
assertError(function() { bus.joinSession(); }, "TypeError");
callback();
});
},
testJoinSession1a: function(queue) {
this._wrap(queue, function(callback) {
assertError(function() { bus.joinSession({ host: 0, port: 1 }); });
callback();
});
},
testJoinSession1b: function(queue) {
this._wrap(queue, function(callback) {
assertNoError(function() { bus.joinSession({ host: 0, port: 1 }, callback); });
});
},
testLeaveSession0: function(queue) {
this._wrap(queue, function(callback) {
assertError(function() { bus.leaveSession(); }, "TypeError");
callback();
});
},
testLeaveSession1a: function(queue) {
this._wrap(queue, function(callback) {
assertError(function() { bus.leaveSession(0); });
callback();
});
},
testLeaveSession1b: function(queue) {
this._wrap(queue, function(callback) {
assertNoError(function() { bus.leaveSession(0, callback); });
});
},
testSetLinkTimeout0: function(queue) {
this._wrap(queue, function(callback) {
assertError(function() { bus.setLinkTimeout(); }, "TypeError");
callback();
});
},
testSetLinkTimeout1: function(queue) {
this._wrap(queue, function(callback) {
assertError(function() { bus.setLinkTimeout(1); }, "TypeError");
callback();
});
},
//should assert a TypeError if value other than a number is passed as parameter
testSetLinkTimeout1a: function(queue) {
this._wrap(queue, function(callback) {
assertError(function() { bus.setLinkTimeout(a); }, "TypeError");
callback();
});
},
testSetLinkTimeout2: function(queue) {
this._wrap(queue, function(callback) {
assertError(function() { bus.setLinkTimeout(1, 1); }, "TypeError");
callback();
});
},
//should assert a TypeError if value other than a number is passed as parameter
testSetLinkTimeout2a: function(queue) {
this._wrap(queue, function(callback) {
assertError(function() { bus.setLinkTimeout(a, 1); }, "TypeError");
callback();
});
},
//should assert a TypeError if value other than a number is passed as parameter
testSetLinkTimeout2b: function(queue) {
this._wrap(queue, function(callback) {
assertError(function() { bus.setLinkTimeout(1, a); }, "TypeError");
callback();
});
},
testSetLinkTimeout3: function(queue) {
this._wrap(queue, function(callback) {
assertNoError(
function() { bus.setLinkTimeout(1, 1,
function(err, linktimeout) {
assertFalsy(err);
assertEquals(1, linktimeout);
});
});
callback();
});
},
testNameHasOwner0: function(queue) {
this._wrap(queue, function(callback) {
assertError(function() { bus.nameHasOwner(); }, "TypeError");
callback();
});
},
testNameHasOwner1: function(queue) {
this._wrap(queue, function(callback) {
assertError(function() { bus.nameHasOwner("name"); }, "TypeError");
callback();
});
},
testSetDaemonDebug0: function(queue) {
this._wrap(queue, function(callback) {
assertError(function() { bus.setDaemonDebug(); }, "TypeError");
callback();
});
},
testSetDaemonDebug1: function(queue) {
this._wrap(queue, function(callback) {
assertError(function() { bus.setDaemonDebug("_module"); }, "TypeError");
callback();
});
},
testSetDaemonDebug2a: function(queue) {
this._wrap(queue, function(callback) {
assertError(function() { bus.setDaemonDebug("_module", 0); });
callback();
});
},
testSetDaemonDebug2b: function(queue) {
this._wrap(queue, function(callback) {
assertNoError(function() { bus.setDaemonDebug("_module", 0, callback); });
});
},
testEnablePeerSecurity0: function(queue) {
this._wrap(queue, function(callback) {
assertError(function() { bus.enablePeerSecurity(); }, "TypeError");
callback();
});
},
testEnablePeerSecurity1a: function(queue) {
this._wrap(queue, function(callback) {
assertError(function() { bus.enablePeerSecurity("authMechanisms"); });
callback();
});
},
testEnablePeerSecurity1b: function(queue) {
this._wrap(queue, function(callback) {
assertNoError(function() { bus.enablePeerSecurity("authMechanisms", callback); });
});
},
testEnablePeerSecurity2: function(queue) {
this._wrap(queue, function(callback) {
assertNoError(function() { bus.enablePeerSecurity("authMechanisms", function() {}, callback); });
});
},
testReloadKeyStore0a: function(queue) {
this._wrap(queue, function(callback) {
assertError(function() { bus.reloadKeyStore(); });
callback();
});
},
testReloadKeyStore0b: function(queue) {
this._wrap(queue, function(callback) {
assertNoError(function() { bus.reloadKeyStore(callback); });
});
},
testClearKeyStore0a: function(queue) {
this._wrap(queue, function(callback) {
assertError(function() { bus.clearKeyStore(); });
callback();
});
},
testClearKeyStore0b: function(queue) {
this._wrap(queue, function(callback) {
assertNoError(function() { bus.clearKeyStore(callback); });
});
},
testClearKeys0: function(queue) {
this._wrap(queue, function(callback) {
assertError(function() { bus.clearKeys(); }, "TypeError");
callback();
});
},
testClearKeys1a: function(queue) {
this._wrap(queue, function(callback) {
assertError(function() { bus.clearKeys("guid"); });
callback();
});
},
testClearKeys1b: function(queue) {
this._wrap(queue, function(callback) {
assertNoError(function() { bus.clearKeys("guid", callback); });
});
},
testSetKeyExpiration0: function(queue) {
this._wrap(queue, function(callback) {
assertError(function() { bus.setKeyExpiration(); }, "TypeError");
callback();
});
},
testSetKeyExpiration1: function(queue) {
this._wrap(queue, function(callback) {
assertError(function() { bus.setKeyExpiration("guid"); }, "TypeError");
callback();
});
},
testSetKeyExpiration2a: function(queue) {
this._wrap(queue, function(callback) {
assertError(function() { bus.setKeyExpiration("guid", 0); }, "TypeError");
callback();
});
},
testSetKeyExpiration2b: function(queue) {
this._wrap(queue, function(callback) {
assertNoError(function() { bus.setKeyExpiration("guid", 0, callback); }, "TypeError");
});
},
testGetKeyExpiration0: function(queue) {
this._wrap(queue, function(callback) {
assertError(function() { bus.getKeyExpiration(); }, "TypeError");
callback();
});
},
testGetKeyExpiration1: function(queue) {
this._wrap(queue, function(callback) {
assertError(function() { bus.getKeyExpiration("guid"); }, "TypeError");
callback();
});
},
testAddLogonEntry0: function(queue) {
this._wrap(queue, function(callback) {
assertError(function() { bus.addLogonEntry(); }, "TypeError");
callback();
});
},
testAddLogonEntry1: function(queue) {
this._wrap(queue, function(callback) {
assertError(function() { bus.addLogonEntry("authMechanism"); }, "TypeError");
callback();
});
},
testAddLogonEntry2: function(queue) {
this._wrap(queue, function(callback) {
assertError(function() { bus.addLogonEntry("authMechanism", "userName"); });
callback();
});
},
testAddLogonEntry3a: function(queue) {
this._wrap(queue, function(callback) {
assertError(function() { bus.addLogonEntry("authMechanism", "userName", "password"); });
callback();
});
},
testAddLogonEntry3b: function(queue) {
this._wrap(queue, function(callback) {
assertNoError(function() { bus.addLogonEntry("authMechanism", "userName", "password", callback); });
});
},
testGetPeerGUID0: function(queue) {
this._wrap(queue, function(callback) {
assertError(function() { bus.getPeerGUID(); }, "TypeError");
callback();
});
},
testGetPeerGUID1: function(queue) {
this._wrap(queue, function(callback) {
assertError(function() { bus.getPeerGUID("name"); }, "TypeError");
callback();
});
},
testCreateInterfacesFromXML0: function(queue) {
this._wrap(queue, function(callback) {
assertError(function() { bus.createInterfacesFromXML(); }, "TypeError");
callback();
});
},
testCreateInterfacesFromXML1a: function(queue) {
this._wrap(queue, function(callback) {
assertError(function() { bus.createInterfacesFromXML("xml"); });
callback();
});
},
testCreateInterfacesFromXML1b: function(queue) {
this._wrap(queue, function(callback) {
assertNoError(function() { bus.createInterfacesFromXML("xml", callback); });
});
},
});
| Vovkasquid/compassApp | alljoyn/alljoyn_js/test/BusAttachmentArgCountTest.js | JavaScript | mit | 24,566 |
module.exports = ngModule => {
describe('factory:globalFiltersFactory', () => {
let globalFiltersFactory;
beforeEach(window.module(ngModule.name));
beforeEach(() => {
window.module(($provide) => {
$provide.factory('daEvents', () => ({}));
$provide.factory('SAMPLE_APP', () => ({}));
});
inject(_globalFiltersFactory_ => {
globalFiltersFactory = _globalFiltersFactory_;
});
});
it('should test properly', () => {
expect(globalFiltersFactory).to.not.equal(undefined);
});
});
};
| DomoApps/advanced-sample-app | src/common/services/global-filters-factory/global-filters-factory.factory.spec.js | JavaScript | mit | 562 |
module.exports = (function() {
var DeviceStreamMapping = {};
DeviceStreamMapping.tableName = "device_stream_mapping";
DeviceStreamMapping.attributes = {
device: {
model: "device"
},
stream: {
model: "stream"
},
alpha: {
type: "boolean"
}
};
return DeviceStreamMapping;
})();
| loftili/api | api/models/DeviceStreamMapping.js | JavaScript | mit | 336 |
define({
"businessAnalyst": "Business Analyst",
"defineWhichInfographics": "Définir les infographies disponibles dans le widget :",
"defineWhichReports": "Définir les rapports disponibles dans le widget :",
"defaultValues": "Valeurs par défaut :",
"disable": "Désactiver",
"driveTime": "Temps de conduite",
"infographics": "Infographie",
"invalidValueRing": "Les valeurs doivent être comprises entre 0 et 1 000.",
"invalidValueDTWT": "Les valeurs doivent être comprises entre 0 et 300.",
"km": "km",
"miles": "miles",
"minutes": "minutes",
"radius": "Rayon",
"reports": "Rapports",
"rings": "Anneaux",
"selectCountry": "Sélectionner le pays :",
"thisEntryIsNotValid": "L’entrée n’est pas valide.",
"time": "Durée",
"walkTime": "Temps de marche"
}); | tmcgee/cmv-wab-widgets | wab/2.13/widgets/BusinessAnalyst/setting/nls/fr/strings.js | JavaScript | mit | 799 |
/**
* The MIT License (MIT)
* Copyright (c) 2015-present Dmitry Soshnikov <[email protected]>
*/
import {EOF} from './special-symbols';
import colors from 'colors';
const EOF_TOKEN = {
type: EOF,
value: EOF,
};
/**
* A default tokenizer that extracts tokens from the string,
* based on the tokens from the grammar. Uses underlying
* regexp implementation.
*/
export default class Tokenizer {
/**
* Creates a tokenizer instance for a string
* that belongs to the given grammar.
*/
constructor({string, lexGrammar}) {
/**
* Corresponding lexical grammar.
*/
this._lexGrammar = lexGrammar;
if (string) {
this.initString(string);
}
}
/**
* Returns tokenizer states.
*/
getStates() {
return this._states;
}
/**
* Returns current state.
*/
getCurrentState() {
return this._states[this._states.length - 1];
}
/**
* Pushes a new state for the tokinizer. Some lex-rules may
* specify in which state they are triggered. A rule won't be
* triggered if a tokenizer is not in this state.
*/
pushState(state) {
this._states.push(state);
}
/**
* Alias for `pushState`.
*/
begin(state) {
this.pushState(state);
}
/**
* Pops a state. If there is only INITIAL state, just returns it.
*/
popState() {
if (this._states.length > 1) {
return this._states.pop();
}
return this._states[0];
}
/**
* Initializes a parsing string, and corresponding meta data.
*/
initString(string) {
/**
* Tokenizing string.
*/
this._string = string;
/**
* Tracking cursor (absolute offset).
*/
this._cursor = 0;
/**
* Tokenizer states to work with start conditions of lex rules.
* The `INITIAL` state always present, i.e. all rules with no
* explicit start conditions are executed, untill a new state is
* pushed. If the state is exclusive, then only the rules with this
* start condition are executed. If it's inclusive, then in addition
* rules with no start conditions are executed as well.
* https://gist.github.com/DmitrySoshnikov/f5e2583b37e8f758c789cea9dcdf238a
*/
this._states = ['INITIAL'];
/**
* In case if a token handler returns multiple tokens from one rule,
* we still return tokens one by one in the `getNextToken`, putting
* other "fake" tokens into the queue. If there is still something in
* this queue, it's just returned.
*/
this._tokensQueue = [];
/**
* Current line number.
*/
this._currentLine = 1;
/**
* Current column number.
*/
this._currentColumn = 0;
/**
* Current offset of the beginning of the current line.
*
* Since new lines can be handled by the lex rules themselves,
* we scan an extracted token for `\n`s, and calculate start/end
* locations of tokens based on the `currentLine`/`currentLineBeginOffset`.
*/
this._currentLineBeginOffset = 0;
/**
* Matched token location data.
*/
this._tokenStartOffset = 0;
this._tokenEndOffset = 0;
this._tokenStartLine = 1;
this._tokenEndLine = 1;
this._tokenStartColumn = 0;
this._tokenEndColumn = 0;
}
getTokens() {
if (!this._tokens) {
// Rewind to calculate all tokens.
let cursor = this._cursor;
this._cursor = 0;
this._tokens = [];
while (this.hasMoreTokens()) {
this._tokens.push(this.getNextToken());
}
// And restore back for the `getNextToken`.
this._cursor = cursor;
}
return this._tokens;
}
/**
* Returns next token.
*/
getNextToken() {
// Something was queued, return it.
if (this._tokensQueue.length > 0) {
return this.onToken(this._toToken(this._tokensQueue.shift()));
}
if (!this.hasMoreTokens()) {
return this.onToken(EOF_TOKEN);
}
// Analyze untokenized yet part of the string starting from
// the current cursor position (so all regexp are from ^).
let string = this._string.slice(this._cursor);
// Get all rules which should be considered for this state.
const lexRulesForState = this._lexGrammar.getRulesForState(
this.getCurrentState()
);
for (let lexRule of lexRulesForState) {
let matched = this._match(string, lexRule.getMatcher());
// Manual handling of EOF token (the end of string). Return it
// as `EOF` symbol.
if (string === '' && matched === '') {
this._cursor++;
}
if (matched !== null) {
let yytext, rawToken;
try {
[yytext, rawToken] = lexRule.getTokenData(matched, this);
} catch (e) {
console.error(
colors.red('\nError in handler:\n\n') +
lexRule.getRawHandler() +
'\n'
);
throw e;
}
// Usually whitespaces, etc.
if (!rawToken) {
return this.getNextToken();
}
// If multiple tokens are returned, save them to return
// on next `getNextToken` call.
if (Array.isArray(rawToken)) {
const tokensToQueue = rawToken.slice(1);
rawToken = rawToken[0];
if (tokensToQueue.length > 0) {
this._tokensQueue.unshift(...tokensToQueue);
}
}
return this.onToken(this._toToken(rawToken, yytext));
}
}
if (this.isEOF()) {
this._cursor++;
return EOF_TOKEN;
}
this.throwUnexpectedToken(
string[0],
this._currentLine,
this._currentColumn
);
}
/**
* Throws default "Unexpected token" exception, showing the actual
* line from the source, pointing with the ^ marker to the bad token.
* In addition, shows `line:column` location.
*/
throwUnexpectedToken(symbol, line, column) {
const lineSource = this._string.split('\n')[line - 1];
let lineData = '';
if (lineSource) {
const pad = ' '.repeat(column);
lineData = '\n\n' + lineSource + '\n' + pad + '^\n';
}
throw new SyntaxError(
`${lineData}Unexpected token: "${symbol}" ` + `at ${line}:${column}.`
);
}
_captureLocation(matched) {
const nlRe = /\n/g;
// Absolute offsets.
this._tokenStartOffset = this._cursor;
// Line-based locations, start.
this._tokenStartLine = this._currentLine;
this._tokenStartColumn =
this._tokenStartOffset - this._currentLineBeginOffset;
// Extract `\n` in the matched token.
let nlMatch;
while ((nlMatch = nlRe.exec(matched)) !== null) {
this._currentLine++;
this._currentLineBeginOffset = this._tokenStartOffset + nlMatch.index + 1;
}
this._tokenEndOffset = this._cursor + matched.length;
// Line-based locations, end.
this._tokenEndLine = this._currentLine;
this._tokenEndColumn = this._currentColumn =
this._tokenEndOffset - this._currentLineBeginOffset;
}
_toToken(tokenType, yytext = '') {
return {
// Basic data.
type: tokenType,
value: yytext,
// Location data.
startOffset: this._tokenStartOffset,
endOffset: this._tokenEndOffset,
startLine: this._tokenStartLine,
endLine: this._tokenEndLine,
startColumn: this._tokenStartColumn,
endColumn: this._tokenEndColumn,
};
}
isEOF() {
return this._cursor === this._string.length;
}
hasMoreTokens() {
return this._cursor <= this._string.length;
}
/**
* Generic tokenizing based on current regexp.
*/
_match(string, regexp) {
let matched = string.match(regexp);
if (matched) {
// Handle `\n` in the matched token to track line numbers.
this._captureLocation(matched[0]);
this._cursor += matched[0].length;
return matched[0];
}
return null;
}
/**
* Allows analyzing, and transforming token. Default implementation
* just passes the token through.
*/
onToken(token) {
return token;
}
}
| DmitrySoshnikov/syntax | src/tokenizer.js | JavaScript | mit | 8,003 |
var targetNodes = $("#ghx-pool");
var MutationObserver = window.MutationObserver || window.WebKitMutationObserver;
var myObserver = new MutationObserver(mutationHandler);
var obsConfig = { childList: false, characterData: false, attributes: true, subtree: true };
// Add a target node to the observer. Can only add one node at a time.
targetNodes.each(function () {
myObserver.observe(this, obsConfig);
});
function mutationHandler(mutationRecords) {
mutationRecords.forEach(function (mutation) {
if (mutation.target.id === 'ghx-column-header-group') {
hoverPopovers();
}
});
}
function appendPopover(element, content) {
$(element).append($('<div class="plus-popover">' + content + '<div class="legend"><p>Legend:</p><ul><li class="mandatory">mandatory</li><li class="recommended">recommended</li></ul></div></div>'));
$(element).hover(
function () {
$(this).children('.plus-popover').show();
},
function () {
$(this).children('.plus-popover').hide();
}
);
}
function hoverPopovers() {
let inProgress = $('.ghx-column[data-id]>h2:contains(In Progress)').parent()[0];
if ($(inProgress).has('.plus-popover').length == 0) {
appendPopover(
inProgress,
'<ul>' +
'<li class="mandatory">Acceptance criteria met</li>' +
'<li class="mandatory">Source code submitted to P4, submit added to JIRA ticket, code collaborator link added to JIRA ticket</li>' +
'<li class="mandatory">Unit tests written and integrated with build</li>' +
'<li class="mandatory">Green build (build passed, automation tests passed)</li>' +
'<li class="recommended">Tech. docs created/updated</li>' +
'<li class="recommended">Automation test steps designed</li>' +
'<li class="recommended">Acceptance tests automation libraries written</li>' +
'<li class="recommended">Non-functional requirements are met</li>' +
'<li class="recommended">Code coverage not getting worse</li>' +
'<li class="recommended">Manual test steps designed (have it earlier the better)</li>' +
'<li class="recommended">Story build number on DEV branch added to JIRA ticket</li>' +
'</ul>'
);
}
let inReview = $('.ghx-column[data-id]>h2:contains(In Review)').parent()[0];
if ($(inReview).has('.plus-popover').length == 0) {
appendPopover(
inReview,
'<ul>' +
'<li class="mandatory">Deploy changes to QAenvironment</li>' +
'<li class="recommended">Peer code review completed</li>' +
'</ul>'
);
}
let inQA = $('.ghx-column[data-id]>h2:contains(In QA)').parent()[0];
if ($(inQA).has('.plus-popover').length == 0) {
appendPopover(
inQA,
'<ul>' +
'<li class="mandatory">Story tested and verified</li>' +
'<li class="mandatory">No Must-Fix defects pending for the story</li>' +
'<li class="recommended">Regression tests added/updated in TestLink</li>' +
'<li class="recommended">Regression tests automated (where possible)</li>' +
'<li class="recommended">Manual targeted regression tests passed successfully</li>' +
'</ul>'
);
}
let inUAT = $('.ghx-column[data-id]>h2:contains(In UAT)').parent()[0];
if ($(inUAT).has('.plus-popover').length == 0) {
appendPopover(
inUAT,
'<ul>' +
'<li class="mandatory">Story accepted by the PO</li>' +
'</ul>'
);
}
let inIntegration = $('.ghx-column[data-id]>h2:contains(Integration)').parent()[0];
if ($(inIntegration).has('.plus-popover').length == 0) {
appendPopover(
inIntegration,
'<ul>' +
'<li class="mandatory">Code integrated to Main branch</li>' +
'<li class="mandatory">Story build number on Main branch added to JIRA ticket, add fixVersion to JIRA ticket</li>' +
'<li class="mandatory">Deploy changes to Integration environment (the way how this is ensured is product specific)</li>' +
'<li class="mandatory">Greeen build (build passd, automation tests passed)</li>' +
'<li class="recommended">Post-integration quick checks</li>' +
'</ul>'
);
}
let inStaging = $('.ghx-column[data-id]>h2:contains(In Staging)').parent()[0];
if ($(inStaging).has('.plus-popover').length == 0) {
appendPopover(
inStaging,
'<ul>' +
'<li class="mandatory">Story tested on Main branch</li>' +
'<li class="mandatory">Automation test suite (all tests) passed successfully on Main branch</li>' +
'</ul>'
);
}
} | granak/jplus | jira-modifications/definition-of-done.js | JavaScript | mit | 4,984 |
'use strict';
var ndarray = require('ndarray');
var ndt = require('ndarray-tests');
var linspace = require('../');
var test = require('tape');
test('fails if the first argument is not a ndarray', function (t) {
t.throws(function () {
linspace(0, 10);
}, Error, /must be a ndarray/);
t.end();
});
test('throws an error if the axis not a number', function (t) {
t.throws(function () {
linspace(ndarray([], [2, 2]), 0, 1, {axis: '4'});
}, Error, 'Axis must be a nonegative integer');
t.end();
});
test('throws an error if the axis is greater than the dimension', function (t) {
t.throws(function () {
linspace(ndarray([], [2, 2]), 0, 1, {axis: 4});
}, Error, 'must be <= dimension');
t.end();
});
test('fails if the endpoint is not a boolean', function (t) {
t.throws(function () {
linspace(ndarray([], [1]), 0, 10, {endpoint: 7});
}, Error, /must be a boolean/);
t.end();
});
test('create a new linspace with an endpoint', function (t) {
var x = linspace(ndarray([], [11]), 0, 10);
var y = ndarray([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
t.assert(ndt.equal(x, y, 1e-8));
t.end();
});
test('create a new linspace without an endpoint', function (t) {
var x = linspace(ndarray([], [10]), 0, 10, {endpoint: false});
var y = ndarray([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
t.assert(ndt.equal(x, y, 1e-8));
t.end();
});
test('fills in more than one dimension', function (t) {
var x = linspace(ndarray([], [2, 2]), 0, 1);
var y = ndarray([0, 0, 1, 1], [2, 2]);
t.assert(ndt.equal(x, y, 1e-8));
t.end();
});
test('accepts a different axis', function (t) {
var x = linspace(ndarray([], [2, 2]), 0, 1, {axis: 1});
var y = ndarray([0, 1, 0, 1], [2, 2]);
t.assert(ndt.equal(x, y, 1e-8));
t.end();
});
test('uses the first point if only one point requested an endpoint = true', function (t) {
var x = linspace(ndarray([], [1]), 1, 2, {endpoint: true});
var y = ndarray([1], [1]);
t.assert(ndt.equal(x, y));
t.end();
});
test('uses the first point if only one point requested an endpoint = false', function (t) {
var x = linspace(ndarray([], [1]), 1, 2, {endpoint: false});
var y = ndarray([1], [1]);
t.assert(ndt.equal(x, y));
t.end();
});
| scijs/ndarray-linspace | test/index.js | JavaScript | mit | 2,215 |
/**
* Created by Pillar on 2015/6/12.
*/
'use strict';
var chai = require('chai');
var expect = chai.expect;
var toc = require('../lib/util/toc');
describe('Generate toc from markdown header', function () {
it('add h1 to first level', function () {
toc.start();
toc.add('jack', 1);
var result = toc.result();
//console.log('toc result is' + result);
//console.log(JSON.parse(toc.result()));
expect(result).to.eql({
//_name:'jack',
_hasChild: true,
jack: {
_hasChild: false,
level: 1
}
});
});
it('add h2 to the next level', function () {
toc.start();
toc.add('jack', 1);
toc.add('jack dog', 2);
expect(toc.result()).to.eql({
_hasChild: true,
jack: {
level: 1, _hasChild: true, 'jack dog': {
_hasChild: false,
level: 2
}
}
});
});
it('add h2 after a h3, should add a new h2', function () {
toc.start();
toc.add('main title', 1);
toc.add('chap1', 2);
toc.add('chap1.1', 3);
toc.add('chap2', 2);
toc.add('chap2.1', 3);
expect(toc.result()).to.eql(
{
_hasChild: true,
'main title': {
_hasChild: true,
level: 1,
chap1: {
_hasChild: true,
level: 2,
'chap1.1': {
_hasChild: false,
level: 3
}
},
chap2: {
_hasChild: true,
level: 2,
'chap2.1': {
_hasChild: false,
level: 3
}
}
}
}
);
});
});
| at15/doc-viewer | test/toc.js | JavaScript | mit | 2,054 |
#!/usr/bin/env node
const program = require("commander");
const fs = require("fs");
const {
default: PurgeCSS,
defaultOptions,
setOptions,
standardizeSafelist,
} = require("../lib/purgecss");
async function writeCSSToFile(filePath, css) {
try {
await fs.promises.writeFile(filePath, css);
} catch (err) {
console.error(err.message);
}
}
program
.usage("--css <css...> --content <content...> [options]")
.option("-con, --content <files...>", "glob of content files")
.option("-css, --css <files...>", "glob of css files")
.option("-c, --config <path>", "path to the configuration file")
.option(
"-o, --output <path>",
"file path directory to write purged css files to"
)
.option("-font, --font-face", "option to remove unused font-faces")
.option("-keyframes, --keyframes", "option to remove unused keyframes")
.option("-rejected, --rejected", "option to output rejected selectors")
.option(
"-s, --safelist <list...>",
"list of classes that should not be removed"
)
.option(
"-b, --blocklist <list...>",
"list of selectors that should be removed"
);
program.parse(process.argv);
const run = async () => {
// config file is not specified or the content and css are not,
// PurgeCSS will not run
if (!program.config && !(program.content && program.css)) {
program.help();
}
// if the config file is present, use it
// other options specified will override
let options = defaultOptions;
if (program.config) {
options = await setOptions(program.config);
}
if (program.content) options.content = program.content;
if (program.css) options.css = program.css;
if (program.fontFace) options.fontFace = program.fontFace;
if (program.keyframes) options.keyframes = program.keyframes;
if (program.rejected) options.rejected = program.rejected;
if (program.variables) options.variables = program.variables;
if (program.safelist)
options.safelist = standardizeSafelist(program.safelist);
if (program.blocklist) options.blocklist = program.blocklist;
const purged = await new PurgeCSS().purge(options);
const output = options.output || program.output;
// output results in specified directory
if (output) {
if (purged.length === 1 && output.endsWith(".css")) {
await writeCSSToFile(output, purged[0].css);
return;
}
for (const purgedResult of purged) {
const fileName = purgedResult.file.split("/").pop();
await writeCSSToFile(`${output}/${fileName}`, purgedResult.css);
}
} else {
console.log(JSON.stringify(purged));
}
};
try {
run();
} catch (error) {
console.error(error.message);
process.exit(1);
}
| matryer/bitbar | xbarapp.com/node_modules/purgecss/bin/purgecss.js | JavaScript | mit | 2,678 |
/*jslint browser: true, unparam: true, indent: 2, bitwise: true */
/*globals window, navigator, document, FormData, File, HTMLInputElement, XMLHttpRequest, Blob*/
var qq = function (element) {
"use strict";
return {
hide: function () {
element.style.display = 'none';
return this;
},
/** Returns the function which detaches attached event */
attach: function (type, fn) {
if (element.addEventListener) {
element.addEventListener(type, fn, false);
} else if (element.attachEvent) {
element.attachEvent('on' + type, fn);
}
return function () {
qq(element).detach(type, fn);
};
},
detach: function (type, fn) {
if (element.removeEventListener) {
element.removeEventListener(type, fn, false);
} else if (element.attachEvent) {
element.detachEvent('on' + type, fn);
}
return this;
},
contains: function (descendant) {
// compareposition returns false in this case
if (element === descendant) {
return true;
}
if (element.contains) {
return element.contains(descendant);
}
return !!(descendant.compareDocumentPosition(element) & 8);
},
/**
* Insert this element before elementB.
*/
insertBefore: function (elementB) {
elementB.parentNode.insertBefore(element, elementB);
return this;
},
remove: function () {
element.parentNode.removeChild(element);
return this;
},
/**
* Sets styles for an element.
* Fixes opacity in IE6-8.
*/
css: function (styles) {
if (styles.opacity !== null) {
if (typeof element.style.opacity !== 'string' && (element.filters) !== undefined) {
styles.filter = 'alpha(opacity=' + Math.round(100 * styles.opacity) + ')';
}
}
qq.extend(element.style, styles);
return this;
},
hasClass: function (name) {
var re = new RegExp('(^| )' + name + '( |$)');
return re.test(element.className);
},
addClass: function (name) {
if (!qq(element).hasClass(name)) {
element.className += ' ' + name;
}
return this;
},
removeClass: function (name) {
var re = new RegExp('(^| )' + name + '( |$)');
element.className = element.className.replace(re, ' ').replace(/^\s+|\s+$/g, "");
return this;
},
getByClass: function (className) {
var candidates,
result = [];
if (element.querySelectorAll) {
return element.querySelectorAll('.' + className);
}
candidates = element.getElementsByTagName("*");
qq.each(candidates, function (idx, val) {
if (qq(val).hasClass(className)) {
result.push(val);
}
});
return result;
},
children: function () {
var children = [],
child = element.firstChild;
while (child) {
if (child.nodeType === 1) {
children.push(child);
}
child = child.nextSibling;
}
return children;
},
setText: function (text) {
element.innerText = text;
element.textContent = text;
return this;
},
clearText: function () {
return qq(element).setText("");
}
};
};
qq.log = function (message, level) {
"use strict";
if (window.console) {
if (!level || level === 'info') {
window.console.log(message);
} else {
if (window.console[level]) {
window.console[level](message);
} else {
window.console.log('<' + level + '> ' + message);
}
}
}
};
qq.isObject = function (variable) {
"use strict";
return ((variable !== null) && variable && (typeof variable === "object") && (variable.constructor === Object));
};
qq.isFunction = function (variable) {
"use strict";
return (typeof variable === "function");
};
qq.trimStr = function (string) {
"use strict";
if (String.prototype.trim) {
return string.trim();
}
return string.replace(/^\s+|\s+$/g, '');
};
qq.isFileOrInput = function (maybeFileOrInput) {
"use strict";
if (qq.isBlob(maybeFileOrInput) && window.File && maybeFileOrInput instanceof File) {
return true;
}
if (window.HTMLInputElement) {
if (maybeFileOrInput instanceof HTMLInputElement) {
if (maybeFileOrInput.type && maybeFileOrInput.type.toLowerCase() === 'file') {
return true;
}
}
} else if (maybeFileOrInput.tagName) {
if (maybeFileOrInput.tagName.toLowerCase() === 'input') {
if (maybeFileOrInput.type && maybeFileOrInput.type.toLowerCase() === 'file') {
return true;
}
}
}
return false;
};
qq.isBlob = function (maybeBlob) {
"use strict";
return window.Blob && maybeBlob instanceof Blob;
};
qq.isXhrUploadSupported = function () {
"use strict";
var input = document.createElement('input');
input.type = 'file';
return (input.multiple !== undefined && File !== undefined && FormData !== undefined && (new XMLHttpRequest()).upload !== undefined);
};
qq.isFolderDropSupported = function (dataTransfer) {
"use strict";
return (dataTransfer.items && dataTransfer.items[0].webkitGetAsEntry);
};
qq.isFileChunkingSupported = function () {
"use strict";
return !qq.android() && qq.isXhrUploadSupported() && (File.prototype.slice || File.prototype.webkitSlice || File.prototype.mozSlice);
};
qq.extend = function (first, second, extendNested) {
"use strict";
qq.each(second, function (prop, val) {
if (extendNested && qq.isObject(val)) {
if (first[prop] === undefined) {
first[prop] = {};
}
qq.extend(first[prop], val, true);
} else {
first[prop] = val;
}
});
};
/**
* Searches for a given element in the array, returns -1 if it is not present.
* @param {Number} [from] The index at which to begin the search
*/
qq.indexOf = function (arr, elt, from) {
"use strict";
var len = arr.length, i;
if (arr.indexOf) {
return arr.indexOf(elt, from);
}
from = from || 0;
if (from < 0) {
from += len;
}
for (i = 0; from < len; from += 1) {
if (arr.hasOwnProperty(from) && arr[from] === elt) {
return from;
}
i += 1;
if (i > len) {
return -1;
}
}
return -1;
};
//this is a version 4 UUID
qq.getUniqueId = function () {
"use strict";
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
/*jslint eqeq: true, bitwise: true*/
var r = Math.random() * 16 | 0,
v = c == 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
};
//
// Browsers and platforms detection
qq.ie = function () {
"use strict";
return navigator.userAgent.indexOf('MSIE') !== -1;
};
qq.ie10 = function () {
"use strict";
return navigator.userAgent.indexOf('MSIE 10') !== -1;
};
qq.safari = function () {
"use strict";
return navigator.vendor !== undefined && navigator.vendor.indexOf("Apple") !== -1;
};
qq.chrome = function () {
"use strict";
return navigator.vendor !== undefined && navigator.vendor.indexOf('Google') !== -1;
};
qq.firefox = function () {
"use strict";
return (navigator.userAgent.indexOf('Mozilla') !== -1 && navigator.vendor !== undefined && navigator.vendor === '');
};
qq.windows = function () {
"use strict";
return navigator.platform === "Win32";
};
qq.android = function () {
"use strict";
return navigator.userAgent.toLowerCase().indexOf('android') !== -1;
};
//
// Events
qq.preventDefault = function (e) {
"use strict";
if (e.preventDefault) {
e.preventDefault();
} else {
e.returnValue = false;
}
};
/**
* Creates and returns element from html string
* Uses innerHTML to create an element
*/
qq.toElement = (function () {
"use strict";
var div = document.createElement('div');
return function (html) {
div.innerHTML = html;
var element = div.firstChild;
div.removeChild(element);
return element;
};
}());
//key and value are passed to callback for each item in the object or array
qq.each = function (obj, callback) {
"use strict";
var key, retVal;
if (obj) {
for (key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
retVal = callback(key, obj[key]);
if (retVal === false) {
break;
}
}
}
}
};
/**
* obj2url() takes a json-object as argument and generates
* a querystring.
*
* how to use:
*
* `qq.obj2url({a:'b',c:'d'},'http://any.url/upload?otherParam=value');`
*
* will result in:
*
* `http://any.url/upload?otherParam=value&a=b&c=d`
*
* @param Object JSON-Object
* @param String current querystring-part
* @return String encoded querystring
*/
qq.obj2url = function (obj, temp, prefixDone) {
"use strict";
/*jshint laxbreak: true*/
var i, len,
uristrings = [],
prefix = '&',
add = function (nextObj, i) {
var nextTemp = temp ? (/\[\]$/.test(temp)) ? temp : temp + '[' + i + ']' : i;
if ((nextTemp !== undefined) && (i !== undefined)) {
uristrings.push(
(typeof nextObj === 'object') ? qq.obj2url(nextObj, nextTemp, true) : (Object.prototype.toString.call(nextObj) === '[object Function]') ? encodeURIComponent(nextTemp) + '=' + encodeURIComponent(nextObj()) : encodeURIComponent(nextTemp) + '=' + encodeURIComponent(nextObj)
);
}
};
if (!prefixDone && temp) {
prefix = (/\?/.test(temp)) ? (/\?$/.test(temp)) ? '' : '&' : '?';
uristrings.push(temp);
uristrings.push(qq.obj2url(obj));
} else if ((Object.prototype.toString.call(obj) === '[object Array]') && (obj !== undefined)) {
// we wont use a for-in-loop on an array (performance)
for (i = -1, len = obj.length; i < len; i += 1) {
add(obj[i], i);
}
} else if ((obj !== undefined) && (obj !== null) && (typeof obj === "object")) {
// for anything else but a scalar, we will use for-in-loop
for (i in obj) {
if (obj.hasOwnProperty(i)) {
add(obj[i], i);
}
}
} else {
uristrings.push(encodeURIComponent(temp) + '=' + encodeURIComponent(obj));
}
if (temp) {
return uristrings.join(prefix);
}
return uristrings.join(prefix).replace(/^&/, '').replace(/%20/g, '+');
};
qq.obj2FormData = function (obj, formData, arrayKeyName) {
"use strict";
if (!formData) {
formData = new FormData();
}
qq.each(obj, function (key, val) {
key = arrayKeyName ? arrayKeyName + '[' + key + ']' : key;
if (qq.isObject(val)) {
qq.obj2FormData(val, formData, key);
} else if (qq.isFunction(val)) {
formData.append(key, val());
} else {
formData.append(key, val);
}
});
return formData;
};
qq.obj2Inputs = function (obj, form) {
"use strict";
var input;
if (!form) {
form = document.createElement('form');
}
qq.obj2FormData(obj, {
append: function (key, val) {
input = document.createElement('input');
input.setAttribute('name', key);
input.setAttribute('value', val);
form.appendChild(input);
}
});
return form;
};
qq.setCookie = function (name, value, days) {
"use strict";
var date = new Date(),
expires = "";
if (days) {
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toGMTString();
}
document.cookie = name + "=" + value + expires + "; path=/";
};
qq.getCookie = function (name) {
"use strict";
var nameEQ = name + "=",
ca = document.cookie.split(';'),
c,
i;
for (i = 0; i < ca.length; i += 1) {
c = ca[i];
while (c.charAt(0) === ' ') {
c = c.substring(1, c.length);
}
if (c.indexOf(nameEQ) === 0) {
return c.substring(nameEQ.length, c.length);
}
}
};
qq.getCookieNames = function (regexp) {
"use strict";
var cookies = document.cookie.split(';'),
cookieNames = [],
equalsIdx;
qq.each(cookies, function (idx, cookie) {
cookie = qq.trimStr(cookie);
equalsIdx = cookie.indexOf("=");
if (cookie.match(regexp)) {
cookieNames.push(cookie.substr(0, equalsIdx));
}
});
return cookieNames;
};
qq.deleteCookie = function (name) {
"use strict";
qq.setCookie(name, "", -1);
};
qq.areCookiesEnabled = function () {
"use strict";
var randNum = Math.random() * 100000,
name = "qqCookieTest:" + randNum;
qq.setCookie(name, 1);
if (qq.getCookie(name)) {
qq.deleteCookie(name);
return true;
}
return false;
};
/**
* Not recommended for use outside of Fine Uploader since this falls back to an unchecked eval if JSON.parse is not
* implemented. For a more secure JSON.parse polyfill, use Douglas Crockford's json2.js.
*/
qq.parseJson = function (json) {
"use strict";
if (window.JSON && qq.isFunction(JSON.parse)) {
return JSON.parse(json);
}
/*jslint evil: true */
return eval("(" + json + ")");
};
/**
* A generic module which supports object disposing in dispose() method.
* */
qq.DisposeSupport = function () {
"use strict";
var disposers = [];
return {
/** Run all registered disposers */
dispose: function () {
var disposer;
do {
disposer = disposers.shift();
if (disposer) {
disposer();
}
} while (disposer);
},
/** Attach event handler and register de-attacher as a disposer */
attach: function () {
var args = arguments;
this.addDisposer(qq(args[0]).attach.apply(this, Array.prototype.slice.call(arguments, 1)));
},
/** Add disposer to the collection */
addDisposer: function (disposeFunction) {
disposers.push(disposeFunction);
}
};
};
| SimonWaldherr/uploader | client/js/util.js | JavaScript | mit | 13,542 |
var short_grass={
opaque: { base_value: 0.4 , pointsList: { pressure:[0,0,1,0.4] } } ,
opaque_multiply:{ base_value: 0.0, pointsList:{ pressure:[0,0,1,1] } } ,
opaque_linearize:{ base_value:0.0},
radius_logarithmic:{base_value: 2.5 },
hardness :{base_value: 0.91} ,
dabs_per_basic_radius:{base_value: 0.0 } ,
dabs_per_actual_radius:{base_value: 3.24} ,
dabs_per_second:{base_value: 0.0} ,
radius_by_random:{base_value: 0.0} ,
speed1_slowness:{base_value: 0.04} ,
speed2_slowness:{base_value: 0.8} ,
speed1_gamma:{base_value: 4.0} ,
speed2_gamma:{base_value: 4.0} ,
offset_by_random:{base_value: 1.79 , pointsList: { pressure:[0,0,1,-1.4] } } ,
offset_by_speed:{base_value: 0.0} ,
offset_by_speed_slowness:{base_value: 1.0} ,
slow_tracking:{base_value: 2.0} ,
slow_tracking_per_dab:{base_value: 0.0} ,
color_value:{base_value: 0.0712} ,
color_saturation:{base_value: 0.306} ,
color_hue:{base_value: 0.625} ,
change_color_h:{base_value:0.0, pointsList: {random:[0,-0.05,1,0.05],stroke :[0,-0.004687,1, 0.004792] }} ,
change_color_l:{base_value:0.0},
change_color_hsl_s:{base_value:0.0 , pointsList:{random:[0,-0.01,1,0.01] }},
change_color_v:{base_value:0.0 , pointsList:{random:[0,-0.28,1,0.28],stroke:[0,-0.23,0.5,0.23,1,-0.227604]}},
change_color_hsv_s:{base_value:0.0},
change_radius:{base_value: 0.0} ,
smudge:{base_value: 0.0} ,
smudge_length:{base_value: 0.5} ,
stroke_treshold:{base_value: 0.0} ,
stroke_duration_logarithmic:{base_value: 5.96} ,
stroke_holdtime:{base_value: 0},
custom_input:{base_value:0.0},
custom_input_slowness:{base_value:0.0},
elliptical_dab_ratio:{base_value:3.91},
elliptical_dab_angle:{base_value:90.0 , pointsList:
{random:[0,-36.46,0.11039,-4.177708,0.899351,4.557500,1,36.460000]}},
direction_filter:{base_value:2.0}
} ; | sqircle/BrushE.js | dist/brushes/short_grass.js | JavaScript | mit | 1,755 |
/***************************************************************************************
jQuery 增删查改功能
Create Date:2015.1.20
Create By:bird
Last Update Date:2016.7.12
Last Update By:bird
修改日志
2015.1.20 创建文件
2016.4.18 新增按钮动作绑定监听
2016.4.26 为删除功能设置传入数组参数delparam[],数组容量为2
delparam[0]为参数名 delparam[1]为获取参数值的html标签id或class
为预更新功能设置传入数组参数updateparam[]
updateparam[0]为参数名 updateparam[1]为获取参数值的html标签id或class
2016.4.27 新增数据更新功能
2016.4.28 bug:{
翻页时需要对删除按钮和预更新按钮被重置,所以每次翻页时需要重新执行绑定监听函数,
而确认更新按钮并没有被重置,所以导致了确认按钮被重复绑定了多次监听,点一下确认更新按钮会导致更新多次
}
解决方法:在绑定监听函数前,新增了解绑函数,绑定前先解绑,避免事件重复绑定
2016.5.3 新增条件查询功能
2016.5.10 新增隐藏空白行功能,当当前页数据不足一页时,自动遍历设置空白行display:none
2016.5.11 代码调优,由300行代码减少至150行
2016.7.12 代码优化,并新增插件配置说明
2016.8.11 整合Spring框架进行的小修改 by sam.t
2016.8.16 新增global函数,validate(),
验证更新框中的所有required的input框的值,返回一个boolean值validateFlag
点击更新按钮时,验证validateFlag,如果为true,则可以更新
如果为false,则存在值为空的必填项
2016.8.26 优化代码,减少输入参数
2016.8.31 新增条件查询功能
2017.1.5 新增匿名函数功能:afterdatafunc,作用是数据完成后自动执行的
对应的crudtype方法:pre-update/update/insert/lovquery
***************************************************************************************/
(function($) {
/******************listener start***********************
监听 data-crudtype 传递的值
暂时只设置对<input> <button> <a> <i> 四种标签的监听绑定
如需为其他更多元素增加点击弹出框效果
请在listener区域绑定新的监听标签
*******************************************************/
$.fn.crudListener = function(){
/****清除绑定****/
$('input[data-crudtype]').off('click');
$('input[data-name]').off('change');
$('button[data-crudtype]').off('click');
$('a[data-crudtype]').off('click');
$('i[data-crudtype]').off('click');
/****绑定<input>标签****/
$('input[data-crudtype]').on('click', function() {
$(this).crud($(this).data());
});
$('input[data-name]').on('change', function() {
$(this).setname($(this).data());
});
/****绑定<button>标签****/
$('button[data-crudtype]').on('click', function() {
$(this).crud($(this).data());
});
/****绑定<a>标签****/
$('a[data-crudtype]').on('click', function(e) {
e.preventDefault();//阻止<a>标签默认的点击事件(超链接跳转)
$(this).crud($(this).data());
});
/****绑定<i>标签****/
$('i[data-crudtype]').on('click', function() {
$(this).crud($(this).data());
});
}
/******************listener end***********************/
$.fn.crud = function(options) {
/*********************************************
设置默认属性
*********************************************/
var defaults={
load:'.ajax_loading',
pageframe:'lov',
refresh:'refresh',
func:null
}
/******继承默认属性******/
var options = $.extend({}, defaults, options);
var tablename=$('#'+options.pageframe).attr('data-table');
/****全局函数****/
jQuery.global={
/******判断当前页是否为首页或末页******/
pageFlag:function(firstPageFlag,lastPageFlag){
if(firstPageFlag=='true'){/****判断是否为首页,若是,隐藏第一页与上一页按钮****/
$('#'+options.pageframe+' i[data-pagetype="prevpage"]').css('display','none');
$('#'+options.pageframe+' i[data-pagetype="firstpage"]').css('display','none');
}else{
$('#'+options.pageframe+' i[data-pagetype="prevpage"]').css('display','');
$('#'+options.pageframe+' i[data-pagetype="firstpage"]').css('display','');
}
if(lastPageFlag=='true'){/****判断是否为末页,若是,隐藏最后一页与下一页按钮****/
$('#'+options.pageframe+' i[data-pagetype="lastpage"]').css('display','none');
$('#'+options.pageframe+' i[data-pagetype="nextpage"]').css('display','none');
}else{
$('#'+options.pageframe+' i[data-pagetype="lastpage"]').css('display','');
$('#'+options.pageframe+' i[data-pagetype="nextpage"]').css('display','');
}
},
validate:function(){
var input=$('#'+options.pageframe+' [required="required"]');
validate_flag=true;
for(i=0;i<input.length;i++){
if(input[i].value==''||input[i].value==null){
id=input[i].id;
label=$('#'+options.pageframe+' label[for="'+id+'"]').text();
layer.alert('提交失败!错误信息:'+label+'不能为空!',{title:'警告',offset:[150]});
input[i].focus();
validate_flag=false;
return;
}else{
continue;
}
}
}
}
return this.each(function() {
/******删除方法******/
if(options.crudtype=='del'){
tr=$(this).parent().parent();
col=tr.children('.'+options.col).text();
result=confirm(options.delmsg+col+'?');
if(result==true){
param=options.delparam[0]+'='+tr.children(options.delparam[1]).text();
$.ajax({
type:'post',
data:param,
url:options.delurl,
dataType:'json',
success: function (data) {
if(data.retcode=="0"){
layer.msg("删除成功!");
$('#'+options.refresh).click();/****点击刷新当前页按钮,刷新数据****/
}else{
layer.alert("删除失败!错误信息:"+data.errbuf,{title:'警告',offset:[150]});
}
},
error: function () {
layer.alert('获取Json数据失败',{title:'警告',offset:[150]});
}
});
return;
}else{
result=null;
}
}
/******预更新方法******/
else if(options.crudtype=='pre-update'){
pageframe=$(this).attr('data-reveal-id');
param = '';
tr=$(this).parent().parent();
if(options.func!=null||options.func!=''){
eval(options.func);
}
//console.log(param);
$('#'+pageframe+' input[data-update="db"]').val('');
$('#'+pageframe+' input[type="checkbox"]').prop('checked',false);
$('#'+pageframe+' select[data-update="db"]').val('');
$('#'+pageframe+' textarea[data-update="db"]').val('');
$('#'+pageframe+' span[data-type]').hide();
$('#'+pageframe+' button[data-type]').hide();
$('#'+pageframe+' span[data-type="'+options.type+'"]').show();
$('#'+pageframe+' button[data-type="'+options.type+'"]').show();
param=param+options.updateparam[0]+'='+tr.children(options.updateparam[1]).text();/****设置参数****/
//console.log(param);
$.ajax({
type:'post',
data:param,
url:options.preupdateurl,
dataType:'json',
success: function (data) {
jQuery.json.getUpdateJSON(data,pageframe);/****获取目标更新行数据****/
if(options.afterdatafunc!=null||options.afterdatafunc!=''){//2017.1.5新增匿名函数功能:数据完成后自动执行的
eval(options.afterdatafunc);
}
},
error: function () {
//alert("获取Json数据失败");
layer.alert('获取Json数据失败',{title:'警告',offset:[150]});
}
});
}
/******更新方法******/
else if(options.crudtype=='update'){
jQuery.global.validate();
if(validate_flag==true){
/****************************/
param=$('#'+options.pageframe+' form').serialize();
if(options.func!=null||options.func!=''){
eval(options.func);
}
//console.log(param);
//param=options.updateparam[0]+'='+$(options.updateparam[1]).val()+'&'+param;/****设置参数****/
//modify by bird 2016.10.26
$.ajax({
type:'post',
data:param,
url:options.updateurl,
dataType:'json',
success: function (data) {
if(data.retcode=="0"){
layer.msg("更新成功!");
$('#'+options.pageframe+' a[data-type="close"]').click();/****点击关闭更新框按钮****/
$('#'+options.refresh).click();/****点击刷新当前页按钮,刷新数据****/
}else{
layer.alert("更新处理失败!错误信息:"+data.errbuf,{title:'警告',offset:[150]});
}
if(options.afterdatafunc!=null||options.afterdatafunc!=''){//2017.1.5新增匿名函数功能:数据完成后自动执行的
eval(options.afterdatafunc);
}
},
error: function () {
layer.alert('获取Json数据失败',{title:'警告',offset:[150]});
}
});
/*****************************************/
}else{
return;
}
}
/******预新增方法******/
else if(options.crudtype=='pre-insert'){
$(options.load).show();/****显示加载动画****/
pageframe=$(this).attr('data-reveal-id');
if(options.func!=null||options.func!=''){
eval(options.func);
}
$('#'+pageframe+' span[data-type]').hide();
$('#'+pageframe+' button[data-type]').hide();
$('#'+pageframe+' span[data-type="'+options.type+'"]').show();
$('#'+pageframe+' button[data-type="'+options.type+'"]').show();
$('#'+pageframe+' input[data-update="db"]').val('');
$('#'+pageframe+' input[type="checkbox"]').prop('checked',false);
$('#'+pageframe+' select[data-update="db"]').val('');
$('#'+pageframe+' textarea[data-update="db"]').val('');
$(options.load).hide();
}
/******新增方法******/
else if(options.crudtype=='insert'){
jQuery.global.validate();
if(validate_flag==true){
/****************************/
param=$('#'+options.pageframe+' form').serialize();
if(options.func!=null||options.func!=''){
eval(options.func);
}
//console.log(param);
$.ajax({
type:'post',
data:param,
url:options.inserturl,
dataType:'json',
success: function (data) {
if(data.retcode=="0"){
layer.msg("新增成功!");
$('#'+options.pageframe+' a[data-type="close"]').click();/****点击关闭更新框按钮****/
$('#'+options.refresh).click();/****点击刷新当前页按钮,刷新数据****/
}else{
layer.alert("新增处理失败!错误信息:"+data.errbuf,{title:'警告',offset:[150]});
}
if(options.afterdatafunc!=null||options.afterdatafunc!=''){//2017.1.5新增匿名函数功能:数据完成后自动执行的
eval(options.afterdatafunc);
}
},
error: function () {
layer.alert('获取Json数据失败',{title:'警告',offset:[150]});
}
});
/*****************************************/
}else{
return;
}
}
/******条件查询方法******/
else if(options.crudtype=='query'){
cond=$('#'+options.pageframe+' form').serialize();
if(options.func!=null||options.func!=''){
eval(options.func);
}
//console.log(cond);
$('#'+options.buttonframe+' input[data-type="cond"]').val(cond);
$('#'+options.buttonframe+' input[data-type="number"]').val(1);
$('#'+options.pageframe+' a[data-type="close"]').click();
$('#'+options.buttonframe+' i[data-pagetype="refresh"]').click();
}
/******lov条件查询方法******/
else if(options.crudtype=='lovquery'){
param=$('option:selected',$('#'+options.pageframe+' select[data-type="select"]')).val();
value=$('#'+options.pageframe+' input[data-type="query_val"]').val();
if(!value){
param=null;
}else{
/***************************************
因为%在url中为转义符,%25表达%字符本身,
所以需要使用正则表达式全局替换,把字符串中
所有的%替换为%25
*****************************************/
value=value.replace(/%/g,'%25');
param=param+'='+value;
}
pageSize=parseInt($('#'+options.pageframe+' input[data-type="size"]').val());
pageNo=parseInt(1);
$('#'+options.pageframe+' input[data-type="number"]').val(pageNo);
param=param+'&pageSize='+pageSize+'&pageNo='+pageNo;
extendParam = $('#'+options.pageframe+' input[data-type="extend_param"]').val();
if(extendParam!=null||extendParam!=''){
param = param + extendParam;
}
queryurl=$('#'+options.pageframe+' input[data-type="url"]').val();
$.ajax({
type:'post',
data:param,
url:queryurl,
dataType:'json',
success: function (data) {
$('table[data-table="'+tablename+'"] td').html('');
if(data.rows.length==0){
layer.msg('提示: 查询无数据!');
return false;
}
jQuery.json.getMSG(data);
$('table[data-table="'+tablename+'"] tr').css('display','');
jsontype=$('#'+options.pageframe+' input[data-type="jsontype"]').val();
jQuery.json.getContent(data,jsontype);
for(j=0;j<=(pageSize-(pageMaxRow-pageMinRow+1));j++){/****隐藏空白行****/
$('table[data-table="'+tablename+'"] tr:eq('+(pageSize-j+1)+')').css('display','none');
};
jQuery.global.pageFlag(firstPageFlag,lastPageFlag);
if(parseInt(data.pageMinRow)==0){
$('#'+options.pageframe+' i[data-pagetype="nextpage"]').css('display','none');
}
width='-'+parseInt($('#'+options.pageframe).css('width'))/2+'px';
$('#'+options.pageframe).css('margin-left',width);
if(options.afterdatafunc!=null||options.afterdatafunc!=''){//2017.1.5新增匿名函数功能:数据完成后自动执行的
eval(options.afterdatafunc);
}
},
error: function () {
layer.alert('获取Json数据失败',{title:'警告',offset:[150]});
}
});
}
});
}
$.fn.setname = function(options) {
/*********************************************
设置默认属性
*********************************************/
var defaults={
fullname:'FULL_NAME'
}
/******继承默认属性******/
var options = $.extend({}, defaults, options);
return this.each(function() {
/******姓******/
if(options.name=='LAST_NAME'){
lastname=$(this).val();
fullname=$('#'+options.fullname).val();
str=fullname.split(',');
if(str[1]==null||str[1]==''||str[1]==undefined){
fullname=lastname;
}else{
fullname=lastname+','+str[1];
}
$('#'+options.fullname).val(fullname);
}
/******名******/
else if(options.name=='FIRST_NAME'){
firstname=$(this).val();
fullname=$('#'+options.fullname).val();
str=fullname.split(',');
if(str[0]==null||str[0]==''||str[0]==undefined){
if(firstname==null||firstname==''){
fullname=firstname;
}else{
fullname=','+firstname;
}
}else{
if(firstname==null||firstname==''){
fullname=str[0];
}else{
fullname=str[0]+','+firstname;
}
}
$('#'+options.fullname).val(fullname);
}
});
}
$.fn.validateRequired = function(pageframe){
var input=$('#'+pageframe+' [required="required"]');
validate_flag=true;
for(i=0;i<input.length;i++){
if(input[i].value==''||input[i].value==null){
id=input[i].id;
label=$('#'+pageframe+' label[for="'+id+'"]').text();
layer.alert('提交失败!错误信息:'+label+'不能为空!',{title:'警告',offset:[150]});
input[i].focus();
validate_flag=false;
return validate_flag;
}else{
continue;
}
}
return validate_flag;
}
//栏位清除按钮
$('i[data-eraser]').on('click',function(){
eraser=$(this).data('eraser');
for(m=0;m<eraser.length;m++){
$('#'+eraser[m]).val('');
}
});
//2017.1.9 二次封装返回数据匹配json的方法
/*
* data:返回的分页数据
* table:mapContent对应的table的选择器
* mapRowArray:匹配关系数组定义。
* 是一个数组,可以是匹配完整模式:[['.HEADER_ID','HEADER_ID'],['.DEPARTMENT_CODE',DEPARTMENT_CODE],...]
* 也可以是简写:['HEADER_ID','DEPARTMENT_CODE',...]
*/
$.fn.mapContentJson = function(data,table,mapRowArray){
var minRow=parseInt(data.pageMinRow);
var maxRow=parseInt(data.pageMaxRow);
if(maxRow==0&&minRow==0){
console.log('no data');
return false;
}
for(i=0;i<(maxRow-minRow+1);i++){
var $trRow=$(table).find('tr:eq('+(i+1)+')');
//console.log('typeof:'+typeof mapRowArray);console.log($trRow[0]);
for(var n in mapRowArray){
if(typeof mapRowArray[n]=='object'){
//console.log('col:'+mapRowArray[n][0]+',json:'+data.rows[i][mapRowArray[n][1]]);
$trRow.find(mapRowArray[n][0]).html(data.rows[i][mapRowArray[n][1]]);
if(mapRowArray[n][2]&&typeof mapRowArray[n][2]== "function"){
mapRowArray[n][2].call();
}
}else if(typeof mapRowArray[n]=='string'){
$trRow.find('.'+mapRowArray[n]).html(data.rows[i][mapRowArray[n]]);
}else{
alert('mapRowArray 定义有误!请联系ERP确认处理!');
}
}
}
/*“原生”的执行方式:
for(i=0;i<(pageMaxRow-pageMinRow+1);i++){
var $trRow=$('#worklogHeader tr:eq('+(i+1)+')');
$('.HEADER_ID',$trRow).html(data.rows[i].HEADER_ID);
$('.DEPARTMENT_CODE',$trRow).html(data.rows[i].DEPARTMENT_CODE);
$('.DEPARTMENT_DESC',$trRow).html(data.rows[i].DEPARTMENT_DESC);
$('.WORK_GROUP',$trRow).html(data.rows[i].WORK_GROUP);
$('.WORK_GROUP_DESC',$trRow).html(data.rows[i].WORK_GROUP_DESC);
$('.WORK_ITEM',$trRow).html(data.rows[i].WORK_ITEM);
$('.WORK_REQ_DOCUMENT',$trRow).html(data.rows[i].WORK_REQ_DOCUMENT);
$('.WORK_REQUEST_NAME',$trRow).html(data.rows[i].WORK_REQUEST_NAME);
$('.WORK_OWNER_NAME',$trRow).html(data.rows[i].WORK_OWNER_NAME);
$('.WORK_DATE',$trRow).html(data.rows[i].WORK_DATE);
$('.DESCRIPTION',$trRow).html(data.rows[i].DESCRIPTION);
}*/
}
/*
* data:返回的更新的数据
* mapRowArray:匹配关系数组定义。
* 是一个数组,可以是匹配完整模式:[['#H_ID','HEADER_ID'],['#DEPARTMENT_CODE',DEPARTMENT_CODE],...]
* 如果可以确定ID匹配的代码和json的名称是一样,也可以是简写:['HEADER_ID','DEPARTMENT_CODE',...]
* 注意:匹配完整模式,第三个参数可以是一个匿名函数。如果有定义,则会自动执行。
* 例如:['#WORK_GROUP','WORK_GROUP',function(){$().listCreator($('#WORK_GROUP')[0]);}]
*/
$.fn.mapUpdateJson = function(data,mapRowArray){
for(var n in mapRowArray){
if(typeof mapRowArray[n]=='object'){
$(mapRowArray[n][0]).val(data.rows[0][mapRowArray[n][1]]);
if(mapRowArray[n][2]&&typeof mapRowArray[n][2]== "function"){
mapRowArray[n][2].call();
}
}else if(typeof mapRowArray[n]=='string'){
$('#'+mapRowArray[n]).val(data.rows[0][mapRowArray[n]]);
}else{
alert('mapUpdateJson-->mapRowArray 定义有误!请联系ERP确认处理!');
}
}
/*需要注意的是:如果有些特殊的代码要写在定义json的时候赋值的,
* 可以考虑用最原生的脚本写。
* 例如下面的自动刷新List的逻辑。
* 也可以用定义匿名函数自动执行。
$('#H_ID').val(data.rows[0].H_ID);
$('#DEPARTMENT_CODE').val(data.rows[0].DEPARTMENT_CODE);
$().listCreator($('#WORK_GROUP')[0]);//需要在这里自动重新刷新list
$('#WORK_GROUP').val(data.rows[0].WORK_GROUP);
$('#WORK_ITEM').val(data.rows[0].WORK_ITEM);
$('#WORK_REQ_DOCUMENT').val(data.rows[0].WORK_REQ_DOCUMENT);
$('#WORK_REQUEST_PID').val(data.rows[0].WORK_REQUEST_PID);
$('#WORK_REQUEST_NAME').val(data.rows[0].WORK_REQUEST_NAME);
$('#WORK_OWNER_PID').val(data.rows[0].WORK_OWNER_PID);
$('#WORK_OWNER_NAME').val(data.rows[0].WORK_OWNER_NAME);
$('#WORK_DATE').val(data.rows[0].WORK_DATE);
$('#DESCRIPTION').val(data.rows[0].DESCRIPTION);*/
}
})(jQuery);
/*****************************插件配置说明*****************************
@ 配置参数
@
@ 暂无,待更新
@
*******************************************************************/ | xygdev/XYG_ALB2B | WebRoot/plugin/js/jQuery.crud.js | JavaScript | mit | 22,836 |
var isEmpty=require('./utils/null').isEmpty;
var path=require('./utils/path').path;
var walk=require('./utils/path').walk;
//helper
var buildQuery=function(query,test,dryOptionFlag)
{
var q=path(query,"q");
if(q === null)
{
q={};
}else
{
q=JSON.parse(q);
}
var options={};
walk(q,function(val)
{
var match=val.match(/^\/(.+)\/$/);
if(match===null)
{
return val;
}else
{
return new RegExp(match[1]);
}
})
for(var prop in query)
{
var key=prop, val=query[prop];
if(prop === "q")
{
continue;
}
var match=val.match(/^\/(.+)\/$/);
if(match===null)
{
if(test.indexOf(prop)>=0)
{
var realprop;
if(!!dryOptionFlag)
{
realprop=prop.replace(/^_/,"");//remove the "_" prefix
}else
{
realprop=prop
}
options[realprop]=val;
}else
{
try{
q[prop]=JSON.parse(val);
}catch(e)
{
q[prop]=val;
}
}
}else
{
val=new RegExp(match[1]);
q[prop]=val;
}
}
return [q,
options
]
}
//class
var MongoDBManager=function(config){
if(typeof config === 'undefined')
{
config={};
}
this.hostname = config.hostname || 'localhost'
this.port = config.port || '27017'
this.dbName = config.dbName || 'test'
this.mongoose=require("mongoose");
this.connection=null;
this.connect();
}
MongoDBManager.prototype.getConnectionString=function()
{
return 'mongodb://'+ this.hostname + ':' + this.port + '/' + this.dbName;
}
MongoDBManager.prototype.reconnect=function()
{
if(this.mongoose.connection.readyState === 0)
{
this.connect();
}
}
MongoDBManager.prototype.isConnected=function()
{
return this.mongoose.connection.readyState === 1;
}
MongoDBManager.prototype.connect=function()
{
console.log("connect to " + this.getConnectionString());
this.mongoose.connect(this.getConnectionString());
connection=this.mongoose.connection;
connection.on('error',function(err){
//quite quietly
console.error(err);
})
connection.once('open',function(){
console.log("connection to the mongodb is established");
})
}
MongoDBManager.prototype._limit=function(mQuery,val)
{
mQuery.limit(Number(val));
}
MongoDBManager.prototype._sort=function(mQuery,val)
{
mQuery.sort(val);
}
MongoDBManager.prototype._select=function(mQuery,val)
{
mQuery.select(val);
}
MongoDBManager.prototype.update=function(Model,query,data,callBack,onError)
{
try
{
var queryoption=buildQuery(query,[
"_safe"
,"_upsert"
,"_multi"
,"_strict"
,"_overwrite"
],true);
var query=queryoption[0],options=queryoption[1];
options.multi = options.multi || true;//reset the default value of the options
Model.update(query,data,options,callBack);
}catch(e)
{
if(!!onError) onError(e);
console.error(e);
}
}
MongoDBManager.prototype.delete=function(Model,query,callBack)
{
var that=this;
if(isEmpty(query))
{
callBack({error:1,message: "Can't delete all by empty parameters" });
return;
}
var q=path(query,"q");
if(q === null)
{
q={};
}else
{
q=JSON.parse(q);
}
walk(q,function(val)
{
var match=val.match(/^\/(.+)\/$/);
if(match===null)
{
return val;
}else
{
return new RegExp(match[1]);
}
});
for(var prop in query)
{
var key=prop, val=query[prop];
if(prop === "q")
{
continue;
}
var match=val.match(/^\/(.+)\/$/);
if(match===null)
{
try{
q[prop]=JSON.parse(val);
}catch(e)
{
q[prop]=val;
}
}else
{
val=new RegExp(match[1]);
q[prop]=val;
}
}
Model.remove(q,callBack);
}
MongoDBManager.prototype.query=function(Model,query,callBack)
{
var that=this;
if(isEmpty(query))
{
Model.find().exec(callBack);
return;
}
var q=path(query,"q");
if(q === null)
{
q={};
}else
{
q=JSON.parse(q);
}
var options={};
var test=["_limit","_sort","_select"];
walk(q,function(val)
{
var match=val.match(/^\/(.+)\/$/);
if(match===null)
{
return val;
}else
{
return new RegExp(match[1]);
}
})
for(var prop in query)
{
var key=prop, val=query[prop];
if(prop === "q")
{
continue;
}
var match=val.match(/^\/(.+)\/$/);
if(match===null)
{
if(test.indexOf(prop)>=0)
{
options[prop]=val;
}else
{
try{
q[prop]=JSON.parse(val);
}catch(e)
{
q[prop]=val;
}
}
}else
{
val=new RegExp(match[1]);
q[prop]=val;
}
}
var mongoQuery=Model.find(q);
for(var prop in options)
{
this[prop].call(this,mongoQuery,options[prop]);
}
mongoQuery.exec(callBack);
}
exports.getInstance=function(config)
{
return new MongoDBManager(config);
} | stelee/NeoCRM | libs/mongodb_manager.js | JavaScript | mit | 4,545 |
(function(win){
var cfg={gap:20};
var lastOpen=null;
function genTree(dom,url,handler){
if(typeof(dom)=="string") dom=document.getElementById(dom);
var data=JSON.parse(ajax(url));
//console.log(data);
var str="";
data.forEach(function(e){
str+="<div v="+e.v+" path="+e.path+">"+e.name+"</div>";
})
dom.innerHTML=str;
makeTree(dom,handler);
}
function makeTree(dom,handler){/*把一个dom 变成tree*/
for(var i=0;i<dom.childNodes.length;){
var c=dom.childNodes[i];
if(c.nodeType==3) dom.removeChild(c);
else i++;
}
var len=dom.children.length;
for(var i=0;i<len;i++){
var node=dom.children[i];
var v=parseInt(node.getAttribute("v"));
node.v=v;
node.c=0;
if(v>2) node.c=v-2;
/*要压缩的级别 compress 第三级进入可视区域要把所有都压缩一级 第四级压缩两级 以此类推*/
node.style.marginLeft=v*cfg.gap+"px";
if(v>1) cssAdd(node,"hide");/*默认只显示第一级别子节点*/
if(i>0&&dom.children[i-1].v==node.v-1){
dom.children[i-1].className="node";
dom.children[i-1].isNode=true;
dom.children[i-1].onclick=function(evt){nodeClick(evt,handler);};
}
else if(i>0){
dom.children[i-1].className="leaf";
dom.children[i-1].onclick=handler;
}
}
dom.children[len-1].className="leaf";/*最后一个必定是叶节点*/
dom.children[0].click();
}
function nodeClick(evt,handler){/*展示子节点*/
var node=evt.target;
if(node.className=="node open"&&lastOpen==node){
node.className="node collapse";
collapse(node);
lastOpen=null;
}
else{
node.className="node open";
lastOpen=node;
up(node);
down(node);
}
handler(evt);
}
function up(node){/*需要重新运算marginLeft的值*/
var target=node,v=node.v,c=node.c,flag=1;
var ifCollapse=(node.className=="node collapse");
if(ifCollapse) c=c-1;
while(target!=null){
target=target.previousSibling;
if(target==null) return;
var rv=target.v-c;/*当显示该节点 需不需要压缩 重新调整margin间距*/
if(rv<1) rv=1;
target.style.marginLeft=rv*cfg.gap+"px";
if(target.v==v-1) v--; /*祖先部分*/
else{
if(target.isNode) target.className="node collapse";
if(target.v==node.v&&target.v==v) ;/*是兄弟节点*/
else cssAdd(target,"hide");
}
}
}
function down(node){/*需要重新运算marginLeft的值*/
var target=node,flag=1,v=node.v,c=node.c;
if(v>1) target.style.marginLeft=2*cfg.gap+"px";
while(target!=null){
target=target.nextSibling;
if(target==null) return;
var rv=target.v-c;/*重新调整margin间距*/
if(rv<1) rv=1;
target.style.marginLeft=rv*cfg.gap+"px";
if(target.isNode) target.className="node collapse";
if(flag==1&&target.v==v+1) cssRm(target,"hide");/*子部分*/
if(flag==1&&target.v>v+1) cssAdd(target,"hide");/*孙部分*/
if(flag<=2&&target.v==v) flag=2;/*兄弟部分*/
if(flag==2&&target.v>v) cssAdd(target,"hide");/*兄弟分支部分*/
if(flag<=3&&target.v<v) flag=3;/*不在一条线上*/
if(flag==3) cssAdd(target,"hide");/*不在一条线上的元素*/
}
}
function collapse(node){
var target=node,flag=1,v=node.v;
while(target!=null){
target=target.nextSibling;
if(target==null) return;
if(target.v==v+1) cssAdd(target,"hide");/*子部分*/
if(target.v<=v) break;
}
}
function cssAdd(dom,css1){/*给元素添加样式*/
if(dom&&dom.className!=null){
var css=dom.className.split(/\s+/g);
if(css.indexOf(css1)<0){/*如果没有该样式 方添加*/
css.push(css1);
dom.className=css.join(" ").trim();
}
}
else dom.className=css1;
}
function cssRm(dom,css1){
if(dom&&dom.className!=null){
var css=dom.className.split(/\s+/g);
var p=css.indexOf(css1);
if(p>=0) dom.className=css.splice(p-1,1).join(" ");
}
}
function ajax(url){
var xhr=new XMLHttpRequest();
xhr.open("get",url,false);
xhr.send();
var text=xhr.responseText;
return text;
}
win.makeTree=makeTree;
win.genTree=genTree;
win.ajax=ajax;
})(window)
| ldjking/wbscreen | web/wb/5editor/tree/rs/tree.js | JavaScript | mit | 4,224 |
export default {
js: [
'node_modules/jquery/dist/jquery.min.js',
'node_modules/materialize-css/dist/js/materialize.min.js',
'node_modules/handlebars/dist/handlebars.min.js',
'node_modules/blueimp-file-upload/js/vendor/jquery.ui.widget.js',
'node_modules/blueimp-file-upload/js/jquery.iframe-transport.js',
'node_modules/blueimp-file-upload/js/jquery.fileupload.js',
'node_modules/blueimp-file-upload/js/jquery.fileupload-process.js',
'node_modules/clipboard/dist/clipboard.min.js',
'static/assets/js/jquery.fileupload-validate.js',
'static/assets/js/main.js'
],
css: [
'node_modules/materialize-css/dist/css/materialize.min.css',
'static/assets/css/main.css'
],
fonts: [
'node_modules/materialize-css/dist/fonts/**/*',
'static/assets/fonts/MaterialIcons.woff2'
]
}
| oohnoitz/jii | assets.js | JavaScript | mit | 833 |
// Step zero in the webauthn flow.
// @param {String} email
// @param {String} username
// @return {PublicKeyCredentialCreationOptions} ret - see https://developer.mozilla.org/en-US/docs/Web/API/PublicKeyCredentialCreationOptions
// @return {Uint8Array} ret.challenge - byte array be signed by the client.
// @return {Object} ret.user - user information
// @return {Uint8Array} ret.user.id - unique id encoded as a byte array.
// @return {String} ret.user.name - the user's email.
// @return {Object} ret.rp - information about the server (or relaying party).
const requestRegistration = async (email, username) => {
const res = await fetch('/users/registration/request', {
method: 'post',
cache: 'no-cache',
headers: {
'Content-type': 'application/json',
'Accept': 'application/json',
},
// TODO server has to do some validation of the payload.
body: JSON.stringify({username, email})
});
return res.json();
}
// @param {Uint8Array} challengeRaw
// @return {Uint8Array} signed challenge
const signChallenge = async (challengeRaw, keyId) => {
// TODO, see https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/sign
return window.crypto.subtle.sign();
}
const onSubmit = async (event) => {
event.preventDefault();
const email = document.getElementById('email').value;
const serverOptions = await requestRegistration(email);
const credentialsCreationOptions = Object.assign({}, serverOptions, {
attestation: 'direct', // what options do we have here? should this be decided by the client?
authenticatorSelection: {
authenticatorAttachment: 'cross-platform', // what options do we have here? should this be on the server?
},
timeout: 60000, // timeout for the user to confirm authentication. Q: should the server have a similar timeout? Q: should it be related to this timeout?
})
const credential = await navigator.credentials.create(credentialsCreationOptions); // Type PublicKeyCredential
const serverConfirmation = await completeRegistration({
signedChallenge: sign(serverOptions.challenge, credential.id),
publicKey: {
id: credential.id,
type: credential.type,
//key: credential.
},
})
}
(async () => {
document.getElementById('register').onsubmit = onSubmit;
})();
/*
const toUint8Array = (str) => {
return Uint8Array.from(str, c => c.charCodeAt(0));
};
// [This page](https://developer.mozilla.org/en-US/docs/Web/API/PublicKeyCredentialCreationOptions) has more descriptions.
const publicKeyCredentailsOptions = {
// Should be used to compute a signature on the client-side
challenge: Uint8Array.from(toUint8Array),
rp: { // relaying party - organization which is
name: 'Pusher',
//id: 'dev.me', // must be a subset of the current domain
},
user: {
// Some random id but has to be ArrayBuffer.
id: toUint8Array(Math.random().toString(36).substring(2, 10)),
name: 'Alexandru Topliceanu',
displayName: 'dru',
},
// this is a required field.
pubKeyCredParams: [
{alg: -7, type: 'public-key'}, // -7 stands for 'ECDSA w/ SHA-256'
],
authenticatorSelection: {
authenticatorAttachment: 'cross-platform',
},
timeout: 60000, // timeout for the user to confirm authentication
attestation: 'direct',
};
(async () => {
// The [navigator credentials object](https://developer.mozilla.org/en-US/docs/Web/API/CredentialsContainer)
const credential = await navigator.credentials.create({
// The [PublicKeyCredentialsCreationOptions](https://developer.mozilla.org/en-US/docs/Web/API/PublicKeyCredentialCreationOptions)
publicKey: publicKeyCredentailsOptions,
});
console.log(credential);
})();
*/
| topliceanu/learn | js/webauthn/public/javascripts/index.js | JavaScript | mit | 3,695 |
var Extendable = require('app/Extendable');
var jQuery = require('jquery');
module.exports = (function() {
var View = function(options) {
this._model = options.model || null;
this.setElement(
options.element || document.createElement(this.getTagName())
);
this.initialize.apply(this, arguments);
};
jQuery.extend(View, Extendable);
jQuery.extend(View.prototype, {
initialize: function(options) {},
getTagName: function() {
return 'div';
},
getModel: function() {
return this._model;
},
getElement: function() {
return this._element;
},
$: function(selector) {
if (!this._$element) {
return null;
}
if (typeof selector === 'undefined') {
return this._$element;
}
return this._$element.find(selector);
},
setModel: function(model) {
this._model = model;
},
setElement: function (element) {
if (!element) {
this._element = null;
this._$element = null;
} else {
this._element = element;
this._$element = jQuery(element);
}
},
render: function() {
return this;
}
});
return View;
})();
| imnotjames/multisearch | src/js/app/View.js | JavaScript | mit | 1,108 |
'use strict';
System.register(['aurelia-templating', '../dialog-controller'], function (_export, _context) {
var customElement, bindable, DialogController, _dec, _class, _desc, _value, _class2, _descriptor, _descriptor2, _class3, _temp, AiDialogFooter;
function _initDefineProp(target, property, descriptor, context) {
if (!descriptor) return;
Object.defineProperty(target, property, {
enumerable: descriptor.enumerable,
configurable: descriptor.configurable,
writable: descriptor.writable,
value: descriptor.initializer ? descriptor.initializer.call(context) : void 0
});
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _applyDecoratedDescriptor(target, property, decorators, descriptor, context) {
var desc = {};
Object['ke' + 'ys'](descriptor).forEach(function (key) {
desc[key] = descriptor[key];
});
desc.enumerable = !!desc.enumerable;
desc.configurable = !!desc.configurable;
if ('value' in desc || desc.initializer) {
desc.writable = true;
}
desc = decorators.slice().reverse().reduce(function (desc, decorator) {
return decorator(target, property, desc) || desc;
}, desc);
if (context && desc.initializer !== void 0) {
desc.value = desc.initializer ? desc.initializer.call(context) : void 0;
desc.initializer = undefined;
}
if (desc.initializer === void 0) {
Object['define' + 'Property'](target, property, desc);
desc = null;
}
return desc;
}
function _initializerWarningHelper(descriptor, context) {
throw new Error('Decorating class property failed. Please ensure that transform-class-properties is enabled.');
}
return {
setters: [function (_aureliaTemplating) {
customElement = _aureliaTemplating.customElement;
bindable = _aureliaTemplating.bindable;
}, function (_dialogController) {
DialogController = _dialogController.DialogController;
}],
execute: function () {
_export('AiDialogFooter', AiDialogFooter = (_dec = customElement('ai-dialog-footer'), _dec(_class = (_class2 = (_temp = _class3 = function () {
function AiDialogFooter(controller) {
_classCallCheck(this, AiDialogFooter);
_initDefineProp(this, 'buttons', _descriptor, this);
_initDefineProp(this, 'useDefaultButtons', _descriptor2, this);
this.controller = controller;
}
AiDialogFooter.prototype.close = function close(buttonValue) {
if (AiDialogFooter.isCancelButton(buttonValue)) {
this.controller.cancel(buttonValue);
} else {
this.controller.ok(buttonValue);
}
};
AiDialogFooter.prototype.useDefaultButtonsChanged = function useDefaultButtonsChanged(newValue) {
if (newValue) {
this.buttons = ['Cancel', 'Ok'];
}
};
AiDialogFooter.isCancelButton = function isCancelButton(value) {
return value === 'Cancel';
};
return AiDialogFooter;
}(), _class3.inject = [DialogController], _temp), (_descriptor = _applyDecoratedDescriptor(_class2.prototype, 'buttons', [bindable], {
enumerable: true,
initializer: function initializer() {
return [];
}
}), _descriptor2 = _applyDecoratedDescriptor(_class2.prototype, 'useDefaultButtons', [bindable], {
enumerable: true,
initializer: function initializer() {
return false;
}
})), _class2)) || _class));
_export('AiDialogFooter', AiDialogFooter);
}
};
}); | rockResolve/dialog | dist/system/resources/ai-dialog-footer.js | JavaScript | mit | 3,727 |
{
"name": "hamsters.js",
"url": "https://github.com/austinksmith/Hamsters.js.git"
}
| bower/components | packages/hamsters.js | JavaScript | mit | 88 |
(function() {
'use strict';
angular
.module('ng-indeterminate', [])
.directive('ngIndeterminate', ngIndeterminate)
;
/* @ngInject */
function ngIndeterminate() {
return {
restrict: 'A',
link: function(scope, element, attributes) {
scope.$watch(attributes['ngIndeterminate'], function(value) {
element.prop('indeterminate', !!value);
});
}
};
}
})();
| kod88vn/ng-smart-grid | src/components/ngIndeterminate.js | JavaScript | mit | 426 |
/*
* skd_tugas2 v0.1
*
* Jufans Anurwan I.
* twitter: @jufanz
* fork me at https://github.com/jufans
*
* copyright(c)2013
* under MIT license
*
*
* M3111086 - Sebelas Maret University
*
*/
function acak(){
var nilai1=document.getElementById('enkrip');
var nilai2=document.getElementById('dekrip');
var pecah=nilai1.value.split('');
for (var i = 0; i < nilai1.value.length; i++) {
var ascii=pecah[i].charCodeAt(0);
ascii=(ascii+65)%128+1;
pecah[i]=String.fromCharCode(ascii);
pecah[i]=pecah[i];
}
pecah=pecah.join('');
nilai2.value=pecah;
}
function tata(){
var nilai1=document.getElementById('enkrip');
var nilai2=document.getElementById('dekrip');
var pecah=nilai2.value.split('');
for (var i = 0; i < nilai2.value.length; i++) {
var ascii=pecah[i].charCodeAt(0);
ascii=(ascii+62)%128;
pecah[i]=String.fromCharCode(ascii);
pecah[i]=pecah[i];
}
pecah=pecah.join('');
nilai1.value=pecah;
}
| jufans/skd-encrypt-decrypt | skd_tugas2.js | JavaScript | mit | 1,035 |
(function () {
'use strict';
angular
.module('module_name')
.controller('Module_nameListController', Module_nameListController);
Module_nameListController.$inject = ['Module_nameService'];
function Module_nameListController(Module_nameService) {
var vm = this;
vm.module_names = Module_nameService.query();
}
}());
| rastemoh/mean | templates/modules/module_name/client/controllers/list-module_name.client.controller.js | JavaScript | mit | 345 |
var Table = function(x, y) {
this.parts = [
Shape.Prism(new Point( x, y, 0), 0.1, 0.1, 0.5),
Shape.Prism(new Point( x, y + 0.9, 0), 0.1, 0.1, 0.5),
Shape.Prism(new Point(x + 0.9, y + 0.9, 0), 0.1, 0.1, 0.5),
Shape.Prism(new Point(x + 0.9, y, 0), 0.1, 0.1, 0.5),
Shape.Prism(new Point( x, y, 0.5), 1, 1, 0.1)
];
}
Table.prototype.getParts = function() {
return this.parts;
} | AVGP/flat-o-mat | objects/table.js | JavaScript | mit | 445 |
export {
streamToBuffers, streamableToBuffers, buffersToStream, buffersToStreamable
} from './buffers'
export {
streamToBuffer, streamableToBuffer, bufferToStream, bufferToStreamable
} from './buffer'
export {
streamToText, streamableToText, textToStream, textToStreamable
} from './text'
export {
streamToJson, streamableToJson, jsonToStream, jsonToStreamable
} from './json'
export {
closeStreamable, streamToStreamable, reuseStream, reuseStreamable, unreuseStreamable
} from './streamable'
export {
pushbackStream
} from './pushback'
export {
nodeToQuiverReadStream, nodeToQuiverWriteStream, nodeReadToStreamable
} from './node-stream'
export {
emptyReadStream, emptyWriteStream, emptyStreamable
} from './empty'
export { pipeStream } from './pipe'
export { pipeStreamableToNodeStream } from './pipe-node'
export { createChannel } from 'quiver-stream-channel'
| quiverjs/quiver-stream-util | src/lib/index.js | JavaScript | mit | 889 |
/**
* jQuery Lined Textarea Plugin
* http://alan.blog-city.com/jquerylinedtextarea.htm
*
* Copyright (c) 2010 Alan Williamson
*
* Version:
* $Id: jquery-linedtextarea.js 464 2010-01-08 10:36:33Z alan $
*
* Released under the MIT License:
* http://www.opensource.org/licenses/mit-license.php
*
* Usage:
* Displays a line number count column to the left of the textarea
*
* Class up your textarea with a given class, or target it directly
* with JQuery Selectors
*
* $(".lined").linedtextarea({
* selectedLine: 10,
* selectedClass: 'lineselect'
* });
*
* History:
* - 2010.01.08: Fixed a Google Chrome layout problem
* - 2010.01.07: Refactored code for speed/readability; Fixed horizontal sizing
* - 2010.01.06: Initial Release
*
*/
(function($) {
$.fn.linedtextarea = function(options) {
// Get the Options
var opts = $.extend({}, $.fn.linedtextarea.defaults, options);
/*
* Helper function to make sure the line numbers are always
* kept up to the current system
*/
var fillOutLines = function(codeLines, h, lineNo){
while ( (codeLines.height() - h ) <= 0 ){
codeLines.append("<div class='lineno'>" + lineNo + "</div>");
lineNo++;
}
return lineNo;
};
/*
* Iterate through each of the elements are to be applied to
*/
return this.each(function() {
var lineNo = 1;
var textarea = $(this);
/* Turn off the wrapping of as we don't want to screw up the line numbers */
textarea.attr("wrap", "off");
textarea.css({resize:'none'});
var originalTextAreaWidth = '90%';
/* Wrap the text area in the elements we need */
textarea.wrap("<div class='linedtextarea'></div>");
var linedTextAreaDiv = textarea.parent().wrap("<div class='linedwrap'></div>");
var linedWrapDiv = linedTextAreaDiv.parent();
linedWrapDiv.prepend("<div class='lines'></div>");
var linesDiv = linedWrapDiv.find(".lines");
linesDiv.height( textarea.height() );
/* Draw the number bar; filling it out where necessary */
linesDiv.append( "<div class='codelines'></div>" );
var codeLinesDiv = linesDiv.find(".codelines");
lineNo = fillOutLines( codeLinesDiv, linesDiv.height(), 1 );
/* Move the textarea to the selected line */
if ( opts.selectedLine != -1 && !isNaN(opts.selectedLine) ){
var fontSize = parseInt( textarea.height() / (lineNo-2) );
var position = parseInt( fontSize * opts.selectedLine ) - (textarea.height()/2);
textarea[0].scrollTop = position;
}
/* Set the width */
var sidebarWidth = linesDiv.outerWidth();
var paddingHorizontal = parseInt( linedWrapDiv.css("border-left-width") ) + parseInt( linedWrapDiv.css("border-right-width") ) + parseInt( linedWrapDiv.css("padding-left") ) + parseInt( linedWrapDiv.css("padding-right") );
var linedWrapDivNewWidth = originalTextAreaWidth;
var textareaNewWidth = originalTextAreaWidth;
textarea.width( textareaNewWidth );
linedWrapDiv.width( linedWrapDivNewWidth );
/* React to the scroll event */
textarea.scroll( function(tn){
var domTextArea = $(this)[0];
var scrollTop = domTextArea.scrollTop;
var clientHeight = domTextArea.clientHeight;
codeLinesDiv.css( {'margin-top': (-1*scrollTop) + "px"} );
lineNo = fillOutLines( codeLinesDiv, scrollTop + clientHeight, lineNo );
});
/* Should the textarea get resized outside of our control */
textarea.resize( function(tn){
var domTextArea = $(this)[0];
linesDiv.height( domTextArea.clientHeight + 6 );
});
});
};
// default options
$.fn.linedtextarea.defaults = {
selectedLine: -1,
selectedClass: 'lineselect'
};
})(jQuery); | mintcreative/editor-line-numbers | jquery-linedtextarea.js | JavaScript | mit | 3,748 |
const mixins = require('./src/styles/mixins/index.js');
module.exports = {
plugins: [
require('postcss-mixins')({
mixins: mixins,
}),
require('postcss-cssnext')({
features: {
customProperties: { variables: false }, //replaced by postcss-css-variables
calc: { preserve: true }
},
}),
require('postcss-css-variables'),
]
};
| sandrina-p/css-mixins-on-javascript-with-unit-tests | postcss.config.js | JavaScript | mit | 439 |
/***********************************************
* DHTML Billboard script- © Dynamic Drive (www.dynamicdrive.com)
* This notice must stay intact for use
* Visit http://www.dynamicdrive.com/ for full source code
***********************************************/
//List of transitional effects to be randomly applied to billboard:
//var billboardeffects=["GradientWipe(GradientSize=1.0 Duration=0.7)", "Inset", "Iris", "Pixelate(MaxSquare=5 enabled=false)", "RadialWipe", "RandomBars", "Slide(slideStyle='push')", "Spiral", "Stretch", "Strips", "Wheel", "ZigZag"]
var billboardeffects=["RandomBars"] //Uncomment this line and input one of the effects above (ie: "Iris") for single effect.
var tickspeed=4000 //ticker speed in miliseconds (2000=2 seconds)
var effectduration=1000 //Transitional effect duration in miliseconds
var hidecontent_from_legacy=1 //Should content be hidden in legacy browsers- IE4/NS4 (0=no, 1=yes).
var filterid=Math.floor(Math.random()*billboardeffects.length)
document.write('<style type="text/css">\n')
if (document.getElementById)
document.write('.billcontent{display:none;\n'+'filter:progid:DXImageTransform.Microsoft.'+billboardeffects[filterid]+'}\n')
else if (hidecontent_from_legacy)
document.write('#contentwrapper{display:none;}')
document.write('</style>\n')
var selectedDiv=0
var totalDivs=0
function contractboard(){
var inc=0
while (document.getElementById("billboard"+inc)){
document.getElementById("billboard"+inc).style.display="none"
inc++
}
}
function expandboard(){
var selectedDivObj=document.getElementById("billboard"+selectedDiv)
contractboard()
if (selectedDivObj.filters){
if (billboardeffects.length>1){
filterid=Math.floor(Math.random()*billboardeffects.length)
selectedDivObj.style.filter="progid:DXImageTransform.Microsoft."+billboardeffects[filterid]
}
selectedDivObj.filters[0].duration=effectduration/1000
selectedDivObj.filters[0].Apply()
}
selectedDivObj.style.display="block"
if (selectedDivObj.filters)
selectedDivObj.filters[0].Play()
selectedDiv=(selectedDiv<totalDivs-1)? selectedDiv+1 : 0
setTimeout("expandboard()",tickspeed)
}
function startbill(){
while (document.getElementById("billboard"+totalDivs)!=null)
totalDivs++
if (document.getElementById("billboard0").filters)
tickspeed+=effectduration
expandboard()
}
if (window.addEventListener)
window.addEventListener("load", startbill, false)
else if (window.attachEvent)
window.attachEvent("onload", startbill)
else if (document.getElementById)
window.onload=startbill
| longde123/MultiversePlatform | server/website/jscripts/adticker.js | JavaScript | mit | 2,499 |
/**
* Create the store with asynchronously loaded reducers
*/
import { createStore, applyMiddleware, compose } from 'redux';
import { fromJS } from 'immutable';
import { routerMiddleware } from 'react-router-redux';
import createSagaMiddleware from 'redux-saga';
import createReducer from './reducers';
import { createLogger } from 'redux-logger'
const logger = createLogger();
const sagaMiddleware = createSagaMiddleware();
export default function configureStore(initialState = {}, history) {
// Create the store with two middlewares
// 1. sagaMiddleware: Makes redux-sagas work
// 2. routerMiddleware: Syncs the location/URL path to the state
const middlewares = [
sagaMiddleware,
routerMiddleware(history),
logger,
];
const enhancers = [
applyMiddleware(...middlewares),
];
// If Redux DevTools Extension is installed use it, otherwise use Redux compose
/* eslint-disable no-underscore-dangle */
const composeEnhancers =
process.env.NODE_ENV !== 'production' &&
typeof window === 'object' &&
window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ?
window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ : compose;
/* eslint-enable */
const store = createStore(
createReducer(),
fromJS(initialState),
composeEnhancers(...enhancers)
);
// Extensions
store.runSaga = sagaMiddleware.run;
store.asyncReducers = {}; // Async reducer registry
// Make reducers hot reloadable, see http://mxs.is/googmo
/* istanbul ignore next */
if (module.hot) {
module.hot.accept('./reducers', () => {
import('./reducers').then((reducerModule) => {
const createReducers = reducerModule.default;
const nextReducers = createReducers(store.asyncReducers);
store.replaceReducer(nextReducers);
});
});
}
return store;
}
| ddobby94/szakdoge_admin | app/store.js | JavaScript | mit | 1,819 |
/*The MIT License (MIT)
Copyright (c) 2013 Andy Dai
Copyright (c) 2014 Codethink Ltd.
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.
*/
flag = 0;
Template.card_edit.events = {
"click .save_card_edit": function () {
var boardId = Session.get('boardId');
var _id = this._id
var title = $('#'+_id).find('textarea[name="title"]').val();
title = title.trim();
var descr = $('#'+_id).find('textarea[name="descr"]').val();
descr = descr.trim();
var archived = $('#'+_id+'archive').is(':checked');
/* if bucket has been changed get pk else this is null and
bucket remains the same. takes 0 for remove from bucket */
var bucket = Session.get('tempBucket');
// remove temp session variable as no longer needed
delete Session.keys['tempBucket'];
var milestone = Session.get('tempMilestone');
delete Session.keys['tempMilestone'];
Meteor.call('putcard',_id,title,descr,archived,bucket,milestone);
// when edit set to 0 in session card_edit template is removed
// and card_content rendered
Session.set("edit",0);
},
"click .discard_card_edit": function () {
// remove temp session variables
delete Session.keys['tempBucket'];
delete Session.keys['tempMilestone'];
// set no card being edited
Session.set("edit",0);
},
"click .add_assignee": function () {
var card_mongo_id = this._id;
var card_id = Cards.findOne({_id: card_mongo_id}).id;
var selectBox = document.getElementById("assignee_picker");
var selectValue = selectBox.options[selectBox.selectedIndex].value;
Meteor.call('postAssignee', card_mongo_id, selectValue);
},
"click .remove_assignee_link": function (e) {
var assignee_id = parseInt(e.currentTarget.id);
var card_id = Assignees.findOne({id: assignee_id}).card;
Meteor.call('deleteAssignee', assignee_id);
},
"change .bucket_picker": function(evt) {
/* put the bucket in a temporary session var so that the data
is not PUT until the user clicks save, this variable is
removed on clicking save or delete */
var bucketId = parseInt($(evt.target).val());
Session.set('tempBucket',bucketId);
},
"change .milestone_picker": function(evt) {
/* put the milest in a temporary session var so that the data
is not PUT until the user clicks save, this variable is
removed on clicking save or delete */
var milestoneId = parseInt($(evt.target).val());
Session.set('tempMilestone',milestoneId);
}
}
Template.card_edit.helpers({
users: function (cardId) {
var users = Users.find({});
var toReturn = new Array;
// take only users not already assigned to card
users.forEach(function(user) {
if(!Assignees.findOne({person:user.id,card:cardId}))
toReturn.push(user);
});
return toReturn;
},
assignees: function(cardId) {
return Assignees.find({card:cardId});
},
assigneeName: function(assignee_id) {
assignee = Assignees.findOne({id: assignee_id}).person;
return Users.findOne({id: assignee}).username;
},
getAssigneeColor: function() {
if (flag) {
flag = 0;
return "#FCDAC0";
}
flag = 1;
return "#FCCEAA";
},
buckets: function() {
return Buckets.find({});
},
milestones: function() {
return Milestones.find({});
},
selectMyBucket: function(cardId,bucketId) {
card = Cards.findOne({id:cardId});
if(card.bucket == bucketId)
return "selected";
},
selectMyMilestone: function(cardId,milestoneId) {
card = Cards.findOne({id:cardId});
if(card.milestone == milestoneId)
return "selected";
}
});
| CodethinkLabs/Djankan-Meteor | client/views/card/card_edit.js | JavaScript | mit | 4,942 |
module.exports = {
extends: '@react-native-community',
rules: {
'no-underscore-dangle': 'off',
'no-use-before-define': 'off',
'import/no-unresolved': 'off', // peer dependencies
// React
'react/destructuring-assignment': 'off',
'react/prop-types': 'off',
'react/jsx-props-no-spreading': 'off',
},
};
| mxck/react-native-material-menu | .eslintrc.js | JavaScript | mit | 336 |
define('app/entity/block/trampoline',
[
'app/entity/block/_base', 'app/entity/_base', 'app/game-options', 'app/stage', 'app/preloader', 'app/episodes/_'
],
function(BlockBase, Base, gameOptions, stage, preloader, episode) {
var
/**
* @property _paddleOptions
* @static
* @private
* @type {Object}
*/
_paddleOptions = {};
function Trampoline() {
BlockBase.call(this);
this.id = 'trampoline';
this.topBitmap = null;
this.bottomBitmap = null;
this.springBitmap = null;
}
Trampoline.prototype = Object.create(BlockBase.prototype, {
constructor: {
value: Trampoline,
enumerable: false
}
});
/**
* @method init
* @param {Object} options
*/
Trampoline.prototype.init = function(options) {
var container;
this.options = options || {};
this.type = this.options.type || {};
this.typeId = this.type.id;
_paddleOptions = episode.getManifest().paddle;
this.topBitmap = new createjs.Bitmap(preloader.get('c-block-trampoline-top').src);
this.bottomBitmap = new createjs.Bitmap(preloader.get('c-block-trampoline-bottom').src);
this.springBitmap = new createjs.Bitmap(preloader.get('c-block-trampoline-spring').src);
this.height = 38;
this.width = 38;
this.bottomBitmap.y = 27;
this.springBitmap.x = 38 / 2 - 12;
this.springBitmap.y = 18;
this.springBitmap.scaleY = 0.6;
container = new createjs.Container();
container.addChild(this.springBitmap, this.topBitmap, this.bottomBitmap);
Base.prototype.init.call(this, container);
this.setLayerId(500);
stage.add(this);
};
/**
* @method create
* @param {Object} options
* @return {Trampoline}
*/
Trampoline.prototype.create = function(options) {
this.init(options);
return this;
};
/**
* @method createNew
* @param {Object} options
* @return {Trampoline}
*/
Trampoline.prototype.createNew = function(options) {
var trampoline = new Trampoline();
trampoline.init(options);
return trampoline;
};
/**
* @method bounce
* @param {Ball} ball
* @param {String} dir
*/
Trampoline.prototype.bounce = function(ball, dir) {
switch (dir) {
case 'left':
case 'right':
ball.speedX = - ball.speedX;
break;
case 'top':
ball.increaseSpeed(2);
if ( ball.getAngle() >= 1.57 ) {
ball.setAngle((Math.random() / 5) + 1.57);
} else {
ball.setAngle(Math.min((Math.random() / 5) + 1.27, 1.56));
}
this.release();
// hmmm?!
ball.speedY = - ball.speedY;
break;
case 'bottom':
ball.speedY = - ball.speedY;
break;
}
};
/**
* @method update
* @param {Object} event
*/
Trampoline.prototype.update = function(event) {
};
/**
* @method release
*/
Trampoline.prototype.release = function() {
var _this = this, d = 200;
if ( this.animating ) {
return this;
}
this.animating = true;
createjs.Tween.get(this).to({height: 56}, d, createjs.Ease.elasticOut).call(function() {
createjs.Tween.get(_this).wait(d * 4).to({height: 38}, d * 5, createjs.Ease.linear);
});
createjs.Tween.get(this.bitmap).to({y: this.getY() - 18}, d, createjs.Ease.elasticOut).call(function() {
createjs.Tween.get(_this.bitmap).wait(d * 4).to({y: _this.getY() + 18}, d * 5, createjs.Ease.linear);
});
createjs.Tween.get(this.bottomBitmap).to({y: 45}, d, createjs.Ease.elasticOut).call(function() {
createjs.Tween.get(_this.bottomBitmap).wait(d * 4).to({y: 27}, d * 5, createjs.Ease.linear);
});
createjs.Tween.get(this.springBitmap).to({scaleY: 1.2}, d, createjs.Ease.elasticOut).call(function() {
createjs.Tween.get(_this.springBitmap).wait(d * 4).to({scaleY: 0.6}, d * 5, createjs.Ease.linear).call(function() {
_this.animating = false;
});
});
};
var instance = null;
if ( instance === null ) {
instance = new Trampoline();
}
return instance;
}); | budnix/ball-and-wall | js/app/entity/block/trampoline.js | JavaScript | mit | 4,714 |
import React, {useEffect, useState} from 'react';
import ReactDOM from 'react-dom';
import {Map} from '@esri/react-arcgis';
import {loadArcGISModules} from '@deck.gl/arcgis';
import {GeoJsonLayer, ArcLayer} from '@deck.gl/layers';
// source: Natural Earth http://www.naturalearthdata.com/ via geojson.xyz
const AIR_PORTS =
'https://d2ad6b4ur7yvpq.cloudfront.net/naturalearth-3.3.0/ne_10m_airports.geojson';
// A React wrapper around https://deck.gl/docs/api-reference/arcgis/deck-layer
function DeckGLLayer(props) {
const [layer, setLayer] = useState(null);
useEffect(() => {
let deckLayer;
loadArcGISModules().then(({DeckLayer}) => {
deckLayer = new DeckLayer({});
setLayer(deckLayer);
props.map.add(deckLayer);
});
// clean up
return () => deckLayer && props.map.remove(deckLayer);
}, []);
if (layer) {
layer.deck.set(props);
}
return null;
}
function App() {
const layers = [
new GeoJsonLayer({
id: 'airports',
data: AIR_PORTS,
// Styles
filled: true,
pointRadiusMinPixels: 2,
pointRadiusScale: 2000,
getRadius: f => 11 - f.properties.scalerank,
getFillColor: [200, 0, 80, 180],
// Interactive props
pickable: true,
autoHighlight: true,
onClick: info =>
info.object &&
// eslint-disable-next-line
alert(`${info.object.properties.name} (${info.object.properties.abbrev})`)
}),
new ArcLayer({
id: 'arcs',
data: AIR_PORTS,
dataTransform: d => d.features.filter(f => f.properties.scalerank < 4),
// Styles
getSourcePosition: f => [-0.4531566, 51.4709959], // London
getTargetPosition: f => f.geometry.coordinates,
getSourceColor: [0, 128, 200],
getTargetColor: [200, 0, 80],
getWidth: 1
})
];
return (
<Map
mapProperties={{basemap: 'dark-gray-vector'}}
viewProperties={{
center: [0.119167, 52.205276],
zoom: 5
}}
>
<DeckGLLayer
getTooltip={info => info.object && info.object.properties.name}
layers={layers}
/>
</Map>
);
}
/* global document */
ReactDOM.render(<App />, document.getElementById('root'));
| uber-common/deck.gl | examples/get-started/react/arcgis/app.js | JavaScript | mit | 2,217 |
/*
* Chris Samuel
* [email protected]
*
* October 2 2015
*
*
*
* */
import React from 'react';
import {RouteHandler} from 'react-router';
import Navbar from './Navbar';
import Footer from './Footer';
class App extends React.Component {
render(){
return (
<div>
<Navbar />
<RouteHandler />
<Footer />
</div>
);
}
}
export default App;
/*
* Routehandler is a component that renders the active child route handler.
* It will render one of the following components depending on the URL path:
* Home,Top 100, Profile or Add Character.
*
* AngularJS Equivalent : <div ng-view></div>
* Which includes the rendered template of current route
* into the main layout.
*
* */
| Alayode/facesOfSpace | app/components/app.js | JavaScript | mit | 819 |
ScalaJS.impls.scala_Function1$mcFD$sp$class__$init$__Lscala_Function1$mcFD$sp__V = (function($$this) {
/*<skip>*/
});
//@ sourceMappingURL=Function1$mcFD$sp$class.js.map
| ignaciocases/hermeneumatics | node_modules/scala-node/main/target/streams/compile/externalDependencyClasspath/$global/package-js/extracted-jars/scalajs-library_2.10-0.4.0.jar--29fb2f8b/scala/Function1$mcFD$sp$class.js | JavaScript | mit | 172 |
// THIS FILE IS NOT MEANT TO BE LOADED - THIS IS MERELY A BASE FOR FUTURE MODES
function input_todo() {
// special checks
if (game.level >= submode.endlevel && deadFrame === 0) {
game.level = submode.endlevel;
deadFrame++;
modeClear = true;
}
if (countdown > 0) {
countdown -= 1;
return;
}
if (deadFrame > 0) {
if (keys[controls.keyCodes[10]] || keys[controls.keyCodes[11]]) {
gamestate = 0;
keys[controls.keyCodes[10]] = false;
keys[controls.keyCodes[11]] = false;
}
deadFrame++;
return;
}
if (deadFrame === 0) {
framecount++;
}
drawGhost = true;
invisMode = false;
movement();
//process eventual piece lock
haveLockedPiece = false;
linesCleared = 0;
lockPiece();
if (game.score < game.level/5) {
game.score = game.level/5;
}
//process level and score
if (haveLockedPiece && (game.level + 1) % 100 !== 0) {
game.level++;
game.score += diffMult;
}
switch (linesCleared) {
case 1:
break;
case 2:
break;
case 3:
break;
case 4:
break;
}
if (linesCleared > 0) {
areFrame += lineDelay;
}
}
| makiki99/blockdrop | code/Input/input???.js | JavaScript | mit | 1,079 |
/**
* @author Anthony
* created on 19.08.2016
*/
(function() {
'use strict';
angular.module('GasNinjasAdmin.pages.login')
.controller('LoginCtrl', LoginCtrl);
/** @ngInject */
function LoginCtrl($scope, $state, $location, toastr, Auth, appConfig) {
$scope.login = fnLogin;
$scope.user = {};
function fnLogin(form) {
Auth.login({
email: $scope.user.email,
password: $scope.user.password
}).then(function(currentUser) {
location.href = 'index.html#' + $location.url();
}).catch(function(error) {
if (error && error.message) {
toastr.error(error.message);
} else {
toastr.error('Failed to log in.');
}
});
return false;
}
}
})(); | AnthonyKim89/gasninjas_admin | src/app/pages/login/login.controller.js | JavaScript | mit | 761 |
'use strict'
var helper = require('./test-helper')
var assert = require('assert')
const pool = new helper.pg.Pool()
pool.connect(assert.success(function (client, done) {
helper.versionGTE(client, '9.2.0', assert.success(function (jsonSupported) {
if (!jsonSupported) {
console.log('skip json test on older versions of postgres')
done()
return pool.end()
}
client.query('CREATE TEMP TABLE stuff(id SERIAL PRIMARY KEY, data JSON)')
var value = { name: 'Brian', age: 250, alive: true, now: new Date() }
client.query('INSERT INTO stuff (data) VALUES ($1)', [value])
client.query('SELECT * FROM stuff', assert.success(function (result) {
assert.equal(result.rows.length, 1)
assert.equal(typeof result.rows[0].data, 'object')
var row = result.rows[0].data
assert.strictEqual(row.name, value.name)
assert.strictEqual(row.age, value.age)
assert.strictEqual(row.alive, value.alive)
assert.equal(JSON.stringify(row.now), JSON.stringify(value.now))
done()
pool.end()
}))
}))
}))
| cricri/node-postgres | test/integration/client/json-type-parsing-tests.js | JavaScript | mit | 1,073 |
"use strict";
const Piii = require("../src/");
describe("Piii", () => {
describe("[filter]", () => {
it("deve filtrar as palavras", () => {
const piii = new Piii({
filters: [["hello"]]
});
expect(piii.filter("foo bar")).toBe("foo bar");
expect(piii.filter("foo hello bar")).toBe("foo * bar");
});
});
describe("[has]", () => {
it("deve verificar se há palavras para ser filtadas", () => {
const piii = new Piii({
filters: [["hello"]]
});
expect(piii.has("foo bar")).toBeFalsy();
expect(piii.has("foo hello bar")).toBeTruthy();
});
});
describe("[options.filters]", () => {
it("deve retornar a string quando não informado", () => {
const piii = new Piii({});
expect(piii.filter("foo")).toBe("foo");
});
it("deve aceitar filtros personalizados", () => {
const piii = new Piii({
filters: [["hello"]]
});
expect(piii.filter("foo hello bar")).toBe("foo * bar");
});
});
describe("[options.aliases]", () => {
it("deve definir aliases para determindas letras", () => {
const piii = new Piii({
filters: [["hello"]],
aliases: {e: ["3", "&"]}
});
expect(piii.filter("hello")).toBe("*");
expect(piii.filter("h3llo")).toBe("*");
expect(piii.filter("h&llo")).toBe("*");
});
});
describe("[options.repeated]", () => {
it("deve ignorar letras repetidas", () => {
const piii = new Piii({
filters: [["hello"]]
});
expect(piii.filter("heeello")).toBe("*");
expect(piii.filter("hellooo")).toBe("*");
});
it("deve filtrar com exatidão", () => {
const piii = new Piii({
filters: [["hello"]],
repeated: false
});
expect(piii.filter("foo heeello bar")).not.toBe("foo * bar");
expect(piii.filter("foo heeello bar")).toBe("foo heeello bar");
});
});
describe("[options.censor]", () => {
it("deve usar censura personalizada como string", () => {
const piii = new Piii({
filters: [["hello"]],
censor: "###"
});
expect(piii.filter("hello")).toBe("###");
expect(piii.filter("hello")).not.toBe("*");
});
it("deve usar censura personalizada como função", () => {
const piii = new Piii({
filters: [["hello"]],
censor: badWord => badWord.charAt(0) + "#"
});
expect(piii.filter("foo hello bar")).toBe("foo h# bar");
});
});
describe("[options.cleaner]", () => {
it("deve usar o desacentuador padrão", () => {
const piii = new Piii({
filters: [["hello"]]
});
expect(piii.filter("foo héllô bar")).toBe("foo * bar");
});
it("deve usar um desacentuador personalizado", () => {
const piii = new Piii({
filters: [["hello"]],
cleaner: string => string.replace(/é/g, "e")
});
expect(piii.filter("foo héllo bar")).toBe("foo * bar");
expect(piii.filter("foo héllô bar")).toBe("foo héllô bar");
});
});
});
| theuves/piii.js | spec/index.spec.js | JavaScript | mit | 3,065 |
var util2 = require('util2');
var Emitter = require('emitter');
var WindowStack = require('ui/windowstack');
var simply = require('ui/simply');
var Stage = function(stageDef) {
this.state = stageDef || {};
this._items = [];
};
util2.copy(Emitter.prototype, Stage.prototype);
Stage.prototype._show = function() {
this.each(function(element, index) {
element._reset();
this._insert(index, element);
}.bind(this));
};
Stage.prototype._prop = function() {
if (this === WindowStack.top()) {
simply.impl.stage.apply(this, arguments);
}
};
Stage.prototype.each = function(callback) {
this._items.forEach(callback);
return this;
};
Stage.prototype.at = function(index) {
return this._items[index];
};
Stage.prototype.index = function(element) {
return this._items.indexOf(element);
};
Stage.prototype._insert = function(index, element) {
if (this === WindowStack.top()) {
simply.impl.stageElement(element._id(), element._type(), element.state, index);
}
};
Stage.prototype._remove = function(element, broadcast) {
if (broadcast === false) { return; }
if (this === WindowStack.top()) {
simply.impl.stageRemove(element._id());
}
};
Stage.prototype.insert = function(index, element) {
element.remove(false);
this._items.splice(index, 0, element);
element.parent = this;
this._insert(this.index(element), element);
return this;
};
Stage.prototype.add = function(element) {
return this.insert(this._items.length, element);
};
Stage.prototype.remove = function(element, broadcast) {
var index = this.index(element);
if (index === -1) { return this; }
this._remove(element, broadcast);
this._items.splice(index, 1);
delete element.parent;
return this;
};
module.exports = Stage;
| argyleink/Colorful-Weather | src/js/ui/stage.js | JavaScript | mit | 1,751 |
const gulp = require('gulp');
const config = require('./config');
const mocha = require('gulp-mocha');
const istanbul = require('gulp-istanbul');
gulp.task('cover', ['instrument'], () => {
return gulp.src(config.tests, { read: false })
.pipe(mocha({
reporter: 'dot',
ui: 'mocha-given',
require: ['coffee-script/register', 'should', 'should-sinon']
}))
.pipe(istanbul.writeReports());
});
| tandrewnichols/defiled | gulp/cover.js | JavaScript | mit | 422 |
// @flow
//
// Copyright (c) 2018 DDN. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
import angular from "angular";
import completionist from "./completionist.js";
import extendScopeModule from "../extend-scope-module.js";
import completionistModelHook from "./completionist-model-hook.js";
import completionistDropdown from "./completionist-dropdown.js";
export default angular
.module("completionist", [extendScopeModule])
.component("completionist", completionist)
.component("completionistDropdown", completionistDropdown)
.directive("completionistModelHook", completionistModelHook).name;
| intel-hpdd/GUI | source/iml/completionist/completionist-module.js | JavaScript | mit | 684 |
//= require jquery
// Used to poll the server to ask how well it getting on
// this module function is called with com.jivatechnology.Upper as 'this'
(function(){
this.Poller = (function(){
// Return the constructor
return function(settings){
// Extract required info from settings
var result = settings.result;
var upload_id = settings.upload_id;
var progress_url = settings.progress_url;
var interval = settings.interval;
var max_size = settings.max_size;
// Set the
var poll_prepare = function(xhr) {
xhr.setRequestHeader("X-Progress-ID", upload_id);
};
var too_big = function(size){
if(max_size){
return size > max_size;
} else {
return false;
}
};
var poll_result = function(data){
// change the width if the inner progress-bar
switch( data.state )
{
case 'starting':
// It's failed to track the upload
// No progress bar will be available
// Skip to processing stage
result.uploaded();
break;
case 'uploading':
// Tracking
result.sizeTotal(data.size);
result.sizeUploaded(data.received);
// Trigger the results callbacks
if(result.progress() >= 1){
result.uploaded();
} else if (too_big(data.size)) {
result.errored("File is too large");
} else {
result.uploading();
}
break;
case 'done':
result.uploaded();
break;
case 'error':
result.errored();
break;
case 'done':
result.uploaded();
break;
}
};
// Private methods
var poll = function(){
$.ajax({
type: "GET",
url: progress_url,
dataType: "json",
beforeSend: poll_prepare,
success: poll_result
});
};
var timer;
// Add callback to result
result.onUpdate.add(function(r){
if(r.hasStarted()){
// Schedule a check as we must still be uploading
timer = window.setTimeout( poll, interval );
} else {
// Cancel any checks
window.clearTimeout(timer);
timer = null;
}
});
};
})();
}).call(com.jivatechnology.Upper);
| theozaurus/jquery-upper | src/upper/poller.js | JavaScript | mit | 2,489 |
(function() {
T.doctypes = {};
T.doctypes.html = T.Doctype('[html]').extend();
T.doctypes.transitional = T.Doctype('[html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"]').extend();
T.doctypes.strict = T.Doctype('[html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"').extend();
T.doctypes.frameset = T.Doctype('[html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd"]').extend();
T.doctypes.basic = T.Doctype('[html PUBLIC "-//W3C//DTD XHTML Basic 1.1//EN" "http://www.w3.org/TR/xhtml-basic/xhtml-basic11.dtd"]').extend();
T.doctypes.mobile = T.Doctype('[html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.2//EN" "http://www.openmobilealliance.org/tech/DTD/xhtml-mobile12.dtd"]').extend();
})(); | OSWS/Templates | sources/doctypes/index.js | JavaScript | mit | 846 |
'use strict';
var _ = require('lodash');
var _it = {};
_it.error = {
usingItWithAUnvalidName : function (bddIdentifier, unvalidName) {
return (""+
"You start to describe something using the it function with an unvalid name in the VibratoBDD instance with identifier \""+bddIdentifier+"\". "+
"A valid name is a non empty string."+
"\""+featureName+"\" isn't a valid valid");
}
}
module.exports = _it; | AlexisTessier/vibrato-bdd | specifications/messages/it.js | JavaScript | mit | 409 |
const EthSplit = artifacts.require('./EthSplit.sol');
const resolveCallback = (resolve, reject) => (err, result) => {
if (err) {
reject(err);
} else {
resolve(result);
}
};
const toPromise = (callback, ...args) => new Promise((resolve, reject) => callback(...args, resolveCallback(resolve, reject)));
const createPayoutTest = (owner, list) => () => {
const startBalance = web3.toWei(1, 'ether');
const payoutAmount = startBalance / list.length;
const expectedBalance = list.map(address => {
return web3.eth.getBalance(address).add(payoutAmount).toNumber();
});
return EthSplit.new(list, '0x0')
.then(instance => {
return toPromise(web3.eth.sendTransaction, {
from: owner,
to: instance.address,
value: startBalance,
})
.then(() => instance.payout({ from: owner }))
.then(() => {
const currentBalance = list.map(address => {
return web3.eth.getBalance(address).toNumber();
})
assert.deepEqual(currentBalance, expectedBalance);
});
});
};
contract('EthSplit', accounts => {
const [owner, jon, arrya, rob, donation] = accounts;
it('accepts money', () => {
return EthSplit.new()
.then(instance => {
return toPromise(web3.eth.sendTransaction, {
from: owner,
to: instance.address,
value: web3.toWei(1, 'ether'),
})
.then(transId => web3.eth.getBalance(instance.address))
.then(balance => balance.toNumber())
.then(balance => assert.equal(balance, web3.toWei(1, 'ether')));
});
});
it('splits eth between two shareholders', createPayoutTest(owner, [jon, arrya]));
it('splits eth between four shareholders', createPayoutTest(owner, [jon, arrya, rob, donation]));
it('supports donations', () => {
const list = [jon, arrya];
const startBalance = web3.toWei(1, 'ether');
const donationValue = startBalance / 1000;
const expectedDonationBalance = web3.eth.getBalance(donation).add(donationValue).toNumber();
const expectedBalance = list.map(address => {
return web3.eth.getBalance(address)
.add((startBalance - donationValue) / list.length)
.toNumber();
});
return EthSplit.new([jon, arrya], donation)
.then(instance => {
return toPromise(web3.eth.sendTransaction, {
from: owner,
to: instance.address,
value: startBalance,
})
.then(() => instance.payout())
.then(() => {
const currentBalance = list.map(address => web3.eth.getBalance(address).toNumber());
assert.deepEqual(currentBalance, expectedBalance);
const donationBalance = web3.eth.getBalance(donation).toNumber();
assert.equal(donationBalance, expectedDonationBalance);
})
});
});
});
| radmen/eth-split | test/eth-split.js | JavaScript | mit | 3,275 |
import React from 'react';
import DocumentTitle from 'react-document-title';
import Logout from '../auth/logout.react';
import requireAuth from '../auth/requireauth.react';
import {msg} from '../intl/store';
class Me extends React.Component {
render() {
return (
<DocumentTitle title={msg('me.title')}>
<div>
<p>
This is your secret page.
</p>
<Logout />
</div>
</DocumentTitle>
);
}
}
export default requireAuth(Me);
| lassecapel/este-isomorphic-app | src/client/pages/me.react.js | JavaScript | mit | 504 |
'use strict';
/**
* @ngdoc function
* @name wavesApp.controller:BootCtrl
* @description
* # BootCtrl
* Controller of the wavesApp
*/
angular.module('wavesApp')
.controller('BootCtrl', ['$rootScope', '$state', 'InflectionsAPIService',
'hollidaysWord', 'weatherWord', 'newsWord',
'localStorageService',
function ($rootScope, $state, InflectionsAPIService,
hollidaysWord, weatherWord, newsWord,
localStorageService) {
//Palabras :: {k*: v} => k: palabras reconocidas, v: parametros/acciones validas
localStorageService.clearAll();
InflectionsAPIService.fetchStartupData([hollidaysWord, weatherWord, newsWord])
.then(function(results){
results.forEach(function(result){
if(result.data.content.body!==undefined){
localStorageService.set(result.data.attributes.query_words.join(', '), result.data.content.body);
}else{
console.error("Check on Inflections why the service with query_word \""+result.data.attributes.query_words.join(', ')+"\" returns undefined.");
}
});
$state.go('active_screen');
});
}]);
| InflectProject/waves | app/scripts/controllers/boot.js | JavaScript | mit | 1,251 |
// All material copyright ESRI, All Rights Reserved, unless otherwise specified.
// See https://js.arcgis.com/4.8/esri/copyright.txt for details.
//>>built
define("require exports ../tsSupport/assignHelper ./get ./utils ./extensions/serializableProperty".split(" "),function(E,e,C,u,D,r){function q(v,b,k){void 0===k&&(k=y);for(var f=D.getProperties(v),p=f.metadatas,e={},d=0,g=Object.getOwnPropertyNames(b);d<g.length;d++){var m=e,h=p,c=g[d],n=b,q=k,a=r.originSpecificReadPropertyDefinition(h[c],q);a&&(!a.read||!1!==a.read.enabled&&!a.read.source)&&(m[c]=!0);for(var w=0,z=Object.getOwnPropertyNames(h);w<z.length;w++){var A=z[w],a=r.originSpecificReadPropertyDefinition(h[A],
q),l;a:{l=c;var B=n;if(a&&a.read&&!1!==a.read.enabled&&a.read.source)if(a=a.read.source,"string"===typeof a){if(a===l||-1<a.indexOf(".")&&0===a.indexOf(l)&&u.exists(a,B)){l=!0;break a}}else for(var x=0;x<a.length;x++){var t=a[x];if(t===l||-1<t.indexOf(".")&&0===t.indexOf(l)&&u.exists(t,B)){l=!0;break a}}l=!1}l&&(m[A]=!0)}}f.setDefaultOrigin(k.origin);g=0;for(m=Object.getOwnPropertyNames(e);g<m.length;g++)d=m[g],c=(h=r.originSpecificReadPropertyDefinition(p[d],k).read)&&h.source,n=void 0,n=c&&"string"===
typeof c?u.valueOf(b,c):b[d],h&&h.reader&&(n=h.reader.call(v,n,b,k)),void 0!==n&&f.set(d,n);b=0;for(p=Object.getOwnPropertyNames(p);b<p.length;b++)d=p[b],e[d]||(g=v,m=f,h=k,c=(c=r.originSpecificReadPropertyDefinition(m.metadatas[d],h))&&c.read&&c.read.default,void 0!==c&&(g="function"===typeof c?c.call(g,d,h):c,void 0!==g&&m.set(d,g)));f.setDefaultOrigin("user")}Object.defineProperty(e,"__esModule",{value:!0});var y={origin:"service"};e.read=q;e.readLoadable=function(e,b,k,f){void 0===f&&(f=y);b=
C({},f,{messages:[]});k(b);b.messages.forEach(function(b){"warning"!==b.type||e.loaded?f&&f.messages.push(b):e.loadWarnings.push(b)})};e.default=q}); | ycabon/presentations | 2018-user-conference/arcgis-js-api-road-ahead/demos/gamepad/api-snapshot/esri/core/accessorSupport/read.js | JavaScript | mit | 1,839 |
(function($) {
if (!navigator.userAgent.match(/(Chrome|Firefox)/i) && $("form .target-area").length) {
document.location.href="/not-supported";
}
$("#title").click(function(e) {
e.stopPropagation();
});
if (navigator.userAgent.match(/Macintosh/i)) {
// Change help text for Mac users
$(".shortcut-key").text("Cmd-V");
}
window.gotImage = function(dataURL) {
$("<img>").attr("src", dataURL).load(function() {
var img = $(this), tgt = $(".target-area");
img.hide().appendTo("body");
if (img.width() > 2048 || img.height() > 2048) {
alert("Sorry, this image is too large");
return;
}
$(".target-area .hint").hide();
tgt.css({backgroundImage: "url(" + dataURL + ")",
width: img.width()+"px",
height: img.height()+"px"});
$("#imgdata").val(dataURL);
$(".form-fields").fadeIn();
$("#home-head").text("Enter image details");
$("#home-expl").html("Well done! Now optionally give the image a title, select a background color, and press <b>share</b>!");
});
};
})(jQuery);
| arjan/stick.im | lib/js/stickim.js | JavaScript | mit | 1,289 |
version https://git-lfs.github.com/spec/v1
oid sha256:e70daccfb3d58f64790615b07341ded2b3d7844d0e6836989be2a7a87e76bc3a
size 51795
| yogeshsaroya/new-cdnjs | ajax/libs/rxjs/2.3.24/rx.compat.min.js | JavaScript | mit | 130 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.