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 React from 'react' import ApartmentTable from './ApartmentListContainer' import TextFieldForm from './ApartmentForm' import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider' import {Tabs, Tab} from 'material-ui/Tabs' import Paper from 'material-ui/Paper' import AppBar from 'material-ui/AppBar' import '../../css/apartment.css' const styles = { headline: { fontSize: 24, paddingTop: 16, marginBottom: 12, fontWeight: 400 } } const style = { height: 500, width: 1000, margin: 20, textAlign: 'center', display: 'inline-block' } const Apartment = () => ( <MuiThemeProvider> <div className='apartment'> <Tabs initialSelectedIndex={0} contentContainerClassName='5' > <Tab label='Apartment Form'> <div style={{textAlign: 'center', margin: '25px'}}> <Paper style={style} zDepth={1}> <AppBar title='Apartment Form' showMenuIconButton={false} /> <TextFieldForm /> </Paper> </div> </Tab> <Tab label='Apartment List'> <div style={{textAlign: 'center', margin: '25px'}}> <Paper style={style} zDepth={1}> <AppBar title='Apartment List' showMenuIconButton={false} /> <ApartmentTable /> </Paper> </div> </Tab> </Tabs> </div> </MuiThemeProvider> ) export default Apartment
jearjujaroen/propertymanagement
public/src/apartments/Apartment.js
JavaScript
mit
1,523
var gulp = require('gulp'); var browserify = require('gulp-browserify'); var uglify = require('gulp-uglify'); var minify = require('gulp-minify'); var rename = require('gulp-rename'); var concat = require('gulp-concat'); var notify = require("gulp-notify"); gulp.task( 'vendors.css', function() { gulp.src([ 'node_modules/todomvc-common/base.css', 'node_modules/todomvc-app-css/index.css' ]) .pipe(concat('vendors.min.css')) .pipe( minify() ) .pipe(gulp.dest('./public/css')) .pipe(notify("Vendors css bundle has been successfully compiled!")); }); gulp.task( 'vendors.js', function() { gulp.src( [ 'node_modules/vue/dist/vue.js', 'node_modules/vue-resource/dist/vue-resource.js', 'node_modules/todomvc-common/base.js', ]) .pipe(uglify()) .pipe(concat('vendors.min.js')) .pipe(gulp.dest('./public/js')) .pipe(notify("Vendors jaavscript bundle has been successfully compiled!")); }); gulp.task( 'css', function() { gulp.src('./resources/assets/css/style.css') .pipe( minify() ) .pipe(rename('style.bundle.css')) .pipe(gulp.dest('./public/css')) .pipe(notify("Css bundle has been successfully compiled!")); }); gulp.task( 'todos', function() { gulp.src('./src/Todos/js/App.js') .pipe(browserify( { transform: [ 'babelify', 'vueify' ], })) .pipe(uglify()) .pipe(rename('todos.bundle.js')) .pipe(gulp.dest('./public/js/todos')) .pipe(notify("Todos bundle has been successfully compiled!")); }); gulp.task( 'watch-todos', function() { gulp.watch('src/Todos/js/App.js', ['todos']); }); gulp.task( 'vendors', [ 'vendors.css', 'vendors.js' ] ); gulp.task( 'watch', [ 'watch-todos' ] ); gulp.task( 'default', [ 'watch' ] );
nezarfadle/laravel-vue-todos
gulpfile.js
JavaScript
mit
1,685
// All symbols in the `Zp` category as per Unicode v2.1.9: [ '\u2029' ];
mathiasbynens/unicode-data
2.1.9/categories/Zp-symbols.js
JavaScript
mit
73
var webpack = require('webpack'); module.exports = { devtool: 'inline-source-map', entry: { 'react-bootstrap-table': './src/index.js' }, output: { path: './dist', filename: '[name].js', library: 'ReactBootstrapTable', libraryTarget: 'umd' }, externals: [ { 'react': { root: 'React', commonjs2: 'react', commonjs: 'react', amd: 'react' } }, { 'react-dom': { root: 'ReactDOM', commonjs2: 'react-dom', commonjs: 'react-dom', amd: 'react-dom' } } ], module: { loaders: [{ test: /\.js$/, exclude: /node_modules/, loaders: ['babel'] }] } };
opensourcegeek/react-bootstrap-table
webpack.base.config.js
JavaScript
mit
712
export default Ember.Component.extend({ classNames: ['pretty-color'], attributeBindings: ['style'], style: function(){ return 'color: ' + this.get('name') + ';'; }.property('name') });
elisam98/mikomos-ember
app/components/pretty-color.js
JavaScript
mit
204
import request from 'supertest'; import low from 'lowdb'; import apiLoader from '../src/api.js'; import Car from '../../models/Car.js'; const freshDB = () => { const fresh = low(); fresh.defaults({ cars: [] }).write(); return fresh; }; describe('GET /api/cars', () => { let db; let api; beforeEach(() => { db = freshDB(); api = apiLoader(db); }); test('respond with json', () => request(api) .get('/api/cars') .set('Accept', 'application/json') .expect('Content-Type', /json/) .expect(200) .then((response) => { expect(response.body.cars).toEqual([]); })); test('respond with cars that match criteria', () => { db.get('cars') .push(new Car('a', 'fox', 20000, 2013, 100000)) .push(new Car('a', 'gol', 20000, 2013, 100000)) .write(); return request(api) .get('/api/cars?query=Fox') .set('Accept', 'application/json') .expect('Content-Type', /json/) .expect(200) .then((response) => { expect(response.body.cars.length).toEqual(1); expect(response.body.cars[0].fullName).toEqual('fox'); }); }); test('respond with cars that match criteria with many words', () => { db.get('cars') .push(new Car('a', 'fox', 20000, 2013, 100000)) .push(new Car('a', 'fox outro', 20000, 2013, 100000)) .push(new Car('a', 'gol', 20000, 2013, 100000)) .write(); return request(api) .get('/api/cars?query=Fox outro') .set('Accept', 'application/json') .expect('Content-Type', /json/) .expect(200) .then((response) => { expect(response.body.cars.length).toEqual(1); expect(response.body.cars[0].fullName).toEqual('fox outro'); }); }); });
rodrigomaia17/seminovos-bh-crawler
api/test/api.test.js
JavaScript
mit
1,756
'use strict'; /*! * Snakeskin * https://github.com/SnakeskinTpl/Snakeskin * * Released under the MIT license * https://github.com/SnakeskinTpl/Snakeskin/blob/master/LICENSE */ import Snakeskin from '../core'; import { ws } from '../helpers/string'; import { any } from '../helpers/gcc'; Snakeskin.addDirective( 'return', { block: true, deferInit: true, group: ['return', 'microTemplate'], placement: 'template', trim: true }, function (command) { if (command.slice(-1) === '/') { this.startInlineDir(null, {command: command.slice(0, -1)}); return; } this.startDir(null, {command}); if (!command) { this.wrap(`__RESULT__ = ${this.getResultDecl()};`); } }, function () { const {command} = this.structure.params; const val = command ? this.out(command, {unsafe: true}) : this.getReturnResultDecl(), parent = any(this.hasParentFunction()); if (!parent || parent.block) { this.append(`return ${val};`); return; } const def = ws` __RETURN__ = true; __RETURN_VAL__ = ${val}; `; let str = ''; if (parent.asyncParent) { if (this.getGroup('Async')[parent.asyncParent]) { str += def; if (this.getGroup('waterfall')[parent.asyncParent]) { str += 'return arguments[arguments.length - 1](__RETURN_VAL__);'; } else { str += ws` if (typeof arguments[0] === 'function') { return arguments[0](__RETURN_VAL__); } return false; `; } } else { str += 'return false;'; } } else { if (parent && !this.getGroup('async')[parent.target.name]) { str += def; this.deferReturn = 1; } str += 'return false;'; } this.append(str); } );
SnakeskinTpl/Snakeskin
src/directives/return.js
JavaScript
mit
1,693
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = undefined; var _defineProperty2 = require('babel-runtime/helpers/defineProperty'); var _defineProperty3 = _interopRequireDefault(_defineProperty2); var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck'); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn'); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = require('babel-runtime/helpers/inherits'); var _inherits3 = _interopRequireDefault(_inherits2); var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _classnames = require('classnames'); var _classnames2 = _interopRequireDefault(_classnames); var _Checkbox = require('./Checkbox.web'); var _Checkbox2 = _interopRequireDefault(_Checkbox); var _getDataAttr = require('../_util/getDataAttr'); var _getDataAttr2 = _interopRequireDefault(_getDataAttr); var _omit = require('omit.js'); var _omit2 = _interopRequireDefault(_omit); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } var __assign = undefined && undefined.__assign || Object.assign || function (t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) { if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } } return t; }; var AgreeItem = function (_React$Component) { (0, _inherits3["default"])(AgreeItem, _React$Component); function AgreeItem() { (0, _classCallCheck3["default"])(this, AgreeItem); return (0, _possibleConstructorReturn3["default"])(this, _React$Component.apply(this, arguments)); } AgreeItem.prototype.render = function render() { var _classNames; var _props = this.props, prefixCls = _props.prefixCls, style = _props.style, className = _props.className; var wrapCls = (0, _classnames2["default"])((_classNames = {}, (0, _defineProperty3["default"])(_classNames, prefixCls + '-agree', true), (0, _defineProperty3["default"])(_classNames, className, className), _classNames)); return _react2["default"].createElement("div", __assign({}, (0, _getDataAttr2["default"])(this.props), { className: wrapCls, style: style }), _react2["default"].createElement(_Checkbox2["default"], __assign({}, (0, _omit2["default"])(this.props, ['style']), { className: prefixCls + '-agree-label' }))); }; return AgreeItem; }(_react2["default"].Component); exports["default"] = AgreeItem; AgreeItem.defaultProps = { prefixCls: 'am-checkbox' }; module.exports = exports['default'];
forwk1990/wechart-checkin
antd-mobile-custom/antd-mobile/lib/checkbox/AgreeItem.web.js
JavaScript
mit
2,828
var request = require('request'); var RestSupport = function() { RestSupport.prototype.get = function(resource, next) { var me = this; request({ url: resource, method: 'GET', headers: { 'content-type': 'application/json' } }, function (err, res, body) { if (err) return next(err); next(err, body, res); }); }; }; module.exports = new RestSupport();
AndrewKeig/express-validation-swagger
test/support.js
JavaScript
mit
420
var path = require("path"); var webpack = require("webpack"); module.exports = function(entries, release) { var config = { // entry file to start from entry: entries, output: { // directory to output to path: path.resolve("./lib"), // output file name filename: "[name].js" }, plugins: [ /* * This makes the left side variable available in every module and assigned to the right side module */ new webpack.ProvidePlugin({ $: "jquery", jQuery: "jquery", "window.jQuery": "jquery", "window.$": "jquery" }) ] }; if (release) { var uglify = new webpack.optimize.UglifyJsPlugin({ beautify: false, mangle: { screw_ie8: true, keep_fnames: true }, compress: { screw_ie8: true }, comments: false }); config.plugins.push(uglify); }else{ //config.devtool = 'cheap-eval-source-map'; } return config; };
tenKinetic/tKcountdown
webpack.config.js
JavaScript
mit
990
/* @flow */ 'use strict' /* :: import type {CorsConfiguration} from '../../types.js' */ const projectMeta = require('../utils/project-meta.js') const values = require('../values.js') function readCors ( cwd /* : string */ ) /* : Promise<CorsConfiguration | false> */ { return projectMeta.read(cwd) .then((config) => { // Want to support two options here: // 1. Falsey to disable CORS if (!config.server || !config.server.cors) { return false } // 2. Truthy to use default CORS and merge in any custom stuff return Object.assign({ credentials: values.DEFAULT_CORS.CREDENTIALS, exposedHeaders: values.DEFAULT_CORS.EXPOSED_HEADERS, headers: values.DEFAULT_CORS.HEADERS, maxAge: values.DEFAULT_CORS.MAX_AGE, origins: values.DEFAULT_CORS.ORIGINS }, typeof config.server.cors === 'boolean' ? {} : config.server.cors) }) } module.exports = readCors
blinkmobile/server-cli
lib/cors/read.js
JavaScript
mit
948
var mongoose = require('mongoose'), _ = require('underscore'), Schema = mongoose.Schema, ObjectId = Schema.ObjectId; var Throw = new Schema({ score: { type: Number, required: true, min: 0, max: 25 }, modifier: { type: Number, required: true, min: 1, max: 3 }, }); var DartsPlayer = new Schema({ name: { type: String, required: true }, throws: [Throw], }); DartsPlayer.virtual('score') .get( function() { var game = this.parentArray._parent; if (_.isEmpty(this.throws)) return +game.startingScore; return _.reduce(this.throws, function(memo, t) { var potentialScore = memo - t.score * t.modifier; if (potentialScore < 0 || potentialScore == 0 && game.out == 2 && t.modifier != 2 || potentialScore == 1 && game.out == 2) return memo; else return potentialScore; }, +game.startingScore); }); var DartsGame = new Schema({ startingScore: { type: Number, required: true, min: 301, max: 1001, default: 501 }, out: { type: Number, required: true, min: 1, max: 2, default: 2 }, players: [DartsPlayer], throwNumber: { type: Number, required: true, min: 0, max: 2, default: 0 }, currentPlayer: { type: Number, required: true, default: 0 }, userId: { type: ObjectId, required: true }, }); DartsGame.method('setPlayers', function(players) { for (var i in players) { this.players.push({ id: players[i].id, name: players[i].name, }); } }); DartsGame.method('throw', function(score, modifier) { function validate(score, modifier) { if (score == 25 && (modifier == 1 || modifier == 2)) return; if (score > 20) throw 'Can\'t score higher than 20'; if (score < 0) throw 'Can\'t score lower than 0'; if (modifier > 4) throw 'Modifier bigger than 3 is not allowed'; if (modifier < 0) throw 'Negative modifer is not allowed'; }; function nextThrow(game) { if (game.throwNumber == 2) { game.throwNumber = 0; if (game.currentPlayer == game.players.length - 1) { game.currentPlayer = 0; } else game.currentPlayer++; } else game.throwNumber++; } if (!this.isOver()) { if (modifier == null) modifier = 1; validate(score, modifier); var player = this.players[this.currentPlayer]; player.throws.push({score: score, modifier: modifier}); nextThrow(this); } }); String.prototype.startsWith = function(str) { return (this.indexOf(str) === 0); }; DartsGame.method('parseThrow', function(score) { if (score.startsWith('D')) { this.throw(score.substring(1), 2); } else if (score.startsWith('T')) { this.throw(score.substring(1), 3); } else { if (_.isNumber(+score)) this.throw(+score); else throw 'Not a legal score'; } }); DartsGame.method('isOver', function() { return _.any(this.players, function(player) { return player.score == 0; }); }); DartsGame.method('winner', function() { return _.detect(this.players, function(player) { return player.score == 0; }); }); DartsGame.method('isStarted', function() { return _.any(this.players, function(player) { return !_.isEmpty(player.throws); }); }); DartsGame.method('lastThrower', function() { if (this.throwNumber == 0) { if (this.currentPlayer == 0) { return this.players[this.players.length - 1]; } return this.players[this.currentPlayer - 1]; } else { return this.players[this.currentPlayer]; } }); DartsGame.method('undoThrow', function() { if (this.isStarted()) { if (this.throwNumber == 0) { this.throwNumber = 2; if (this.currentPlayer == 0) { this.currentPlayer = this.players.length - 1; } else { this.currentPlayer--; } } else { this.throwNumber--; } _.last(this.players[this.currentPlayer].throws).remove(); } }); mongoose.model('DartsGame', DartsGame);
mmozuras/dartboard
models/darts_game.js
JavaScript
mit
4,110
{ if (Array.isArray(t) && c(e)) return (t.length = Math.max(t.length, e)), t.splice(e, 1, n), n; if (d(t, e)) return (t[e] = n), n; var r = t.__ob__; return t._isVue || (r && r.vmCount) ? n : r ? (D(r.value, e, n), r.dep.notify(), n) : ((t[e] = n), n); }
stas-vilchik/bdd-ml
data/10394.js
JavaScript
mit
275
(function () { 'use strict'; angular .module('users.admin') .controller('UserController', UserController); UserController.$inject = ['$scope', '$state', '$window', 'Authentication', 'userResolve', '$mdToast']; function UserController($scope, $state, $window, Authentication, user, $mdToast) { var vm = this; vm.authentication = Authentication; vm.user = user; vm.remove = remove; vm.update = update; function remove(user) { if ($window.confirm('Are you sure you want to delete this user?')) { if (user) { user.$remove(); vm.users.splice(vm.users.indexOf(user), 1); } else { vm.user.$remove(function () { $state.go('admin.users'); }); } } } function update(isValid) { if (!isValid) { $scope.$broadcast('show-errors-check-validity', 'vm.userForm'); return false; } var user = vm.user; user.$update(function () { $state.go('admin.user', { userId: user._id }); }, function (errorResponse) { vm.error = errorResponse.data.message; $mdToast.show( $mdToast.simple() .textContent(vm.error) .hideDelay(3000) ); }); } } }());
tennosys/autoworks
modules/users/client/controllers/admin/user.client.controller.js
JavaScript
mit
1,304
module.exports = { extends: 'airbnb', parser: 'babel-eslint', plugins: [ 'react', 'jsx-a11y', 'import' ], globals: { OT: true }, env: { browser: true, }, rules: { 'no-confusing-arrow': ['error', { allowParens: true }], 'react/jsx-filename-extension': 'off', 'react/forbid-prop-types': ['error', { forbid: ['any', 'array'] }] } };
aiham/opentok-react
src/.eslintrc.js
JavaScript
mit
382
"use strict"; let datafire = require('datafire'); let openapi = require('./openapi.json'); module.exports = datafire.Integration.fromOpenAPI(openapi, "azure_network_virtualrouter");
DataFire/Integrations
integrations/generated/azure_network_virtualrouter/index.js
JavaScript
mit
181
export const GET_RESOURCE_TO_VERIFY = 'verificationPortal/GET_RESOURCE_TO_VERIFY' export const FORM_SUCCESSFULLY_SUBMITTED = 'FORM_SUCCESSFULLY_SUBMITTED' export const CLEAR_RESOURCE = 'verificationPortal/CLEAR_RESOURCE'
HelpAssistHer/help-assist-her
client/verification-portal/pregnancy-resource-center/action-types.js
JavaScript
mit
222
import React from 'react' import PropTypes from 'prop-types' import { connect } from 'react-redux' import { bindActionCreators } from 'redux' import { selectUser } from '../../../store/actions' import { PagingState, SortingState, } from '@devexpress/dx-react-grid' import { Grid, TableView, TableHeaderRow, PagingPanel, } from '@devexpress/dx-react-grid-bootstrap3' const URL = 'https://js.devexpress.com/Demos/WidgetsGallery/data/orderItems' class UserList extends React.Component { constructor (props) { super(props) this.state = { columns: [ { name: 'OrderNumber', title: 'Order #', align: 'right' }, { name: 'OrderDate', title: 'Order Date' }, { name: 'StoreCity', title: 'Store City' }, { name: 'StoreState', title: 'Store State' }, { name: 'Employee', title: 'Employee' }, { name: 'SaleAmount', title: 'Sale Amount', align: 'right' }, ], rows: [], sorting: [{ columnName: 'StoreCity', direction: 'asc' }], totalCount: 0, pageSize: 10, allowedPageSizes: [5, 10, 15], currentPage: 0, // loading: true, } this.changeSorting = this.changeSorting.bind(this) this.changeCurrentPage = this.changeCurrentPage.bind(this) this.changePageSize = this.changePageSize.bind(this) } componentDidMount () { this.loadData() } componentDidUpdate () { this.loadData() } changeSorting (sorting) { this.setState({ // loading: true, sorting, }) } changeCurrentPage (currentPage) { this.setState({ // loading: true, currentPage, }) } changePageSize (pageSize) { const totalPages = Math.ceil(this.state.totalCount / pageSize) const currentPage = Math.min(this.state.currentPage, totalPages - 1) this.setState({ // loading: true, pageSize, currentPage, }) } queryString () { const { sorting, pageSize, currentPage } = this.state let queryString = `${URL}?take=${pageSize}&skip=${pageSize * currentPage}` const columnSorting = sorting[0] if (columnSorting) { const sortingDirectionString = columnSorting.direction === 'desc' ? ' desc' : '' queryString = `${queryString}&orderby=${columnSorting.columnName}${sortingDirectionString}` } return queryString } loadData () { const queryString = this.queryString() if (queryString === this.lastQuery) { // this.setState({ loading: false }) return } fetch(queryString) .then(response => response.json()) .then(data => { console.log(data.items.length) this.setState({ rows: data.items, totalCount: data.totalCount, // loading: false, }) }) .catch(() => this.setState({ // loading: false })) this.lastQuery = queryString } createTableItems () { return this.props.users.map((user, i) => { return ( <tr onClick={() => this.props.selectUser(user)} key={i}> <th>{user.id}</th> <th>{user.name}</th> <th>{user.born}</th> <th>{user.description}</th> <th><img src={user.image} alt='' /></th> </tr> ) }) } render () { const { rows, columns, sorting, pageSize, allowedPageSizes, currentPage, totalCount, loading, } = this.state return ( <div style={{ position: 'relative' }}> <Grid rows={rows} columns={columns} > <SortingState sorting={sorting} onSortingChange={this.changeSorting} /> <PagingState currentPage={currentPage} onCurrentPageChange={this.changeCurrentPage} pageSize={pageSize} onPageSizeChange={this.changePageSize} totalCount={totalCount} /> <TableView tableCellTemplate={({ row, column }) => { if (column.name === 'SaleAmount') { return ( <td style={{ textAlign: 'right' }}>${row.SaleAmount}</td> ) } return undefined }} tableNoDataCellTemplate={({ colspan }) => ( <td style={{ textAlign: 'center', padding: '40px 0', }} colSpan={colspan} > <big className='text-muted'>{loading ? '' : 'No data'}</big> </td> )} /> <TableHeaderRow allowSorting /> <PagingPanel allowedPageSizes={allowedPageSizes} /> </Grid> </div> ) } } UserList.propTypes = { users: PropTypes.array, selectUser: PropTypes.func } const mapStateToProps = (state) => ({ users: state.users }) const matchDispatchToProps = (dispatch) => { return bindActionCreators({ selectUser: selectUser }, dispatch) } export default connect(mapStateToProps, matchDispatchToProps)(UserList)
roslaneshellanoo/react-redux-tutorial
src/routes/Users/containers/userListContainer.js
JavaScript
mit
5,095
module.exports = { // Load Mock Product Data Into localStorage init: function() { // localStorage.clear(); localStorage.setItem('thing', JSON.stringify([{ _id:'cbus-254-56-61', parent:null, label:'much test' }, { _id:'mesh-099', parent:'voltage', label:'wow' }])); localStorage.setItem('items',JSON.stringify([ { _id:'cbus-254-56-61.level', thing:'cbus-254-56-61', item:'level', label:'much test', value:1, type:'number', icon: 'scotch-beer.png', widget:'Slider' }, { _id:'mesh-099.voltage', thing:'mesh-099', item:'voltage', label:'wow', value:2, type:'number', icon: 'scotch-beer.png', widget:'Slider' } ])); } };
the1laz/quicksilver-ui
js/ThingData.js
JavaScript
mit
845
function generateArray(table) { var out = []; var rows = table.querySelectorAll('tr'); var ranges = []; for (var R = 0; R < rows.length; ++R) { var outRow = []; var row = rows[R]; var columns = row.querySelectorAll('td'); for (var C = 0; C < columns.length; ++C) { var cell = columns[C]; var colspan = cell.getAttribute('colspan'); var rowspan = cell.getAttribute('rowspan'); var cellValue = cell.innerText; if(cellValue !== "" && cellValue == +cellValue) cellValue = +cellValue; //Skip ranges ranges.forEach(function(range) { if(R >= range.s.r && R <= range.e.r && outRow.length >= range.s.c && outRow.length <= range.e.c) { for(var i = 0; i <= range.e.c - range.s.c; ++i) outRow.push(null); } }); //Handle Row Span if (rowspan || colspan) { rowspan = rowspan || 1; colspan = colspan || 1; ranges.push({s:{r:R, c:outRow.length},e:{r:R+rowspan-1, c:outRow.length+colspan-1}}); }; //Handle Value outRow.push(cellValue !== "" ? cellValue : null); //Handle Colspan if (colspan) for (var k = 0; k < colspan - 1; ++k) outRow.push(null); } out.push(outRow); } return [out, ranges]; }; function datenum(v, date1904) { if(date1904) v+=1462; var epoch = Date.parse(v); return (epoch - new Date(Date.UTC(1899, 11, 30))) / (24 * 60 * 60 * 1000); } function sheet_from_array_of_arrays(data, opts) { var ws = {}; var range = {s: {c:10000000, r:10000000}, e: {c:0, r:0 }}; for(var R = 0; R != data.length; ++R) { for(var C = 0; C != data[R].length; ++C) { if(range.s.r > R) range.s.r = R; if(range.s.c > C) range.s.c = C; if(range.e.r < R) range.e.r = R; if(range.e.c < C) range.e.c = C; var cell = {v: data[R][C] }; if(cell.v == null) continue; var cell_ref = XLSX.utils.encode_cell({c:C,r:R}); if(typeof cell.v === 'number') cell.t = 'n'; else if(typeof cell.v === 'boolean') cell.t = 'b'; else if(cell.v instanceof Date) { cell.t = 'n'; cell.z = XLSX.SSF._table[14]; cell.v = datenum(cell.v); } else cell.t = 's'; ws[cell_ref] = cell; } } if(range.s.c < 10000000) ws['!ref'] = XLSX.utils.encode_range(range); return ws; } function Workbook() { if(!(this instanceof Workbook)) return new Workbook(); this.SheetNames = []; this.Sheets = {}; } function s2ab(s) { var buf = new ArrayBuffer(s.length); var view = new Uint8Array(buf); for (var i=0; i!=s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF; return buf; } function export_table_to_excel(id) { var theTable = document.getElementById(id); var oo = generateArray(theTable); var ranges = oo[1]; /* original data */ var data = oo[0]; var ws_name = "SheetJS"; var wb = new Workbook(), ws = sheet_from_array_of_arrays(data); /* add ranges to worksheet */ ws['!merges'] = ranges; /* add worksheet to workbook */ wb.SheetNames.push(ws_name); wb.Sheets[ws_name] = ws; var wbout = XLSX.write(wb, {bookType:'xlsx', bookSST:false, type: 'binary'}); saveAs(new Blob([s2ab(wbout)],{type:"application/octet-stream"}), "test.xlsx") }
hui-w/misc-fragment
javascript-excel/browser-version/vendor/Export2Excel.js
JavaScript
mit
3,330
export default function formatUrl({ baseUrl, size, theme, uri, view }) { let src = `${baseUrl}/?uri=${uri}&size=${size}&theme=${theme}`; if (view) { src += `&view=${view}`; } return src; }
sir-dunxalot/ember-spotify
tests/helpers/format-url.js
JavaScript
mit
203
const test = require('tape') const parse = require('../../parse').element('Body') test('b(N+1,N+2)', function (t) { const res = parse('b(N+1,N+2)') t.equal(typeof res, 'object') t.ok(res instanceof Array) t.equal(res.length, 1) t.end() }) test('b(N+1,N+2), c(N-1)', function (t) { const res = parse('b(N+1,N+2), c(N-1)') t.equal(typeof res, 'object') t.ok(res instanceof Array) t.equal(res.length, 2) t.end() })
fnogatz/CHR.js
test/parser/body.js
JavaScript
mit
439
'use strict'; // Setting up route angular.module('users').config(['$stateProvider', function ($stateProvider) { // Users state routing $stateProvider .state('settings', { abstract: true, url: '/settings', templateUrl: 'modules/users/client/views/settings/settings.client.view.html', data: { // DL - adding supervisor and technician roles roles: ['user', 'admin', 'technician', 'supervisor'] } }) .state('settings.profile', { url: '/profile', templateUrl: 'modules/users/client/views/settings/edit-profile.client.view.html' }) .state('settings.password', { url: '/password', templateUrl: 'modules/users/client/views/settings/change-password.client.view.html' }) .state('settings.accounts', { url: '/accounts', templateUrl: 'modules/users/client/views/settings/manage-social-accounts.client.view.html' }) .state('settings.picture', { url: '/picture', templateUrl: 'modules/users/client/views/settings/change-profile-picture.client.view.html' }) .state('authentication', { abstract: true, url: '/authentication', templateUrl: 'modules/users/client/views/authentication/authentication.client.view.html' }) .state('authentication.signup', { url: '/signup', templateUrl: 'modules/users/client/views/authentication/signup.client.view.html' }) .state('authentication.signin', { url: '/signin?err', templateUrl: 'modules/users/client/views/authentication/signin.client.view.html' }) .state('password', { abstract: true, url: '/password', template: '<ui-view/>' }) .state('password.forgot', { url: '/forgot', templateUrl: 'modules/users/client/views/password/forgot-password.client.view.html' }) .state('password.reset', { abstract: true, url: '/reset', template: '<ui-view/>' }) .state('password.reset.invalid', { url: '/invalid', templateUrl: 'modules/users/client/views/password/reset-password-invalid.client.view.html' }) .state('password.reset.success', { url: '/success', templateUrl: 'modules/users/client/views/password/reset-password-success.client.view.html' }) .state('password.reset.form', { url: '/:token', templateUrl: 'modules/users/client/views/password/reset-password.client.view.html' }); } ]);
davidrocklee/mean
modules/users/client/config/users.client.routes.js
JavaScript
mit
2,566
var Todo = React.createClass({displayName: "Todo", getInitialState: function() { this.text = ""; return {text: ""}; }, componentWillUnmount: function() { this.ref.off(); }, componentWillMount: function() { this.ref = new Firebase("https://glaring-fire-5349.firebaseio.com/react_todos/" + this.props.todoKey); // Update the todo's text when it changes. this.ref.on("value", function(snap) { if (snap.val() !== null) { this.text = snap.val().text; this.setState({ text: this.text }); } else { this.ref.update({ text: "" }); } }.bind(this)); }, onTextBlur: function(event) { this.ref.update({ text: $(event.target).text() }); }, render: function() { return ( React.createElement("li", {id: this.props.todoKey, className: "list-group-item todo"}, React.createElement("a", {href: "#", className: "pull-left todo-check"}, React.createElement("span", { className: "todo-check-mark glyphicon glyphicon-ok", "aria-hidden": "true"} ) ), React.createElement("span", { onBlur: this.onTextBlur, contentEditable: "true", "data-ph": "Todo", className: "todo-text"}, this.state.text ) ) ); } }); var TodoList = React.createClass({displayName: "TodoList", getInitialState: function() { this.todos = []; return {todos: []}; }, componentWillMount: function() { this.ref = new Firebase("https://glaring-fire-5349.firebaseio.com/react_todos/"); // Add an empty todo if none currently exist. this.ref.on("value", function(snap) { if (snap.val() === null) { this.ref.push({ text: "", checked: false, }); } }.bind(this)); // Add an added child to this.todos. this.ref.on("child_added", function(childSnap) { this.todos.push({ k: childSnap.key(), val: childSnap.val() }); this.setState({ todos: this.todos }); }.bind(this)); this.ref.on("child_removed", function(childSnap) { var key = childSnap.key(); var i; for (i = 0; i < this.todos.length; i++) { if (this.todos[i].k == key) { break; } } this.todos.splice(i, 1); this.setState({ todos: this.todos }); }.bind(this)); }, componentWillUnmount: function() { this.ref.off(); }, render: function() { var todos = this.state.todos.map(function (todo) { return ( React.createElement(Todo, {todoKey: todo.k}) ); }); return ( React.createElement("div", null, React.createElement("h1", {id: "list_title"}, this.props.title), React.createElement("ul", {id: "todo-list", className: "list-group"}, todos ) ) ); } }); var ListPage = React.createClass({displayName: "ListPage", render: function() { return ( React.createElement("div", null, React.createElement("div", {id: "list_page"}, React.createElement("a", { onClick: this.props.app.navOnClick({page: "LISTS"}), href: "/#/lists", id: "lists_link", className: "btn btn-primary"}, "Back to Lists" ) ), React.createElement("div", {className: "page-header"}, this.props.children ) ) ); } }); var Nav = React.createClass({displayName: "Nav", render: function() { return ( React.createElement("nav", {className: "navbar navbar-default navbar-static-top"}, React.createElement("div", {className: "container"}, React.createElement("div", {className: "navbar-header"}, React.createElement("a", {onClick: this.props.app.navOnClick({page: "LISTS"}), className: "navbar-brand", href: "?"}, "Firebase Todo") ), React.createElement("ul", {className: "nav navbar-nav"}, React.createElement("li", null, React.createElement("a", {href: "?"}, "Lists")) ) ) ) ); }, }); var App = React.createClass({displayName: "App", getInitialState: function() { var state = this.getState(); this.setHistory(state, true); return this.getState(); }, setHistory: function(state, replace) { var histFunc = replace ? history.replaceState.bind(history) : history.pushState.bind(history); if (state.page === "LIST") { histFunc(state, "", "#/list/" + state.todoListKey); } else if (state.page === "LISTS") { histFunc(state, "", "#/lists"); } else { console.log("Unknown page: " + state.page); } }, getState: function() { var url = document.location.toString(); if (url.match(/#/)) { var path = url.split("#")[1]; var res = path.match(/\/list\/([^\/]*)$/); if (res) { return { page: "LIST", todoListKey: res[1], }; } res = path.match(/lists$/); if (res) { return { page: "LISTS" } } } return { page: "LISTS" } }, componentWillMount: function() { // Register history listeners. window.onpopstate = function(event) { this.setState(event.state); }; }, navOnClick: function(state) { return function(event) { this.setHistory(state, false); this.setState(state); event.preventDefault(); }.bind(this); }, getPage: function() { if (this.state.page === "LIST") { return ( React.createElement(ListPage, {app: this}, React.createElement(TodoList, {todoListKey: this.state.todoListKey}) ) ); } else if (this.state.page === "LISTS") { return ( React.createElement("a", {onClick: this.navOnClick({page: "LIST", todoListKey: "-JjcFYgp1LyD5oDNNSe2"}), href: "/#/list/-JjcFYgp1LyD5oDNNSe2"}, "hi") ); } else { console.log("Unknown page: " + this.state.page); } }, render: function() { return ( React.createElement("div", null, React.createElement(Nav, {app: this}), React.createElement("div", {className: "container", role: "main"}, this.getPage() ) ) ); } }); React.render( React.createElement(App, null), document.getElementById('content') );
jasharpe/firebase-react-todo
build/.module-cache/317ce6b677c486cd0ff0fa900186c6309aa26ae3.js
JavaScript
mit
6,463
'use strict'; angular.module('myApp').factory('inboundRulesApi', function($resource) { return $resource('/api/scm.config/1.0/inbound_rules', {}, { 'query': { method: 'GET', isArray: true , responseType: 'json', transformResponse: function (data) { var wrapped = angular.fromJson(data); return wrapped.items; } }, 'delete': { method: 'DELETE', url: '/api/scm.config/1.0/inbound_rule/:ruleid', params: { ruleid: '@ruleid' } }, 'update': { method: 'PUT', url: '/api/scm.config/1.0/inbound_rule/:ruleid', params: { ruleid: '@ruleid' } } }); }); angular.module('myApp').service('inboundRulesSelectionSvc', function() { this.inboundRules = { }; this.setinboundRules = function(obj){ this.inboundRules = obj; } this.getinboundRules = function(){ return this.inboundRules; } });
marcerod/scmBrowser
app/views/inboundRules/inboundRules-service.js
JavaScript
mit
927
/** * EditableSlot is an abstract class representing Slots that can have a value directly entered into them * in addition to accepting Blocks. * Subclasses must implement createInputSystem() and formatTextSummary() * @param {Block} parent * @param {string} key * @param {number} inputType * @param {number} snapType * @param {number} outputType - [any, num, string, select] The type of data that can be directly entered * @param {Data} data - The initial value of the Slot * @constructor */ function EditableSlot(parent, key, inputType, snapType, outputType, data) { Slot.call(this, parent, key, snapType, outputType); this.inputType = inputType; this.enteredData = data; this.editing = false; //TODO: make the slotShape be an extra argument } EditableSlot.prototype = Object.create(Slot.prototype); EditableSlot.prototype.constructor = EditableSlot; EditableSlot.setConstants = function() { /* The type of Data that can be directly entered into the Slot. */ EditableSlot.inputTypes = {}; EditableSlot.inputTypes.any = 0; EditableSlot.inputTypes.num = 1; EditableSlot.inputTypes.string = 2; EditableSlot.inputTypes.select = 3; }; /** * @param {string} text - The text to set the slotShape to display * @param {boolean} updateDim - Should the Stack be told to update after this? */ EditableSlot.prototype.changeText = function(text, updateDim) { this.slotShape.changeText(text); if (updateDim && this.parent.stack != null) { this.parent.stack.updateDim(); //Update dimensions. } }; /** * Tells the Slot to display an InputSystem so it can be edited. Also sets the slotShape to appear selected */ EditableSlot.prototype.edit = function() { DebugOptions.assert(!this.hasChild); if (!this.editing) { this.editing = true; this.slotShape.select(); const inputSys = this.createInputSystem(); inputSys.show(this.slotShape, this.updateEdit.bind(this), this.finishEdit.bind(this), this.enteredData); } }; /** * @inheritDoc */ EditableSlot.prototype.onTap = function() { this.edit(); }; /** * Generates and displays an interface to modify the Slot's value */ EditableSlot.prototype.createInputSystem = function() { DebugOptions.markAbstract(); }; /** * Called by the InputSystem to change the Slot's data and displayed text * @param {Data} data - The Data the Slot should set its value to * @param {string} [visibleText] - The text the Slot should display as its value. Should correspond to Data. */ EditableSlot.prototype.updateEdit = function(data, visibleText) { DebugOptions.assert(this.editing); if (visibleText == null) { visibleText = this.dataToString(data); } this.enteredData = data; this.changeText(visibleText, true); SaveManager.markEdited(); }; /** * Called when an InputSystem finishes editing the Slot * @param {Data} data - The Data the Slot should be set to */ EditableSlot.prototype.finishEdit = function(data) { DebugOptions.assert(this.editing); if (this.editing) { this.setData(data, true, true); //Sanitize data, updateDims this.slotShape.deselect(); this.editing = false; SaveManager.markEdited(); } }; /** * Returns whether the Slot is being edited * @return {boolean} */ EditableSlot.prototype.isEditing = function() { return this.editing; }; /** * Assigns the Slot's Data and updates its text.w * @param {Data} data - The Data to set to * @param {boolean} sanitize - indicates whether the Data should be run through sanitizeData first * @param {boolean} updateDim - indicates if the Stack should updateDim after this */ EditableSlot.prototype.setData = function(data, sanitize, updateDim) { if (sanitize) { data = this.sanitizeData(data); } if (data == null) return; this.enteredData = data; this.changeText(this.dataToString(this.enteredData), updateDim); }; /** * Converts the Slot's data to a displayable string. Subclasses override this method to apply formatting. * @param {Data} data * @return {string} */ EditableSlot.prototype.dataToString = function(data) { return data.asString().getValue(); }; /** * Validates that the Data is compatible with this Slot. May attempt to fix invalid Data. * By default, this function just converts the data to the correct type. Subclasses override this method. * Makes use of inputType * @param {Data|null} data - The Data to sanitize * @return {Data|null} - The sanitized Data or null if the Data cannot be sanitized */ EditableSlot.prototype.sanitizeData = function(data) { if (data == null) return null; const inputTypes = EditableSlot.inputTypes; // Only valid Data of the correct type is allowed if (this.inputType === inputTypes.string) { data = data.asString(); } else if (this.inputType === inputTypes.num) { data = data.asNum(); } else if (this.inputType === inputTypes.select) { data = data.asSelection(); } if (data.isValid) { return data; } return null; }; /** * @inheritDoc * @return {string} */ EditableSlot.prototype.textSummary = function() { let result = "..."; if (!this.hasChild) { //If it has a child, just use an ellipsis. result = this.dataToString(this.enteredData); } return this.formatTextSummary(result); }; /** * Takes a textSummary and performs string manipulation to format it according to the Slot type * @param {string} textSummary * @return {string} */ EditableSlot.prototype.formatTextSummary = function(textSummary) { DebugOptions.markAbstract(); }; /** * Reads the Data from the Slot, assuming that the Slot has no children. * @return {Data} - The Data stored in the Slot */ EditableSlot.prototype.getDataNotFromChild = function() { return this.enteredData; }; /** * Converts the Slot and its children into XML, storing the value in the enteredData as well * @inheritDoc * @param {Document} xmlDoc * @return {Node} */ EditableSlot.prototype.createXml = function(xmlDoc) { let slot = Slot.prototype.createXml.call(this, xmlDoc); let enteredData = XmlWriter.createElement(xmlDoc, "enteredData"); enteredData.appendChild(this.enteredData.createXml(xmlDoc)); slot.appendChild(enteredData); return slot; }; /** * @inheritDoc * @param {Node} slotNode * @return {EditableSlot} */ EditableSlot.prototype.importXml = function(slotNode) { Slot.prototype.importXml.call(this, slotNode); const enteredDataNode = XmlWriter.findSubElement(slotNode, "enteredData"); const dataNode = XmlWriter.findSubElement(enteredDataNode, "data"); if (dataNode != null) { const data = Data.importXml(dataNode); if (data != null) { this.setData(data, true, false); } } return this; }; /** * @inheritDoc * @param {EditableSlot} slot */ EditableSlot.prototype.copyFrom = function(slot) { Slot.prototype.copyFrom.call(this, slot); this.setData(slot.enteredData, false, false); }; /** * @inheritDoc * @return {boolean} */ EditableSlot.prototype.isEditable = function() { return true; };
BirdBrainTechnologies/HummingbirdDragAndDrop-
BlockParts/Slot/EditableSlot/EditableSlot.js
JavaScript
mit
6,839
'use strict'; describe('Controller: EventCtrl', function () { // load the controller's module beforeEach(module('ngBrxApp')); var EventCtrl, scope; // Initialize the controller and a mock scope beforeEach(inject(function ($controller, $rootScope) { scope = $rootScope.$new(); EventCtrl = $controller('EventCtrl', { $scope: scope }); })); it('should attach a list of awesomeThings to the scope', function () { expect(scope.awesomeThings.length).toBe(3); }); });
freizl/shBrowse
test/spec/controllers/event.js
JavaScript
mit
508
import Component from '@glimmer/component'; import VerifiLogoSvg from 'dummy/images/media-registry/verifi-logo.svg'; export default class RegistrationEmbedded extends Component { get registrationEmbedded() { let verifi_id = this.args.model?.verifi_id; if (verifi_id) { return { id: verifi_id, type: 'registration', imgURL: VerifiLogoSvg, title: 'Verifi Registry', description: verifi_id, fields: [ { title: 'asset type', value: this.args.model.asset_type || 'Master Recording', }, { title: 'created', value: this.args.model.verifi_reg_date, type: 'date', }, ], }; } return null; } }
cardstack/cardstack
packages/boxel/tests/dummy/app/components/cards/registration-embedded.js
JavaScript
mit
774
// 3rd const Router = require('koa-router') const compress = require('koa-compress') const nunjucks = require('nunjucks') // 1st const cache = require('../cache') const router = new Router() //////////////////////////////////////////////////////////// router.get('/sitemap.txt', async ctx => { ctx.redirect('/sitemap.xml') }) router.get('/sitemaps/:idx.txt', compress(), async ctx => { const idx = parseInt(ctx.params.idx) || 0 const chunk = cache.get('sitemaps')[idx] ctx.assert(chunk, 404) ctx.type = 'text/plain' ctx.body = chunk.join('\n') }) //////////////////////////////////////////////////////////// // { count: <sitemaps total> } const indexTemplate = nunjucks.compile( ` <?xml version="1.0" encoding="UTF-8"?> <sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> {% for i in range(0, count) %} <sitemap> <loc>https://www.roleplayerguild.com/sitemaps/{{ i }}.txt</loc> </sitemap> {% endfor %} </sitemapindex> `.trim() ) router.get('/sitemap.xml', async ctx => { var chunks = cache.get('sitemaps') ctx.type = 'text/xml' ctx.body = indexTemplate.render({ count: chunks.length }) }) //////////////////////////////////////////////////////////// module.exports = router
danneu/guild
server/routes/sitemaps.js
JavaScript
mit
1,255
'use strict'; var SIGNALING_SERVER = 'https://112.108.40.152:443/'; var config = { openSocket: function(config) { console.log('s1'); /* Firebase ver. */ var channel = config.channel || 'screen-capturing-' + location.href.replace( /\/|:|#|%|\.|\[|\]/g , ''); var socket = new Firebase('https://webrtc.firebaseIO.com/' + channel); socket.channel = channel; socket.on("child_added", function(data) { console.log('s2'); config.onmessage && config.onmessage(data.val()); }); socket.send = function(data) { console.log('s3'); this.push(data); }; config.onopen && setTimeout(config.onopen, 1); socket.onDisconnect().remove(); return socket; /* Socket.io ver. (Not yet) */ //var SIGNALING_SERVER = 'https://112.108.40.152:443/'; // //config.channel = config.channel || location.href.replace(/\/|:|#|%|\.|\[|\]/g, ''); //var sender = Math.round(Math.random() * 999999999) + 999999999; // //io.connect(SIGNALING_SERVER).emit('new-channel', { // channel: config.channel, // sender: sender //}); // //var socket = io.connect(SIGNALING_SERVER + config.channel); //socket.channel = config.channel; //socket.on('connect', function () { // if (config.callback) config.callback(socket); //}); // //socket.send = function (message) { // socket.emit('message', { // sender: sender, // data: message // }); //}; // //socket.on('message', config.onmessage); }, onRemoteStream: function(media) { console.log('s4'); var video = media.video; video.setAttribute('controls', true); videosContainer.insertBefore(video, videosContainer.firstChild); video.play(); }, onRoomFound: function(room) { console.log('s5'); dualrtcUI.joinRoom({ roomToken: room.broadcaster, joinUser: room.broadcaster }); }, onNewParticipant: function(numberOfParticipants) { console.log('s7'); //document.title = numberOfParticipants + ' users are viewing your screen!'; }, oniceconnectionstatechange: function(state) { console.log('s8'); if(state == 'failed') { alert('Failed to bypass Firewall rules.'); } if(state == 'connected') { alert('A user successfully received screen.'); } } }; // end of config function captureUserMedia(callback, extensionAvailable) { console.log('s9'); console.log('captureUserMedia chromeMediaSource', DetectRTC.screen.chromeMediaSource); var screen_constraints = { mandatory: { chromeMediaSource: DetectRTC.screen.chromeMediaSource, maxWidth: screen.width > 1920 ? screen.width : 1920, maxHeight: screen.height > 1080 ? screen.height : 1080 // minAspectRatio: 1.77 }, optional: [{ // non-official Google-only optional constraints googTemporalLayeredScreencast: true }, { googLeakyBucket: true }] }; // try to check if extension is installed. if(isChrome && typeof extensionAvailable == 'undefined' && DetectRTC.screen.chromeMediaSource != 'desktop') { DetectRTC.screen.isChromeExtensionAvailable(function(available) { console.log('s10'); captureUserMedia(callback, available); }); return; } if(isChrome && DetectRTC.screen.chromeMediaSource == 'desktop' && !DetectRTC.screen.sourceId) { DetectRTC.screen.getSourceId(function(error) { console.log('s11'); if(error && error == 'PermissionDeniedError') { alert('PermissionDeniedError: User denied to share content of his screen.'); } captureUserMedia(callback); }); return; } if(isChrome && !DetectRTC.screen.sourceId) { window.addEventListener('message', function (event) { console.log('s12'); if (event.data && event.data.chromeMediaSourceId) { var sourceId = event.data.chromeMediaSourceId; DetectRTC.screen.sourceId = sourceId; DetectRTC.screen.chromeMediaSource = 'desktop'; if (sourceId == 'PermissionDeniedError') { return alert('User denied to share content of his screen.'); } captureUserMedia(callback, true); } if (event.data && event.data.chromeExtensionStatus) { warn('Screen capturing extension status is:', event.data.chromeExtensionStatus); DetectRTC.screen.chromeMediaSource = 'screen'; captureUserMedia(callback, true); } }); return; } if(isChrome && DetectRTC.screen.chromeMediaSource == 'desktop') { screen_constraints.mandatory.chromeMediaSourceId = DetectRTC.screen.sourceId; } var constraints = { audio: false, video: screen_constraints }; if(!!navigator.mozGetUserMedia) { console.warn(Firefox_Screen_Capturing_Warning); constraints.video = { mozMediaSource: 'window', mediaSource: 'window', maxWidth: 1920, maxHeight: 1080, minAspectRatio: 1.77 }; } console.log( JSON.stringify( constraints , null, '\t') ); var video = document.createElement('video'); video.setAttribute('autoplay', true); video.setAttribute('controls', true); videosContainer.insertBefore(video, videosContainer.firstChild); getUserMedia({ video: video, constraints: constraints, onsuccess: function(stream) { console.log('s13'); config.attachStream = stream; callback && callback(); video.setAttribute('muted', true); }, onerror: function() { console.log('s14'); if (isChrome && location.protocol === 'http:') { alert('Please test on HTTPS.'); } else if(isChrome) { alert('Screen capturing is either denied or not supported. Please install chrome extension for screen capturing or run chrome with command-line flag: --enable-usermedia-screen-capturing'); } else if(!!navigator.mozGetUserMedia) { alert(Firefox_Screen_Capturing_Warning); } } }); } // end of captureUserMedia var dualrtcUI = dualrtc(config); var videosContainer = document.getElementById('videos-container'); var secure = (Math.random() * new Date().getTime()).toString(36).toUpperCase().replace( /\./g , '-'); var makeName = $('#makeName'); var joinName = $('#joinName'); var btnMakeRoom = $('#btnMakeRoom'); var btnJoinRoom = $('#btnJoinRoom'); var btnCopy = $('#btnCopy'); var divMake = $('#divMakeRoom'); var divJoin = $('#divJoinRoom'); var divScreen = $('#divScreen'); // about description var divDescript = $('#divDescript'); var divInstallCE01 = $('#divInstallCE01'); var divInstallCE02 = $('#divInstallCE02'); var divWikiWDDM = $('#divWikiWDDM'); btnMakeRoom.click(function () { if (makeName.val()) { makeName.attr('disabled', true); btnJoinRoom.attr('disabled', true); joinName.attr('disabled', true); btnJoinRoom.attr('disabled', true); window.open('about:black').location.href = location.href + makeName.val(); } }); btnJoinRoom.click(function () { if (joinName.val()) { joinName.attr('disabled', true); btnJoinRoom.attr('disabled', true); window.open('about:black').location.href = location.href + joinName.val(); } }); btnCopy.click(function () { makeName.select(); try { var successful = document.execCommand('copy'); var msg = successful ? 'successful' : 'unsuccessful'; console.log('Copy email command was ' + msg); } catch(err) { console.log('Oops, unable to copy'); } }); divInstallCE01.click(function () { window.open('about:black').location.href = 'https://chrome.google.com/webstore/detail/desktopcapture/mhpddeoilenchcefgimjlbbccdiepnnk'; }); divInstallCE02.click(function () { window.open('about:black').location.href = 'https://chrome.google.com/webstore/detail/dualrtcio/kdgjponegkkhkigjlknapimncipajbpi'; }); divWikiWDDM.click(function () { window.open('about:black').location.href = 'https://dualrtc-io.github.io/'; }); (function() { if (location.hash.length <= 2) { makeName.val(secure); //makeName.attr('placeholder', secure); } else { // 방 들어왔을 때 var roomName = location.hash.substring(2, 21); if (divMake.css('display') == 'block') $('#divMakeRoom').hide(); if (divJoin.css('display') == 'block') $('#divJoinRoom').hide(); if (divScreen.css('display') == 'none') $('#divScreen').show(); if (divDescript.css('display') == 'block') $('#divDescript').hide(); captureUserMedia(function() { dualrtcUI.createRoom({ roomName: (roomName || 'Anonymous') + ' shared his screen with you' }); }); } })(); var Firefox_Screen_Capturing_Warning = 'Make sure that you are using Firefox Nightly and you enabled: media.getusermedia.screensharing.enabled flag from about:config page. You also need to add your domain in "media.getusermedia.screensharing.allowed_domains" flag.';
DualRTC-io/DualRTC.io-Demo
public/dualrtc/screenShare.js
JavaScript
mit
9,740
(function(){ var active = scrolling = false; var MagicScroll = function(selector, options) { if(!(this instanceof MagicScroll)) { return new MagicScroll(selector, options); } if(!selector) { console.log('WTF Bro! Give me selector!'); } else { this.elements = document.querySelectorAll(selector); } return this; }; MagicScroll.prototype.create = function() { for(var i = 0; i < this.elements.length; i++) { var element = this.elements[i]; if(!element.magicScroll) { element.magicScroll = true; element.addEventListener('mousedown', this._start); element.addEventListener('mouseup', this._stop); element.addEventListener('mouseleave', this._stop); element.addEventListener('mousemove', this._move); } } return this; }; MagicScroll.prototype._start = function(e) { active = true; }; MagicScroll.prototype._stop = function(e) { active = false; e.currentTarget.classList.remove('scrolling'); scrolling = false; }; MagicScroll.prototype._move = function(event) { if(active) { event && event.preventDefault(); var $current= event.currentTarget, mY = (event.movementY) ? event.movementY : event.webkitMovementY; if(!scrolling) { $current.classList.add('scrolling'); scrolling = true; } if(mY > 0) { $current.scrollTop -= Math.abs(mY * 2); } else if(mY < 0) { $current.scrollTop += Math.abs(mY * 2); } } }; MagicScroll.prototype.destroy = function() { for(var i = 0; i < this.elements.length; i++) { var element = this.elements[i]; if(element.magicScroll) { element.removeEventListener('mousedown', this._start); element.removeEventListener('mouseup', this._stop); element.removeEventListener('mouseleave', this._stop); element.removeEventListener('mousemove', this._move); delete element.magicScroll; } } }; if (typeof exports !== 'undefined') { if (typeof module !== 'undefined' && module.exports) { exports = module.exports = MagicScroll; } exports.MagicScroll = MagicScroll; } else { this.MagicScroll = MagicScroll; } // AMD Registrity if (typeof define === 'function' && define.amd) { define('MagicScroll', [], function() { return MagicScroll; }); } }).call(this);
lamo2k123/magic-scroll
src/magic-scroll.js
JavaScript
mit
2,816
const curry = require('../../curry'); const compose = require('..'); describe('Compose', () => { test('should compose name', () => { const prefixDr = curry((prefix, name) => `${prefix} ${name}`)('Dr'); const suffixBatchelor = curry((suffix, name) => `${name} ${suffix}`)('BSc'); const suffixMasters = curry((suffix, name) => `${name} ${suffix}`)('MSc'); const suffixDoctor = curry((suffix, name) => `${name} ${suffix}`)('PhD'); const composeName = compose([prefixDr, suffixDoctor, suffixMasters, suffixBatchelor]); expect(composeName('Bob Johnson')).toEqual('Dr Bob Johnson BSc MSc PhD'); }); });
roppa/funcker
lib/compose/__tests__/compose.spec.js
JavaScript
mit
627
'use strict'; var Bluebird = require('bluebird'); var _ = require('lodash'); var debug = require('debug')('oradbpm:ctrl:get'); var Queue = require('queue-fifo'); var promiseWhile = require('promise-while')(Bluebird); var error = require('./../../common/error.js'); var PackageDependencyTreeModel = require('./../../model/package-dependency-tree-node.model.js'); var PackageVersionDefinition = require('./../../model/package-version-definition.model'); var PackageDependency = require('./../../model/package-dependency.model'); var DeploymentPlan = require('./../../model/deployment-plan.model'); var PackageVersionDeployment = require('./../../model/package-version-deployment.model'); var PackageDependencyTreeRootFactory = require('./../../factory/package-dependency-tree-root.factory'); // TODO: Move to PackageDependencyTreeNode /** * * @param deploymentPlan * @param queue * @param packageRepositoryService * @return Array of {Promise} which resolves with processDependencyTreeNode */ var processDependencyTreeNode = function (deploymentPlan, queue, packageRepositoryService) { // breadth first algorithm var nodeToProcess = queue.dequeue(); // process packageDependencyTreeNode // 1. populate dependencies return Bluebird.all(nodeToProcess.createChildDependencyTreeNodes(packageRepositoryService)) .then(function (dependencyTreeNodes) { // add children to node nodeToProcess.children = dependencyTreeNodes; // 2. TODO: add packageVersionDeploymentProposal to DeploymentPlan.getSchema(packageName) //debug(nodeToProcess.packageVersionDefinition.name, nodeToProcess.packageVersionDefinition.language); //debug(nodeToProcess.packageVersionDefinition); if (nodeToProcess.packageVersionDefinition.language === 'sqlplus') { // do not add to deploymentPlan as it is used only on client side and stored within package, that required it as its dependency //deploymentPlan // .getSchema(nodeToProcess.packageVersionDefinition.name, nodeToProcess.packageVersionDefinition.version) // .addProposal( // new PackageVersionDeployment(nodeToProcess.packageVersionDefinition, nodeToProcess.dependency) // ); } else { var nearestGlobalNode = nodeToProcess.getNearestGlobal(); deploymentPlan // run sql and plsql packages in nearest global package // add deployment to nearest global schema .getSchema(nearestGlobalNode.packageVersionDefinition.name, nearestGlobalNode.packageVersionDefinition.version) .addProposal( new PackageVersionDeployment(nodeToProcess) ); } // breadth first algorithm // 3. enqueue all children _.forEach(nodeToProcess.children, function (childNode) { queue.enqueue(childNode); }); return Bluebird.resolve(); }) .catch(function (err) { return Bluebird.reject(err); }); }; /** * * @param deploymentPlan * @param packageDependencyTreeRoot * @param packageRepositoryService * @return {Promise} */ var populateDependencies = function (deploymentPlan, packageDependencyTreeRoot, packageRepositoryService) { var nodesToProcessQueue = new Queue(); // breadth first resolve dependencies - start with root nodesToProcessQueue.enqueue(packageDependencyTreeRoot); return promiseWhile( function () { return !nodesToProcessQueue.isEmpty(); }, function () { return new Bluebird(function (resolve, reject) { return processDependencyTreeNode(deploymentPlan, nodesToProcessQueue, packageRepositoryService) .then(resolve) .catch(function (err) { return reject(err); }); }); } ) .catch(function (err) { return Bluebird.reject(err); }); }; /** * * @return {DeploymentPlan} */ var createDeploymentPlan = function () { // TODO: populate DeploymentPlan from existing (stored as oradb_modules + oradb_package.json within each package folder) return new DeploymentPlan(); }; /** * @param pkgReferences * @param options * @returns {Promise} */ var get = function (pkgReferences, options) { debug('pkgReferences %s options %s', pkgReferences, JSON.stringify(options, null, 2)); var oraDBPMClient = this; var packageDependencyTreeRootFactory = new PackageDependencyTreeRootFactory(oraDBPMClient.packageFileServiceFactory); // populate stored DeploymentPlan or create new var deploymentPlan = createDeploymentPlan(); var packageDependencyTreeRoot = null; // create PackageReferences array from required pkgReferences var newDependencies = _.reduce(pkgReferences, function (acc, pkgReference) { acc.push(new PackageDependency(pkgReference, options.local)); return acc; }, []); // create PackageDependencyTreeRoot // - read mainPackageVersionDefinitionFile = oradb_package.json // - or create anonymous root return packageDependencyTreeRootFactory.createPackageDependencyTreeRoot(options.packageFilePath) // merge required dependencies (pkgReferences) with dependencies already defined on root (loaded from file) .then(function (treeRoot) { treeRoot.mergeDependencies(newDependencies, {}); packageDependencyTreeRoot = treeRoot; return treeRoot; }) // populate tree of PackageDependencyTreeNodes - start with root .then(function (treeRoot) { return populateDependencies(deploymentPlan, treeRoot, oraDBPMClient.packageRepositoryService); }) .then(function () { //debug(JSON.stringify(packageDependencyTreeRoot.removeCycles())); return deploymentPlan.resolveConflicts(); }) .then(function () { // TODO: download to oradb_modules folder //console.log(JSON.stringify(deploymentPlan.logPlan())); deploymentPlan.logPlan(); return Bluebird.resolve(); }) .then(function () { // TODO: write to file if --save/--save-dev return Bluebird.resolve(); }) .catch(new error.errorHandler(debug)); }; module.exports = get;
s-oravec/oradbpm-cli
lib/oradbpm-client/controller/package/get.controller.js
JavaScript
mit
6,031
version https://git-lfs.github.com/spec/v1 oid sha256:e2a38d0984b9d8a85bbc1b3e0131e2fee2b6a6dc5f31aeb248b213f41f36038d size 575053
yogeshsaroya/new-cdnjs
ajax/libs/phaser/2.2.2/custom/p2.js
JavaScript
mit
131
'use strict'; const chai = require('chai'), expect = chai.expect, Support = require(__dirname + '/../../support'), DataTypes = require(__dirname + '/../../../../lib/data-types'), dialect = Support.getTestDialect(), _ = require('lodash'), moment = require('moment'), QueryGenerator = require('../../../../lib/dialects/sqlite/query-generator'); if (dialect === 'sqlite') { describe('[SQLITE Specific] QueryGenerator', () => { beforeEach(function() { this.User = this.sequelize.define('User', { username: DataTypes.STRING }); return this.User.sync({ force: true }); }); const suites = { arithmeticQuery: [ { title:'Should use the plus operator', arguments: ['+', 'myTable', { foo: 'bar' }, {}], expectation: 'UPDATE `myTable` SET `foo`=`foo`+ \'bar\' ' }, { title:'Should use the plus operator with where clause', arguments: ['+', 'myTable', { foo: 'bar' }, { bar: 'biz'}], expectation: 'UPDATE `myTable` SET `foo`=`foo`+ \'bar\' WHERE `bar` = \'biz\'' }, { title:'Should use the minus operator', arguments: ['-', 'myTable', { foo: 'bar' }], expectation: 'UPDATE `myTable` SET `foo`=`foo`- \'bar\' ' }, { title:'Should use the minus operator with negative value', arguments: ['-', 'myTable', { foo: -1 }], expectation: 'UPDATE `myTable` SET `foo`=`foo`- -1 ' }, { title:'Should use the minus operator with where clause', arguments: ['-', 'myTable', { foo: 'bar' }, { bar: 'biz'}], expectation: 'UPDATE `myTable` SET `foo`=`foo`- \'bar\' WHERE `bar` = \'biz\'' } ], attributesToSQL: [ { arguments: [{id: 'INTEGER'}], expectation: {id: 'INTEGER'} }, { arguments: [{id: 'INTEGER', foo: 'VARCHAR(255)'}], expectation: {id: 'INTEGER', foo: 'VARCHAR(255)'} }, { arguments: [{id: {type: 'INTEGER'}}], expectation: {id: 'INTEGER'} }, { arguments: [{id: {type: 'INTEGER', allowNull: false}}], expectation: {id: 'INTEGER NOT NULL'} }, { arguments: [{id: {type: 'INTEGER', allowNull: true}}], expectation: {id: 'INTEGER'} }, { arguments: [{id: {type: 'INTEGER', primaryKey: true, autoIncrement: true}}], expectation: {id: 'INTEGER PRIMARY KEY AUTOINCREMENT'} }, { arguments: [{id: {type: 'INTEGER', defaultValue: 0}}], expectation: {id: 'INTEGER DEFAULT 0'} }, { arguments: [{id: {type: 'INTEGER', defaultValue: undefined}}], expectation: {id: 'INTEGER'} }, { arguments: [{id: {type: 'INTEGER', unique: true}}], expectation: {id: 'INTEGER UNIQUE'} }, // New references style { arguments: [{id: {type: 'INTEGER', references: { model: 'Bar' }}}], expectation: {id: 'INTEGER REFERENCES `Bar` (`id`)'} }, { arguments: [{id: {type: 'INTEGER', references: { model: 'Bar', key: 'pk' }}}], expectation: {id: 'INTEGER REFERENCES `Bar` (`pk`)'} }, { arguments: [{id: {type: 'INTEGER', references: { model: 'Bar' }, onDelete: 'CASCADE'}}], expectation: {id: 'INTEGER REFERENCES `Bar` (`id`) ON DELETE CASCADE'} }, { arguments: [{id: {type: 'INTEGER', references: { model: 'Bar' }, onUpdate: 'RESTRICT'}}], expectation: {id: 'INTEGER REFERENCES `Bar` (`id`) ON UPDATE RESTRICT'} }, { arguments: [{id: {type: 'INTEGER', allowNull: false, defaultValue: 1, references: { model: 'Bar' }, onDelete: 'CASCADE', onUpdate: 'RESTRICT'}}], expectation: {id: 'INTEGER NOT NULL DEFAULT 1 REFERENCES `Bar` (`id`) ON DELETE CASCADE ON UPDATE RESTRICT'} } ], createTableQuery: [ { arguments: ['myTable', {data: 'BLOB'}], expectation: 'CREATE TABLE IF NOT EXISTS `myTable` (`data` BLOB);' }, { arguments: ['myTable', {data: 'LONGBLOB'}], expectation: 'CREATE TABLE IF NOT EXISTS `myTable` (`data` LONGBLOB);' }, { arguments: ['myTable', {title: 'VARCHAR(255)', name: 'VARCHAR(255)'}], expectation: 'CREATE TABLE IF NOT EXISTS `myTable` (`title` VARCHAR(255), `name` VARCHAR(255));' }, { arguments: ['myTable', {title: 'VARCHAR BINARY(255)', number: 'INTEGER(5) UNSIGNED PRIMARY KEY '}], // length and unsigned are not allowed on primary key expectation: 'CREATE TABLE IF NOT EXISTS `myTable` (`title` VARCHAR BINARY(255), `number` INTEGER PRIMARY KEY);' }, { arguments: ['myTable', {title: 'ENUM("A", "B", "C")', name: 'VARCHAR(255)'}], expectation: 'CREATE TABLE IF NOT EXISTS `myTable` (`title` ENUM(\"A\", \"B\", \"C\"), `name` VARCHAR(255));' }, { arguments: ['myTable', {title: 'VARCHAR(255)', name: 'VARCHAR(255)', id: 'INTEGER PRIMARY KEY'}], expectation: 'CREATE TABLE IF NOT EXISTS `myTable` (`title` VARCHAR(255), `name` VARCHAR(255), `id` INTEGER PRIMARY KEY);' }, { arguments: ['myTable', {title: 'VARCHAR(255)', name: 'VARCHAR(255)', otherId: 'INTEGER REFERENCES `otherTable` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION'}], expectation: 'CREATE TABLE IF NOT EXISTS `myTable` (`title` VARCHAR(255), `name` VARCHAR(255), `otherId` INTEGER REFERENCES `otherTable` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION);' }, { arguments: ['myTable', {id: 'INTEGER PRIMARY KEY AUTOINCREMENT', name: 'VARCHAR(255)'}], expectation: 'CREATE TABLE IF NOT EXISTS `myTable` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `name` VARCHAR(255));' }, { arguments: ['myTable', {id: 'INTEGER PRIMARY KEY AUTOINCREMENT', name: 'VARCHAR(255)', surname: 'VARCHAR(255)'}, {uniqueKeys: {uniqueConstraint: {fields: ['name', 'surname']}}}], expectation: 'CREATE TABLE IF NOT EXISTS `myTable` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `name` VARCHAR(255), `surname` VARCHAR(255), UNIQUE (`name`, `surname`));' } ], selectQuery: [ { arguments: ['myTable'], expectation: 'SELECT * FROM `myTable`;', context: QueryGenerator }, { arguments: ['myTable', {attributes: ['id', 'name']}], expectation: 'SELECT `id`, `name` FROM `myTable`;', context: QueryGenerator }, { arguments: ['myTable', {where: {id: 2}}], expectation: 'SELECT * FROM `myTable` WHERE `myTable`.`id` = 2;', context: QueryGenerator }, { arguments: ['myTable', {where: {name: 'foo'}}], expectation: "SELECT * FROM `myTable` WHERE `myTable`.`name` = 'foo';", context: QueryGenerator }, { arguments: ['myTable', {where: {name: "foo';DROP TABLE myTable;"}}], expectation: "SELECT * FROM `myTable` WHERE `myTable`.`name` = 'foo\'\';DROP TABLE myTable;';", context: QueryGenerator }, { arguments: ['myTable', {where: 2}], expectation: 'SELECT * FROM `myTable` WHERE `myTable`.`id` = 2;', context: QueryGenerator }, { arguments: ['foo', { attributes: [['count(*)', 'count']] }], expectation: 'SELECT count(*) AS `count` FROM `foo`;', context: QueryGenerator }, { arguments: ['myTable', {order: ['id']}], expectation: 'SELECT * FROM `myTable` ORDER BY `id`;', context: QueryGenerator }, { arguments: ['myTable', {order: ['id', 'DESC']}], expectation: 'SELECT * FROM `myTable` ORDER BY `id`, `DESC`;', context: QueryGenerator }, { arguments: ['myTable', {order: ['myTable.id']}], expectation: 'SELECT * FROM `myTable` ORDER BY `myTable`.`id`;', context: QueryGenerator }, { arguments: ['myTable', {order: [['myTable.id', 'DESC']]}], expectation: 'SELECT * FROM `myTable` ORDER BY `myTable`.`id` DESC;', context: QueryGenerator }, { arguments: ['myTable', {order: [['id', 'DESC']]}, function(sequelize) {return sequelize.define('myTable', {});}], expectation: 'SELECT * FROM `myTable` AS `myTable` ORDER BY `myTable`.`id` DESC;', context: QueryGenerator, needsSequelize: true }, { arguments: ['myTable', {order: [['id', 'DESC'], ['name']]}, function(sequelize) {return sequelize.define('myTable', {});}], expectation: 'SELECT * FROM `myTable` AS `myTable` ORDER BY `myTable`.`id` DESC, `myTable`.`name`;', context: QueryGenerator, needsSequelize: true }, { title: 'sequelize.where with .fn as attribute and default comparator', arguments: ['myTable', function(sequelize) { return { where: sequelize.and( sequelize.where(sequelize.fn('LOWER', sequelize.col('user.name')), 'jan'), { type: 1 } ) }; }], expectation: "SELECT * FROM `myTable` WHERE (LOWER(`user`.`name`) = 'jan' AND `myTable`.`type` = 1);", context: QueryGenerator, needsSequelize: true }, { title: 'sequelize.where with .fn as attribute and LIKE comparator', arguments: ['myTable', function(sequelize) { return { where: sequelize.and( sequelize.where(sequelize.fn('LOWER', sequelize.col('user.name')), 'LIKE', '%t%'), { type: 1 } ) }; }], expectation: "SELECT * FROM `myTable` WHERE (LOWER(`user`.`name`) LIKE '%t%' AND `myTable`.`type` = 1);", context: QueryGenerator, needsSequelize: true }, { title: 'functions can take functions as arguments', arguments: ['myTable', function(sequelize) { return { order: [[sequelize.fn('f1', sequelize.fn('f2', sequelize.col('id'))), 'DESC']] }; }], expectation: 'SELECT * FROM `myTable` ORDER BY f1(f2(`id`)) DESC;', context: QueryGenerator, needsSequelize: true }, { title: 'functions can take all types as arguments', arguments: ['myTable', function(sequelize) { return { order: [ [sequelize.fn('f1', sequelize.col('myTable.id')), 'DESC'], [sequelize.fn('f2', 12, 'lalala', new Date(Date.UTC(2011, 2, 27, 10, 1, 55))), 'ASC'] ] }; }], expectation: "SELECT * FROM `myTable` ORDER BY f1(`myTable`.`id`) DESC, f2(12, 'lalala', '2011-03-27 10:01:55.000 +00:00') ASC;", context: QueryGenerator, needsSequelize: true }, { title: 'single string argument is not quoted', arguments: ['myTable', {group: 'name'}], expectation: 'SELECT * FROM `myTable` GROUP BY name;', context: QueryGenerator }, { arguments: ['myTable', {group: ['name']}], expectation: 'SELECT * FROM `myTable` GROUP BY `name`;', context: QueryGenerator }, { title: 'functions work for group by', arguments: ['myTable', function(sequelize) { return { group: [sequelize.fn('YEAR', sequelize.col('createdAt'))] }; }], expectation: 'SELECT * FROM `myTable` GROUP BY YEAR(`createdAt`);', context: QueryGenerator, needsSequelize: true }, { title: 'It is possible to mix sequelize.fn and string arguments to group by', arguments: ['myTable', function(sequelize) { return { group: [sequelize.fn('YEAR', sequelize.col('createdAt')), 'title'] }; }], expectation: 'SELECT * FROM `myTable` GROUP BY YEAR(`createdAt`), `title`;', context: QueryGenerator, needsSequelize: true }, { arguments: ['myTable', {group: ['name', 'title']}], expectation: 'SELECT * FROM `myTable` GROUP BY `name`, `title`;', context: QueryGenerator }, { arguments: ['myTable', {group: 'name', order: [['id', 'DESC']]}], expectation: 'SELECT * FROM `myTable` GROUP BY name ORDER BY `id` DESC;', context: QueryGenerator }, { title: 'HAVING clause works with where-like hash', arguments: ['myTable', function(sequelize) { return { attributes: ['*', [sequelize.fn('YEAR', sequelize.col('createdAt')), 'creationYear']], group: ['creationYear', 'title'], having: { creationYear: { gt: 2002 } } }; }], expectation: 'SELECT *, YEAR(`createdAt`) AS `creationYear` FROM `myTable` GROUP BY `creationYear`, `title` HAVING `creationYear` > 2002;', context: QueryGenerator, needsSequelize: true }, { arguments: ['myTable', {limit: 10}], expectation: 'SELECT * FROM `myTable` LIMIT 10;', context: QueryGenerator }, { arguments: ['myTable', {limit: 10, offset: 2}], expectation: 'SELECT * FROM `myTable` LIMIT 2, 10;', context: QueryGenerator }, { title: 'uses default limit if only offset is specified', arguments: ['myTable', {offset: 2}], expectation: 'SELECT * FROM `myTable` LIMIT 2, 10000000000000;', context: QueryGenerator }, { title: 'multiple where arguments', arguments: ['myTable', {where: {boat: 'canoe', weather: 'cold'}}], expectation: "SELECT * FROM `myTable` WHERE `myTable`.`boat` = 'canoe' AND `myTable`.`weather` = 'cold';", context: QueryGenerator }, { title: 'no where arguments (object)', arguments: ['myTable', {where: {}}], expectation: 'SELECT * FROM `myTable`;', context: QueryGenerator }, { title: 'no where arguments (string)', arguments: ['myTable', {where: ['']}], expectation: 'SELECT * FROM `myTable` WHERE 1=1;', context: QueryGenerator }, { title: 'no where arguments (null)', arguments: ['myTable', {where: null}], expectation: 'SELECT * FROM `myTable`;', context: QueryGenerator }, { title: 'buffer as where argument', arguments: ['myTable', {where: { field: new Buffer('Sequelize')}}], expectation: "SELECT * FROM `myTable` WHERE `myTable`.`field` = X'53657175656c697a65';", context: QueryGenerator }, { title: 'use != if ne !== null', arguments: ['myTable', {where: {field: {ne: 0}}}], expectation: 'SELECT * FROM `myTable` WHERE `myTable`.`field` != 0;', context: QueryGenerator }, { title: 'use IS NOT if ne === null', arguments: ['myTable', {where: {field: {ne: null}}}], expectation: 'SELECT * FROM `myTable` WHERE `myTable`.`field` IS NOT NULL;', context: QueryGenerator }, { title: 'use IS NOT if not === BOOLEAN', arguments: ['myTable', {where: {field: {not: true}}}], expectation: 'SELECT * FROM `myTable` WHERE `myTable`.`field` IS NOT 1;', context: QueryGenerator }, { title: 'use != if not !== BOOLEAN', arguments: ['myTable', {where: {field: {not: 3}}}], expectation: 'SELECT * FROM `myTable` WHERE `myTable`.`field` != 3;', context: QueryGenerator } ], insertQuery: [ { arguments: ['myTable', { name: 'foo' }], expectation: "INSERT INTO `myTable` (`name`) VALUES ('foo');" }, { arguments: ['myTable', { name: "'bar'" }], expectation: "INSERT INTO `myTable` (`name`) VALUES ('''bar''');" }, { arguments: ['myTable', {data: new Buffer('Sequelize') }], expectation: "INSERT INTO `myTable` (`data`) VALUES (X'53657175656c697a65');" }, { arguments: ['myTable', { name: 'bar', value: null }], expectation: "INSERT INTO `myTable` (`name`,`value`) VALUES ('bar',NULL);" }, { arguments: ['myTable', { name: 'bar', value: undefined }], expectation: "INSERT INTO `myTable` (`name`,`value`) VALUES ('bar',NULL);" }, { arguments: ['myTable', {name: 'foo', birthday: moment('2011-03-27 10:01:55 +0000', 'YYYY-MM-DD HH:mm:ss Z').toDate()}], expectation: "INSERT INTO `myTable` (`name`,`birthday`) VALUES ('foo','2011-03-27 10:01:55.000 +00:00');" }, { arguments: ['myTable', { name: 'foo', value: true }], expectation: "INSERT INTO `myTable` (`name`,`value`) VALUES ('foo',1);" }, { arguments: ['myTable', { name: 'foo', value: false }], expectation: "INSERT INTO `myTable` (`name`,`value`) VALUES ('foo',0);" }, { arguments: ['myTable', {name: 'foo', foo: 1, nullValue: null}], expectation: "INSERT INTO `myTable` (`name`,`foo`,`nullValue`) VALUES ('foo',1,NULL);" }, { arguments: ['myTable', {name: 'foo', foo: 1, nullValue: null}], expectation: "INSERT INTO `myTable` (`name`,`foo`,`nullValue`) VALUES ('foo',1,NULL);", context: {options: {omitNull: false}} }, { arguments: ['myTable', {name: 'foo', foo: 1, nullValue: null}], expectation: "INSERT INTO `myTable` (`name`,`foo`) VALUES ('foo',1);", context: {options: {omitNull: true}} }, { arguments: ['myTable', {name: 'foo', foo: 1, nullValue: undefined}], expectation: "INSERT INTO `myTable` (`name`,`foo`) VALUES ('foo',1);", context: {options: {omitNull: true}} }, { arguments: ['myTable', function(sequelize) { return { foo: sequelize.fn('NOW') }; }], expectation: 'INSERT INTO `myTable` (`foo`) VALUES (NOW());', needsSequelize: true } ], bulkInsertQuery: [ { arguments: ['myTable', [{name: 'foo'}, {name: 'bar'}]], expectation: "INSERT INTO `myTable` (`name`) VALUES ('foo'),('bar');" }, { arguments: ['myTable', [{name: "'bar'"}, {name: 'foo'}]], expectation: "INSERT INTO `myTable` (`name`) VALUES ('''bar'''),('foo');" }, { arguments: ['myTable', [{name: 'foo', birthday: moment('2011-03-27 10:01:55 +0000', 'YYYY-MM-DD HH:mm:ss Z').toDate()}, {name: 'bar', birthday: moment('2012-03-27 10:01:55 +0000', 'YYYY-MM-DD HH:mm:ss Z').toDate()}]], expectation: "INSERT INTO `myTable` (`name`,`birthday`) VALUES ('foo','2011-03-27 10:01:55.000 +00:00'),('bar','2012-03-27 10:01:55.000 +00:00');" }, { arguments: ['myTable', [{name: 'bar', value: null}, {name: 'foo', value: 1}]], expectation: "INSERT INTO `myTable` (`name`,`value`) VALUES ('bar',NULL),('foo',1);" }, { arguments: ['myTable', [{name: 'bar', value: undefined}, {name: 'bar', value: 2}]], expectation: "INSERT INTO `myTable` (`name`,`value`) VALUES ('bar',NULL),('bar',2);" }, { arguments: ['myTable', [{name: 'foo', value: true}, {name: 'bar', value: false}]], expectation: "INSERT INTO `myTable` (`name`,`value`) VALUES ('foo',1),('bar',0);" }, { arguments: ['myTable', [{name: 'foo', value: false}, {name: 'bar', value: false}]], expectation: "INSERT INTO `myTable` (`name`,`value`) VALUES ('foo',0),('bar',0);" }, { arguments: ['myTable', [{name: 'foo', foo: 1, nullValue: null}, {name: 'bar', foo: 2, nullValue: null}]], expectation: "INSERT INTO `myTable` (`name`,`foo`,`nullValue`) VALUES ('foo',1,NULL),('bar',2,NULL);" }, { arguments: ['myTable', [{name: 'foo', foo: 1, nullValue: null}, {name: 'bar', foo: 2, nullValue: null}]], expectation: "INSERT INTO `myTable` (`name`,`foo`,`nullValue`) VALUES ('foo',1,NULL),('bar',2,NULL);", context: {options: {omitNull: false}} }, { arguments: ['myTable', [{name: 'foo', foo: 1, nullValue: null}, {name: 'bar', foo: 2, nullValue: null}]], expectation: "INSERT INTO `myTable` (`name`,`foo`,`nullValue`) VALUES ('foo',1,NULL),('bar',2,NULL);", context: {options: {omitNull: true}} // Note: We don't honour this because it makes little sense when some rows may have nulls and others not }, { arguments: ['myTable', [{name: 'foo', foo: 1, nullValue: null}, {name: 'bar', foo: 2, nullValue: null}]], expectation: "INSERT INTO `myTable` (`name`,`foo`,`nullValue`) VALUES ('foo',1,NULL),('bar',2,NULL);", context: {options: {omitNull: true}} // Note: As above }, { arguments: ['myTable', [{name: 'foo'}, {name: 'bar'}], {ignoreDuplicates: true}], expectation: "INSERT OR IGNORE INTO `myTable` (`name`) VALUES ('foo'),('bar');" } ], updateQuery: [ { arguments: ['myTable', {name: 'foo', birthday: moment('2011-03-27 10:01:55 +0000', 'YYYY-MM-DD HH:mm:ss Z').toDate()}, {id: 2}], expectation: "UPDATE `myTable` SET `name`='foo',`birthday`='2011-03-27 10:01:55.000 +00:00' WHERE `id` = 2" }, { arguments: ['myTable', {name: 'foo', birthday: moment('2011-03-27 10:01:55 +0000', 'YYYY-MM-DD HH:mm:ss Z').toDate()}, {id: 2}], expectation: "UPDATE `myTable` SET `name`='foo',`birthday`='2011-03-27 10:01:55.000 +00:00' WHERE `id` = 2" }, { arguments: ['myTable', { name: 'foo' }, { id: 2 }], expectation: "UPDATE `myTable` SET `name`='foo' WHERE `id` = 2" }, { arguments: ['myTable', { name: "'bar'" }, { id: 2 }], expectation: "UPDATE `myTable` SET `name`='''bar''' WHERE `id` = 2" }, { arguments: ['myTable', { name: 'bar', value: null }, { id: 2 }], expectation: "UPDATE `myTable` SET `name`='bar',`value`=NULL WHERE `id` = 2" }, { arguments: ['myTable', { name: 'bar', value: undefined }, { id: 2 }], expectation: "UPDATE `myTable` SET `name`='bar',`value`=NULL WHERE `id` = 2" }, { arguments: ['myTable', { flag: true }, { id: 2 }], expectation: 'UPDATE `myTable` SET `flag`=1 WHERE `id` = 2' }, { arguments: ['myTable', { flag: false }, { id: 2 }], expectation: 'UPDATE `myTable` SET `flag`=0 WHERE `id` = 2' }, { arguments: ['myTable', {bar: 2, nullValue: null}, {name: 'foo'}], expectation: "UPDATE `myTable` SET `bar`=2,`nullValue`=NULL WHERE `name` = 'foo'" }, { arguments: ['myTable', {bar: 2, nullValue: null}, {name: 'foo'}], expectation: "UPDATE `myTable` SET `bar`=2,`nullValue`=NULL WHERE `name` = 'foo'", context: {options: {omitNull: false}} }, { arguments: ['myTable', {bar: 2, nullValue: null}, {name: 'foo'}], expectation: "UPDATE `myTable` SET `bar`=2 WHERE `name` = 'foo'", context: {options: {omitNull: true}} }, { arguments: ['myTable', function(sequelize) { return { bar: sequelize.fn('NOW') }; }, {name: 'foo'}], expectation: "UPDATE `myTable` SET `bar`=NOW() WHERE `name` = 'foo'", needsSequelize: true }, { arguments: ['myTable', function(sequelize) { return { bar: sequelize.col('foo') }; }, {name: 'foo'}], expectation: "UPDATE `myTable` SET `bar`=`foo` WHERE `name` = 'foo'", needsSequelize: true } ], renameColumnQuery: [ { title: 'Properly quotes column names', arguments: ['myTable', 'foo', 'commit', {commit: 'VARCHAR(255)', bar: 'VARCHAR(255)'}], expectation: 'CREATE TEMPORARY TABLE IF NOT EXISTS `myTable_backup` (`commit` VARCHAR(255), `bar` VARCHAR(255));' + 'INSERT INTO `myTable_backup` SELECT `foo` AS `commit`, `bar` FROM `myTable`;' + 'DROP TABLE `myTable`;' + 'CREATE TABLE IF NOT EXISTS `myTable` (`commit` VARCHAR(255), `bar` VARCHAR(255));' + 'INSERT INTO `myTable` SELECT `commit`, `bar` FROM `myTable_backup`;' + 'DROP TABLE `myTable_backup`;' } ], removeColumnQuery: [ { title: 'Properly quotes column names', arguments: ['myTable', {commit: 'VARCHAR(255)', bar: 'VARCHAR(255)'}], expectation: 'CREATE TEMPORARY TABLE IF NOT EXISTS `myTable_backup` (`commit` VARCHAR(255), `bar` VARCHAR(255));' + 'INSERT INTO `myTable_backup` SELECT `commit`, `bar` FROM `myTable`;' + 'DROP TABLE `myTable`;' + 'CREATE TABLE IF NOT EXISTS `myTable` (`commit` VARCHAR(255), `bar` VARCHAR(255));' + 'INSERT INTO `myTable` SELECT `commit`, `bar` FROM `myTable_backup`;' + 'DROP TABLE `myTable_backup`;' } ] }; _.each(suites, (tests, suiteTitle) => { describe(suiteTitle, () => { tests.forEach(test => { const title = test.title || 'SQLite correctly returns ' + test.expectation + ' for ' + JSON.stringify(test.arguments); it(title, function() { // Options would normally be set by the query interface that instantiates the query-generator, but here we specify it explicitly const context = test.context || {options: {}}; if (test.needsSequelize) { if (_.isFunction(test.arguments[1])) test.arguments[1] = test.arguments[1](this.sequelize); if (_.isFunction(test.arguments[2])) test.arguments[2] = test.arguments[2](this.sequelize); } QueryGenerator.options = _.assign(context.options, { timezone: '+00:00' }); QueryGenerator._dialect = this.sequelize.dialect; QueryGenerator.sequelize = this.sequelize; const conditions = QueryGenerator[suiteTitle].apply(QueryGenerator, test.arguments); expect(conditions).to.deep.equal(test.expectation); }); }); }); }); }); }
p0vidl0/sequelize
test/unit/dialects/sqlite/query-generator.test.js
JavaScript
mit
26,755
Package.describe("Telescope BKX theme"); Package.on_use(function (api) { // api.use(['telescope-lib'], ['client', 'server']); // api.use([ // 'jquery', // 'underscore', // 'templating' // ], 'client'); api.add_files([ 'lib/client/stylesheets/screen.css', ], ['client']); });
p4bloch/bkx
packages/telescope-theme-bkx/package.js
JavaScript
mit
309
/*jshint node:true, indent:2, curly:false, eqeqeq:true, immed:true, latedef:true, newcap:true, noarg:true, regexp:true, undef:true, strict:true, trailing:true, white:true */ /*global X:true, XT:true */ (function () { "use strict"; // All of the "big 4" routes are in here: commit, dispatch, fetch, and retrieve // They all share a lot of similar code so I've broken out the functions createGlobalOptions // and queryInstanceDatabase to reuse code. // All of the functions have "engine" functions that do all the work, and then // "adapter" functions that call the engines and adapt to the express convention. These // adapter functions are also nearly identical so I've reused code there as well. // Sorry for the indirection. /** The options parameter in the XT.dataSource calls to the global database are all the same. Notably, we have to massage the client-expected callback to fit into the backboney callback system of XT.dataSource. */ var createGlobalOptions = function (payload, globalUsername, callback) { var options = JSON.parse(JSON.stringify(payload)); // clone options.username = globalUsername; options.success = function (resp) { callback({data: resp}); }; options.error = function (model, err) { callback({isError: true, message: err}); }; return options; }; /** To query the instance database we pass in a query string to X.database in a way that's very similar for all four operations. We have to massage the client-expected callback to fit with the native callback of X.database. */ var queryInstanceDatabase = function (queryString, functionName, payload, session, callback) { var query, adaptorCallback = function (err, res) { if (err) { callback({isError: true, error: err, message: err.message}); } else if (res && res.rows && res.rows.length > 0) { // the data comes back in an awkward res.rows[0].dispatch form, // and we want to normalize that here so that the data is in response.data callback({data: JSON.parse(res.rows[0][functionName])}); } else { callback({isError: true, message: "No results"}); } }; payload.username = session.passport.user.username; query = queryString.f(JSON.stringify(payload)); X.database.query(session.passport.user.organization, query, adaptorCallback); }; /** Does all the work of commit. Can be called by websockets, or the express route (below), or REST, etc. */ var commitEngine = function (payload, session, callback) { var organization, query, binaryField = payload.binaryField, buffer, binaryData, options; // We need to convert js binary into pg hex (see the file route for // the opposite conversion). See issue #18661 if (binaryField) { binaryData = payload.dataHash[binaryField]; buffer = new Buffer(binaryData, "binary"); // XXX uhoh: binary is deprecated but necessary here binaryData = '\\x' + buffer.toString("hex"); payload.dataHash[binaryField] = binaryData; } if (payload && payload.databaseType === 'global') { // Run this query against the global database. options = createGlobalOptions(payload, session.passport.user.id, callback); if (!payload.dataHash) { callback({message: "Invalid Commit"}); return; } // Passing payload through, but trick dataSource into thinking it's a Model: payload.changeSet = function () { return payload.dataHash; }; options.force = true; XT.dataSource.commitRecord(payload, options); } else { // Run this query against an instance database. queryInstanceDatabase("select xt.commit_record($$%@$$)", "commit_record", payload, session, callback); } }; exports.commitEngine = commitEngine; /** Does all the work of dispatch. Can be called by websockets, or the express route (below), or REST, etc. */ var dispatchEngine = function (payload, session, callback) { var organization, query, options; if (payload && payload.databaseType === 'global') { // Run this query against the global database. options = createGlobalOptions(payload, session.passport.user.id, callback); XT.dataSource.dispatch(payload.className, payload.functionName, payload.parameters, options); } else { // Run this query against an instance database. queryInstanceDatabase("select xt.dispatch('%@')", "dispatch", payload, session, callback); } }; exports.dispatchEngine = dispatchEngine; /** Does all the work of fetch. Can be called by websockets, or the express route (below), or REST, etc. */ var fetchEngine = function (payload, session, callback) { var organization, query, options; if (payload && payload.databaseType === 'global') { // run this query against the global database options = createGlobalOptions(payload, session.passport.user.id, callback); XT.dataSource.fetch(options); } else { // run this query against an instance database queryInstanceDatabase("select xt.fetch('%@')", "fetch", payload, session, callback); } }; exports.fetchEngine = fetchEngine; /** Does all the work of retrieve. Can be called by websockets, or the express route (below), or REST, etc. */ var retrieveEngine = function (payload, session, callback) { var organization, query, options; // TODO: authenticate if (payload && payload.databaseType === 'global') { // run this query against the global database options = createGlobalOptions(payload, session.passport.user.id, callback); XT.dataSource.retrieveRecord(payload.recordType, payload.id, options); } else { // run this query against an instance database queryInstanceDatabase("select xt.retrieve_record('%@')", "retrieve_record", payload, session, callback); } }; exports.retrieveEngine = retrieveEngine; /** The adaptation of express routes to engine functions is the same for all four operations, so we centralize the code here: */ var routeAdapter = function (req, res, engineFunction) { var callback = function (err, resp) { if (err) { res.send(500, {data: err}); } else { res.send({data: resp}); } }; engineFunction(req.query, req.session, callback); }; /** Accesses the commitEngine (above) for a request a la Express */ exports.commit = function (req, res) { routeAdapter(req, res, commitEngine); }; /** Accesses the dispatchEngine (above) for a request a la Express */ exports.dispatch = function (req, res) { routeAdapter(req, res, dispatchEngine); }; /** Accesses the fetchEngine (above) for a request a la Express */ exports.fetch = function (req, res) { routeAdapter(req, res, fetchEngine); }; /** Accesses the retrieveEngine (above) for a request a la Express */ exports.retrieve = function (req, res) { routeAdapter(req, res, retrieveEngine); }; }());
shackbarth/node-datasource
routes/data.js
JavaScript
mit
7,170
console.log('Hello World!');
djogss/modern-javascript-webapp-base
app/index.js
JavaScript
mit
30
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M6 22h12l-6-6-6 6zM23 3H1v16h6v-2H3V5h18v12h-4v2h6V3z" /> , 'AirplaySharp');
kybarg/material-ui
packages/material-ui-icons/src/AirplaySharp.js
JavaScript
mit
197
function addClass(elem, className) { elem.attr('class', function(index, classNames) { if (typeof classNames == 'undefined') { classNames = ''; } var newcls = classNames + ' ' + className; console.log('ClassNamesA = ' + newcls); return newcls;}); } function removeClass(elem, className) { elem.attr('class', function(index, classNames) { var newcls = classNames.replace(className, ''); console.log('ClassNamesR = ' + newcls); return newcls;}); } function findNode(name) { var node = $("#"+name); console.log('Finding node ' + name); console.log(node); return node } function findEdge(fromName, toName) { console.log('Finding edge ' + fromName + ' to ' + toName); var edge = $("#"+fromName+"_to_"+toName); console.log(edge); return edge; } function enterNode(nodeName) { console.log('entering node ' + nodeName); addClass(findNode(nodeName).find('ellipse'), 'active'); addClass(findNode(nodeName).find('ellipse'), 'current'); }; function exitNode(nodeName) { console.log('exiting node ' + nodeName); removeClass(findNode(nodeName).find('ellipse'), 'current'); removeClass(findNode(nodeName).find('ellipse'), 'active'); }; function callChild(nodeName, childNodeName) { var edge = findEdge(nodeName, childNodeName); addClass(edge.find('path'), 'visited'); var node = findNode(nodeName); removeClass(node.find('ellipse'), 'current'); enterNode(childNodeName); }; function reteAdd(s, p, o, g) { $("#rete-operation-name").html('Add'); $("#rete-operation-graph").html(g); $("#rete-operation-subject").html(s); $("#rete-operation-predicate").html(p); $("#rete-operation-object").html(o); } function reteRemove(s, p, o, g) { $("#rete-operation-name").html('Remove'); $("#rete-operation-graph").html(g); $("#rete-operation-subject").html(s); $("#rete-operation-predicate").html(p); $("#rete-operation-object").html(o); }
aaltodsg/instans
tests/jquery/oldinstans.js
JavaScript
mit
1,951
// @flow class Context { user: Object; req: express$Request; res: express$Response; depth: number; constructor(req: express$Request, res: express$Response, depth: number = 0) { this.req = req; this.res = res; this.depth = depth; // $FlowIgnore this.user = res.locals.user; } stepInto() { return new Context(this.req, this.res, this.depth + 1); } isInternal() { return this.depth > 0; } } export default Context;
kjubo/api
src/Context.js
JavaScript
mit
466
import PerfectNumbers from './perfect-numbers'; describe('Exercise - Perfect Numbers', () => { const perfectNumbers = new PerfectNumbers(); describe('Perfect Numbers', () => { it('Smallest perfect number is classified correctly', () => { expect(perfectNumbers.classify(6)).toEqual('perfect'); }); it('Medium perfect number is classified correctly', () => { expect(perfectNumbers.classify(28)).toEqual('perfect'); }); it('Large perfect number is classified correctly', () => { expect(perfectNumbers.classify(33550336)).toEqual('perfect'); }); }); describe('Abundant Numbers', () => { it('Smallest abundant number is classified correctly', () => { expect(perfectNumbers.classify(12)).toEqual('abundant'); }); it('Medium abundant number is classified correctly', () => { expect(perfectNumbers.classify(30)).toEqual('abundant'); }); it('Large abundant number is classified correctly', () => { expect(perfectNumbers.classify(33550335)).toEqual('abundant'); }); }); describe('Deficient Numbers', () => { it('Smallest prime deficient number is classified correctly', () => { expect(perfectNumbers.classify(2)).toEqual('deficient'); }); it('Smallest non-prime deficient number is classified correctly', () => { expect(perfectNumbers.classify(4)).toEqual('deficient'); }); it('Medium deficient number is classified correctly', () => { expect(perfectNumbers.classify(32)).toEqual('deficient'); }); it('Large deficient number is classified correctly', () => { expect(perfectNumbers.classify(33550337)).toEqual('deficient'); }); it('Edge case (no factors other than itself) is classified correctly', () => { expect(perfectNumbers.classify(1)).toEqual('deficient'); }); }); describe('Invalid Inputs', () => { it('Zero is rejected (not a natural number)', () => { expect(() => perfectNumbers.classify(0)) .toThrow('Classification is only possible for natural numbers.'); }); it('Negative integer is rejected (not a natural number)', () => { expect(() => perfectNumbers.classify(-1)) .toThrow('Classification is only possible for natural numbers.'); }); }); });
BigGillyStyle/exercism
ecmascript/perfect-numbers/perfect-numbers.spec.js
JavaScript
mit
2,287
'use strict'; module.exports = { plugins: ['jsdoc'], rules: { 'jsdoc/check-access': 'error', 'jsdoc/check-alignment': 'error', 'jsdoc/check-examples': 'error', 'jsdoc/check-indentation': 'error', 'jsdoc/check-param-names': 'error', 'jsdoc/check-property-names': 'error', 'jsdoc/check-syntax': 'error', 'jsdoc/check-tag-names': 'error', 'jsdoc/check-types': 'error', 'jsdoc/check-values': 'error', 'jsdoc/empty-tags': 'error', 'jsdoc/implements-on-classes': 'error', 'jsdoc/match-description': 'error', 'jsdoc/newline-after-description': 'error', 'jsdoc/no-bad-blocks': 'error', 'jsdoc/no-defaults': 'error', 'jsdoc/no-types': 'off', 'jsdoc/no-undefined-types': 'error', 'jsdoc/require-description': 'off', 'jsdoc/require-description-complete-sentence': 'error', 'jsdoc/require-example': 'off', 'jsdoc/require-file-overview': 'off', 'jsdoc/require-hyphen-before-param-description': 'error', 'jsdoc/require-jsdoc': 'off', 'jsdoc/require-param': 'error', 'jsdoc/require-param-description': 'error', 'jsdoc/require-param-name': 'error', 'jsdoc/require-param-type': 'error', 'jsdoc/require-property': 'error', 'jsdoc/require-property-description': 'error', 'jsdoc/require-property-name': 'error', 'jsdoc/require-property-type': 'error', 'jsdoc/require-returns': 'error', 'jsdoc/require-returns-check': 'error', 'jsdoc/require-returns-description': 'error', 'jsdoc/require-returns-type': 'error', 'jsdoc/valid-types': 'error' } };
egy186/eslint-config-egy186
jsdoc.js
JavaScript
mit
1,580
//Needed components import React from 'react'; import HeaderScrolling from './header-scrolling'; import HeaderTopRow from './header-top-row'; import HeaderContent from './header-content'; import HeaderActions from './header-actions'; /** * Application header */ const AppHeader = () => { return ( <HeaderScrolling> <HeaderTopRow /> <HeaderContent /> <HeaderActions /> </HeaderScrolling> ); } AppHeader.displayName = 'AppHeader'; export default AppHeader;
KleeGroup/focus-components
src/components/layout/header-default-template.js
JavaScript
mit
520
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = undefined; var _style = require('antd/lib/icon/style'); var _icon = require('antd/lib/icon'); var _icon2 = _interopRequireDefault(_icon); var _extends2 = require('babel-runtime/helpers/extends'); var _extends3 = _interopRequireDefault(_extends2); var _getPrototypeOf = require('babel-runtime/core-js/object/get-prototype-of'); var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf); var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck'); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _createClass2 = require('babel-runtime/helpers/createClass'); var _createClass3 = _interopRequireDefault(_createClass2); var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn'); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = require('babel-runtime/helpers/inherits'); var _inherits3 = _interopRequireDefault(_inherits2); var _class, _temp; var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _tableRow = require('./tableRow'); var _tableRow2 = _interopRequireDefault(_tableRow); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var TBody = (_temp = _class = function (_React$Component) { (0, _inherits3.default)(TBody, _React$Component); function TBody(props) { (0, _classCallCheck3.default)(this, TBody); var _this = (0, _possibleConstructorReturn3.default)(this, (TBody.__proto__ || (0, _getPrototypeOf2.default)(TBody)).call(this, props)); _this.state = {}; return _this; } (0, _createClass3.default)(TBody, [{ key: 'render', value: function render() { var _this2 = this; var _props = this.props; var dataSource = _props.dataSource; var _props$locale = _props.locale; var locale = _props$locale === undefined ? {} : _props$locale; return _react2.default.createElement( 'div', { className: 'nd-body' }, dataSource.length ? _react2.default.createElement( 'div', null, dataSource.map(function (item, dataIndex) { return _react2.default.createElement(_tableRow2.default, (0, _extends3.default)({ key: dataIndex, data: item }, _this2.props)); }) ) : _react2.default.createElement( 'div', null, _react2.default.createElement(_icon2.default, { type: 'frown' }), ' ', locale.no_data || 'No Data' ) ); } }]); return TBody; }(_react2.default.Component), _class.propTypes = { dataSource: _react.PropTypes.array.isRequired, locale: _react.PropTypes.object }, _temp); exports.default = TBody; module.exports = exports['default'];
kagawagao/react-grid
lib/components/tableBody.js
JavaScript
mit
2,875
(function() { var Application, PubSub, Request, Router, Spineless; Application = (function() { function Application() { return { controllers: {}, helpers: { _default: function(locals) { return $.extend(true, {}, locals); } } }; } return Application; })(); Request = (function() { function Request(controller, action, params) { var p; p = params != null ? params : {}; return { controller: $(".controller[data-controller=" + controller + "]"), view: $(".controller[data-controller=" + controller + "] .view[data-action=" + action + "]"), params: $.extend(true, p, { controller: controller, action: action }) }; } return Request; })(); Router = (function() { function Router() { return { parseRoute: function(route) { var hsh, str; str = route + ""; hsh = $.extend(true, {}, { controller: 'application', action: 'index' }); while (str.charAt(0) === '/') { str = str.substr(1); } if (str.length > 0) { $.each(str.split('/'), function(i, e) { if (i === 0) { hsh.controller = e; } if (i === 1) { return hsh.action = e; } }); } return hsh; }, route: function(element) { var route, url; url = element.attr('href') || $(element).attr('data-href'); route = this.parseRoute(url); return this.get(route.controller, route.action, route.params); } }; } return Router; })(); PubSub = (function() { function PubSub() { var o; o = $({}); return { subscribe: function() { return o.on.apply(o, arguments); }, unsubscribe: function() { return o.off.apply(o, arguments); }, publish: function() { return o.trigger.apply(o, arguments); } }; } return PubSub; })(); Spineless = (function() { function Spineless(options) { var controllerActionAvailable, get, init, parseLocals, postRender, prepareRender, render, renderTemplate, root, templates; root = this; templates = function(method, locals) { if (root.app.helpers.hasOwnProperty(method)) { return root.app.helpers[method].apply(root.app, [locals]); } else { return root.app.helpers._default(locals); } }; parseLocals = function(view) { var locals; locals = $(view).attr('data-locals'); if (locals != null) { return $.parseJSON(locals); } else { return {}; } }; prepareRender = function() { if (root.request.controller && root.request.view) { $('.view.active').removeClass('active'); $('.controller.active').removeClass('active'); root.request.view.addClass('active'); root.request.controller.addClass("active"); return root.request.view.find("*[data-template]"); } return []; }; renderTemplate = function(view) { var locals, name, template; name = $(view).attr('data-template'); if (name != null) { locals = parseLocals($(view)); template = $('.templates *[data-template-name=' + name + ']').html(); return view.html($.mustache(template, templates(name, locals))); } }; render = function(elements) { return $.each(elements, function(i, e) { return renderTemplate($(e)); }); }; controllerActionAvailable = function() { return root.app.controllers.hasOwnProperty(root.request.params.controller) && root.app.controllers[root.request.params.controller].hasOwnProperty(root.request.params.action); }; postRender = function() { $('body').attr('data-controller', root.request.params.controller); $('body').attr('data-action', root.request.params.action); $('body').addClass('rendered'); return root.app.publish("afterRender", root.app); }; get = function(controller, action, params) { var itemsToRender; root.request = new Request(controller, action, params); root.app.request = root.request; $('body').removeClass('rendered'); $('html,body').animate({ scrollTop: 0 }, 1); itemsToRender = prepareRender(); if (controllerActionAvailable()) { root.app.controllers[root.request.params.controller][root.request.params.action].apply(root.app, [itemsToRender, root.request]); } else { render(itemsToRender); } return postRender(); }; init = function(options) { $(document).on('click', '.route', function(event) { event.preventDefault(); return root.app.route($(this)); }); return $.extend(true, root.app, options); }; this.app = new Application(); $.extend(true, this.app, new Router()); $.extend(true, this.app, new PubSub()); this.app.get = get; this.app.render = render; init(options); return this.app; } return Spineless; })(); $.spineless = function(options) { return new Spineless(options); }; }).call(this);
heavysixer/spineless
spineless.js
JavaScript
mit
5,542
Stage.prototype = Object.create(MovieClip.prototype); function Stage(canvas_id, args) { // private vars args = args || {}; args._name = 'stage'; var self = this, _frameRate = args.frameRate || 0, _interval = null, _canvas = document.getElementById(canvas_id), _context = _canvas.getContext('2d'), _displayState = args.displayState || 'dynamic', _lastFrameTime = 0, // private function declarations _updateDisplay, _render, _resize; Object.defineProperty(this, 'frameRate', { get: function() { return _frameRate; }, set: function(fps) { if (fps !== _frameRate) { _frameRate = fps; } } }); Object.defineProperty(this, 'displayState', { get: function() { return _displayState; }, set: function(displayState) { _displayState = displayState; _updateDisplay(); } }); _resize = function() { // updating display _updateDisplay(); self.trigger('onResize'); }; _render = function(time) { if (time-_lastFrameTime >= 1000/_frameRate || _frameRate === 0) { _lastFrameTime = time; // clear canvas _context.clearRect(0, 0, _canvas.width, _canvas.height); // render new graphics self.tickGraphics(_context, Mouse.event); // run logic for tweens and such self.trigger('tickLogic', null, true); // calling on enter frame self.trigger('onEnterFrame'); // clear input context Mouse.clear(); Key.clear(); } _interval = window.requestAnimationFrame(_render); }; //_renderTimer = function _updateDisplay = function() { // code for making sure canvas resolution matches dpi _canvas.width = _canvas.offsetWidth; _canvas.height = _canvas.offsetHeight; // logic for screen if (_displayState == 'original') { self._x = (_canvas.width - self._width)/2; self._y = (_canvas.height - self._height)/2; self._scaleX = 1; self._scaleY = 1; } else if (_displayState == 'stretch') { self._x = 0; self._y = 0; self._scaleX = _canvas.width / self._width; self._scaleY = _canvas.height / self._height; } else if (_displayState == 'fit') { self._x = 0; self._y = 0; self._scaleX = _canvas.width / self._width; self._scaleY = _canvas.height / self._height; if (self._scaleX > self._scaleY) { self._scaleX = self._scaleY; self._x = (_canvas.width - self._width*self._scaleX)/2; } else { self._scaleY = self._scaleX; self._y = (_canvas.height - self._height*self._scaleY)/2; } } else if (_displayState == 'dynamic') { // experimental self._width = _canvas.offsetWidth; self._height = _canvas.offsetHeight; self._x = 0; self._y = 0; self._scaleX = 1; self._scaleY = 1; } }; // public functions this.onResize = null; this.onBlur = null; this.onFocus = null; this.play = function() { if (!self.isPlaying()) { _interval = window.requestAnimationFrame(_render); } }; this.isPlaying = function() { return _interval !== null; }; this.stop = function() { if (self.isPlaying()) { window.cancelAnimationFrame(_interval); //clearInterval(_interval); _interval = null; // render new graphics self.tickGraphics(_context, Mouse.event); } }; // init extended class args._graphic = 'stage'; MovieClip.call(this, args); Mouse.register(_canvas); // setting up handler for resize window.addEventListener('resize', _resize); // setting up handler for blur window.addEventListener('blur', function(e) { // trigger blur events self.trigger('onBlur'); }); // setting up handler for focus window.addEventListener('focus', function(e) { // trigger focus events self.trigger('onFocus'); }); _resize(); }
spiderrobb/MovieClip5
src/Stage.js
JavaScript
mit
3,733
import { moduleFor, test } from 'ember-qunit'; moduleFor('controller:plants/trees', 'Unit | Controller | plants/trees', { // Specify the other units that are required for this test. // needs: ['controller:foo'] }); // Replace this with your real tests. test('it exists', function(assert) { let controller = this.subject(); assert.ok(controller); });
mattadri/delacook-homestead-client
tests/unit/controllers/plants/trees-test.js
JavaScript
mit
360
var dojox; //globals var df = dojox.lang.functional; describe("About Applying What We Have Learnt", function() { var operations; beforeEach(function () { operations = [ { direction: "RT", distance: 200}, { direction: "FWD", distance: 50}, { direction: "RT", distance: 100}, { direction: "RT", distance: 20}, { direction: "FWD", distance: 200}, { direction: "RT", distance: 10} ] }); /*********************************************************************************/ it("should find a needle in a haystack (imperative)", function () { var findNeedle = function (ops) { var hasInvalidOperation = false; for (var i = 0; i < ops.length; i+=1) { if (ops[i].direction === "FWD" && ops[i].distance > 100) { hasInvalidOperation = true; break; } } return hasInvalidOperation; }; expect(findNeedle(operations)).toBe(true); }); it("should find needle in a haystack (functional)", function () { expect(df.some(operations, "x.direction === 'FWD' && x.distance > 100")).toBe(true); }); /*********************************************************************************/ it("should add all the natural numbers below 1000 that are multiples of 3 or 5 (imperative)", function () { var sum = 0; for(var i=1; i<=1000; i+=1) { if (i % 3 === 0 || i % 5 === 0) { sum += i; } } expect(sum).toBe(234168); }); it("should add all the natural numbers below 1000 that are multiples of 3 or 5 (functional)", function () { var sumIfMultipleOf3Or5 = function (sum, next) { if (next % 3 === 0 || next % 5 === 0) { return sum + next; } return sum; }; var numbers = df.repeat(1000, "+1", 1); expect(df.reduce(numbers, sumIfMultipleOf3Or5, 0)).toBe(234168); }); /*********************************************************************************/ it("should find the sum of all the even valued terms in the fibonacci sequence which do not exceed four million (imperative)", function () { var sum = 0; var fib = [0,1,1]; var i = 3; var currentFib = 0; do { currentFib = fib[i] = fib[i-1] + fib[i-2]; if (currentFib % 2 === 0) { sum += currentFib; } i+=1; } while (currentFib < 4000000); expect(sum).toBe(4613732); }); it("should find the sum of all the even valued terms in the fibonacci sequence which do not exceed four million (functional)", function () { var calcNextFibTuple = function(item, index, array) { return [item[1], item[0]+item[1]]; }; var addEven = function(result, item) { if (item[0] % 2 === 0) { return result + item[0]; } return result; }; var fib = df.until("item[0] > 4000000", calcNextFibTuple, [0,1]); var sum = df.reduce(fib, addEven, 0); expect(sum).toBe(4613732); }); /*********************************************************************************/ /* UNCOMMENT FOR EXTRA CREDIT */ it("should find the largest prime factor of a composite number", function () { }); it("should find the largest palindrome made from the product of two 3 digit numbers", function () { }); it("should what is the smallest number divisible by each of the numbers 1 to 20", function () { }); it("should what is the difference between the sum of the squares and the square of the sums", function () { }); it("should find the 10001st prime", function () { function find_prime_by_index (prime-index) { if :(prime-index > 0) { } i = 1 do { if (i) { } } while (i < prime-index); } expect(find_prime_by_index(10001)).toBe(__); }); });
CrossTheStreams/javascript_koans
koans/AboutApplyingWhatWeHaveLearnt.js
JavaScript
mit
3,956
'use strict'; module.exports = { Model: require('./model') };
thinkeloquent/npm-build-script
src/entity/index.js
JavaScript
mit
65
// Generated by CoffeeScript 1.12.6 (function() { var Bits, CustomReceiver, DEBUG_INCOMING_PACKET_DATA, DEBUG_INCOMING_PACKET_HASH, DEFAULT_SERVER_NAME, Sequent, StreamServer, aac, avstreams, config, crypto, fs, h264, http, logger, mp4, net, packageJson, ref, rtmp, rtsp, serverName; var uuid = require('node-uuid'); net = require('net'); fs = require('fs'); crypto = require('crypto'); config = require('./config'); rtmp = require('./rtmp'); http = require('./http'); rtsp = require('./rtsp'); h264 = require('./h264'); aac = require('./aac'); mp4 = require('./mp4'); Bits = require('./bits'); avstreams = require('./avstreams'); CustomReceiver = require('./custom_receiver'); logger = require('./logger'); packageJson = require('./package.json'); Sequent = require('sequent'); // var datastore = require('@google-cloud/datastore')({ // projectId: 'hivecast-syndicate', // keyFilename: './hivecast-syndicate.json' // }); DEBUG_INCOMING_PACKET_DATA = false; DEBUG_INCOMING_PACKET_HASH = false; DEFAULT_SERVER_NAME = "node-rtsp-rtmp-server/" + packageJson.version; serverName = (ref = config.serverName) != null ? ref : DEFAULT_SERVER_NAME; StreamServer = (function() { function StreamServer(opts) { var httpHandler, ref1, rtmptCallback; this.serverName = (ref1 = opts != null ? opts.serverName : void 0) != null ? ref1 : serverName; if (config.enableRTMP || config.enableRTMPT) { this.rtmpServer = new rtmp.RTMPServer; this.rtmpServer.on('video_start', (function(_this) { return function(streamId) { var stream; stream = avstreams.getOrCreate(streamId); _this.dumpToFile(streamId); return _this.onReceiveVideoControlBuffer(stream); }; })(this)); this.rtmpServer.on('video_data', (function(_this) { return function(streamId, pts, dts, nalUnits) { var stream; stream = avstreams.get(streamId); if (stream != null) { return _this.onReceiveVideoPacket(stream, nalUnits, pts, dts); } else { return logger.warn("warn: Received invalid streamId from rtmp: " + streamId); } }; })(this)); this.rtmpServer.on('audio_start', (function(_this) { return function(streamId) { var stream; stream = avstreams.getOrCreate(streamId); return _this.onReceiveAudioControlBuffer(stream); }; })(this)); this.rtmpServer.on('audio_data', (function(_this) { return function(streamId, pts, dts, adtsFrame) { var stream; stream = avstreams.get(streamId); if (stream != null) { return _this.onReceiveAudioPacket(stream, adtsFrame, pts, dts); } else { return logger.warn("warn: Received invalid streamId from rtmp: " + streamId); } }; })(this)); } if (config.enableCustomReceiver) { this.customReceiver = new CustomReceiver(config.receiverType, { videoControl: (function(_this) { return function() { return _this.onReceiveVideoControlBuffer.apply(_this, arguments); }; })(this), audioControl: (function(_this) { return function() { return _this.onReceiveAudioControlBuffer.apply(_this, arguments); }; })(this), videoData: (function(_this) { return function() { return _this.onReceiveVideoDataBuffer.apply(_this, arguments); }; })(this), audioData: (function(_this) { return function() { return _this.onReceiveAudioDataBuffer.apply(_this, arguments); }; })(this) }); this.customReceiver.deleteReceiverSocketsSync(); } if (config.enableHTTP) { this.httpHandler = new http.HTTPHandler({ serverName: this.serverName, documentRoot: opts != null ? opts.documentRoot : void 0 }); } if (config.enableRTSP || config.enableHTTP || config.enableRTMPT) { if (config.enableRTMPT) { rtmptCallback = (function(_this) { return function() { var ref2; return (ref2 = _this.rtmpServer).handleRTMPTRequest.apply(ref2, arguments); }; })(this); } else { rtmptCallback = null; } if (config.enableHTTP) { httpHandler = this.httpHandler; } else { httpHandler = null; } this.rtspServer = new rtsp.RTSPServer({ serverName: this.serverName, httpHandler: httpHandler, rtmptCallback: rtmptCallback }); this.rtspServer.on('video_start', (function(_this) { return function(stream) { return _this.onReceiveVideoControlBuffer(stream); }; })(this)); this.rtspServer.on('audio_start', (function(_this) { return function(stream) { return _this.onReceiveAudioControlBuffer(stream); }; })(this)); this.rtspServer.on('video', (function(_this) { return function(stream, nalUnits, pts, dts) { return _this.onReceiveVideoNALUnits(stream, nalUnits, pts, dts); }; })(this)); this.rtspServer.on('audio', (function(_this) { return function(stream, accessUnits, pts, dts) { return _this.onReceiveAudioAccessUnits(stream, accessUnits, pts, dts); }; })(this)); } avstreams.on('new', function(stream) { if (DEBUG_INCOMING_PACKET_HASH) { return stream.lastSentVideoTimestamp = 0; } }); avstreams.on('reset', function(stream) { if (DEBUG_INCOMING_PACKET_HASH) { return stream.lastSentVideoTimestamp = 0; } }); avstreams.on('end', (function(_this) { return function(stream) { if (config.enableRTSP) { _this.rtspServer.sendEOS(stream); } if (config.enableRTMP || config.enableRTMPT) { return _this.rtmpServer.sendEOS(stream); } }; })(this)); avstreams.on('audio_data', (function(_this) { return function(stream, data, pts) { return _this.onReceiveAudioAccessUnits(stream, [data], pts, pts); }; })(this)); avstreams.on('video_data', (function(_this) { return function(stream, nalUnits, pts, dts) { if (dts == null) { dts = pts; } return _this.onReceiveVideoNALUnits(stream, nalUnits, pts, dts); }; })(this)); avstreams.on('audio_start', (function(_this) { return function(stream) { return _this.onReceiveAudioControlBuffer(stream); }; })(this)); avstreams.on('video_start', (function(_this) { return function(stream) { return _this.onReceiveVideoControlBuffer(stream); }; })(this)); } StreamServer.prototype.dumpToFile = function(streamId) { var serverAddr = config.serverAddress; var dumpId = (streamId.split('/'))[1]; var spawn = require('child_process').spawn; var fileName = dumpId + '_' + uuid.v1() + '.flv'; var dumpCmd = 'rtmpdump'; //ffmpeg -re -i input.mp4 -c:v copy -c:a copy -f flv rtmp://localhost/live/STREAM_NAME //rtmpdump -v -r rtmp://localhost/live/STREAM_NAME -o dump.flv var dumpArgs = [ '-v', '-r', `rtmp://${serverAddr}/` + streamId, '-o', `public/file/${fileName}` ]; var dumpProc = spawn(dumpCmd, dumpArgs); //var ds_key = datastore.key(['Stream', ]) dumpProc.stdout.on('data', function(data) { }); dumpProc.stderr.on('data', function(data) { }); dumpProc.on('close', function() { console.log(`Stream dump is finished. File could be found at file/${fileName}`); /*setTimeout(function() { var streamCmd = 'ffmpeg'; var streamArgs = [ '-re', '-i', 'file/' + dumpId + '.flv', '-c', 'copy', '-f', 'flv', `rtmp://${serverAddr}/live/cloned_` + dumpId ]; var streamProc = spawn(streamCmd, streamArgs); streamProc.on('close', function() { console.log(`FLV: file/${dumpId}.flv is streamed successfully.`); }); }, 3000);*/ }); }; StreamServer.prototype.attachRecordedDir = function(dir) { if (config.recordedApplicationName != null) { logger.info("attachRecordedDir: dir=" + dir + " app=" + config.recordedApplicationName); return avstreams.attachRecordedDirToApp(dir, config.recordedApplicationName); } }; StreamServer.prototype.attachMP4 = function(filename, streamName) { var context, generator; logger.info("attachMP4: file=" + filename + " stream=" + streamName); context = this; generator = new avstreams.AVStreamGenerator({ generate: function() { var ascBuf, ascInfo, audioSpecificConfig, bits, err, mp4File, mp4Stream, streamId; try { mp4File = new mp4.MP4File(filename); } catch (error) { err = error; logger.error("error opening MP4 file " + filename + ": " + err); return null; } streamId = avstreams.createNewStreamId(); mp4Stream = new avstreams.MP4Stream(streamId); logger.info("created stream " + streamId + " from " + filename); avstreams.emit('new', mp4Stream); avstreams.add(mp4Stream); mp4Stream.type = avstreams.STREAM_TYPE_RECORDED; audioSpecificConfig = null; mp4File.on('audio_data', function(data, pts) { return context.onReceiveAudioAccessUnits(mp4Stream, [data], pts, pts); }); mp4File.on('video_data', function(nalUnits, pts, dts) { if (dts == null) { dts = pts; } return context.onReceiveVideoNALUnits(mp4Stream, nalUnits, pts, dts); }); mp4File.on('eof', (function(_this) { return function() { return mp4Stream.emit('end'); }; })(this)); mp4File.parse(); mp4Stream.updateSPS(mp4File.getSPS()); mp4Stream.updatePPS(mp4File.getPPS()); ascBuf = mp4File.getAudioSpecificConfig(); bits = new Bits(ascBuf); ascInfo = aac.readAudioSpecificConfig(bits); mp4Stream.updateConfig({ audioSpecificConfig: ascBuf, audioASCInfo: ascInfo, audioSampleRate: ascInfo.samplingFrequency, audioClockRate: 90000, audioChannels: ascInfo.channelConfiguration, audioObjectType: ascInfo.audioObjectType }); mp4Stream.durationSeconds = mp4File.getDurationSeconds(); mp4Stream.lastTagTimestamp = mp4File.getLastTimestamp(); mp4Stream.mp4File = mp4File; mp4File.fillBuffer(function() { context.onReceiveAudioControlBuffer(mp4Stream); return context.onReceiveVideoControlBuffer(mp4Stream); }); return mp4Stream; }, play: function() { return this.mp4File.play(); }, pause: function() { return this.mp4File.pause(); }, resume: function() { return this.mp4File.resume(); }, seek: function(seekSeconds, callback) { var actualStartTime; actualStartTime = this.mp4File.seek(seekSeconds); return callback(null, actualStartTime); }, sendVideoPacketsSinceLastKeyFrame: function(endSeconds, callback) { return this.mp4File.sendVideoPacketsSinceLastKeyFrame(endSeconds, callback); }, teardown: function() { this.mp4File.close(); return this.destroy(); }, getCurrentPlayTime: function() { return this.mp4File.currentPlayTime; }, isPaused: function() { return this.mp4File.isPaused(); } }); return avstreams.addGenerator(streamName, generator); }; StreamServer.prototype.stop = function(callback) { if (config.enableCustomReceiver) { this.customReceiver.deleteReceiverSocketsSync(); } return typeof callback === "function" ? callback() : void 0; }; StreamServer.prototype.start = function(callback) { var seq, waitCount; seq = new Sequent; waitCount = 0; if (config.enableRTMP) { waitCount++; this.rtmpServer.start({ port: config.rtmpServerPort }, function() { return seq.done(); }); } if (config.enableCustomReceiver) { this.customReceiver.start(); } if (config.enableRTSP || config.enableHTTP || config.enableRTMPT) { waitCount++; this.rtspServer.start({ port: config.serverPort }, function() { return seq.done(); }); } return seq.wait(waitCount, function() { return typeof callback === "function" ? callback() : void 0; }); }; StreamServer.prototype.setLivePathConsumer = function(func) { if (config.enableRTSP) { return this.rtspServer.setLivePathConsumer(func); } }; StreamServer.prototype.setAuthenticator = function(func) { if (config.enableRTSP) { return this.rtspServer.setAuthenticator(func); } }; StreamServer.prototype.onReceiveVideoControlBuffer = function(stream, buf) { stream.resetFrameRate(stream); stream.isVideoStarted = true; stream.timeAtVideoStart = Date.now(); return stream.timeAtAudioStart = stream.timeAtVideoStart; }; StreamServer.prototype.onReceiveAudioControlBuffer = function(stream, buf) { stream.isAudioStarted = true; stream.timeAtAudioStart = Date.now(); return stream.timeAtVideoStart = stream.timeAtAudioStart; }; StreamServer.prototype.onReceiveVideoDataBuffer = function(stream, buf) { var dts, nalUnit, pts; pts = buf[1] * 0x010000000000 + buf[2] * 0x0100000000 + buf[3] * 0x01000000 + buf[4] * 0x010000 + buf[5] * 0x0100 + buf[6]; dts = pts; nalUnit = buf.slice(7); return this.onReceiveVideoPacket(stream, nalUnit, pts, dts); }; StreamServer.prototype.onReceiveAudioDataBuffer = function(stream, buf) { var adtsFrame, dts, pts; pts = buf[1] * 0x010000000000 + buf[2] * 0x0100000000 + buf[3] * 0x01000000 + buf[4] * 0x010000 + buf[5] * 0x0100 + buf[6]; dts = pts; adtsFrame = buf.slice(7); return this.onReceiveAudioPacket(stream, adtsFrame, pts, dts); }; StreamServer.prototype.onReceiveVideoNALUnits = function(stream, nalUnits, pts, dts) { var hasVideoFrame, j, len, md5, nalUnit, nalUnitType, tsDiff; if (DEBUG_INCOMING_PACKET_DATA) { logger.info("receive video: num_nal_units=" + nalUnits.length + " pts=" + pts); } if (config.enableRTSP) { this.rtspServer.sendVideoData(stream, nalUnits, pts, dts); } if (config.enableRTMP || config.enableRTMPT) { this.rtmpServer.sendVideoPacket(stream, nalUnits, pts, dts); } hasVideoFrame = false; for (j = 0, len = nalUnits.length; j < len; j++) { nalUnit = nalUnits[j]; nalUnitType = h264.getNALUnitType(nalUnit); if (nalUnitType === h264.NAL_UNIT_TYPE_SPS) { stream.updateSPS(nalUnit); } else if (nalUnitType === h264.NAL_UNIT_TYPE_PPS) { stream.updatePPS(nalUnit); } else if ((nalUnitType === h264.NAL_UNIT_TYPE_IDR_PICTURE) || (nalUnitType === h264.NAL_UNIT_TYPE_NON_IDR_PICTURE)) { hasVideoFrame = true; } if (DEBUG_INCOMING_PACKET_HASH) { md5 = crypto.createHash('md5'); md5.update(nalUnit); tsDiff = pts - stream.lastSentVideoTimestamp; logger.info("video: pts=" + pts + " pts_diff=" + tsDiff + " md5=" + (md5.digest('hex').slice(0, 7)) + " nal_unit_type=" + nalUnitType + " bytes=" + nalUnit.length); stream.lastSentVideoTimestamp = pts; } } if (hasVideoFrame) { stream.calcFrameRate(pts); } }; StreamServer.prototype.onReceiveVideoPacket = function(stream, nalUnitGlob, pts, dts) { var nalUnits; nalUnits = h264.splitIntoNALUnits(nalUnitGlob); if (nalUnits.length === 0) { return; } this.onReceiveVideoNALUnits(stream, nalUnits, pts, dts); }; StreamServer.prototype.onReceiveAudioAccessUnits = function(stream, accessUnits, pts, dts) { var accessUnit, i, j, len, md5, ptsPerFrame; if (config.enableRTSP) { this.rtspServer.sendAudioData(stream, accessUnits, pts, dts); } if (DEBUG_INCOMING_PACKET_DATA) { logger.info("receive audio: num_access_units=" + accessUnits.length + " pts=" + pts); } ptsPerFrame = 90000 / (stream.audioSampleRate / 1024); for (i = j = 0, len = accessUnits.length; j < len; i = ++j) { accessUnit = accessUnits[i]; if (DEBUG_INCOMING_PACKET_HASH) { md5 = crypto.createHash('md5'); md5.update(accessUnit); logger.info("audio: pts=" + pts + " md5=" + (md5.digest('hex').slice(0, 7)) + " bytes=" + accessUnit.length); } if (config.enableRTMP || config.enableRTMPT) { this.rtmpServer.sendAudioPacket(stream, accessUnit, Math.round(pts + ptsPerFrame * i), Math.round(dts + ptsPerFrame * i)); } } }; StreamServer.prototype.onReceiveAudioPacket = function(stream, adtsFrameGlob, pts, dts) { var adtsFrame, adtsFrames, adtsInfo, i, isConfigUpdated, j, len, rawDataBlock, rawDataBlocks, rtpTimePerFrame; adtsFrames = aac.splitIntoADTSFrames(adtsFrameGlob); if (adtsFrames.length === 0) { return; } adtsInfo = aac.parseADTSFrame(adtsFrames[0]); isConfigUpdated = false; stream.updateConfig({ audioSampleRate: adtsInfo.sampleRate, audioClockRate: adtsInfo.sampleRate, audioChannels: adtsInfo.channels, audioObjectType: adtsInfo.audioObjectType }); rtpTimePerFrame = 1024; rawDataBlocks = []; for (i = j = 0, len = adtsFrames.length; j < len; i = ++j) { adtsFrame = adtsFrames[i]; rawDataBlock = adtsFrame.slice(7); rawDataBlocks.push(rawDataBlock); } return this.onReceiveAudioAccessUnits(stream, rawDataBlocks, pts, dts); }; return StreamServer; })(); module.exports = StreamServer; }).call(this);
mingming1986/hivecast
stream_server.js
JavaScript
mit
18,940
exports.view = function(req, res){ res.render('settings'); };
jclinn/myCloset2
routes/settings.js
JavaScript
mit
65
var Bookshelf = require('../config/bookshelf'); var Director = Bookshelf.Model.extend({ tableName: 'directors', movies: function() { 'use strict'; return this.hasMany('Movie', 'directorID'); }, virtuals: { fullName: function () { 'use strict'; return this.get('firstName') + ' ' + this.get('lastName'); } } }); module.exports = Bookshelf.model('Director', Director);
steveherschleb/moviefactsdb
models/director.js
JavaScript
mit
419
import { Meteor } from 'meteor/meteor'; import { $ } from 'meteor/jquery'; import { OHIF } from 'meteor/ohif:core'; import { toolManager } from './toolManager'; import { setActiveViewport } from './setActiveViewport'; import { switchToImageRelative } from './switchToImageRelative'; import { switchToImageByIndex } from './switchToImageByIndex'; import { viewportUtils } from './viewportUtils'; import { panelNavigation } from './panelNavigation'; import { WLPresets } from './WLPresets'; // TODO: add this to namespace definitions Meteor.startup(function() { if (!OHIF.viewer) { OHIF.viewer = {}; } OHIF.viewer.loadIndicatorDelay = 200; OHIF.viewer.defaultTool = 'wwwc'; OHIF.viewer.refLinesEnabled = true; OHIF.viewer.isPlaying = {}; OHIF.viewer.cine = { framesPerSecond: 24, loop: true }; OHIF.viewer.defaultHotkeys = { defaultTool: 'ESC', angle: 'A', stackScroll: 'S', pan: 'P', magnify: 'M', scrollDown: 'DOWN', scrollUp: 'UP', nextDisplaySet: 'PAGEDOWN', previousDisplaySet: 'PAGEUP', nextPanel: 'RIGHT', previousPanel: 'LEFT', invert: 'I', flipV: 'V', flipH: 'H', wwwc: 'W', zoom: 'Z', cinePlay: 'SPACE', rotateR: 'R', rotateL: 'L', toggleOverlayTags: 'SHIFT', WLPresetSoftTissue: ['NUMPAD1', '1'], WLPresetLung: ['NUMPAD2', '2'], WLPresetLiver: ['NUMPAD3', '3'], WLPresetBone: ['NUMPAD4', '4'], WLPresetBrain: ['NUMPAD5', '5'] }; // For now OHIF.viewer.hotkeys = OHIF.viewer.defaultHotkeys; OHIF.viewer.hotkeyFunctions = { wwwc() { toolManager.setActiveTool('wwwc'); }, zoom() { toolManager.setActiveTool('zoom'); }, angle() { toolManager.setActiveTool('angle'); }, dragProbe() { toolManager.setActiveTool('dragProbe'); }, ellipticalRoi() { toolManager.setActiveTool('ellipticalRoi'); }, magnify() { toolManager.setActiveTool('magnify'); }, annotate() { toolManager.setActiveTool('annotate'); }, stackScroll() { toolManager.setActiveTool('stackScroll'); }, pan() { toolManager.setActiveTool('pan'); }, length() { toolManager.setActiveTool('length'); }, spine() { toolManager.setActiveTool('spine'); }, wwwcRegion() { toolManager.setActiveTool('wwwcRegion'); }, zoomIn() { const button = document.getElementById('zoomIn'); flashButton(button); viewportUtils.zoomIn(); }, zoomOut() { const button = document.getElementById('zoomOut'); flashButton(button); viewportUtils.zoomOut(); }, zoomToFit() { const button = document.getElementById('zoomToFit'); flashButton(button); viewportUtils.zoomToFit(); }, scrollDown() { const container = $('.viewportContainer.active'); const button = container.find('#nextImage').get(0); if (!container.find('.imageViewerViewport').hasClass('empty')) { flashButton(button); switchToImageRelative(1); } }, scrollFirstImage() { const container = $('.viewportContainer.active'); if (!container.find('.imageViewerViewport').hasClass('empty')) { switchToImageByIndex(0); } }, scrollLastImage() { const container = $('.viewportContainer.active'); if (!container.find('.imageViewerViewport').hasClass('empty')) { switchToImageByIndex(-1); } }, scrollUp() { const container = $('.viewportContainer.active'); if (!container.find('.imageViewerViewport').hasClass('empty')) { const button = container.find('#prevImage').get(0); flashButton(button); switchToImageRelative(-1); } }, previousDisplaySet() { OHIF.viewerbase.layoutManager.moveDisplaySets(false); }, nextDisplaySet() { OHIF.viewerbase.layoutManager.moveDisplaySets(true); }, nextPanel() { panelNavigation.loadNextActivePanel(); }, previousPanel() { panelNavigation.loadPreviousActivePanel(); }, invert() { const button = document.getElementById('invert'); flashButton(button); viewportUtils.invert(); }, flipV() { const button = document.getElementById('flipV'); flashButton(button); viewportUtils.flipV(); }, flipH() { const button = document.getElementById('flipH'); flashButton(button); viewportUtils.flipH(); }, rotateR() { const button = document.getElementById('rotateR'); flashButton(button); viewportUtils.rotateR(); }, rotateL() { const button = document.getElementById('rotateL'); flashButton(button); viewportUtils.rotateL(); }, cinePlay() { viewportUtils.toggleCinePlay(); }, defaultTool() { const tool = toolManager.getDefaultTool(); toolManager.setActiveTool(tool); }, toggleOverlayTags() { const dicomTags = $('.imageViewerViewportOverlay .dicomTag'); if (dicomTags.eq(0).css('display') === 'none') { dicomTags.show(); } else { dicomTags.hide(); } }, resetStack() { const button = document.getElementById('resetStack'); flashButton(button); resetStack(); }, clearImageAnnotations() { const button = document.getElementById('clearImageAnnotations'); flashButton(button); clearImageAnnotations(); }, cineDialog () { /** * TODO: This won't work in OHIF's, since this element * doesn't exist */ const button = document.getElementById('cine'); flashButton(button); viewportUtils.toggleCineDialog(); button.classList.toggle('active'); } }; OHIF.viewer.loadedSeriesData = {}; }); // Define a jQuery reverse function $.fn.reverse = [].reverse; /** * Overrides OHIF's refLinesEnabled * @param {Boolean} refLinesEnabled True to enable and False to disable */ function setOHIFRefLines(refLinesEnabled) { OHIF.viewer.refLinesEnabled = refLinesEnabled; } /** * Overrides OHIF's hotkeys * @param {Object} hotkeys Object with hotkeys mapping */ function setOHIFHotkeys(hotkeys) { OHIF.viewer.hotkeys = hotkeys; } /** * Global function to merge different hotkeys configurations * but avoiding conflicts between different keys with same action * When this occurs, it will delete the action from OHIF's configuration * So if you want to keep all OHIF's actions, use an unused-ohif-key * Used for compatibility with others systems only * * @param hotkeysActions {object} Object with actions map * @return {object} */ function mergeHotkeys(hotkeysActions) { // Merge hotkeys, overriding OHIF's settings let mergedHotkeys = { ...OHIF.viewer.defaultHotkeys, ...hotkeysActions }; const defaultHotkeys = OHIF.viewer.defaultHotkeys; const hotkeysKeys = Object.keys(hotkeysActions); // Check for conflicts with same keys but different actions Object.keys(defaultHotkeys).forEach(ohifAction => { hotkeysKeys.forEach(definedAction => { // Different action but same key: // Remove action from merge if is not in "hotkeysActions" // If it is, it's already merged so nothing to do if(ohifAction !== definedAction && hotkeysActions[definedAction] === defaultHotkeys[ohifAction] && !hotkeysActions[ohifAction]) { delete mergedHotkeys[ohifAction]; } }); }); return mergedHotkeys; } /** * Add an active class to a button for 100ms only * to give the impressiont the button was pressed. * This is for tools that don't keep the button "pressed" * all the time the tool is active. * * @param button DOM Element for the button to be "flashed" */ function flashButton(button) { if (!button) { return; } button.classList.add('active'); setTimeout(() => { button.classList.remove('active'); }, 100); } /** * Binds a task to a hotkey keydown event * @param {String} hotkey keyboard key * @param {String} task task function name */ function bindHotkey(hotkey, task) { var hotkeyFunctions = OHIF.viewer.hotkeyFunctions; // Only bind defined, non-empty HotKeys if (!hotkey || hotkey === '') { return; } var fn; if (task.indexOf('WLPreset') > -1) { var presetName = task.replace('WLPreset', ''); fn = function() { WLPresets.applyWLPresetToActiveElement(presetName); }; } else { fn = hotkeyFunctions[task]; // If the function doesn't exist in the // hotkey function list, try the viewer-specific function list if (!fn && OHIF.viewer && OHIF.viewer.functionList) { fn = OHIF.viewer.functionList[task]; } } if (!fn) { return; } var hotKeyForBinding = hotkey.toLowerCase(); $(document).bind('keydown', hotKeyForBinding, fn); } /** * Binds all hotkeys keydown events to the tasks defined in * OHIF.viewer.hotkeys or a given param * @param {Object} hotkeys hotkey and task mapping (not required). If not given, uses OHIF.viewer.hotkeys */ function enableHotkeys(hotkeys) { const viewerHotkeys = hotkeys || OHIF.viewer.hotkeys; $(document).unbind('keydown'); Object.keys(viewerHotkeys).forEach(function(task) { const taskHotkeys = viewerHotkeys[task]; if (!taskHotkeys || !taskHotkeys.length) { return; } if (taskHotkeys instanceof Array) { taskHotkeys.forEach(function(hotkey) { bindHotkey(hotkey, task); }); } else { // taskHotkeys represents a single key bindHotkey(taskHotkeys, task); } }); } /** * Export functions inside hotkeyUtils namespace. */ const hotkeyUtils = { setOHIFRefLines, /* @TODO: find a better place for this... */ setOHIFHotkeys, mergeHotkeys, enableHotkeys }; export { hotkeyUtils };
NucleusIo/HealthGenesis
viewerApp/Packages/ohif-viewerbase/client/lib/hotkeyUtils.js
JavaScript
mit
10,990
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; import registerServiceWorker from './registerServiceWorker'; ReactDOM.render(<App />, document.getElementById('root')); registerServiceWorker();
madforjs/react-comp
src/index.js
JavaScript
mit
253
import React from 'react'; import ReactDOM from 'react-dom'; import { Router, IndexRoute, Route, browserHistory } from 'react-router' import App from './components/App'; import Home from './components/Home'; import Page1 from './components/Page1'; import Page2 from './components/Page2'; ReactDOM.render(( <Router history={browserHistory}> <Route component={App}> <Route path="/" component={Home}></Route> <Route path="page1" component={Page1}></Route> <Route path="page2" component={Page2}></Route> </Route> </Router> ), document.getElementById('root'));
theJoeBiz/react-boilerplate
src/index.js
JavaScript
mit
587
$('#new-orders-button').click(function(){ $('#orders-pane').find('div').remove(); $.ajax({ type: 'POST', url: "http://localhost/3k/orders/app/getNewOrders", //data: {activitiesArray : pass_order}, dataType: 'json' }).done(function(response) { $.each(response, function(){ $.each(this, function(){ $('#orders-title').text(this.status+" Orders"); $('#orders-pane').append('<div class="row"> <div class="col-sm-2">'+this.datecreated+'</div>'+'<div class="col-sm-8">'+this.customer_order+'</div>'+'<div class="col-sm-2"><i class="fa fa-check" data-id="'+this.id+'"></i><i class="fa fa-remove" data-id="'+this.id+'"></i></div></div>'); //console.log(this.id); }); }); }); }); $('#old-orders-button').click(function(){ $('#orders-pane').find('div').remove(); $.ajax({ type: 'POST', url: "http://localhost/3k/orders/app/getOldOrders", //data: {activitiesArray : pass_order}, dataType: 'json' }).done(function(response) { $.each(response, function(){ $.each(this, function(){ $('#orders-title').text("Fulfilled Orders"); $('#orders-pane').append('<div class="row"> <div class="col-sm-2">'+this.datecreated+'</div>'+'<div class="col-sm-8">'+this.customer_order+'</div>'+'<div class="col-sm-2"><i class="fa fa-check" data-id="'+this.id+'"></i><i class="fa fa-remove" data-id="'+this.id+'"></i><i class="fa fa-undo" data-id="'+this.id+'"></i></div></div>'); //console.log(this.id); }); }); }); }); $('#orders-pane').on("click", ".fa-check", function(){ //$(this).closest('.row').remove(); var order_line = $(this); var id = $(this).attr('data-id'); //console.log(id); //$(this).closest('.row').remove(); $.ajax({ type: 'POST', url: "http://localhost/3k/orders/app/fulfill/"+id, //data: {activitiesArray : pass_order}, dataType: 'json' }).done(function(response) { console.log(response); if (response == 'success'){ order_line.closest('.row').remove(); console.log('Order Fulfilled'); }else{ console.log('Error Processing Order'); }; }); }) $('#orders-pane').on("click", ".fa-remove", function(){ $(this).closest('.row').remove(); }) $('#orders-pane').on("click", ".fa-undo", function(){ $(this).closest('.row').remove(); var order_line = $(this); var id = $(this).attr('data-id'); //console.log(id); //$(this).closest('.row').remove(); $.ajax({ type: 'POST', url: "http://localhost/3k/orders/app/undo/"+id, //data: {activitiesArray : pass_order}, dataType: 'json' }).done(function(response) { console.log(response); if (response == 'success'){ order_line.closest('.row').remove(); console.log('Order Reversed'); }else{ console.log('Error Reversing Order'); }; }); })
skwill/3kings
orders/assets/3k/js/management.js
JavaScript
mit
2,916
/*********************************************************************** * Module: Transform Matrix * Description: * Author: Copyright 2012-2014, Tyler Beck * License: MIT ***********************************************************************/ define([ '../math/Matrix4x4', '../math/Vector4' ], function( M, V ){ /*================================================ * Helper Methods *===============================================*/ /** * converts almost 0 float values to true 0 * @param v * @returns {*} */ function floatZero( v ){ if (v == 0) { v = 0; } return v; } /** * converts degrees to radians * @param deg * @returns {number} */ function degToRad( deg ){ return deg * Math.PI / 180; } /** * true 0 cosine * @param a * @returns {*} */ function cos( a ){ return floatZero( Math.cos(a ) ); } /** * true 0 sine * @param a * @returns {*} */ function sin( a ){ return floatZero( Math.sin(a ) ); } /** * true 0 tangent * @param a * @returns {*} */ function tan( a ){ return floatZero( Math.tan(a ) ); } /*================================================ * Transform Constructor *===============================================*/ var TransformMatrix = function( v ){ this.init( v ); return this; }; /*================================================ * Transform Prototype *===============================================*/ TransformMatrix.prototype = { /** * initialize class * @param v */ init: function( v ){ this.value = M.identity(); if (v && v.length ){ var l = v.length; for (var i = 0; i < l; i++ ){ this.value[i] = v[i]; } } }, /** * applies translation * @param x * @param y * @param z * @returns {TransformMatrix} */ translate: function( x, y, z ){ var translation = [ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, x, y, z, 1 ]; return new TransformMatrix( M.multiply( this.value, translation ) ); }, /** * applies scale * @param x * @param y * @param z * @returns {TransformMatrix} */ scale: function( x, y, z ){ var scaler = [ x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1 ]; return new TransformMatrix( M.multiply( this.value, scaler ) ); }, /** * applies x axis rotation * @param a * @returns {TransformMatrix} */ rotateX: function( a ){ return this.rotate( 1, 0, 0, a ); }, /** * applies y axis rotation * @param a * @returns {TransformMatrix} */ rotateY: function( a ){ return this.rotate( 0, 1, 0, a ); }, /** * applies z axis rotation * @param a * @returns {TransformMatrix} */ rotateZ: function( a ){ return this.rotate( 0, 0, 1, a ); }, /** * applies vector rotation * @param x * @param y * @param z * @param a * @returns {TransformMatrix} */ rotate: function( x, y, z, a ){ var norm = ( new V( x, y, z ) ).normalize(); x = norm.x; y = norm.y; z = norm.z; var c = cos(a); var s = sin(a); var rotation = [ 1+(1-c)*(x*x-1), z*s+x*y*(1-c), -y*s+x*z*(1-c), 0, -z*s+x*y*(1-c), 1+(1-c)*(y*y-1), x*s+y*z*(1-c), 0, y*s+x*z*(1-c), -x*s+y*z*(1-c), 1+(1-c)*(z*z-1), 0, 0, 0, 0, 1 ]; return new TransformMatrix( M.multiply( this.value, rotation ) ); }, /** * applies x skew * @param a * @returns {TransformMatrix} */ skewX: function( a ){ var t = tan( a ); var skew = [ 1, 0, 0, 0, t, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ]; return new TransformMatrix( M.multiply( this.value, skew ) ); }, /** * applies y skew * @param a * @returns {TransformMatrix} */ skewY: function( a ){ var t = tan( a ); var skew = [ 1, t, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ]; return new TransformMatrix( M.multiply( this.value, skew ) ); }, /** * decomposes transform into component parts * @returns {{}} */ decompose: function(){ var m = this.value; var i, j, p, perspective, translate, scale, skew, quaternion; // Normalize the matrix. if (m[15] == 0) return false; p = m[15]; for ( i=0; i<4; ++i ){ for ( j=0; j<4; ++j ){ m[i*4+j] /= p; } } // perspectiveMatrix is used to solve for perspective, but it also provides // an easy way to test for singularity of the upper 3x3 component. var perspectiveMatrix = m.slice(0); perspectiveMatrix[3] = 0; perspectiveMatrix[7] = 0; perspectiveMatrix[11] = 0; perspectiveMatrix[15] = 1; if ( M.determinant( perspectiveMatrix ) == 0){ return false; } //perspective. if (m[3] != 0 || m[7] != 0 || m[11] != 0) { // rightHandSide is the right hand side of the equation. var right = new V( m[3], m[7], m[11], m[15] ); var tranInvPers = M.transpose( M.inverse( perspectiveMatrix ) ); perspective = right.multiplyMatrix( tranInvPers ); } else{ perspective = new V(0,0,0,1); } //translation translate = new V( m[12], m[13], m[14] ); //scale & skew var row = [ new V(), new V(), new V() ]; for ( i = 0; i < 3; i++ ) { row[i].x = m[4*i]; row[i].y = m[4*i+1]; row[i].z = m[4*i+2]; } scale = new V(); skew = new V(); scale.x = row[0].length(); row[0] = row[0].normalize(); // Compute XY shear factor and make 2nd row orthogonal to 1st. skew.x = row[0].dot(row[1]); row[1] = row[1].combine(row[0], 1.0, -skew.x); // Now, compute Y scale and normalize 2nd row. scale.y = row[1].length(); row[1] = row[1].normalize(); skew.x = skew.x/scale.y; // Compute XZ and YZ shears, orthogonalize 3rd row skew.y = row[0].dot(row[2]); row[2] = row[2].combine(row[0], 1.0, -skew.y); skew.z = row[1].dot(row[2]); row[2] = row[2].combine(row[1], 1.0, -skew.z); // Next, get Z scale and normalize 3rd row. scale.z = row[2].length(); row[2] = row[2].normalize(); skew.y = (skew.y / scale.z); skew.z = (skew.z / scale.z); // At this point, the matrix (in rows) is orthonormal. // Check for a coordinate system flip. If the determinant // is -1, then negate the matrix and the scaling factors. var pdum3 = row[1].cross(row[2]); if (row[0].dot( pdum3 ) < 0) { for (i = 0; i < 3; i++) { scale.at(i, scale.at(i)* -1); row[i].x *= -1; row[i].y *= -1; row[i].z *= -1; } } // Now, get the rotations out // FROM W3C quaternion = new V(); quaternion.x = 0.5 * Math.sqrt(Math.max(1 + row[0].x - row[1].y - row[2].z, 0)); quaternion.y = 0.5 * Math.sqrt(Math.max(1 - row[0].x + row[1].y - row[2].z, 0)); quaternion.z = 0.5 * Math.sqrt(Math.max(1 - row[0].x - row[1].y + row[2].z, 0)); quaternion.w = 0.5 * Math.sqrt(Math.max(1 + row[0].x + row[1].y + row[2].z, 0)); if (row[2].y > row[1].z) quaternion.x = -quaternion.x; if (row[0].z > row[2].x) quaternion.y = -quaternion.y; if (row[1].x > row[0].y) quaternion.z = -quaternion.z; return { perspective: perspective, translate: translate, skew: skew, scale: scale, quaternion: quaternion.normalize() }; }, /** * converts matrix to css string * @returns {string} */ toString: function(){ return "matrix3d("+ this.value.join(", ")+ ")"; } }; /** * recomposes transform from component parts * @param d * @returns {TransformMatrix} */ TransformMatrix.recompose = function( d ){ //console.log('Matrix4x4.recompose'); var m = M.identity(); var i, j, x, y, z, w; var perspective = d.perspective; var translate = d.translate; var skew = d.skew; var scale = d.scale; var quaternion = d.quaternion; // apply perspective m[3] = perspective.x; m[7] = perspective.y; m[11] = perspective.z; m[15] = perspective.w; // apply translation for ( i=0; i<3; ++i ){ for ( j=0; j<3; ++j ){ m[12+i] += translate.at( j ) * m[j*4+i] } } // apply rotation x = quaternion.x; y = quaternion.y; z = quaternion.z; w = quaternion.w; // Construct a composite rotation matrix from the quaternion values /**/ var rmv = M.identity(); rmv[0] = 1 - 2 * ( y * y + z * z ); rmv[1] = 2 * ( x * y - z * w ); rmv[2] = 2 * ( x * z + y * w ); rmv[4] = 2 * ( x * y + z * w ); rmv[5] = 1 - 2 * ( x * x + z * z ); rmv[6] = 2 * ( y * z - x * w ); rmv[8] = 2 * ( x * z - y * w ); rmv[9] = 2 * ( y * z + x * w ); rmv[10] = 1 - 2 * ( x * x + y * y ); /* var rmv = [ 1 - 2*y*y - 2*z*z, 2*x*y - 2*z*w, 2*x*z + 2*y*w, 0, 2*x*y + 2*z*w, 1 - 2*x*x - 2*z*z, 2*y*z - 2*x*w, 0, 2*x*z - 2*y*w, 2*y*z + 2*x*w, 1 - 2*x*x - 2*y*y, 0, 0, 0, 0, 1 ]; */ var rotationMatrix = M.transpose( rmv ); var matrix = M.multiply( m, rotationMatrix ); //console.log(' skew'); // apply skew var temp = Matrix4x4.identity(); if ( skew.z ){ temp[9] = skew.z; matrix = M.multiply( matrix, temp ); } if (skew.y){ temp[9] = 0; temp[8] = skew.y; matrix = M.multiply( matrix, temp ); } if (skew.x){ temp[8] = 0; temp[4] = skew.x; matrix = M.multiply( matrix, temp ); } // apply scale m = matrix; for ( i=0; i<3; ++i ){ for ( j=0; j<3; ++j ){ m[4*i+j] *= scale.at( i ); } } return new TransformMatrix( m ); } return TransformMatrix; });
tylerbeck/amd-toolbox
lib/graphics/TransformMatrix.js
JavaScript
mit
9,417
import { h } from 'omi'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon(h("path", { d: "M16.14 12.5c0 1-.1 1.85-.3 2.55s-.48 1.27-.83 1.7c-.36.44-.79.75-1.3.95s-1.07.3-1.7.3c-.62 0-1.18-.1-1.69-.3-.51-.2-.95-.51-1.31-.95s-.65-1.01-.85-1.7c-.2-.7-.3-1.55-.3-2.55v-2.04c0-1 .1-1.85.3-2.55.2-.7.48-1.26.84-1.69.36-.43.8-.74 1.31-.93C10.81 5.1 11.38 5 12 5c.63 0 1.19.1 1.7.29.51.19.95.5 1.31.93.36.43.64.99.84 1.69.2.7.3 1.54.3 2.55v2.04h-.01zm-2.11-2.36c0-.64-.05-1.18-.13-1.62-.09-.44-.22-.79-.4-1.06-.17-.27-.39-.46-.64-.58-.25-.13-.54-.19-.86-.19s-.61.06-.86.18-.47.31-.64.58-.31.62-.4 1.06-.13.98-.13 1.62v2.67c0 .64.05 1.18.14 1.62.09.45.23.81.4 1.09s.39.48.64.61.54.19.87.19.62-.06.87-.19.46-.33.63-.61.3-.64.39-1.09.13-.99.13-1.62v-2.66h-.01z" }), 'ExposureZeroRounded');
AlloyTeam/Nuclear
components/icon/esm/exposure-zero-rounded.js
JavaScript
mit
811
{ // environment "browser": true, "node": true, "globals": { "L": true, "define": true, "map":true, "jQuery":true // "drawnItems":true }, "strict": false, // code style "bitwise": true, "camelcase": true, "curly": true, "eqeqeq": true, "forin": false, "immed": true, "latedef": true, "newcap": true, "noarg": true, "noempty": true, "nonew": true, "undef": true, "unused": true, "quotmark": "single", // whitespace "indent": 4, "trailing": true, "white": true, "smarttabs": true, "maxlen": 150 // code simplicity - not enforced but nice to check from time to time // "maxstatements": 20, // "maxcomplexity": 5 // "maxparams": 4, // "maxdepth": 4 }
trash0000/Leaflet.RSWE
build/hintrc.js
JavaScript
mit
691
import React from "react" import { Link } from "gatsby" import numberToColor from "../utils/number-to-color" import "./post-link.css" const year = node => new Date(node.frontmatter.date).getFullYear() const PostLink = ({ post }) => ( <div className="post-link"> <Link to={post.frontmatter.path} style={{color: numberToColor(year(post))}}> {post.frontmatter.title} </Link> </div> ) export default PostLink
ambirdsall/ambirdsall.github.io
src/components/post-link.js
JavaScript
mit
424
goog.provide('crow.ConnectedNode'); goog.require('crow.Node'); /** * ConnectedNodes are nodes that have to be explicitly "connected" to other nodes. * @class */ crow.ConnectedNode = function(id){ crow.Node.apply(this, arguments); this.connections = []; this.connectionDistances = {}; }; crow.ConnectedNode.prototype = new crow.Node(); crow.ConnectedNode.prototype.connectTo = function(otherNode, distance, symmetric){ if(typeof distance == "undefined") distance = 1; this.connections.push(otherNode); this.connectionDistances[otherNode.id] = distance; if(typeof symmetric !== "false" && otherNode instanceof crow.ConnectedNode){ otherNode.connections.push(this); otherNode.connectionDistances[this.id] = distance; } }; crow.ConnectedNode.prototype.getNeighbors = function(){ return this.connections; }; crow.ConnectedNode.prototype.distanceToNeighbor = function(otherNode){ return this.connectionDistances[otherNode.id] || Infinity; }
nanodeath/CrowLib
src/crow/ConnectedNode.js
JavaScript
mit
954
(function () { var color = window.color; var getset = color.getset; color.pie = function () { var options = { height: color.available( "height" ), width: color.available( "width" ), value: null, color: null, hole: 0, palette: window.color.palettes.default, data: null, legend: color.legend() .color( "key" ) .value( "key" ) .direction( "vertical" ) } function pie () { return pie.draw( this ) } pie.height = getset( options, "height" ); pie.width = getset( options, "width" ); pie.value = getset( options, "value" ); pie.color = getset( options, "color" ); pie.hole = getset( options, "hole" ); pie.palette = getset( options, "palette" ); pie.data = getset( options, "data" ); pie.legend = getset( options, "legend" ); pie.draw = function ( selection ) { if ( selection instanceof Element ) { selection = d3.selectAll( [ selection ] ); } selection.each( function ( data ) { var data = layout( pie, pie.data() || data ); draw( pie, this, data ); }) return this; } return pie; } function draw( that, el, data ) { el = d3.select( el ); if ( el.attr( "data-color-chart" ) != "pie" ) { el.attr( "data-color-chart", "pie" ) .text( "" ); } el.node().__colorchart = that; var height = that.height.get( el ) var width = that.width.get( el ) var radius = Math.min( height / 2, width / 2 ) - 10; var c = color.palette() .colors( that.palette() ) .domain( data.map( function ( d ) { return d.key } ) ) .scale(); var arc = d3.svg.arc() .outerRadius( radius ) .innerRadius( radius * that.hole() ); // tooltip var tooltip = color.tooltip() .title( function ( d ) { return !d.key ? that.value() : d.key }) .content( function ( d ) { return !d.key ? d.value : that.value() + ": " + d.value; }) // draw the legend var legend = c.domain().length > 1; var legend = el.selectAll( "g[data-pie-legend]" ) .data( legend ? [ data ] : [] ); legend.enter().append( "g" ) .attr( "data-pie-legend", "" ) legend.call( that.legend().palette( that.palette() ) ); legend.attr( "transform", function () { var top = ( height - legend.node().getBBox().height ) / 2; return "translate(35," + top + ")"; }) // start drawing var pies = el.selectAll( "g[data-pie]" ) .data( [ data ] ); pies.enter().append( "g" ) .attr( "data-pie", "" ) .attr( "transform", function () { return "translate(" + ( width / 2 ) + "," + ( height / 2 ) + ")"; }); var slices = pies.selectAll( "path[data-pie-slice]" ) .data( function ( d ) { return d } ); slices.exit().remove(); slices.enter().append( "path" ); slices .attr( "data-pie-slice", function ( d ) { return d.key; }) .attr( "d", arc ) .attr( "fill", function ( d ) { return c( d.key ); }) .call( tooltip ); } function layout ( that, data ) { // extract the values for each obj data = data.map( function ( d ) { var v = +d[ that.value() ] if ( isNaN( v ) ) { throw new Error( "pie value must be a number" ); } return { v: v, c: d[ that.color() ], obj: d } }) // group by colors data = d3.nest() .key( function ( d ) { return d.c || "" } ) .rollup ( function ( data ) { return data.reduce( function ( v, d ) { return v + d.v; }, 0 ) }) .entries( data ); // lay out the pie data = d3.layout.pie() .sort( null ) .value( function ( d ) { return d.values })( data ) .map( function ( d ) { d.key = d.data.key; delete d.data; return d; }); return data; } })();
avinoamr/colorcharts
charts/pie.js
JavaScript
mit
4,703
var gulp = require('gulp'); var sass = require('gulp-sass'); var cssmin = require('gulp-cssmin'); var plumber = require('gulp-plumber'); var webpack = require('gulp-webpack'); gulp.task('css', function() { return gulp.src(['styles/*.scss']) .pipe(plumber()) .pipe(sass().on('error', sass.logError)) .pipe(cssmin()) .pipe(gulp.dest('static/css/common/')); }); gulp.task('webpack', function() { return gulp.src(['./']) .pipe(plumber()) .pipe(webpack(require('./webpack.config.js'))) .pipe(gulp.dest('./static/')); }); gulp.task('watch', ['publish'], function(){ gulp.watch(['styles/*.scss'], ['css']); gulp.watch(['src/**/*'], ['webpack']); }); gulp.task('publish',['css', 'webpack']);
UgliFan/FYBlog-BackEnd
gulpfile.js
JavaScript
mit
724
// Utility functions String.prototype.endsWith = function (suffix) { return this.indexOf(suffix, this.length - suffix.length) !== -1; }; String.prototype.contains = function(it) { return this.indexOf(it) != -1; }; if (!String.prototype.trim) { String.prototype.trim = function () { return this.replace(/^\s+|\s+$/g, ''); }; String.prototype.ltrim = function () { return this.replace(/^\s+/, ''); }; String.prototype.rtrim = function () { return this.replace(/\s+$/, ''); }; String.prototype.fulltrim = function () { return this.replace(/(?:(?:^|\n)\s+|\s+(?:$|\n))/g, '').replace(/\s+/g, ' '); }; } function colorToHex(color) { if (color.substr(0, 1) === '#') { return color; } var digits = /(.*?)rgb\((\d+), (\d+), (\d+)\)/.exec(color); var red = parseInt(digits[2]); var green = parseInt(digits[3]); var blue = parseInt(digits[4]); var rgb = blue | (green << 8) | (red << 16); return digits[1] + '#' + rgb.toString(16); };
TimCollins/jQueryPluginTest
script/util.js
JavaScript
mit
998
"use strict"; var Extension = require("../runtime/extension"); /** * @constructor Trait * @memberof module:impulse * * @summary Traits allow classes to be extended without modification, and support isTypeOf() when used as parameters. **/ function Trait(parent, funcs, required) { this._parent = parent || null; this._types = new Set(); this._methods = funcs; this.required = required; } Trait.isTypeOf = function(that) { return that instanceof this; } Trait.prototype.add = function (type) { this._types = this._types.add(type); return this; } Trait.prototype.isTypeOf = function (value) { for (var scope = this; scope !== null; scope = scope._parent) { for (var type of scope._types) { if (type.isTypeOf(value)) { return true; } } } return false; } Trait.prototype.bind = function() { return this._methods.apply(null, arguments); } Trait.addtrait = function(type, parent) { var trait = parent ? clone(parent) : new Trait(); return trait.add(type); } function clone(object) { if (object == null || typeof object != "object") { return object; } var copy = new object.constructor(); for (var property in object) { if (object.hasOwnProperty(property)) { copy[property] = object[property]; } } return copy; } // // Exports // module.exports = Trait; /* Value : Type 0 : 1 Bottom == Void 1 : 1 Unit () == () 1 : 1 Scalar 1 == Number 1 : N Union or Intersection 1 == (Number | String), (Number & String) N : 1 Array [1, 2, 3] == [Number] N : N Record (1, "foo") == (Number, String) 1 : 0 Untyped Scalar N : 1 Top 1, "foo" == Object import { symbol } from "core-js/es6/symbol"; import * from core-js.fn.object.assign; eval("var symbol = Symbol.symbol;"); import foo, bar from library; import * from library.module; */
mikeaustin/impulse-js
lib/runtime/module.js
JavaScript
mit
1,868
const alter = require('../lib/alter.js'); const Chainable = require('../lib/classes/chainable'); module.exports = new Chainable('yaxis', { args: [ { name: 'inputSeries', types: ['seriesList'] }, { name: 'yaxis', types: ['number', 'null'], help: 'The numbered y-axis to plot this series on, eg .yaxis(2) for a 2nd y-axis.' }, { name: 'min', types: ['number', 'null'], help: 'Min value' }, { name: 'max', types: ['number', 'null'], help: 'Max value' }, { name: 'position', types: ['string', 'null'], help: 'left or right' }, { name: 'label', types: ['string', 'null'], help: 'Label for axis' }, { name: 'color', types: ['string', 'null'], help: 'Color of axis label' }, ], help: 'Configures a variety of y-axis options, the most important likely being the ability to add an Nth (eg 2nd) y-axis', fn: function yaxisFn(args) { return alter(args, function (eachSeries, yaxis, min, max, position, label, color) { yaxis = yaxis || 1; eachSeries.yaxis = yaxis; eachSeries._global = eachSeries._global || {}; eachSeries._global.yaxes = eachSeries._global.yaxes || []; eachSeries._global.yaxes[yaxis - 1] = eachSeries._global.yaxes[yaxis - 1] || {}; const myAxis = eachSeries._global.yaxes[yaxis - 1]; myAxis.position = position || (yaxis % 2 ? 'left' : 'right'); myAxis.min = min; myAxis.max = max; myAxis.axisLabelFontSizePixels = 11; myAxis.axisLabel = label; myAxis.axisLabelColour = color; myAxis.axisLabelUseCanvas = true; return eachSeries; }); } });
istresearch/PulseTheme
kibana/src/core_plugins/timelion/server/series_functions/yaxis.js
JavaScript
mit
1,733
(function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(); else if(typeof define === 'function' && define.amd) define([], factory); else { var a = factory(); for(var i in a) (typeof exports === 'object' ? exports : root)[i] = a[i]; } })(this, function() { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ({ /***/ 0: /***/ function(module, exports, __webpack_require__) { __webpack_require__(228); /***/ }, /***/ 228: /***/ function(module, exports, __webpack_require__) { module.exports = __webpack_require__(229); /***/ }, /***/ 229: /***/ function(module, exports, __webpack_require__) { /** * @name Utility Classes * @collection core * @example-file ./examples.html */ __webpack_require__(230); /***/ }, /***/ 230: /***/ function(module, exports) { // removed by extract-text-webpack-plugin /***/ } /******/ }) }); ;
gorohoroh/reveal.js
css/jetbrains-bundle/utility-classes.js
JavaScript
mit
2,230
///* //Project Name: Spine Admin //Version: 1.6.0 //Author: BharaniGuru R // //*/var handleCalendarDemo=function(){"use strict";var e={left:"prev today",center:"title",right:"agendaWeek next"};var t=new Date;var n=t.getMonth();var r=t.getFullYear();var i=$("#calendar").fullCalendar({header:e,selectable:true,selectHelper:true,droppable:true,drop:function(e,t){var n=$(this).data("eventObject");var r=$.extend({},n);r.start=e;r.allDay=t;$("#calendar").fullCalendar("renderEvent",r,true);if($("#drop-remove").is(":checked")){$(this).remove()}}, //select:function(e,t,n) //{var r= $('.model_test').trigger('click');if(r){i.fullCalendar("renderEvent",{title:r,start:e,end:t,allDay:n},true)}i.fullCalendar("unselect")}, ////{var r=prompt("LEAVE TYPE:");if(r){i.fullCalendar("renderEvent",{title:r,start:e,end:t,allDay:n},true)}i.fullCalendar("unselect")}, //eventRender:function(e,t,n){var r=e.media?e.media:"";var i=e.description?e.description:"";t.find(".fc-event-title").after($('<span class="fc-event-icons"></span>').html(r));t.find(".fc-event-title").append("<small>"+i+"</small>")},editable:true,events:[/*{title:"Event",start:new Date(r,n,0),}*/]});$("#external-events .external-event").each(function(){var e={title:$.trim($(this).attr("data-title")),className:$(this).attr("data-bg"),media:$(this).attr("data-media"),description:$(this).attr("data-desc")};$(this).data("eventObject",e);$(this).draggable({zIndex:999,revert:true,revertDuration:0})})};var Calendar=function(){"use strict";return{init:function(){handleCalendarDemo()}}}() /* Project Name: Spine Admin Version: 1.6.0 Author: BharaniGuru R */ //--------------------------------------// var handleCalendarDemo = function() { "use strict"; var e = { left: "prev today", center: "title", right: "agendaWeek next" }; var t = new Date; var n = t.getMonth(); var r = t.getFullYear(); var i = $("#calendar").fullCalendar({ header: e, selectable: true, selectHelper: true, droppable: true, drop: function(e, t) { var n = $(this).data("eventObject"); var r = $.extend({}, n); r.start = e; r.allDay = t; $("#calendar").fullCalendar("renderEvent", r, true); if ($("#drop-remove").is(":checked")) { $(this).remove() } }, select: function(e, t, n) { //var r = prompt("LEAVE TYPE:"); modalwindowevent(); var r = data+"/"+data1; console.log(r,'value'); if (r) { //alert('in rr'); i.fullCalendar("renderEvent", { title: r, start: e, end: t, allDay: n }, true) } i.fullCalendar("unselect") }, eventRender: function(e, t, n) { var r = e.media ? e.media : ""; var i = e.description ? e.description : ""; t.find(".fc-event-title").after($('<span class="fc-event-icons"></span>').html(r)); console.log(t.find(".fc-event-title").after($('<span class="fc-event-icons"></span>').html(r)),'testmin'); t.find(".fc-event-title").append("<small>" + i + "</small>") }, editable: true, events: [ /*{title:"Event",start:new Date(r,n,0),}*/ ] }); $("#external-events .external-event").each(function() { var e = { title: $.trim($(this).attr("data-title")), className: $(this).attr("data-bg"), media: $(this).attr("data-media"), description: $(this).attr("data-desc") }; $(this).data("eventObject", e); $(this).draggable({ zIndex: 999, revert: true, revertDuration: 0 }) }) }; var Calendar = function() { "use strict"; return { init: function() { handleCalendarDemo() } } }() //$(document).ready(function(){ //function getInputvalue(){ // var reson=$('#resoan_val').val(); // var leave=$('.leave_days').val(); // var type=$('#leave_type').val(); // var all=reson+" "+leave+" "+type; // $('.fc-event-title').addClass('value').text('all').css('color','red'); // console.log(all,'alldata'); // //modelwindform(); //} // function modelwindform(){ // $('.model_test').trigger('click'); //} //}); //$(function(modelwindform) { //function modelwindform(){ // $('#dialogboxxxxxxxx').trigger('click'); // $("#dialogboxxxxxxxx").dialog({ // autoOpen: false, // modal: true, // buttons : { // "Confirm" : function() { // alert("You have confirmed!"); // }, // "Cancel" : function() { // $(this).dialog("close"); // } // } // }); // // $("#callConfirm").on("click", function(e) { // e.preventDefault(); // $("#dialog").dialog("open"); // }); //} //}); //$('#Save_btn').trigger('click'); //}) //$('.fc-widget-content3').addClass('tt').css('background','red'); //$('.tt').text('dsudyhdsy').css('color','white').removeClass('tt'); //$('.tt'); //function newmoadl(){ // $("#bootbox").trigger("click"); // var modal = bootbox.dialog({ // message: $(".form-content").html(), // title: "Your awesome modal", // buttons: [ // { // label: "Save", // className: "btn btn-primary pull-left", // callback: function() { // // alert($('form #email').val()); // console.log(modal); // // return false; // } // }, // { // label: "Close", // className: "btn btn-default pull-left", // callback: function() { // console.log("just do something on close"); // } // } // ], // show: false, // onEscape: function() { // modal.modal("hide"); // } // }); //} //$(document).ready(function() { // ////function newmoadl(){ // $("#bootbox").on("click", function(event) { // var modal = bootbox.dialog({ // message: $(".form-content").html(), // title: "Your awesome modal", // buttons: [ // { // label: "Save", // className: "btn btn-primary pull-left", // callback: function() { // var select=$('#leave_type').val(); // var hiddenval=$('#hidden').val(select); // //$("#myHiddenField").val($(this).attr("temp")); // //var name=$('#name').val(); // // var select="CL"; // //var name="manikandan"; // //var all=select+name; // //console.log(name); // //console.log(select); // return false; // } // }, // { // label: "Close", // className: "btn btn-default pull-left", // callback: function() { // console.log("just do something on close"); // } // } // ], // show: false, // onEscape: function() { // modal.modal("hide"); // } // }); // console.log(modal); // modal.modal("show"); // }); // //} ////} //}); var data; var data1 function modalwindowevent(){ //alert('event in'); $("#open").trigger("click"); $("#dialog").removeClass('hidden'); $("#dialog").dialog({ autoOpen: false, buttons: { Ok: function() { data=$('#name').val(); data1=$('#valuesofanem').val(); $("#nameentered").text($("#name").val()); $("#sdasdasd").text($("#valuesofanem").val()); $(this).dialog("close"); }, Cancel: function () { $(this).dialog("close"); } } }); $("#open").click(function () { $("#dialog").dialog("open"); }); }
junaidappimagine/smartedu
assets/js/calendar.demo.min.js
JavaScript
mit
8,006
/** * Created by ionagamed on 8/19/16. */ import { Card } from '../../../Card'; import { Item } from '../helpers/Item'; const id = 'sneaky_bastard_sword'; class _ extends Item { constructor() { super(); this.id = id; this.pack = 'pack1'; this.kind = 'treasure'; this.type = '1-handed'; this.hands = 1; this.wieldable = true; this.price = 400; } getAttackFor(player) { return 2; } } Card.cards[id] = new _();
ionagamed/munchkin
logic/packs/pack1/treasure/sneaky_bastard_sword.js
JavaScript
mit
502
import React from 'react' import GMManhattanChart from './GMManhattanChart' import GMManhattanToolbar from './GMManhattanToolbar' import fetch from './fetch' import config from '../../config' const GMManhattanVisualization = React.createClass({ componentDidMount() { this.loadData(this.props.params), this.setState({ pageParams: [] }) }, componentWillReceiveProps(nextProps) { this.loadData(nextProps.params) }, getInitialState() { return { pageParams: [] } }, loadData: function (params) { let dataRequest = { method: 'GET', headers: { 'Content-Type': 'application/json' } } const vizData = { } return fetch(`${config.api.dataUrl}/${params.results}`, dataRequest) .then(response => { if (!response.ok) Promise.reject(response.json()) return response.json() }).then(json => { vizData.data = JSON.parse(json.data) return fetch(`${config.api.dataUrl}/${params.markers}`, dataRequest) }).then(response => { if (!response.ok) Promise.reject(response.json()) return response.json() }).then(json => { vizData.markerLabels = json.data.split('\n').filter(function(line){ return line.length > 0 }) return fetch(`${config.api.dataUrl}/${params.traits}`, dataRequest) }).then(response => { if (!response.ok) Promise.reject(response.json()) return response.json() }).then(json => { vizData.traitLabels = json.data.split('\n').filter(function(line){ return line.length > 0 }) this.setState({ data: vizData.data, markerLabels: vizData.markerLabels, traitLabels: vizData.traitLabels, pageParams: params }) return json }).catch(err => console.log(err)) }, render() { return ( <div> <div className="Manhattan"> <GMManhattanChart data={this.state.data} markerLabels={this.state.markerLabels} traitLabelsNum={this.state.pageParams.traitNum} pageParams={this.state.pageParams} /> </div> <GMManhattanToolbar left={this.props.minPad} right={this.props.minPad} pageParams={this.state.pageParams} /> </div> ) } }) export default GMManhattanVisualization
blengerich/GenAMap
src/frontend/src/components/GMManhattanVisualization.js
JavaScript
mit
2,347
$(document).ready(function() { var text = $("#hSleep").text(); var results = []; var data = []; results = text.split(","); // alert(results); console.log("results: " + text); for(var i = results.length-1; i >= 0; i--) { data.push([new Date(results[i-1]).getTime(), results[i]]); i--; } var barOptions = { series: { bars: { show: true, barWidth: 43200000 } }, xaxis: { mode: "time", timeformat: "%m/%d", minTickSize: [1, "day"] }, grid: { hoverable: true }, legend: { show: false }, tooltip: true, tooltipOpts: { content: "Date: %x, Minutes: %y" } }; var barData = { label: "bar", data: data }; $.plot($("#flot-line-chart"), [barData], barOptions); text = $("#hSteps").text(); results = text.split(","); data = []; for(var i = results.length-1; i >= 0; i--) { data.push([new Date(results[i-1]).getTime(), results[i]]); i--; } var options = { series: { lines: { show: true }, points: { show: true } }, grid: { hoverable: true //IMPORTANT! this is needed for tooltip to work }, xaxis: { mode: "time", timeformat: "%m/%d", minTickSize: [1, "day"] }, tooltip: true, tooltipOpts: { content: "'Date: %x.1, Steps: %y", shifts: { x: -60, y: 25 } } }; var plotObj = $.plot($("#flot-bar-chart"), [{ data: data, label: "Steps" }], options); text = $("#hDistance").text(); results = text.split(","); data = []; //alert(text); for(var i = results.length-1; i >= 0; i--) { data.push([new Date(results[i-1]).getTime(), results[i]]); i--; } var options = { series: { lines: { show: true }, points: { show: true } }, grid: { hoverable: true //IMPORTANT! this is needed for tooltip to work }, xaxis: { mode: "time", timeformat: "%m/%d", minTickSize: [1, "day"] }, tooltip: true, tooltipOpts: { content: "'Date: %x.1, Heart Rates: %y", shifts: { x: -60, y: 25 } } }; var plotObj = $.plot($("#flot-moving-line-chart"), [{ data: data, label: "Heart Rates" }], options); text = $("#hCalories").text(); results = text.split(","); data = []; for(var i = results.length-1; i >= 0; i--) { data.push([new Date(results[i-1]).getTime(), results[i]]); i--; } var options = { series: { lines: { show: true }, points: { show: true } }, grid: { hoverable: true //IMPORTANT! this is needed for tooltip to work }, xaxis: { mode: "time", timeformat: "%m/%d", minTickSize: [1, "day"] }, tooltip: true, tooltipOpts: { content: "'Date: %x.1, Steps: %y", shifts: { x: -60, y: 25 } } }; var plotObj = $.plot($("#flot-multiple-axes-chart"), [{ data: data, label: "Calories" }], options); });
BaierGroup/FitApp
FitAppMS/public/javascripts/js/index1.js
JavaScript
mit
3,826
export default from './CallToAction.jsx';
natac13/portfolio-2016
app/components/Main/CallToAction/index.js
JavaScript
mit
42
'use strict'; chrome.devtools.panels.create('Luffa', '', 'devtool.html', function (panel) { var reactPanel = null; panel.onShown.addListener(function (window) { // when the user switches to the panel, check for an elements tab // selection window.panel.getNewSelection(); reactPanel = window.panel; reactPanel.resumeTransfer(); }); panel.onHidden.addListener(function () { if (reactPanel) { reactPanel.hideHighlight(); reactPanel.pauseTransfer(); } }); }); //# sourceMappingURL=panel.js.map
phodal/luffa-chrome
app/scripts/panel.js
JavaScript
mit
542
var express = require('express'); var path = require('path'); var favicon = require('serve-favicon'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var api = require('./routes/api'); var app = express(); // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'jade'); // uncomment after placing your favicon in /public //app.use(favicon(path.join(__dirname, 'public', 'favicon.ico'))); app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(cookieParser()); app.use(express.static(path.join(__dirname, 'public'))); app.use(express.static(__dirname + '/dist')); app.use('/api', api); app.use('*', function(req, res) { res.sendfile(__dirname + '/dist/index.html'); }); // catch 404 and forward to error handler app.use(function(req, res, next) { var err = new Error('Not Found'); err.status = 404; next(err); }); // error handlers // development error handler // will print stacktrace if (app.get('env') === 'development') { app.use(function(err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: err }); }); } // production error handler // no stacktraces leaked to user app.use(function(err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: {} }); }); module.exports = app;
Exxpen/authenticate-express-bcrypt-jwt
app.js
JavaScript
mit
1,504
// flow-typed signature: e6263c15ef6789188b11afd5007f8d74 // flow-typed version: <<STUB>>/css-to-react-native_v^2.2.2/flow_v0.100.0 /** * This is an autogenerated libdef stub for: * * 'css-to-react-native' * * Fill this stub out by replacing all the `any` types. * * Once filled out, we encourage you to share your work with the * community by sending a pull request to: * https://github.com/flowtype/flow-typed */ declare module 'css-to-react-native' { declare module.exports: any; } /** * We include stubs for each file inside this npm package in case you need to * require those files directly. Feel free to delete any files that aren't * needed. */ declare module 'css-to-react-native/src/__tests__/border' { declare module.exports: any; } declare module 'css-to-react-native/src/__tests__/borderColor' { declare module.exports: any; } declare module 'css-to-react-native/src/__tests__/boxModel' { declare module.exports: any; } declare module 'css-to-react-native/src/__tests__/boxShadow' { declare module.exports: any; } declare module 'css-to-react-native/src/__tests__/colors' { declare module.exports: any; } declare module 'css-to-react-native/src/__tests__/flex' { declare module.exports: any; } declare module 'css-to-react-native/src/__tests__/flexFlow' { declare module.exports: any; } declare module 'css-to-react-native/src/__tests__/font' { declare module.exports: any; } declare module 'css-to-react-native/src/__tests__/fontFamily' { declare module.exports: any; } declare module 'css-to-react-native/src/__tests__/fontVariant' { declare module.exports: any; } declare module 'css-to-react-native/src/__tests__/fontWeight' { declare module.exports: any; } declare module 'css-to-react-native/src/__tests__/index' { declare module.exports: any; } declare module 'css-to-react-native/src/__tests__/shadowOffsets' { declare module.exports: any; } declare module 'css-to-react-native/src/__tests__/textDecoration' { declare module.exports: any; } declare module 'css-to-react-native/src/__tests__/textDecorationLine' { declare module.exports: any; } declare module 'css-to-react-native/src/__tests__/textShadow' { declare module.exports: any; } declare module 'css-to-react-native/src/__tests__/transform' { declare module.exports: any; } declare module 'css-to-react-native/src/__tests__/units' { declare module.exports: any; } declare module 'css-to-react-native/src/index' { declare module.exports: any; } declare module 'css-to-react-native/src/TokenStream' { declare module.exports: any; } declare module 'css-to-react-native/src/tokenTypes' { declare module.exports: any; } declare module 'css-to-react-native/src/transforms/boxShadow' { declare module.exports: any; } declare module 'css-to-react-native/src/transforms/flex' { declare module.exports: any; } declare module 'css-to-react-native/src/transforms/font' { declare module.exports: any; } declare module 'css-to-react-native/src/transforms/fontFamily' { declare module.exports: any; } declare module 'css-to-react-native/src/transforms/index' { declare module.exports: any; } declare module 'css-to-react-native/src/transforms/textDecoration' { declare module.exports: any; } declare module 'css-to-react-native/src/transforms/textDecorationLine' { declare module.exports: any; } declare module 'css-to-react-native/src/transforms/textShadow' { declare module.exports: any; } declare module 'css-to-react-native/src/transforms/transform' { declare module.exports: any; } declare module 'css-to-react-native/src/transforms/util' { declare module.exports: any; } // Filename aliases declare module 'css-to-react-native/index' { declare module.exports: $Exports<'css-to-react-native'>; } declare module 'css-to-react-native/index.js' { declare module.exports: $Exports<'css-to-react-native'>; } declare module 'css-to-react-native/src/__tests__/border.js' { declare module.exports: $Exports<'css-to-react-native/src/__tests__/border'>; } declare module 'css-to-react-native/src/__tests__/borderColor.js' { declare module.exports: $Exports<'css-to-react-native/src/__tests__/borderColor'>; } declare module 'css-to-react-native/src/__tests__/boxModel.js' { declare module.exports: $Exports<'css-to-react-native/src/__tests__/boxModel'>; } declare module 'css-to-react-native/src/__tests__/boxShadow.js' { declare module.exports: $Exports<'css-to-react-native/src/__tests__/boxShadow'>; } declare module 'css-to-react-native/src/__tests__/colors.js' { declare module.exports: $Exports<'css-to-react-native/src/__tests__/colors'>; } declare module 'css-to-react-native/src/__tests__/flex.js' { declare module.exports: $Exports<'css-to-react-native/src/__tests__/flex'>; } declare module 'css-to-react-native/src/__tests__/flexFlow.js' { declare module.exports: $Exports<'css-to-react-native/src/__tests__/flexFlow'>; } declare module 'css-to-react-native/src/__tests__/font.js' { declare module.exports: $Exports<'css-to-react-native/src/__tests__/font'>; } declare module 'css-to-react-native/src/__tests__/fontFamily.js' { declare module.exports: $Exports<'css-to-react-native/src/__tests__/fontFamily'>; } declare module 'css-to-react-native/src/__tests__/fontVariant.js' { declare module.exports: $Exports<'css-to-react-native/src/__tests__/fontVariant'>; } declare module 'css-to-react-native/src/__tests__/fontWeight.js' { declare module.exports: $Exports<'css-to-react-native/src/__tests__/fontWeight'>; } declare module 'css-to-react-native/src/__tests__/index.js' { declare module.exports: $Exports<'css-to-react-native/src/__tests__/index'>; } declare module 'css-to-react-native/src/__tests__/shadowOffsets.js' { declare module.exports: $Exports<'css-to-react-native/src/__tests__/shadowOffsets'>; } declare module 'css-to-react-native/src/__tests__/textDecoration.js' { declare module.exports: $Exports<'css-to-react-native/src/__tests__/textDecoration'>; } declare module 'css-to-react-native/src/__tests__/textDecorationLine.js' { declare module.exports: $Exports<'css-to-react-native/src/__tests__/textDecorationLine'>; } declare module 'css-to-react-native/src/__tests__/textShadow.js' { declare module.exports: $Exports<'css-to-react-native/src/__tests__/textShadow'>; } declare module 'css-to-react-native/src/__tests__/transform.js' { declare module.exports: $Exports<'css-to-react-native/src/__tests__/transform'>; } declare module 'css-to-react-native/src/__tests__/units.js' { declare module.exports: $Exports<'css-to-react-native/src/__tests__/units'>; } declare module 'css-to-react-native/src/index.js' { declare module.exports: $Exports<'css-to-react-native/src/index'>; } declare module 'css-to-react-native/src/TokenStream.js' { declare module.exports: $Exports<'css-to-react-native/src/TokenStream'>; } declare module 'css-to-react-native/src/tokenTypes.js' { declare module.exports: $Exports<'css-to-react-native/src/tokenTypes'>; } declare module 'css-to-react-native/src/transforms/boxShadow.js' { declare module.exports: $Exports<'css-to-react-native/src/transforms/boxShadow'>; } declare module 'css-to-react-native/src/transforms/flex.js' { declare module.exports: $Exports<'css-to-react-native/src/transforms/flex'>; } declare module 'css-to-react-native/src/transforms/font.js' { declare module.exports: $Exports<'css-to-react-native/src/transforms/font'>; } declare module 'css-to-react-native/src/transforms/fontFamily.js' { declare module.exports: $Exports<'css-to-react-native/src/transforms/fontFamily'>; } declare module 'css-to-react-native/src/transforms/index.js' { declare module.exports: $Exports<'css-to-react-native/src/transforms/index'>; } declare module 'css-to-react-native/src/transforms/textDecoration.js' { declare module.exports: $Exports<'css-to-react-native/src/transforms/textDecoration'>; } declare module 'css-to-react-native/src/transforms/textDecorationLine.js' { declare module.exports: $Exports<'css-to-react-native/src/transforms/textDecorationLine'>; } declare module 'css-to-react-native/src/transforms/textShadow.js' { declare module.exports: $Exports<'css-to-react-native/src/transforms/textShadow'>; } declare module 'css-to-react-native/src/transforms/transform.js' { declare module.exports: $Exports<'css-to-react-native/src/transforms/transform'>; } declare module 'css-to-react-native/src/transforms/util.js' { declare module.exports: $Exports<'css-to-react-native/src/transforms/util'>; }
css-components/styled-components
flow-typed/npm/css-to-react-native_vx.x.x.js
JavaScript
mit
8,522
(function (angular) { 'use strict'; angular .module('ngTagsInput', []); })(window.angular);
showpad/angular-tags
src/config/src/angular-tags.module.js
JavaScript
mit
109
const fs = require('fs'); const path = require('path'); // eslint-disable-next-line import/no-extraneous-dependencies const sharedsession = require('express-socket.io-session'); /** * Checks to see if sockets are configured and then sets up socket.io * @param {Ceres} ceres * @param {Express} app * @param {HTTP} server * @return {socket.io} */ module.exports = function sockets(ceres, app, server) { const clientSocketEntryPath = path.resolve(ceres.config.folders.sockets, './index.js'); try { // Can we access the file? fs.accessSync(clientSocketEntryPath); } catch (err) { if (err.code === 'ENOENT') { ceres.log.internal.silly('Websockets configuration not found at %s', clientSocketEntryPath); return {}; } throw err; } // Setup socket.io // eslint-disable-next-line import/no-extraneous-dependencies const io = require('socket.io')(server); // Get socket router const handler = require(clientSocketEntryPath); // Connect it to client connection event io.on('connection', handler.bind(ceres, io, ceres.Database)); // Share express sessions io.use(sharedsession(app.get('sharedSession'))); ceres.log.internal.silly('Websockets configured'); return io; };
isuttell/ceres-framework
src/setup/sockets.js
JavaScript
mit
1,242
'use strict' const _toArray = require('lodash.toarray') const shelljs = require('shelljs') module.exports = function (config) { // parse loader [ 'loaders', 'preLoaders', 'postLoaders' ].forEach(key => { config.module[key] = _toArray(config.module[key]) }) // parse plugin config.plugins = _toArray(config.plugins) // install resolve path require('./load-resolve-path')(config) if (process.env.NODE_ENV === 'development') { // install dev server config.devServer = require('../util/load-server')(config.devServer) if (config.devServer.enable) { config.devServer.host = config.devServer.protocol + '//' + config.devServer.hostname + ':' + config.devServer.port } // update path config.output.publicPath = config.devServer.publicPath || config.output.publicPath || '/' } // load hot loader config.entry = require('./hot-reload')( config.entry, process.env.NODE_ENV === 'development' ? config.devServer : false ) if (config.__XDC_CLEAN__) { shelljs.rm('-rf', config.output.path) } return config }
x-xdc/xdc
packages/xdc/util/parse.js
JavaScript
mit
1,092
(function() { 'use strict'; var app = angular.module('app'); app.directive('ccImgPerson', ['config', function (config) { //Usage: //<img data-cc-img-person="{{s.speaker.imageSource}}"/> var basePath = config.imageSettings.imageBasePath; var unknownImage = config.imageSettings.unknownPersonImageSource; var directive = { link: link, restrict: 'A' }; return directive; function link(scope, element, attrs) { attrs.$observe('ccImgPerson', function(value) { value = basePath + (value || unknownImage); attrs.$set('src', value); }); } }]); app.directive('ccSidebar', function () { // Opens and clsoes the sidebar menu. // Usage: // <div data-cc-sidebar> // Creates: // <div data-cc-sidebar class="sidebar"> var directive = { link: link, restrict: 'A' }; return directive; function link(scope, element, attrs) { var $sidebarInner = element.find('.sidebar-inner'); var $dropdownElement = element.find('.sidebar-dropdown a'); element.addClass('sidebar'); $dropdownElement.click(dropdown); function dropdown(e) { var dropClass = 'dropy'; e.preventDefault(); if (!$dropdownElement.hasClass(dropClass)) { hideAllSidebars(); $sidebarInner.slideDown(350); $dropdownElement.addClass(dropClass); } else if ($dropdownElement.hasClass(dropClass)) { $dropdownElement.removeClass(dropClass); $sidebarInner.slideUp(350); } function hideAllSidebars() { $sidebarInner.slideUp(350); $('.sidebar-dropdown a').removeClass(dropClass); } } } }); app.directive('ccWidgetClose', function () { // Usage: // <a data-cc-widget-close></a> // Creates: // <a data-cc-widget-close="" href="#" class="wclose"> // <i class="icon-remove"></i> // </a> var directive = { link: link, template: '<i class="icon-remove"></i>', restrict: 'A' }; return directive; function link(scope, element, attrs) { attrs.$set('href', '#'); attrs.$set('wclose'); element.click(close); function close(e) { e.preventDefault(); element.parent().parent().parent().hide(100); } } }); app.directive('ccWidgetMinimize', function () { // Usage: // <a data-cc-widget-minimize></a> // Creates: // <a data-cc-widget-minimize="" href="#"><i class="icon-chevron-up"></i></a> var directive = { link: link, template: '<i class="icon-chevron-up"></i>', restrict: 'A' }; return directive; function link(scope, element, attrs) { //$('body').on('click', '.widget .wminimize', minimize); attrs.$set('href', '#'); attrs.$set('wminimize'); element.click(minimize); function minimize(e) { e.preventDefault(); var $wcontent = element.parent().parent().next('.widget-content'); var iElement = element.children('i'); if ($wcontent.is(':visible')) { iElement.removeClass('icon-chevron-up'); iElement.addClass('icon-chevron-down'); } else { iElement.removeClass('icon-chevron-down'); iElement.addClass('icon-chevron-up'); } $wcontent.toggle(500); } } }); app.directive('ccScrollToTop', ['$window', // Usage: // <span data-cc-scroll-to-top></span> // Creates: // <span data-cc-scroll-to-top="" class="totop"> // <a href="#"><i class="icon-chevron-up"></i></a> // </span> function ($window) { var directive = { link: link, template: '<a href="#"><i class="icon-chevron-up"></i></a>', restrict: 'A' }; return directive; function link(scope, element, attrs) { var $win = $($window); element.addClass('totop'); $win.scroll(toggleIcon); element.find('a').click(function (e) { e.preventDefault(); // Learning Point: $anchorScroll works, but no animation //$anchorScroll(); $('body').animate({ scrollTop: 0 }, 500); }); function toggleIcon() { $win.scrollTop() > 300 ? element.slideDown(): element.slideUp(); } } } ]); app.directive('ccSpinner', ['$window', function ($window) { // Description: // Creates a new Spinner and sets its options // Usage: // <div data-cc-spinner="vm.spinnerOptions"></div> var directive = { link: link, restrict: 'A' }; return directive; function link(scope, element, attrs) { scope.spinner = null; scope.$watch(attrs.ccSpinner, function (options) { if (scope.spinner) { scope.spinner.stop(); } scope.spinner = new $window.Spinner(options); scope.spinner.spin(element[0]); }, true); } }]); app.directive('ccWidgetHeader', function() { //Usage: //<div data-cc-widget-header title="vm.map.title"></div> var directive = { link: link, scope: { 'title': '@', 'subtitle': '@', 'rightText': '@', 'allowCollapse': '@' }, templateUrl: '/app/layout/widgetheader.html', restrict: 'A', }; return directive; function link(scope, element, attrs) { attrs.$set('class', 'widget-head'); } }); app.directive('ccWip', ['$route', function ($route) { //Usage: //<li data-cc-wip // wip="vm.wip" // routes="vm.routes" // changed-event="{{vm.wipChangedEvent}}" // class="nlightblue"></li> var wipRouteName = 'workinprogress'; var directive = { controller: ['$scope', wipController], link: link, template: getTemplate(), scope: { 'wip': '=', 'changedEvent': '@', 'routes': '=' }, restrict: 'A' }; return directive; function link(scope, element, attrs) { scope.$watch(wipIsCurrent, function (value) { value ? element.addClass('current') : element.removeClass('current'); }); function wipIsCurrent() { if (!$route.current || !$route.current.title) { return false; } return $route.current.title.substr(0, wipRouteName.length) === wipRouteName; } } function wipController($scope) { $scope.wipExists = function () { return !!$scope.wip.length; }; $scope.wipRoute = undefined; $scope.getWipClass = function () { return $scope.wipExists() ? 'icon-asterisk-alert' : ''; }; activate(); function activate() { var eventName = $scope.changedEvent; $scope.$on(eventName, function (event, data) { $scope.wip = data.wip; }); $scope.wipRoute = $scope.routes.filter(function (r) { return r.config.title === wipRouteName; })[0]; } } function getTemplate() { return '<a href="#{{wipRoute.url}}" >' + '<i class="icon-asterisk" data-ng-class="getWipClass()"></i>' + 'Work in Progress ({{wip.length}})</a>'; } }]); })();
christrees/CAT_HWPC_Bug
09_cat/htHWPCBug/app/services/directives.js
JavaScript
mit
8,798
/** * Session Configuration * (sails.config.session) * * Sails session integration leans heavily on the great work already done by * Express, but also unifies Socket.io with the Connect session store. It uses * Connect's cookie parser to normalize configuration differences between Express * and Socket.io and hooks into Sails' middleware interpreter to allow you to access * and auto-save to `req.session` with Socket.io the same way you would with Express. * * For more information on configuring the session, check out: * http://sailsjs.org/#/documentation/reference/sails.config/sails.config.session.html */ module.exports.session = { /*************************************************************************** * * * Session secret is automatically generated when your new app is created * * Replace at your own risk in production-- you will invalidate the cookies * * of your users, forcing them to log in again. * * * ***************************************************************************/ secret: '0e12331bed5965a0443585ad3157def3', /*************************************************************************** * * * Set the session cookie expire time The maxAge is set by milliseconds, * * the example below is for 24 hours * * * ***************************************************************************/ // cookie: { // maxAge: 24 * 60 * 60 * 1000 // } /*************************************************************************** * * * In production, uncomment the following lines to set up a shared redis * * session store that can be shared across multiple Sails.js servers * ***************************************************************************/ // adapter: 'redis', /*************************************************************************** * * * The following values are optional, if no options are set a redis * * instance running on localhost is expected. Read more about options at: * * https://github.com/visionmedia/connect-redis * * * * * ***************************************************************************/ // host: 'localhost', // port: 6379, // ttl: <redis session TTL in seconds>, // db: 0, // pass: <redis auth password> // prefix: 'sess:' /*************************************************************************** * * * Uncomment the following lines to use your Mongo adapter as a session * * store * * * ***************************************************************************/ // adapter: 'mongo', // host: 'localhost', // port: 27017, // db: 'sails', // collection: 'sessions', /*************************************************************************** * * * Optional Values: * * * * # Note: url will override other connection settings url: * * 'mongodb://user:pass@host:port/database/collection', * * * ***************************************************************************/ // username: '', // password: '', // auto_reconnect: false, // ssl: false, // stringify: true };
Actonate/upload-manager-node
config/session.js
JavaScript
mit
4,320
module.exports = require('./lib/bionode-bwa')
bionode/bionode-bwa
index.js
JavaScript
mit
46
import React from 'react' import {observer} from 'mobx-react' import {Route, Link} from 'react-router-dom' import {IMAGE_DIR, TOKEN, GET_HOTEL_INFO, RESPONSE_CODE_SUCCESS} from 'macros' import {setParamsToURL, dateToZh} from 'utils' import Cookies from 'js-cookie' import WeiXinShareTips from 'WeiXinShareTips' import './hotel.less' export default observer( (props) => ( <div className="hotel-container"> <div className="banner-container"> <div className="colllect"> {Cookies.get(TOKEN)? props.store.isFavorite == 1? <i className="iconfont btn-colllect icon-hotle_icon_like1" /> : <i className="iconfont btn-colllect icon-hotle_icon_like" /> : ''} <span className="btn-share"><i className="iconfont icon-share1" /></span> </div> <div className="swiper-container"> <div className="swiper-wrapper"> { props.store.hotelImgs.map((item, index) => { return <div className="swiper-slide" key={index} style={{backgroundImage:`url(${item.imgPath})`}}></div> }) } </div> <div className="swiper-pagination"></div> </div> </div> <div className="hotel-name-wrapper"> <div className="hotel-box"> <div className="hotel-name">{props.store.hotelName}</div> <div className="hotel-address">{props.store.address}</div> </div> <Link to={setParamsToURL(`${props.match.url}/map`, {longitude: props.store.longitude, latitude: props.store.latitude})}> <i className="iconfont icon-will_live_icon_loction" /> </Link> </div> <ul className="hotel-funs"> <li><img src={`${IMAGE_DIR}/use-face.jpg`} /><span>刷脸入住</span></li> <li><img src={`${IMAGE_DIR}/use-lock.jpg`} /><span>无卡开锁</span></li> <li><img src={`${IMAGE_DIR}/use-free.jpg`} /><span>面排队/查房</span></li> </ul> <Link to={`${props.match.url}/select-date`} className="checking-in-out"> <div><p>入住</p><span>{dateToZh(props.store.checkInDate)}</span></div> <div><p>退房</p><span>{dateToZh(props.store.checkOutDate)}</span></div> <i className="iconfont icon-hotle_icon_show" /> </Link> <div className="hotel-cards"> <div className="swiper-container"> <div className="swiper-wrapper"> { props.store.roomTypes.map((item, index) => { return ( <div className="swiper-slide" key={index} style={{backgroundImage:`url(${item.imgPath})`}}> <div className="slide-adjust"> <p className="price-box">&yen;{`${item.price}`}</p> <Link className="clickable-area" to={`/room/${props.match.params.hotelID}/${item.roomTypeID}`} ></Link> <div className="hotel-type"> <div className="info-wrapper"> <p>{item.roomType}</p> <p>{`${item.roomSize}m², ${item.bedType}`}</p> </div> <Link to={{pathname:`/booking/${props.match.params.hotelID}/${item.roomTypeID}`, search: `?checkInDate=${props.store.checkInDate}&checkOutDate=${props.store.checkOutDate}`}} className="btn-booking">立即预订</Link> </div> </div> </div> ) }) } </div> </div> </div> { props.store.isShowShareTips? ( <WeiXinShareTips onClick={(e) => { props.store.isShowShareTips = false }}/> ) : '' } </div> ) )
bugknightyyp/leyizhu
app/routes/routes/Hotel/components/Hotel.view.js
JavaScript
mit
3,718
import GameEvent from "../../../src/artifact/js/GameEvent.js"; QUnit.module("GameEvent"); var GameEventTest = {}; QUnit.test("GameEvent properties Quest card drawn", function(assert) { var eventKey = GameEvent.QUEST_CARD_DRAWN; var properties = GameEvent.properties[eventKey]; assert.equal(properties.name, "Quest card drawn"); assert.equal(properties.key, "questCardDrawn"); }); QUnit.test("keys and values", function(assert) { // Setup. // Run. var result = GameEvent.keys(); var ownPropertyNames = Object.getOwnPropertyNames(GameEvent); // Verify. ownPropertyNames.forEach(function(key) { var key2 = GameEvent[key]; if (key !== "properties" && typeof key2 === "string") { assert.ok(GameEvent.properties[key2], "Missing value for key = " + key); } }); result.forEach(function(value) { var p = ownPropertyNames.filter(function(key) { return GameEvent[key] === value; }); assert.equal(p.length, 1, "Missing key for value = " + value); }); }); QUnit.test("GameEvent.keys()", function(assert) { // Run. var result = GameEvent.keys(); // Verify. assert.ok(result); var length = 6; assert.equal(result.length, length); var i = 0; assert.equal(result[i++], GameEvent.CARD_PLAYED); assert.equal(result[i++], GameEvent.QUEST_CARD_DRAWN); assert.equal(result[i++], GameEvent.QUEST_SUCCEEDED); assert.equal(result[i++], GameEvent.SHADOW_CARD_REVEALED); assert.equal(result[i++], GameEvent.TRAVELED); assert.equal(result[i++], GameEvent.WOUNDED); }); export default GameEventTest;
jmthompson2015/lotr-card-game
test/artifact/js/GameEventTest.js
JavaScript
mit
1,632
var $ = function (selector) { return document.querySelector(selector); }; var $all = function (selector) { return document.querySelectorAll(selector); }; var colorScheme = [ '#6BED08', '#A0F261', '#86EF35', '#60DD00', '#4AAA00', '#F8FE09', '#FBFE66', '#F9FE39', '#F2F800', '#BABF00', '#06BEBE', '#54D1D1', '#2CC5C5', '#009595', '#007373' ]; getRandomColor = function () { return colorScheme[Math.floor(colorScheme.length * Math.random())]; }; window.addEventListener('DOMContentLoaded', function () { function makeBox(el, x, y, className) { className = className ? className : ''; var d = document.createElement("div"); d.className = "frame"; d.style.left = 50 * x + "%"; d.style.top = 50 * y + "%"; var box = document.createElement("div"); box.classList.add('box'); if (className) box.classList.add(className); box.style.backgroundColor = getRandomColor(); d.appendChild(box); el.appendChild(d); } function divide(el, remove) { remove = remove === void 0 ? true : !!remove; makeBox(el, 0, 0); makeBox(el, 1, 0, 'diagonal'); makeBox(el, 0, 1, 'diagonal'); makeBox(el, 1, 1); if (!remove) { return; } el.removeChild(el.childNodes[0]); } var level = 1; divide($("#screen"), false, level); document.onclick = function () { if (level > 9) { $all('.box').forEach(function (box) { box.onclick = function () { divide(this.parentNode); }; }); return; } level++; $all('.box.diagonal').forEach(function (box) { divide(box.parentNode); }); } }, false);
ray7551/amazing101
tinyGrid/box.js
JavaScript
mit
1,653
'use strict'; // 1. npm install body-parser express request // 2. Download and install ngrok from https://ngrok.com/download // 3. ./ngrok http 8445 // 4. WIT_TOKEN=your_access_token FB_PAGE_ID=your_page_id FB_PAGE_TOKEN=your_page_token FB_VERIFY_TOKEN=verify_token node examples/messenger.js // 5. Subscribe your page to the Webhooks using verify_token and `https://<your_ngrok_io>/fb` as callback URL. // 6. Talk to your bot on Messenger! const bodyParser = require('body-parser'); const express = require('express'); const request = require('request'); const Wit = require('node-wit').Wit; // Webserver parameter const PORT = process.env.PORT || 8445; // Wit.ai parameters const WIT_TOKEN = process.env.WIT_TOKEN; // Messenger API parameters const FB_PAGE_ID = process.env.FB_PAGE_ID; if (!FB_PAGE_ID) { throw new Error('missing FB_PAGE_ID'); } const FB_PAGE_TOKEN = process.env.FB_PAGE_TOKEN; if (!FB_PAGE_TOKEN) { throw new Error('missing FB_PAGE_TOKEN'); } const FB_VERIFY_TOKEN = process.env.FB_VERIFY_TOKEN; // Messenger API specific code // See the Send API reference // https://developers.facebook.com/docs/messenger-platform/send-api-reference const fbReq = request.defaults({ uri: 'https://graph.facebook.com/me/messages', method: 'POST', json: true, qs: { access_token: FB_PAGE_TOKEN }, headers: {'Content-Type': 'application/json'}, }); const fbMessage = (recipientId, msg, cb) => { const opts = { form: { recipient: { id: recipientId, }, message: { text: msg, }, }, }; fbReq(opts, (err, resp, data) => { if (cb) { cb(err || data.error && data.error.message, data); } }); }; // See the Webhook reference // https://developers.facebook.com/docs/messenger-platform/webhook-reference const getFirstMessagingEntry = (body) => { const val = body.object == 'page' && body.entry && Array.isArray(body.entry) && body.entry.length > 0 && body.entry[0] && body.entry[0].id === FB_PAGE_ID && body.entry[0].messaging && Array.isArray(body.entry[0].messaging) && body.entry[0].messaging.length > 0 && body.entry[0].messaging[0] ; return val || null; }; // Wit.ai bot specific code // This will contain all user sessions. // Each session has an entry: // sessionId -> {fbid: facebookUserId, context: sessionState} const sessions = {}; const findOrCreateSession = (fbid) => { let sessionId; // Let's see if we already have a session for the user fbid Object.keys(sessions).forEach(k => { if (sessions[k].fbid === fbid) { // Yep, got it! sessionId = k; } }); if (!sessionId) { // No session found for user fbid, let's create a new one sessionId = new Date().toISOString(); sessions[sessionId] = {fbid: fbid, context: {}}; } return sessionId; }; const firstEntityValue = (entities, entity) => { const val = entities && entities[entity] && Array.isArray(entities[entity]) && entities[entity].length > 0 && entities[entity][0].value ; if (!val) { return null; } return typeof val === 'object' ? val.value : val; }; // Our bot actions const actions = { say(sessionId, context, message, cb) { // Our bot has something to say! // Let's retrieve the Facebook user whose session belongs to const recipientId = sessions[sessionId].fbid; if (recipientId) { // Yay, we found our recipient! // Let's forward our bot response to her. fbMessage(recipientId, message, (err, data) => { if (err) { console.log( 'Oops! An error occurred while forwarding the response to', recipientId, ':', err ); } // Let's give the wheel back to our bot cb(); }); } else { console.log('Oops! Couldn\'t find user for session:', sessionId); // Giving the wheel back to our bot cb(); } }, merge(sessionId, context, entities, message, cb) { cb(context); }, error(sessionId, context, error) { console.log(error.message); }, ['blank'](sessionId, context, cb) { // Herer is where an API call would go // context.return = apiCall(context.loc); context.return = 'return String'; cb(context); } }; // Setting up our bot const wit = new Wit(WIT_TOKEN, actions); // Starting our webserver and putting it all together const app = express(); app.set('port', PORT); app.listen(app.get('port')); app.use(bodyParser.json()); // Webhook setup app.get('/fb', (req, res) => { if (!FB_VERIFY_TOKEN) { throw new Error('missing FB_VERIFY_TOKEN'); } if (req.query['hub.mode'] === 'subscribe' && req.query['hub.verify_token'] === FB_VERIFY_TOKEN) { res.send(req.query['hub.challenge']); } else { res.sendStatus(400); } }); // Message handler app.post('/fb', (req, res) => { // Parsing the Messenger API response const messaging = getFirstMessagingEntry(req.body); if (messaging && messaging.message && messaging.recipient.id === FB_PAGE_ID) { // Yay! We got a new message! // We retrieve the Facebook user ID of the sender const sender = messaging.sender.id; // We retrieve the user's current session, or create one if it doesn't exist // This is needed for our bot to figure out the conversation history const sessionId = findOrCreateSession(sender); // We retrieve the message content const msg = messaging.message.text; const atts = messaging.message.attachments; if (atts) { // We received an attachment // Let's reply with an automatic message fbMessage( sender, 'Sorry I can only process text messages for now.' ); } else if (msg) { // We received a text message // Let's forward the message to the Wit.ai Bot Engine // This will run all actions until our bot has nothing left to do wit.runActions( sessionId, // the user's current session msg, // the user's message sessions[sessionId].context, // the user's current session state (error, context) => { if (error) { console.log('Oops! Got an error from Wit:', error); } else { // Our bot did everything it has to do. // Now it's waiting for further messages to proceed. console.log('Waiting for futher messages.'); // Based on the session state, you might want to reset the session. // This depends heavily on the business logic of your bot. // Example: // if (context['done']) { // delete sessions[sessionId]; // } // Updating the user's current session state sessions[sessionId].context = context; } } ); } } res.sendStatus(200); });
bhberson/messenger-wit-bot
index.js
JavaScript
mit
6,836
var structarm__pid__instance__q15 = [ [ "A0", "structarm__pid__instance__q15.html#ad77f3a2823c7f96de42c92a3fbf3246b", null ], [ "A1", "structarm__pid__instance__q15.html#ad8ac5ff736c0e51180398c31f777f18a", null ], [ "A2", "structarm__pid__instance__q15.html#a33e8b4c2d3e24b8b494f6edca6a89c1b", null ], [ "Kd", "structarm__pid__instance__q15.html#af5d4b53091f19eff7536636b7cc43111", null ], [ "Ki", "structarm__pid__instance__q15.html#a0dcc19d5c8f7bc401acea9e8318cd777", null ], [ "Kp", "structarm__pid__instance__q15.html#ad228aae24a1b6d855c93a8b9bbc1c4f1", null ], [ "state", "structarm__pid__instance__q15.html#a4a3f0a878b5b6b055e3478a2f244cd30", null ] ];
ryankurte/stm32f4-base
drivers/CMSIS/docs/DSP/html/structarm__pid__instance__q15.js
JavaScript
mit
695
define([ 'backbone', 'text!templates/item_chooser.tpl', 'models/item', 'models/trigger', 'models/instance', 'models/media', 'views/item_chooser_row', 'views/trigger_creator', 'vent', 'util', ], function( Backbone, Template, Item, Trigger, Instance, Media, ItemChooserRowView, TriggerCreatorView, vent, util ) { return Backbone.Marionette.CompositeView.extend( { template: _.template(Template), itemView: ItemChooserRowView, itemViewContainer: ".items", itemViewOptions: function(model, index) { return { parent: this.options.parent } }, events: { "click .new-item": "onClickNewItem" }, /* TODO move complex sets like this into a controller */ onClickNewItem: function() { var loc = util.default_location(); var trigger = new Trigger ({game_id:this.options.parent.get("game_id"), scene_id:this.options.parent.get("scene_id"), latitude:loc.latitude, longitude:loc.longitude }); var instance = new Instance ({game_id: this.options.parent.get("game_id")}); var item = new Item ({game_id: this.options.parent.get("game_id")}); var trigger_creator = new TriggerCreatorView({scene: this.options.parent, game_object: item, instance: instance, model: trigger}); vent.trigger("application:popup:show", trigger_creator, "Add Item to Scene"); }, // Marionette override appendBuffer: function(compositeView, buffer) { var $container = this.getItemViewContainer(compositeView); $container.find(".foot").before(buffer); }, appendHtml: function(compositeView, itemView, index) { if (compositeView.isBuffering) { compositeView.elBuffer.appendChild(itemView.el); } else { // If we've already rendered the main collection, just // append the new items directly into the element. var $container = this.getItemViewContainer(compositeView); $container.find(".foot").before(itemView.el); } } }); });
ARISGames/jsEditor
scripts/views/item_chooser.js
JavaScript
mit
2,056
import * as React from 'react'; import MarkdownDocs from 'docs/src/modules/components/MarkdownDocs'; import { demos, docs, requireDemo, } from '!@material-ui/markdown/loader!docs/src/pages/guides/api/api.md'; export default function Page() { return <MarkdownDocs demos={demos} docs={docs} requireDemo={requireDemo} />; }
mbrookes/material-ui
docs/pages/guides/api.js
JavaScript
mit
330
var mongoose = require('mongoose'); var TreatmentPrescription = mongoose.model('TreatmentPrescription', require('../models/TreatmentPrescription').TreatmentPrescriptionSchema); function list(response, params){ TreatmentPrescription.find(params) .sort('created_at') .exec(function(error, prescriptions){ if(error){ console.log(error); prescriptions = []; } response.json(prescriptions); }); } function create_from_body(request){ return { doctor: request.user._id, treatment: request.param('treatment'), items: request.body.items }; } exports.list = function(request, response){ var params = { treatment: request.param('treatment') }; list(response, params); }; exports.single = function(request, response){ if(request.param('prescription') === 'new') { response.json(new TreatmentPrescription({ treatment: request.param('treatment') })); return; } var params = { _id: request.param('prescription'), treatment: request.param('treatment') }; TreatmentPrescription.findOne(params, function(error, prescription){ if(error){ console.log(error); prescription = null; } response.json(prescription); }); }; exports.create = function(request, response){ var values = create_from_body(request); var treatment = new TreatmentPrescription(values); treatment.save(function(error, document){ if(error || !document){ response.json({ error: error }); } else { response.json(document); } }); }; exports.edit = function(request, response){ var values = create_from_body(request); TreatmentPrescription.findByIdAndUpdate(request.body._id, values, function(error, document){ if(error){ response.json({ error: error }); return; } response.json(document); }); }; exports.remove = function(request, response){ if(request.user.type === 'doctor'){ TreatmentPrescription.findByIdAndRemove(request.param('prescription'), function(error){ if(error){ console.log(error); response.send(400); return; } response.send(200) }); } else { response.send(200) } };
megawebmaster/care-center
routes/treatment_prescription.js
JavaScript
mit
2,054
/* global describe, it, assert, expect */ 'use strict'; // TESTS // describe( 'paddingLeft', function tests() { var el = document.querySelector( '#fixture' ); it( 'should expose an attribute for specifying the left padding between the canvas edge and the graph area', function test() { expect( el.paddingLeft ).to.be.a( 'number' ); }); it( 'should emit an `error` if not set to a positive integer', function test( done ) { var num = el.paddingLeft, values; values = [ function(){}, '5', -1, 3.14, NaN, // undefined, // TODO: enable once https://github.com/Polymer/polymer/issues/1053 is resolved true, [], {} ]; el.addEventListener( 'err', onError ); next(); function next() { el.paddingLeft = values.shift(); } function onError( evt ) { assert.instanceOf( evt.detail, TypeError ); if ( values.length ) { setTimeout( next, 0 ); return; } setTimeout( end, 0 ); } function end() { assert.strictEqual( el.paddingLeft, num ); el.removeEventListener( 'err', onError ); done(); } }); it( 'should emit a `changed` event when set to a new value', function test( done ) { el.addEventListener( 'changed', onChange ); el.paddingLeft = 0; function onChange( evt ) { assert.isObject( evt.detail ); assert.strictEqual( evt.detail.attr, 'paddingLeft' ); el.removeEventListener( 'changed', onChange ); done(); } }); it( 'should update the background width' ); it( 'should update the clipPath width' ); it( 'should update the graph position' ); it( 'should update the vertices' ); it( 'should update the edges' ); });
figure-io/polymer-graph-force-directed
test/paddingLeft/test.js
JavaScript
mit
1,637
const project = require('../config/project.config') const server = require('../server/index') const debug = require('debug')('app:bin:dev-server') server.listen(project.server_port) debug(`Server is now running at http://localhost:${project.server_port}.`)
willthefirst/book-buddy
bin/dev-server.js
JavaScript
mit
258
var is_touch; function is_touch_device() { return 'ontouchstart' in window // works on most browsers || navigator.maxTouchPoints; // works on IE10/11 and Surface } (function() { is_touch = is_touch_device(); })();
JumpStartGeorgia/Air-Pollution
app/assets/javascripts/application/helper.js
JavaScript
mit
239
module.exports = require('./lib/goldwasher-aws-lambda.js');
alexlangberg/node-goldwasher-aws-lambda
index.js
JavaScript
mit
59
/*Generated by KISSY Module Compiler*/ config({ 'editor/plugin/unordered-list': {requires: ['editor','editor/plugin/list-utils/btn']} });
007slm/kissy
src/editor/sub-modules/plugin/unordered-list/ke-meta/modules.js
JavaScript
mit
138
import {smartTable} from 'smart-table-core'; //change the structure of returned items const smartTableExtension = function ({table, tableState, data}) { const oldChangeRegister = table.onDisplayChange; //will overwrite the default onDisplayChange return { onDisplayChange(listener) { oldChangeRegister(function (items) { const itemValues = items.map(i => i.value); listener(itemValues); }); } }; }; // our composed factory const superSmartTable = function ({data}) { const core = smartTable({data}); return Object.assign(core, smartTableExtension({table: core})); //overwrite core method by mixin the extension within the core }; //use our super smart table const data = [ {surname: 'Deubaze', name: 'Raymond'}, {surname: 'Foo', name: 'Bar'}, {surname: 'Doe', name: 'John'} ]; const table = superSmartTable({data}); // core methods available table.onDisplayChange(items => console.log(items)); // no need to extract "value" property as the method has been overwritten table.exec();
smart-table/www
src/views/code/mixin.js
JavaScript
mit
1,099
var debug = require('util').debug, inspect = require('util').inspect, path = require('path'), fs = require('fs'), exec = require('child_process').exec, spawn = require('child_process').spawn, Connection = require('../../lib/mongodb').Connection, Db = require('../../lib/mongodb').Db, Server = require('../../lib/mongodb').Server; var ServerManager = exports.ServerManager = function(options) { options = options == null ? {} : options; // Basic unpack values this.path = path.resolve("data"); this.port = options["start_port"] != null ? options["start_port"] : 27017; this.db_path = getPath(this, "data-" + this.port); this.log_path = getPath(this, "log-" + this.port); this.journal = options["journal"] != null ? options["journal"] : false; this.auth = options['auth'] != null ? options['auth'] : false; this.purgedirectories = options['purgedirectories'] != null ? options['purgedirectories'] : true; // Server status values this.up = false; this.pid = null; } // Start up the server instance ServerManager.prototype.start = function(killall, callback) { var self = this; // Unpack callback and variables var args = Array.prototype.slice.call(arguments, 0); callback = args.pop(); killall = args.length ? args.shift() : true; // Create start command var startCmd = generateStartCmd({log_path: self.log_path, db_path: self.db_path, port: self.port, journal: self.journal, auth:self.auth}); // console.log("----------------------------------------------------------------------- start") // console.log(startCmd) exec(killall ? 'killall mongod' : '', function(err, stdout, stderr) { if(self.purgedirectories) { // Remove directory exec("rm -rf " + self.db_path, function(err, stdout, stderr) { if(err != null) return callback(err, null); // Create directory exec("mkdir -p " + self.db_path, function(err, stdout, stderr) { if(err != null) return callback(err, null); // Start up mongod process var mongodb = exec(startCmd, function (error, stdout, stderr) { // console.log('stdout: ' + stdout); // console.log('stderr: ' + stderr); if (error !== null) { console.log('exec error: ' + error); } }); // Wait for a half a second then save the pids setTimeout(function() { // Mark server as running self.up = true; self.pid = fs.readFileSync(path.join(self.db_path, "mongod.lock"), 'ascii').trim(); // Callback callback(); }, 500); }); }); } else { // Ensure we remove the lock file as we are not purging the directory fs.unlinkSync(path.join(self.db_path, "mongod.lock")); // Start up mongod process var mongodb = exec(startCmd, function (error, stdout, stderr) { if (error !== null) { console.log('exec error: ' + error); } }); // Wait for a half a second then save the pids setTimeout(function() { // Mark server as running self.up = true; self.pid = fs.readFileSync(path.join(self.db_path, "mongod.lock"), 'ascii').trim(); // Callback callback(); }, 5000); } }); } ServerManager.prototype.stop = function(signal, callback) { var self = this; // Unpack callback and variables var args = Array.prototype.slice.call(arguments, 0); callback = args.pop(); signal = args.length ? args.shift() : 2; // Stop the server var command = "kill -" + signal + " " + self.pid; // Kill process exec(command, function (error, stdout, stderr) { // console.log('stdout: ' + stdout); // console.log('stderr: ' + stderr); if (error !== null) { console.log('exec error: ' + error); } self.up = false; // Wait for a second setTimeout(callback, 1000); }); } ServerManager.prototype.killAll = function(callback) { exec('killall mongod', function(err, stdout, stderr) { callback(null, null); }); } // Get absolute path var getPath = function(self, name) { return path.join(self.path, name); } // Generate start command var generateStartCmd = function(options) { // Create boot command var startCmd = "mongod --noprealloc --logpath '" + options['log_path'] + "' " + " --dbpath " + options['db_path'] + " --port " + options['port'] + " --fork"; startCmd = options['journal'] ? startCmd + " --journal" : startCmd; startCmd = options['auth'] ? startCmd + " --auth" : startCmd; return startCmd; }
liminglu/node_iblog
node_modules/mongoose/node_modules/mongodb/test/tools/server_manager.js
JavaScript
mit
4,715
import * as React from 'react'; import PropTypes from 'prop-types'; import { useTheme } from '@mui/material/styles'; import Box from '@mui/material/Box'; import Table from '@mui/material/Table'; import TableBody from '@mui/material/TableBody'; import TableCell from '@mui/material/TableCell'; import TableContainer from '@mui/material/TableContainer'; import TableFooter from '@mui/material/TableFooter'; import TablePagination from '@mui/material/TablePagination'; import TableRow from '@mui/material/TableRow'; import Paper from '@mui/material/Paper'; import IconButton from '@mui/material/IconButton'; import FirstPageIcon from '@mui/icons-material/FirstPage'; import KeyboardArrowLeft from '@mui/icons-material/KeyboardArrowLeft'; import KeyboardArrowRight from '@mui/icons-material/KeyboardArrowRight'; import LastPageIcon from '@mui/icons-material/LastPage'; function TablePaginationActions(props) { const theme = useTheme(); const { count, page, rowsPerPage, onPageChange } = props; const handleFirstPageButtonClick = (event) => { onPageChange(event, 0); }; const handleBackButtonClick = (event) => { onPageChange(event, page - 1); }; const handleNextButtonClick = (event) => { onPageChange(event, page + 1); }; const handleLastPageButtonClick = (event) => { onPageChange(event, Math.max(0, Math.ceil(count / rowsPerPage) - 1)); }; return ( <Box sx={{ flexShrink: 0, ml: 2.5 }}> <IconButton onClick={handleFirstPageButtonClick} disabled={page === 0} aria-label="first page" > {theme.direction === 'rtl' ? <LastPageIcon /> : <FirstPageIcon />} </IconButton> <IconButton onClick={handleBackButtonClick} disabled={page === 0} aria-label="previous page" > {theme.direction === 'rtl' ? <KeyboardArrowRight /> : <KeyboardArrowLeft />} </IconButton> <IconButton onClick={handleNextButtonClick} disabled={page >= Math.ceil(count / rowsPerPage) - 1} aria-label="next page" > {theme.direction === 'rtl' ? <KeyboardArrowLeft /> : <KeyboardArrowRight />} </IconButton> <IconButton onClick={handleLastPageButtonClick} disabled={page >= Math.ceil(count / rowsPerPage) - 1} aria-label="last page" > {theme.direction === 'rtl' ? <FirstPageIcon /> : <LastPageIcon />} </IconButton> </Box> ); } TablePaginationActions.propTypes = { count: PropTypes.number.isRequired, onPageChange: PropTypes.func.isRequired, page: PropTypes.number.isRequired, rowsPerPage: PropTypes.number.isRequired, }; function createData(name, calories, fat) { return { name, calories, fat }; } const rows = [ createData('Cupcake', 305, 3.7), createData('Donut', 452, 25.0), createData('Eclair', 262, 16.0), createData('Frozen yoghurt', 159, 6.0), createData('Gingerbread', 356, 16.0), createData('Honeycomb', 408, 3.2), createData('Ice cream sandwich', 237, 9.0), createData('Jelly Bean', 375, 0.0), createData('KitKat', 518, 26.0), createData('Lollipop', 392, 0.2), createData('Marshmallow', 318, 0), createData('Nougat', 360, 19.0), createData('Oreo', 437, 18.0), ].sort((a, b) => (a.calories < b.calories ? -1 : 1)); export default function CustomPaginationActionsTable() { const [page, setPage] = React.useState(0); const [rowsPerPage, setRowsPerPage] = React.useState(5); // Avoid a layout jump when reaching the last page with empty rows. const emptyRows = page > 0 ? Math.max(0, (1 + page) * rowsPerPage - rows.length) : 0; const handleChangePage = (event, newPage) => { setPage(newPage); }; const handleChangeRowsPerPage = (event) => { setRowsPerPage(parseInt(event.target.value, 10)); setPage(0); }; return ( <TableContainer component={Paper}> <Table sx={{ minWidth: 500 }} aria-label="custom pagination table"> <TableBody> {(rowsPerPage > 0 ? rows.slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage) : rows ).map((row) => ( <TableRow key={row.name}> <TableCell component="th" scope="row"> {row.name} </TableCell> <TableCell style={{ width: 160 }} align="right"> {row.calories} </TableCell> <TableCell style={{ width: 160 }} align="right"> {row.fat} </TableCell> </TableRow> ))} {emptyRows > 0 && ( <TableRow style={{ height: 53 * emptyRows }}> <TableCell colSpan={6} /> </TableRow> )} </TableBody> <TableFooter> <TableRow> <TablePagination rowsPerPageOptions={[5, 10, 25, { label: 'All', value: -1 }]} colSpan={3} count={rows.length} rowsPerPage={rowsPerPage} page={page} SelectProps={{ inputProps: { 'aria-label': 'rows per page', }, native: true, }} onPageChange={handleChangePage} onRowsPerPageChange={handleChangeRowsPerPage} ActionsComponent={TablePaginationActions} /> </TableRow> </TableFooter> </Table> </TableContainer> ); }
oliviertassinari/material-ui
docs/data/material/components/tables/CustomPaginationActionsTable.js
JavaScript
mit
5,418
#!/usr/bin/env node var argv = require('yargs/yargs')(process.argv.slice(2)) .boolean(['r','v']) .argv ; console.dir([ argv.r, argv.v ]); console.dir(argv._);
yargs/yargs
example/boolean_single.js
JavaScript
mit
167
/*! * Uploader - Uploader library implements html5 file upload and provides multiple simultaneous, stable, fault tolerant and resumable uploads * @version v0.5.6 * @author dolymood <dolymood@gmail.com> * @link https://github.com/simple-uploader/Uploader * @license MIT */ !function(e){if("object"==typeof exports)module.exports=e();else if("function"==typeof define&&define.amd)define(e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.Uploader=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){ var utils = _dereq_('./utils') function Chunk (uploader, file, offset) { utils.defineNonEnumerable(this, 'uploader', uploader) utils.defineNonEnumerable(this, 'file', file) utils.defineNonEnumerable(this, 'bytes', null) this.offset = offset this.tested = false this.retries = 0 this.pendingRetry = false this.preprocessState = 0 this.readState = 0 this.loaded = 0 this.total = 0 this.chunkSize = this.uploader.opts.chunkSize this.startByte = this.offset * this.chunkSize this.endByte = this.computeEndByte() this.xhr = null } var STATUS = Chunk.STATUS = { PENDING: 'pending', UPLOADING: 'uploading', READING: 'reading', SUCCESS: 'success', ERROR: 'error', COMPLETE: 'complete', PROGRESS: 'progress', RETRY: 'retry' } utils.extend(Chunk.prototype, { _event: function (evt, args) { args = utils.toArray(arguments) args.unshift(this) this.file._chunkEvent.apply(this.file, args) }, computeEndByte: function () { var endByte = Math.min(this.file.size, (this.offset + 1) * this.chunkSize) if (this.file.size - endByte < this.chunkSize && !this.uploader.opts.forceChunkSize) { // The last chunk will be bigger than the chunk size, // but less than 2 * this.chunkSize endByte = this.file.size } return endByte }, getParams: function () { return { chunkNumber: this.offset + 1, chunkSize: this.uploader.opts.chunkSize, currentChunkSize: this.endByte - this.startByte, totalSize: this.file.size, identifier: this.file.uniqueIdentifier, filename: this.file.name, relativePath: this.file.relativePath, totalChunks: this.file.chunks.length } }, getTarget: function (target, params) { if (!params.length) { return target } if (target.indexOf('?') < 0) { target += '?' } else { target += '&' } return target + params.join('&') }, test: function () { this.xhr = new XMLHttpRequest() this.xhr.addEventListener('load', testHandler, false) this.xhr.addEventListener('error', testHandler, false) var testMethod = utils.evalOpts(this.uploader.opts.testMethod, this.file, this) var data = this.prepareXhrRequest(testMethod, true) this.xhr.send(data) var $ = this function testHandler (event) { var status = $.status(true) if (status === STATUS.ERROR) { $._event(status, $.message()) $.uploader.uploadNextChunk() } else if (status === STATUS.SUCCESS) { $._event(status, $.message()) $.tested = true } else if (!$.file.paused) { // Error might be caused by file pause method // Chunks does not exist on the server side $.tested = true $.send() } } }, preprocessFinished: function () { // Compute the endByte after the preprocess function to allow an // implementer of preprocess to set the fileObj size this.endByte = this.computeEndByte() this.preprocessState = 2 this.send() }, readFinished: function (bytes) { this.readState = 2 this.bytes = bytes this.send() }, send: function () { var preprocess = this.uploader.opts.preprocess var read = this.uploader.opts.readFileFn if (utils.isFunction(preprocess)) { switch (this.preprocessState) { case 0: this.preprocessState = 1 preprocess(this) return case 1: return } } switch (this.readState) { case 0: this.readState = 1 read(this.file, this.file.fileType, this.startByte, this.endByte, this) return case 1: return } if (this.uploader.opts.testChunks && !this.tested) { this.test() return } this.loaded = 0 this.total = 0 this.pendingRetry = false // Set up request and listen for event this.xhr = new XMLHttpRequest() this.xhr.upload.addEventListener('progress', progressHandler, false) this.xhr.addEventListener('load', doneHandler, false) this.xhr.addEventListener('error', doneHandler, false) var uploadMethod = utils.evalOpts(this.uploader.opts.uploadMethod, this.file, this) var data = this.prepareXhrRequest(uploadMethod, false, this.uploader.opts.method, this.bytes) this.xhr.send(data) var $ = this function progressHandler (event) { if (event.lengthComputable) { $.loaded = event.loaded $.total = event.total } $._event(STATUS.PROGRESS, event) } function doneHandler (event) { var msg = $.message() $.processingResponse = true $.uploader.opts.processResponse(msg, function (err, res) { $.processingResponse = false if (!$.xhr) { return } $.processedState = { err: err, res: res } var status = $.status() if (status === STATUS.SUCCESS || status === STATUS.ERROR) { // delete this.data $._event(status, res) status === STATUS.ERROR && $.uploader.uploadNextChunk() } else { $._event(STATUS.RETRY, res) $.pendingRetry = true $.abort() $.retries++ var retryInterval = $.uploader.opts.chunkRetryInterval if (retryInterval !== null) { setTimeout(function () { $.send() }, retryInterval) } else { $.send() } } }, $.file, $) } }, abort: function () { var xhr = this.xhr this.xhr = null this.processingResponse = false this.processedState = null if (xhr) { xhr.abort() } }, status: function (isTest) { if (this.readState === 1) { return STATUS.READING } else if (this.pendingRetry || this.preprocessState === 1) { // if pending retry then that's effectively the same as actively uploading, // there might just be a slight delay before the retry starts return STATUS.UPLOADING } else if (!this.xhr) { return STATUS.PENDING } else if (this.xhr.readyState < 4 || this.processingResponse) { // Status is really 'OPENED', 'HEADERS_RECEIVED' // or 'LOADING' - meaning that stuff is happening return STATUS.UPLOADING } else { var _status if (this.uploader.opts.successStatuses.indexOf(this.xhr.status) > -1) { // HTTP 200, perfect // HTTP 202 Accepted - The request has been accepted for processing, but the processing has not been completed. _status = STATUS.SUCCESS } else if (this.uploader.opts.permanentErrors.indexOf(this.xhr.status) > -1 || !isTest && this.retries >= this.uploader.opts.maxChunkRetries) { // HTTP 415/500/501, permanent error _status = STATUS.ERROR } else { // this should never happen, but we'll reset and queue a retry // a likely case for this would be 503 service unavailable this.abort() _status = STATUS.PENDING } var processedState = this.processedState if (processedState && processedState.err) { _status = STATUS.ERROR } return _status } }, message: function () { return this.xhr ? this.xhr.responseText : '' }, progress: function () { if (this.pendingRetry) { return 0 } var s = this.status() if (s === STATUS.SUCCESS || s === STATUS.ERROR) { return 1 } else if (s === STATUS.PENDING) { return 0 } else { return this.total > 0 ? this.loaded / this.total : 0 } }, sizeUploaded: function () { var size = this.endByte - this.startByte // can't return only chunk.loaded value, because it is bigger than chunk size if (this.status() !== STATUS.SUCCESS) { size = this.progress() * size } return size }, prepareXhrRequest: function (method, isTest, paramsMethod, blob) { // Add data from the query options var query = utils.evalOpts(this.uploader.opts.query, this.file, this, isTest) query = utils.extend(this.getParams(), query) // processParams query = this.uploader.opts.processParams(query, this.file, this, isTest) var target = utils.evalOpts(this.uploader.opts.target, this.file, this, isTest) var data = null if (method === 'GET' || paramsMethod === 'octet') { // Add data from the query options var params = [] utils.each(query, function (v, k) { params.push([encodeURIComponent(k), encodeURIComponent(v)].join('=')) }) target = this.getTarget(target, params) data = blob || null } else { // Add data from the query options data = new FormData() utils.each(query, function (v, k) { data.append(k, v) }) if (typeof blob !== 'undefined') { data.append(this.uploader.opts.fileParameterName, blob, this.file.name) } } this.xhr.open(method, target, true) this.xhr.withCredentials = this.uploader.opts.withCredentials // Add data from header options utils.each(utils.evalOpts(this.uploader.opts.headers, this.file, this, isTest), function (v, k) { this.xhr.setRequestHeader(k, v) }, this) return data } }) module.exports = Chunk },{"./utils":5}],2:[function(_dereq_,module,exports){ var each = _dereq_('./utils').each var event = { _eventData: null, on: function (name, func) { if (!this._eventData) this._eventData = {} if (!this._eventData[name]) this._eventData[name] = [] var listened = false each(this._eventData[name], function (fuc) { if (fuc === func) { listened = true return false } }) if (!listened) { this._eventData[name].push(func) } }, off: function (name, func) { if (!this._eventData) this._eventData = {} if (!this._eventData[name] || !this._eventData[name].length) return if (func) { each(this._eventData[name], function (fuc, i) { if (fuc === func) { this._eventData[name].splice(i, 1) return false } }, this) } else { this._eventData[name] = [] } }, trigger: function (name) { if (!this._eventData) this._eventData = {} if (!this._eventData[name]) return true var args = this._eventData[name].slice.call(arguments, 1) var preventDefault = false each(this._eventData[name], function (fuc) { preventDefault = fuc.apply(this, args) === false || preventDefault }, this) return !preventDefault } } module.exports = event },{"./utils":5}],3:[function(_dereq_,module,exports){ var utils = _dereq_('./utils') var event = _dereq_('./event') var File = _dereq_('./file') var Chunk = _dereq_('./chunk') var version = '0.5.6' var isServer = typeof window === 'undefined' // ie10+ var ie10plus = isServer ? false : window.navigator.msPointerEnabled var support = (function () { if (isServer) { return false } var sliceName = 'slice' var _support = utils.isDefined(window.File) && utils.isDefined(window.Blob) && utils.isDefined(window.FileList) var bproto = null if (_support) { bproto = window.Blob.prototype utils.each(['slice', 'webkitSlice', 'mozSlice'], function (n) { if (bproto[n]) { sliceName = n return false } }) _support = !!bproto[sliceName] } if (_support) Uploader.sliceName = sliceName bproto = null return _support })() var supportDirectory = (function () { if (isServer) { return false } var input = window.document.createElement('input') input.type = 'file' var sd = 'webkitdirectory' in input || 'directory' in input input = null return sd })() function Uploader (opts) { this.support = support /* istanbul ignore if */ if (!this.support) { return } this.supportDirectory = supportDirectory utils.defineNonEnumerable(this, 'filePaths', {}) this.opts = utils.extend({}, Uploader.defaults, opts || {}) this.preventEvent = utils.bind(this._preventEvent, this) File.call(this, this) } /** * Default read function using the webAPI * * @function webAPIFileRead(fileObj, fileType, startByte, endByte, chunk) * */ var webAPIFileRead = function (fileObj, fileType, startByte, endByte, chunk) { chunk.readFinished(fileObj.file[Uploader.sliceName](startByte, endByte, fileType)) } Uploader.version = version Uploader.defaults = { chunkSize: 1024 * 1024, forceChunkSize: false, simultaneousUploads: 3, singleFile: false, fileParameterName: 'file', progressCallbacksInterval: 500, speedSmoothingFactor: 0.1, query: {}, headers: {}, withCredentials: false, preprocess: null, method: 'multipart', testMethod: 'GET', uploadMethod: 'POST', prioritizeFirstAndLastChunk: false, allowDuplicateUploads: false, target: '/', testChunks: true, generateUniqueIdentifier: null, maxChunkRetries: 0, chunkRetryInterval: null, permanentErrors: [404, 415, 500, 501], successStatuses: [200, 201, 202], onDropStopPropagation: false, initFileFn: null, readFileFn: webAPIFileRead, checkChunkUploadedByResponse: null, initialPaused: false, processResponse: function (response, cb) { cb(null, response) }, processParams: function (params) { return params } } Uploader.utils = utils Uploader.event = event Uploader.File = File Uploader.Chunk = Chunk // inherit file Uploader.prototype = utils.extend({}, File.prototype) // inherit event utils.extend(Uploader.prototype, event) utils.extend(Uploader.prototype, { constructor: Uploader, _trigger: function (name) { var args = utils.toArray(arguments) var preventDefault = !this.trigger.apply(this, arguments) if (name !== 'catchAll') { args.unshift('catchAll') preventDefault = !this.trigger.apply(this, args) || preventDefault } return !preventDefault }, _triggerAsync: function () { var args = arguments utils.nextTick(function () { this._trigger.apply(this, args) }, this) }, addFiles: function (files, evt) { var _files = [] var oldFileListLen = this.fileList.length utils.each(files, function (file) { // Uploading empty file IE10/IE11 hangs indefinitely // Directories have size `0` and name `.` // Ignore already added files if opts.allowDuplicateUploads is set to false if ((!ie10plus || ie10plus && file.size > 0) && !(file.size % 4096 === 0 && (file.name === '.' || file.fileName === '.'))) { var uniqueIdentifier = this.generateUniqueIdentifier(file) if (this.opts.allowDuplicateUploads || !this.getFromUniqueIdentifier(uniqueIdentifier)) { var _file = new File(this, file, this) _file.uniqueIdentifier = uniqueIdentifier if (this._trigger('fileAdded', _file, evt)) { _files.push(_file) } else { File.prototype.removeFile.call(this, _file) } } } }, this) // get new fileList var newFileList = this.fileList.slice(oldFileListLen) if (this._trigger('filesAdded', _files, newFileList, evt)) { utils.each(_files, function (file) { if (this.opts.singleFile && this.files.length > 0) { this.removeFile(this.files[0]) } this.files.push(file) }, this) this._trigger('filesSubmitted', _files, newFileList, evt) } else { utils.each(newFileList, function (file) { File.prototype.removeFile.call(this, file) }, this) } }, addFile: function (file, evt) { this.addFiles([file], evt) }, cancel: function () { for (var i = this.fileList.length - 1; i >= 0; i--) { this.fileList[i].cancel() } }, removeFile: function (file) { File.prototype.removeFile.call(this, file) this._trigger('fileRemoved', file) }, generateUniqueIdentifier: function (file) { var custom = this.opts.generateUniqueIdentifier if (utils.isFunction(custom)) { return custom(file) } /* istanbul ignore next */ // Some confusion in different versions of Firefox var relativePath = file.relativePath || file.webkitRelativePath || file.fileName || file.name /* istanbul ignore next */ return file.size + '-' + relativePath.replace(/[^0-9a-zA-Z_-]/img, '') }, getFromUniqueIdentifier: function (uniqueIdentifier) { var ret = false utils.each(this.files, function (file) { if (file.uniqueIdentifier === uniqueIdentifier) { ret = file return false } }) return ret }, uploadNextChunk: function (preventEvents) { var found = false var pendingStatus = Chunk.STATUS.PENDING var checkChunkUploaded = this.uploader.opts.checkChunkUploadedByResponse if (this.opts.prioritizeFirstAndLastChunk) { utils.each(this.files, function (file) { if (file.paused) { return } if (checkChunkUploaded && !file._firstResponse && file.isUploading()) { // waiting for current file's first chunk response return } if (file.chunks.length && file.chunks[0].status() === pendingStatus) { file.chunks[0].send() found = true return false } if (file.chunks.length > 1 && file.chunks[file.chunks.length - 1].status() === pendingStatus) { file.chunks[file.chunks.length - 1].send() found = true return false } }) if (found) { return found } } // Now, simply look for the next, best thing to upload utils.each(this.files, function (file) { if (!file.paused) { if (checkChunkUploaded && !file._firstResponse && file.isUploading()) { // waiting for current file's first chunk response return } utils.each(file.chunks, function (chunk) { if (chunk.status() === pendingStatus) { chunk.send() found = true return false } }) } if (found) { return false } }) if (found) { return true } // The are no more outstanding chunks to upload, check is everything is done var outstanding = false utils.each(this.files, function (file) { if (!file.isComplete()) { outstanding = true return false } }) // should check files now // if now files in list // should not trigger complete event if (!outstanding && !preventEvents && this.files.length) { // All chunks have been uploaded, complete this._triggerAsync('complete') } return outstanding }, upload: function (preventEvents) { // Make sure we don't start too many uploads at once var ret = this._shouldUploadNext() if (ret === false) { return } !preventEvents && this._trigger('uploadStart') var started = false for (var num = 1; num <= this.opts.simultaneousUploads - ret; num++) { started = this.uploadNextChunk(!preventEvents) || started if (!started && preventEvents) { // completed break } } if (!started && !preventEvents) { this._triggerAsync('complete') } }, /** * should upload next chunk * @function * @returns {Boolean|Number} */ _shouldUploadNext: function () { var num = 0 var should = true var simultaneousUploads = this.opts.simultaneousUploads var uploadingStatus = Chunk.STATUS.UPLOADING utils.each(this.files, function (file) { utils.each(file.chunks, function (chunk) { if (chunk.status() === uploadingStatus) { num++ if (num >= simultaneousUploads) { should = false return false } } }) return should }) // if should is true then return uploading chunks's length return should && num }, /** * Assign a browse action to one or more DOM nodes. * @function * @param {Element|Array.<Element>} domNodes * @param {boolean} isDirectory Pass in true to allow directories to * @param {boolean} singleFile prevent multi file upload * @param {Object} attributes set custom attributes: * http://www.w3.org/TR/html-markup/input.file.html#input.file-attributes * eg: accept: 'image/*' * be selected (Chrome only). */ assignBrowse: function (domNodes, isDirectory, singleFile, attributes) { if (typeof domNodes.length === 'undefined') { domNodes = [domNodes] } utils.each(domNodes, function (domNode) { var input if (domNode.tagName === 'INPUT' && domNode.type === 'file') { input = domNode } else { input = document.createElement('input') input.setAttribute('type', 'file') // display:none - not working in opera 12 utils.extend(input.style, { visibility: 'hidden', position: 'absolute', width: '1px', height: '1px' }) // for opera 12 browser, input must be assigned to a document domNode.appendChild(input) // https://developer.mozilla.org/en/using_files_from_web_applications) // event listener is executed two times // first one - original mouse click event // second - input.click(), input is inside domNode domNode.addEventListener('click', function (e) { if (domNode.tagName.toLowerCase() === 'label') { return } input.click() }, false) } if (!this.opts.singleFile && !singleFile) { input.setAttribute('multiple', 'multiple') } if (isDirectory) { input.setAttribute('webkitdirectory', 'webkitdirectory') } attributes && utils.each(attributes, function (value, key) { input.setAttribute(key, value) }) // When new files are added, simply append them to the overall list var that = this input.addEventListener('change', function (e) { that._trigger(e.type, e) if (e.target.value) { that.addFiles(e.target.files, e) e.target.value = '' } }, false) }, this) }, onDrop: function (evt) { this._trigger(evt.type, evt) if (this.opts.onDropStopPropagation) { evt.stopPropagation() } evt.preventDefault() this._parseDataTransfer(evt.dataTransfer, evt) }, _parseDataTransfer: function (dataTransfer, evt) { if (dataTransfer.items && dataTransfer.items[0] && dataTransfer.items[0].webkitGetAsEntry) { this.webkitReadDataTransfer(dataTransfer, evt) } else { this.addFiles(dataTransfer.files, evt) } }, webkitReadDataTransfer: function (dataTransfer, evt) { var self = this var queue = dataTransfer.items.length var files = [] utils.each(dataTransfer.items, function (item) { var entry = item.webkitGetAsEntry() if (!entry) { decrement() return } if (entry.isFile) { // due to a bug in Chrome's File System API impl - #149735 fileReadSuccess(item.getAsFile(), entry.fullPath) } else { readDirectory(entry.createReader()) } }) function readDirectory (reader) { reader.readEntries(function (entries) { if (entries.length) { queue += entries.length utils.each(entries, function (entry) { if (entry.isFile) { var fullPath = entry.fullPath entry.file(function (file) { fileReadSuccess(file, fullPath) }, readError) } else if (entry.isDirectory) { readDirectory(entry.createReader()) } }) readDirectory(reader) } else { decrement() } }, readError) } function fileReadSuccess (file, fullPath) { // relative path should not start with "/" file.relativePath = fullPath.substring(1) files.push(file) decrement() } function readError (fileError) { throw fileError } function decrement () { if (--queue === 0) { self.addFiles(files, evt) } } }, _assignHelper: function (domNodes, handles, remove) { if (typeof domNodes.length === 'undefined') { domNodes = [domNodes] } var evtMethod = remove ? 'removeEventListener' : 'addEventListener' utils.each(domNodes, function (domNode) { utils.each(handles, function (handler, name) { domNode[evtMethod](name, handler, false) }, this) }, this) }, _preventEvent: function (e) { utils.preventEvent(e) this._trigger(e.type, e) }, /** * Assign one or more DOM nodes as a drop target. * @function * @param {Element|Array.<Element>} domNodes */ assignDrop: function (domNodes) { this._onDrop = utils.bind(this.onDrop, this) this._assignHelper(domNodes, { dragover: this.preventEvent, dragenter: this.preventEvent, dragleave: this.preventEvent, drop: this._onDrop }) }, /** * Un-assign drop event from DOM nodes * @function * @param domNodes */ unAssignDrop: function (domNodes) { this._assignHelper(domNodes, { dragover: this.preventEvent, dragenter: this.preventEvent, dragleave: this.preventEvent, drop: this._onDrop }, true) this._onDrop = null } }) module.exports = Uploader },{"./chunk":1,"./event":2,"./file":4,"./utils":5}],4:[function(_dereq_,module,exports){ var utils = _dereq_('./utils') var Chunk = _dereq_('./chunk') function File (uploader, file, parent) { utils.defineNonEnumerable(this, 'uploader', uploader) this.isRoot = this.isFolder = uploader === this utils.defineNonEnumerable(this, 'parent', parent || null) utils.defineNonEnumerable(this, 'files', []) utils.defineNonEnumerable(this, 'fileList', []) utils.defineNonEnumerable(this, 'chunks', []) utils.defineNonEnumerable(this, '_errorFiles', []) utils.defineNonEnumerable(this, 'file', null) this.id = utils.uid() if (this.isRoot || !file) { this.file = null } else { if (utils.isString(file)) { // folder this.isFolder = true this.file = null this.path = file if (this.parent.path) { file = file.substr(this.parent.path.length) } this.name = file.charAt(file.length - 1) === '/' ? file.substr(0, file.length - 1) : file } else { this.file = file this.fileType = this.file.type this.name = file.fileName || file.name this.size = file.size this.relativePath = file.relativePath || file.webkitRelativePath || this.name this._parseFile() } } this.paused = uploader.opts.initialPaused this.error = false this.allError = false this.aborted = false this.completed = false this.averageSpeed = 0 this.currentSpeed = 0 this._lastProgressCallback = Date.now() this._prevUploadedSize = 0 this._prevProgress = 0 this.bootstrap() } utils.extend(File.prototype, { _parseFile: function () { var ppaths = parsePaths(this.relativePath) if (ppaths.length) { var filePaths = this.uploader.filePaths utils.each(ppaths, function (path, i) { var folderFile = filePaths[path] if (!folderFile) { folderFile = new File(this.uploader, path, this.parent) filePaths[path] = folderFile this._updateParentFileList(folderFile) } this.parent = folderFile folderFile.files.push(this) if (!ppaths[i + 1]) { folderFile.fileList.push(this) } }, this) } else { this._updateParentFileList() } }, _updateParentFileList: function (file) { if (!file) { file = this } var p = this.parent if (p) { p.fileList.push(file) } }, _eachAccess: function (eachFn, fileFn) { if (this.isFolder) { utils.each(this.files, function (f, i) { return eachFn.call(this, f, i) }, this) return } fileFn.call(this, this) }, bootstrap: function () { if (this.isFolder) return var opts = this.uploader.opts if (utils.isFunction(opts.initFileFn)) { opts.initFileFn.call(this, this) } this.abort(true) this._resetError() // Rebuild stack of chunks from file this._prevProgress = 0 var round = opts.forceChunkSize ? Math.ceil : Math.floor var chunks = Math.max(round(this.size / opts.chunkSize), 1) for (var offset = 0; offset < chunks; offset++) { this.chunks.push(new Chunk(this.uploader, this, offset)) } }, _measureSpeed: function () { var smoothingFactor = this.uploader.opts.speedSmoothingFactor var timeSpan = Date.now() - this._lastProgressCallback if (!timeSpan) { return } var uploaded = this.sizeUploaded() // Prevent negative upload speed after file upload resume this.currentSpeed = Math.max((uploaded - this._prevUploadedSize) / timeSpan * 1000, 0) this.averageSpeed = smoothingFactor * this.currentSpeed + (1 - smoothingFactor) * this.averageSpeed this._prevUploadedSize = uploaded if (this.parent && this.parent._checkProgress()) { this.parent._measureSpeed() } }, _checkProgress: function (file) { return Date.now() - this._lastProgressCallback >= this.uploader.opts.progressCallbacksInterval }, _chunkEvent: function (chunk, evt, message) { var uploader = this.uploader var STATUS = Chunk.STATUS var that = this var rootFile = this.getRoot() var triggerProgress = function () { that._measureSpeed() uploader._trigger('fileProgress', rootFile, that, chunk) that._lastProgressCallback = Date.now() } switch (evt) { case STATUS.PROGRESS: if (this._checkProgress()) { triggerProgress() } break case STATUS.ERROR: this._error() this.abort(true) uploader._trigger('fileError', rootFile, this, message, chunk) break case STATUS.SUCCESS: this._updateUploadedChunks(message, chunk) if (this.error) { return } clearTimeout(this._progeressId) this._progeressId = 0 var timeDiff = Date.now() - this._lastProgressCallback if (timeDiff < uploader.opts.progressCallbacksInterval) { this._progeressId = setTimeout(triggerProgress, uploader.opts.progressCallbacksInterval - timeDiff) } if (this.isComplete()) { clearTimeout(this._progeressId) triggerProgress() this.currentSpeed = 0 this.averageSpeed = 0 uploader._trigger('fileSuccess', rootFile, this, message, chunk) if (rootFile.isComplete()) { uploader._trigger('fileComplete', rootFile, this) } } else if (!this._progeressId) { triggerProgress() } break case STATUS.RETRY: uploader._trigger('fileRetry', rootFile, this, chunk) break } }, _updateUploadedChunks: function (message, chunk) { var checkChunkUploaded = this.uploader.opts.checkChunkUploadedByResponse if (checkChunkUploaded) { var xhr = chunk.xhr utils.each(this.chunks, function (_chunk) { if (!_chunk.tested) { var uploaded = checkChunkUploaded.call(this, _chunk, message) if (_chunk === chunk && !uploaded) { // fix the first chunk xhr status // treated as success but checkChunkUploaded is false // so the current chunk should be uploaded again _chunk.xhr = null } if (uploaded) { // first success and other chunks are uploaded // then set xhr, so the uploaded chunks // will be treated as success too _chunk.xhr = xhr } _chunk.tested = true } }, this) if (!this._firstResponse) { this._firstResponse = true this.uploader.upload(true) } else { this.uploader.uploadNextChunk() } } else { this.uploader.uploadNextChunk() } }, _error: function () { this.error = this.allError = true var parent = this.parent while (parent && parent !== this.uploader) { parent._errorFiles.push(this) parent.error = true if (parent._errorFiles.length === parent.files.length) { parent.allError = true } parent = parent.parent } }, _resetError: function () { this.error = this.allError = false var parent = this.parent var index = -1 while (parent && parent !== this.uploader) { index = parent._errorFiles.indexOf(this) parent._errorFiles.splice(index, 1) parent.allError = false if (!parent._errorFiles.length) { parent.error = false } parent = parent.parent } }, isComplete: function () { if (!this.completed) { var outstanding = false this._eachAccess(function (file) { if (!file.isComplete()) { outstanding = true return false } }, function () { if (this.error) { outstanding = true } else { var STATUS = Chunk.STATUS utils.each(this.chunks, function (chunk) { var status = chunk.status() if (status === STATUS.ERROR || status === STATUS.PENDING || status === STATUS.UPLOADING || status === STATUS.READING || chunk.preprocessState === 1 || chunk.readState === 1) { outstanding = true return false } }) } }) this.completed = !outstanding } return this.completed }, isUploading: function () { var uploading = false this._eachAccess(function (file) { if (file.isUploading()) { uploading = true return false } }, function () { var uploadingStatus = Chunk.STATUS.UPLOADING utils.each(this.chunks, function (chunk) { if (chunk.status() === uploadingStatus) { uploading = true return false } }) }) return uploading }, resume: function () { this._eachAccess(function (f) { f.resume() }, function () { this.paused = false this.aborted = false this.uploader.upload() }) this.paused = false this.aborted = false }, pause: function () { this._eachAccess(function (f) { f.pause() }, function () { this.paused = true this.abort() }) this.paused = true }, cancel: function () { this.uploader.removeFile(this) }, retry: function (file) { var fileRetry = function (file) { if (file.error) { file.bootstrap() } } if (file) { file.bootstrap() } else { this._eachAccess(fileRetry, function () { this.bootstrap() }) } this.uploader.upload() }, abort: function (reset) { if (this.aborted) { return } this.currentSpeed = 0 this.averageSpeed = 0 this.aborted = !reset var chunks = this.chunks if (reset) { this.chunks = [] } var uploadingStatus = Chunk.STATUS.UPLOADING utils.each(chunks, function (c) { if (c.status() === uploadingStatus) { c.abort() this.uploader.uploadNextChunk() } }, this) }, progress: function () { var totalDone = 0 var totalSize = 0 var ret = 0 this._eachAccess(function (file, index) { totalDone += file.progress() * file.size totalSize += file.size if (index === this.files.length - 1) { ret = totalSize > 0 ? totalDone / totalSize : this.isComplete() ? 1 : 0 } }, function () { if (this.error) { ret = 1 return } if (this.chunks.length === 1) { this._prevProgress = Math.max(this._prevProgress, this.chunks[0].progress()) ret = this._prevProgress return } // Sum up progress across everything var bytesLoaded = 0 utils.each(this.chunks, function (c) { // get chunk progress relative to entire file bytesLoaded += c.progress() * (c.endByte - c.startByte) }) var percent = bytesLoaded / this.size // We don't want to lose percentages when an upload is paused this._prevProgress = Math.max(this._prevProgress, percent > 0.9999 ? 1 : percent) ret = this._prevProgress }) return ret }, getSize: function () { var size = 0 this._eachAccess(function (file) { size += file.size }, function () { size += this.size }) return size }, getFormatSize: function () { var size = this.getSize() return utils.formatSize(size) }, getRoot: function () { if (this.isRoot) { return this } var parent = this.parent while (parent) { if (parent.parent === this.uploader) { // find it return parent } parent = parent.parent } return this }, sizeUploaded: function () { var size = 0 this._eachAccess(function (file) { size += file.sizeUploaded() }, function () { utils.each(this.chunks, function (chunk) { size += chunk.sizeUploaded() }) }) return size }, timeRemaining: function () { var ret = 0 var sizeDelta = 0 var averageSpeed = 0 this._eachAccess(function (file, i) { if (!file.paused && !file.error) { sizeDelta += file.size - file.sizeUploaded() averageSpeed += file.averageSpeed } if (i === this.files.length - 1) { ret = calRet(sizeDelta, averageSpeed) } }, function () { if (this.paused || this.error) { ret = 0 return } var delta = this.size - this.sizeUploaded() ret = calRet(delta, this.averageSpeed) }) return ret function calRet (delta, averageSpeed) { if (delta && !averageSpeed) { return Number.POSITIVE_INFINITY } if (!delta && !averageSpeed) { return 0 } return Math.floor(delta / averageSpeed) } }, removeFile: function (file) { if (file.isFolder) { while (file.files.length) { var f = file.files[file.files.length - 1] this._removeFile(f) } } this._removeFile(file) }, _delFilePath: function (file) { if (file.path && this.filePaths) { delete this.filePaths[file.path] } utils.each(file.fileList, function (file) { this._delFilePath(file) }, this) }, _removeFile: function (file) { if (!file.isFolder) { utils.each(this.files, function (f, i) { if (f === file) { this.files.splice(i, 1) return false } }, this) file.abort() var parent = file.parent var newParent while (parent && parent !== this) { newParent = parent.parent parent._removeFile(file) parent = newParent } } file.parent === this && utils.each(this.fileList, function (f, i) { if (f === file) { this.fileList.splice(i, 1) return false } }, this) if (!this.isRoot && this.isFolder && !this.files.length) { this.parent._removeFile(this) this.uploader._delFilePath(this) } file.parent = null }, getType: function () { if (this.isFolder) { return 'folder' } return this.file.type && this.file.type.split('/')[1] }, getExtension: function () { if (this.isFolder) { return '' } return this.name.substr((~-this.name.lastIndexOf('.') >>> 0) + 2).toLowerCase() } }) module.exports = File function parsePaths (path) { var ret = [] var paths = path.split('/') var len = paths.length var i = 1 paths.splice(len - 1, 1) len-- if (paths.length) { while (i <= len) { ret.push(paths.slice(0, i++).join('/') + '/') } } return ret } },{"./chunk":1,"./utils":5}],5:[function(_dereq_,module,exports){ var oproto = Object.prototype var aproto = Array.prototype var serialize = oproto.toString var isFunction = function (fn) { return serialize.call(fn) === '[object Function]' } var isArray = Array.isArray || /* istanbul ignore next */ function (ary) { return serialize.call(ary) === '[object Array]' } var isPlainObject = function (obj) { return serialize.call(obj) === '[object Object]' && Object.getPrototypeOf(obj) === oproto } var i = 0 var utils = { uid: function () { return ++i }, noop: function () {}, bind: function (fn, context) { return function () { return fn.apply(context, arguments) } }, preventEvent: function (evt) { evt.preventDefault() }, stop: function (evt) { evt.preventDefault() evt.stopPropagation() }, nextTick: function (fn, context) { setTimeout(utils.bind(fn, context), 0) }, toArray: function (ary, start, end) { if (start === undefined) start = 0 if (end === undefined) end = ary.length return aproto.slice.call(ary, start, end) }, isPlainObject: isPlainObject, isFunction: isFunction, isArray: isArray, isObject: function (obj) { return Object(obj) === obj }, isString: function (s) { return typeof s === 'string' }, isUndefined: function (a) { return typeof a === 'undefined' }, isDefined: function (a) { return typeof a !== 'undefined' }, each: function (ary, func, context) { if (utils.isDefined(ary.length)) { for (var i = 0, len = ary.length; i < len; i++) { if (func.call(context, ary[i], i, ary) === false) { break } } } else { for (var k in ary) { if (func.call(context, ary[k], k, ary) === false) { break } } } }, /** * If option is a function, evaluate it with given params * @param {*} data * @param {...} args arguments of a callback * @returns {*} */ evalOpts: function (data, args) { if (utils.isFunction(data)) { // `arguments` is an object, not array, in FF, so: args = utils.toArray(arguments) data = data.apply(null, args.slice(1)) } return data }, extend: function () { var options var name var src var copy var copyIsArray var clone var target = arguments[0] || {} var i = 1 var length = arguments.length var force = false // 如果第一个参数为布尔,判定是否深拷贝 if (typeof target === 'boolean') { force = target target = arguments[1] || {} i++ } // 确保接受方为一个复杂的数据类型 if (typeof target !== 'object' && !isFunction(target)) { target = {} } // 如果只有一个参数,那么新成员添加于 extend 所在的对象上 if (i === length) { target = this i-- } for (; i < length; i++) { // 只处理非空参数 if ((options = arguments[i]) != null) { for (name in options) { src = target[name] copy = options[name] // 防止环引用 if (target === copy) { continue } if (force && copy && (isPlainObject(copy) || (copyIsArray = isArray(copy)))) { if (copyIsArray) { copyIsArray = false clone = src && isArray(src) ? src : [] } else { clone = src && isPlainObject(src) ? src : {} } target[name] = utils.extend(force, clone, copy) } else if (copy !== undefined) { target[name] = copy } } } } return target }, formatSize: function (size) { if (size < 1024) { return size.toFixed(0) + ' bytes' } else if (size < 1024 * 1024) { return (size / 1024.0).toFixed(0) + ' KB' } else if (size < 1024 * 1024 * 1024) { return (size / 1024.0 / 1024.0).toFixed(1) + ' MB' } else { return (size / 1024.0 / 1024.0 / 1024.0).toFixed(1) + ' GB' } }, defineNonEnumerable: function (target, key, value) { Object.defineProperty(target, key, { enumerable: false, configurable: true, writable: true, value: value }) } } module.exports = utils },{}]},{},[3]) (3) });
dolymood/Uploader
dist/uploader.js
JavaScript
mit
45,241