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
/*global module, process */ module.exports = process.env.AWS_REGION || 'us-east-1';
tuesdaylabs/claudia
spec/util/test-aws-region.js
JavaScript
mit
84
/** * Open the Eyes Instance */ import {getBrowserFor} from './utils' module.exports = ( person, page, done ) => { console.log("(openEyes) Opening the Eyes for: " + person) getBrowserFor(person).EyesOpen(page); global.eyesIsOpen = true done() };
LiranApplitools/automation-web
test/support/action/openEyes.js
JavaScript
mit
264
jQuery.fn.showMeMore = function (options) { var options = $.extend({ current: 4, // number to be displayed at start count: 4, // how many show in one click fadeSpeed: 300, // animation speed showButton: '', // show button (false / string) hideButton: '', // hide button showButtonText: 'showButton', //text at the showButton hideButtonText: 'hideButton', //text at the showButton enableHide: false, // allow to hide (true / false) generateBtn: true,// auto generate buttons if they not added by default list: 'li' //tile elements }, options); var make = function () { var showButton = $(options.showButton), hideButton = $(options.hideButton), enableHide = options.enableHide, count = options.count, current = options.current, fadeSpeed = options.fadeSpeed, list = $(this).find(options.list),//find all 'list' elements quantity = list.length;//list elements count //add SHOW button if it is not installed by the user if (options.generateBtn && options.showButton == '') { $(this).append('<button class="showButton">' + options.showButtonText + '</button>'); showButton = $(this).find('.showButton'); } //add HIDE button if it is not installed by the user and if enableHide is true if (options.generateBtn && enableHide && options.showButton == '') { $(this).append('<button class="hideButton">' + options.hideButtonText + '</button>'); hideButton = $(this).find('.hideButton'); } list.hide();//hide all elements hideButton.hide()//hide "hideButton" if (quantity <= current) { showButton.hide(); } showItem(0);//show first elements function switchButtons() { if (enableHide == false) { showButton.hide(); } else { showButton.hide(); hideButton.show(); } } //this function show next elements function showItem(time) { for (var i = 0; i < current; i++) { if ($(list[i]).is(':hidden')) { $(list[i]).fadeIn(time); } } } //this function hide all elements function hideAll(time) { for (var i = current; i < quantity; i++) { $(list[i]).fadeOut(time); } } showButton.click(function (event) { event.preventDefault(); current += count; showItem(fadeSpeed); if (current >= quantity) { switchButtons(); } }); hideButton.click(function (event) { event.preventDefault(); current = options.current; hideAll(fadeSpeed); hideButton.hide(); showButton.show(); }); }; return this.each(make); };
alexandr-prikhodko/showMeMore
dev/showMeMore.js
JavaScript
mit
3,143
import _ from 'lodash'; import 'ui/paginated_table'; import popularityHtml from 'plugins/kibana/management/sections/indices/_field_popularity.html'; import controlsHtml from 'plugins/kibana/management/sections/indices/_field_controls.html'; import dateScripts from 'plugins/kibana/management/sections/indices/_date_scripts'; import uiModules from 'ui/modules'; import scriptedFieldsTemplate from 'plugins/kibana/management/sections/indices/_scripted_fields.html'; import { getSupportedScriptingLangs } from 'ui/scripting_langs'; import { scriptedFields as docLinks } from 'ui/documentation_links/documentation_links'; uiModules.get('apps/management') .directive('scriptedFields', function (kbnUrl, Notifier, $filter, confirmModal) { const rowScopes = []; // track row scopes, so they can be destroyed as needed const filter = $filter('filter'); const notify = new Notifier(); return { restrict: 'E', template: scriptedFieldsTemplate, scope: true, link: function ($scope) { const fieldCreatorPath = '/management/kibana/indices/{{ indexPattern }}/scriptedField'; const fieldEditorPath = fieldCreatorPath + '/{{ fieldName }}'; $scope.docLinks = docLinks; $scope.perPage = 25; $scope.columns = [ { title: 'name' }, { title: 'lang' }, { title: 'script' }, { title: 'format' }, { title: 'controls', sortable: false } ]; $scope.$watchMulti(['[]indexPattern.fields', 'fieldFilter'], refreshRows); function refreshRows() { _.invoke(rowScopes, '$destroy'); rowScopes.length = 0; const fields = filter($scope.indexPattern.getScriptedFields(), { name: $scope.fieldFilter }); _.find($scope.editSections, { index: 'scriptedFields' }).count = fields.length; // Update the tab count $scope.rows = fields.map(function (field) { const rowScope = $scope.$new(); rowScope.field = field; rowScopes.push(rowScope); return [ _.escape(field.name), _.escape(field.lang), _.escape(field.script), _.get($scope.indexPattern, ['fieldFormatMap', field.name, 'type', 'title']), { markup: controlsHtml, scope: rowScope } ]; }); } $scope.addDateScripts = function () { const conflictFields = []; let fieldsAdded = 0; _.each(dateScripts($scope.indexPattern), function (script, field) { try { $scope.indexPattern.addScriptedField(field, script, 'number'); fieldsAdded++; } catch (e) { conflictFields.push(field); } }); if (fieldsAdded > 0) { notify.info(fieldsAdded + ' script fields created'); } if (conflictFields.length > 0) { notify.info('Not adding ' + conflictFields.length + ' duplicate fields: ' + conflictFields.join(', ')); } }; $scope.create = function () { const params = { indexPattern: $scope.indexPattern.id }; kbnUrl.change(fieldCreatorPath, params); }; $scope.edit = function (field) { const params = { indexPattern: $scope.indexPattern.id, fieldName: field.name }; kbnUrl.change(fieldEditorPath, params); }; $scope.remove = function (field) { const confirmModalOptions = { confirmButtonText: 'Delete field', onConfirm: () => { $scope.indexPattern.removeScriptedField(field.name); } }; confirmModal(`Are you sure want to delete ${field.name}? This action is irreversible!`, confirmModalOptions); }; $scope.getDeprecatedLanguagesInUse = function () { const fields = $scope.indexPattern.getScriptedFields(); const langsInUse = _.uniq(_.map(fields, 'lang')); return _.difference(langsInUse, getSupportedScriptingLangs()); }; } }; });
istresearch/PulseTheme
kibana/src/core_plugins/kibana/public/management/sections/indices/_scripted_fields.js
JavaScript
mit
4,010
import { connecting, connected, reconnecting, connectionFailed } from './actions'; export default uri => store => { let ws; let hasEverConnected = false; const RECONNECT_TIMEOUT_MS = 2000; const ACTION = 'ACTION'; const connect = () => { ws = new WebSocket(uri); // NOTE: could maybe set a flat 'hasBeenOpenBefore' to help with error states/dispatches and such ws.onopen = () => { hasEverConnected = true; store.dispatch(connected()); }; ws.onclose = function() { if (hasEverConnected) { store.dispatch(reconnecting()); setTimeout(connect, RECONNECT_TIMEOUT_MS); } else { //TODO: THIS TAKES A LOOOOONG TIME ON CHROME... MAYBE BUILD SOME EXTRA DISPATCHES? store.dispatch(connectionFailed()); } }; ws.onmessage = ({data}) => { const serverAction = JSON.parse(data); if (serverAction.type == ACTION) { const localAction = serverAction.payload; store.dispatch(localAction); } }; }; store.dispatch(connecting()); connect(); return next => action => { if(WebSocket.OPEN === ws.readyState && action.meta && action.meta.remote) { const serverAction = JSON.stringify({ type: ACTION, payload: action }); ws.send(serverAction); } return next(action); }; };
jesse-robertson/game-night
src/store/enhancers/middleware/websocket/src.js
JavaScript
mit
1,599
import {FkJsListener} from './antlr/FkJsListener'; import {FkJsParser} from './antlr/FkJsParser'; /** * Obtains a list of modes and mixins from a .fk * file, as well as other information. */ export default class PreProcessor extends FkJsListener { /** * @type {string} */ defaultMode; /** * @type {Object} */ mixins = {}; /** * @type {Object} */ modes = {}; /** * * @param ctx {FkJsParser.ModeDeclContext} */ enterModeDecl(ctx) { this.modes[ctx.name.text] = ctx; } enterMixinDecl(ctx) { this.mixins[ctx.name.text] = ctx; } enterDefaultModeDecl(ctx) { this.defaultMode = ctx.ID().getText(); } }
fkjs/fkjs
src/pre-processor.js
JavaScript
mit
723
/** * Created by Deathnerd on 1/23/2015. */ var gulp = require('gulp'); var usemin = require('gulp-usemin'); var uglify = require('gulp-uglify'); var shell = require('gulp-shell'); var replace = require('gulp-replace'); gulp.task('usemin', function(){ gulp.src(['./src/template.html']) .pipe(usemin({ js:[uglify(), 'concat'] })) .pipe(gulp.dest('dist/')); }); gulp.task('js', function(){ gulp.src(['src/story_js/cookie.js', 'src/story_js/utils.js', 'src/story_js/story.js', 'src/story_js/js.class/js.class.js']) .pipe(uglify()) .pipe(gulp.dest('dist')); }); gulp.task('closure', function(){ gulp.src('') .pipe(shell([ 'ccjs dist/story.concat.js > dist/story.min.js' ])); }); gulp.task('default', function(){ gulp.run('usemin'); gulp.run('closure'); });
Deathnerd/story.js
gulpfile.js
JavaScript
mit
890
export const bell = {"viewBox":"0 0 64 64","children":[{"name":"g","attribs":{"id":"BELL_1_","enable-background":"new "},"children":[{"name":"g","attribs":{"id":"BELL"},"children":[{"name":"g","attribs":{"id":"BELL"},"children":[{"name":"g","attribs":{},"children":[{"name":"g","attribs":{},"children":[{"name":"path","attribs":{"d":"M52,45c-1.657,0-3-1.343-3-3V22c0-7.732-6.268-14-14-14c0-1.657-1.343-3-3-3s-3,1.343-3,3c-7.732,0-14,6.268-14,14v20\r\n\t\t\t\tc0,1.657-1.343,3-3,3s-3,1.343-3,3s1.343,3,3,3h40c1.657,0,3-1.343,3-3S53.657,45,52,45z M32,60c3.314,0,6-2.686,6-6H26\r\n\t\t\t\tC26,57.314,28.686,60,32,60z"},"children":[{"name":"path","attribs":{"d":"M52,45c-1.657,0-3-1.343-3-3V22c0-7.732-6.268-14-14-14c0-1.657-1.343-3-3-3s-3,1.343-3,3c-7.732,0-14,6.268-14,14v20\r\n\t\t\t\tc0,1.657-1.343,3-3,3s-3,1.343-3,3s1.343,3,3,3h40c1.657,0,3-1.343,3-3S53.657,45,52,45z M32,60c3.314,0,6-2.686,6-6H26\r\n\t\t\t\tC26,57.314,28.686,60,32,60z"},"children":[]}]}]}]}]}]}]}]};
wmira/react-icons-kit
src/ikons/bell.js
JavaScript
mit
973
//~ name b258 alert(b258); //~ component b259.js
homobel/makebird-node
test/projects/large/b258.js
JavaScript
mit
52
var WO = WO || {}; WO.Track = Backbone.Model.extend({ urlRoot: '/api/tracks', idAttribute: '_id', defaults: { notes: "", title: 'Acoustic Piano', isMuted: false, solo: false, octave: 4, volume: 0.75, instrument: "", type: 'MIDI' }, initialize : function(){ this.set('notes', []); this.set('instrument', WO.InstrumentFactory( "Acoustic Piano", this.cid)); WO.instrumentKeyHandler.create(this.get('instrument')); this.on('changeInstrument', function(instrumentName){this.changeInstrument(instrumentName);}, this); }, genObjectId: (function() { function s4() { return Math.floor((1 + Math.random()) * 0x10000) .toString(16) .substring(1); } return function() { return s4() + s4() + s4(); }; })(), changeInstrument: function(instrumentName) { var instType = { 'Acoustic Piano': 'MIDI', 'Audio File': 'Audio', 'Microphone': 'Microphone', 'Acoustic Guitar Steel': 'MIDI', 'Alto Sax': 'MIDI', 'Church Organ': 'MIDI', 'Distortion Guitar': 'MIDI', 'Electric Piano 1': 'MIDI', 'Flute': 'MIDI', 'Muted Trumpet': 'MIDI', 'Oboe': 'MIDI', 'Overdriven Guitar': 'MIDI', 'Pad 3 Polysynth': 'MIDI', 'Synth': 'MIDI', 'Synth Bass 1': 'MIDI', 'Synth Strings 2': 'MIDI', 'Viola': 'MIDI', 'Violin': 'MIDI', 'Xylophone': 'MIDI' }; var previousInstrumentType = this.get('type'); WO.appView.unbindKeys(); this.set('type', instType[instrumentName]); this.set('title', instrumentName); if (this.get('type') === 'MIDI') { this.set('instrument', WO.InstrumentFactory(instrumentName, this)); WO.instrumentKeyHandler.create(this.get('instrument')); if (previousInstrumentType !== 'MIDI') { $('.active-track .track-notes').html(''); this.set('mRender', new WO.MidiRender(this.cid + ' .track-notes')); } } else { this.set('notes', []); $('.active-track .track-notes').html(''); this.set('instrument', WO.InstrumentFactory(instrumentName, this)); } }, saveTrack: function(){ var instrument = this.get('instrument'); var mRender = this.get('mRender'); this.set('instrument', ''); this.set('mRender', ''); var that = this; var newlySaveTrack = $.when(that.save()).done(function(){ that.set('instrument', instrument); that.set('mRender', mRender); return that; }); return newlySaveTrack; } }); //see what type of instrumetn current serection is // midi -> mic => remove svg , add mic // midi -> audio => remove svg , add audio // midi -> midi => null // mic -> audio => remove mic , add audio // mic -> midi => remove mike, add svg // audio -> mic => remove audio, add mic // audio -> midi => remove audio, add svg // keep notes only for midi change to hear different instruments.
WorldOrchestra/WorldOrchestra
public/js/models/trackModel.js
JavaScript
mit
2,998
describe('GiftCard Purchase Workflow', function () { 'use strict'; function waitForUrlToChangeTo (urlRegex) { var currentUrl; return browser.getCurrentUrl().then(function storeCurrentUrl (url) { currentUrl = url; } ).then(function waitForUrlToChangeTo () { return browser.wait(function waitForUrlToChangeTo () { return browser.getCurrentUrl().then(function compareCurrentUrl (url) { return urlRegex === url; }); }); } ); } it('should load first screen', function () { browser.get('#/cadeau/vinibar/formule?test=true'); expect(browser.getTitle()).toEqual('Cadeau | vinibar'); }); it('should choose gift_card and add some credit', function () { element(by.css('#init-card')).click(); element(by.model('gift.order.credits')).sendKeys('15'); element(by.css('#delivery-postcard')).click(); element(by.css('.btn-block-primary')).click(); }); it('should fill lucky boy & giver infos', function () { expect(browser.getCurrentUrl()).toEqual('http://0.0.0.0:9001/#/cadeau/vinibar/infos?test=true'); element(by.cssContainingText('option', 'Mme')).click(); element(by.model('gift.order.receiver_first_name')).sendKeys('John'); element(by.model('gift.order.receiver_last_name')).sendKeys('Mc Test'); element(by.model('gift.order.receiver_email')).sendKeys('felix+test' + Math.random() * 1000 + '@vinify.co'); element(by.model('gift.order.message')).sendKeys('un cadeau pour toi !'); element(by.model('gift.order.comment')).sendKeys('Il aime le chocolat'); element.all(by.css('.gift-checkbox')).first().click(); element(by.model('gift.order.receiver_address.first_name')).sendKeys('John'); element(by.model('gift.order.receiver_address.last_name')).sendKeys('Mc Test'); element(by.model('gift.order.receiver_address.street')).sendKeys('12 rue boinod'); element(by.model('gift.order.receiver_address.zipcode')).sendKeys('75018'); element(by.model('gift.order.receiver_address.city')).sendKeys('Paris'); element(by.css('#is-not-client')).click(); element(by.model('gift.giver.first_name')).sendKeys('John'); element(by.model('gift.giver.last_name')).sendKeys('MacTest'); element(by.model('gift.giver.email')).sendKeys('felix+test' + Math.random() * 1000 + '@vinify.co'); element(by.model('gift.giver.password')).sendKeys('wineisgood'); element(by.css('.btn-block-primary')).click(); }); it('should fill lucky boy & giver infos', function () { // make payment element(by.model('number')).sendKeys('4242424242424242'); element(by.model('cvc')).sendKeys('001'); element(by.cssContainingText('option', 'Mai')).click(); element(by.cssContainingText('option', '2017')).click(); element.all(by.css('.btn-block-primary')).last().click(); waitForUrlToChangeTo('http://0.0.0.0:9001/#/remerciement/cadeau?print=false'); }); });
FelixLC/questionnaire.vinify
src/app/workflow.gift.card.e2e.spec.js
JavaScript
mit
2,937
var structaaa_1_1sqrt__type = [ [ "type", "structaaa_1_1sqrt__type.html#a5843af2f9db00396bf14cf79cabecac0", null ] ];
mabur/aaa
documentation/html/structaaa_1_1sqrt__type.js
JavaScript
mit
121
import React from 'react'; import Wrapper, { Header, Content, Footer, Sidebar, SidebarItem, MainContent, MainItem, } from '../components/common/layouts/Container/Container'; import Menu from '../components/Menu/Menu'; import Filter from '../components/Filter/Filter'; const Main = () => <Wrapper> <Header> <Menu /> </Header> <Content> <Sidebar> <SidebarItem> <Filter /> </SidebarItem> </Sidebar> <MainContent> <MainItem> <div>git checkout step-2</div> </MainItem> </MainContent> </Content> <Footer> <div>hex22a</div> </Footer> </Wrapper>; export default Main;
AlbertFazullin/redux-form-demo
src/containers/StepTwo.js
JavaScript
mit
693
var path = require("path"); module.exports = { watch: false, module: { loaders: [ { test: /\.jsx?$/, exclude: /node_modules/, loader: 'babel-loader' } ], postLoaders: [{ // test: /\.js$/, exclude: /(test|node_modules|bower_components|test_helpers)\//, loader: 'istanbul-instrumenter' }], preLoaders: [ { test: /\.js$/, include: [ path.resolve(__dirname, "src") ], loader: "eslint-loader" } ] }, resolve: { // add bower components and main source to resolved root: [path.join(__dirname, 'src/main'), path.join(__dirname, 'src/test_helpers')] } };
BowlingX/marklib
webpack.test.config.js
JavaScript
mit
858
recipes['Fiery Ginger Ale (2L)'] = { type: 'Fiery Ginger Ale (2L)', volume: '2L', brewTime: [ '2 days', ], ingredients: [ '1.5 oz. finely grated fresh ginger (the younger the better; microplane suggested)', '6 oz. table sugar', '7.5 cups filtered water', '1/8 teaspoon (should be around 750mg) champagne yeast (Red Star Premier Blanc formerly known as Pastuer Champagne)', '2 tablespoons freshly squeezed lemon juice', 'StarSan soln.', ], equipmentMisc: [ '2L PET bottle (i.e. plastic soda bottle)', ], recipe: [ 'Clean 2L PET bottle with StarSan soln.', 'Place ginger, sugar, and 1/2 cup of the water into a saucepan over medium-high heat. Stir until the sugar dissolves. Remove from heat, cover, and allow to steep for 1 hour.', 'Pour the syrup through a fine strainer, cheese cloth over a bowl, or t-shirt, using pressure to get all the juice out of the mixture. Rapidly chill in an ice bath and stir until the mixture reaches 70 degrees F.', 'Pour the syrup into a 2L PET bottle and add yeast, lemon juice, and remaining 7 cups of water. Shake vigorously for five minutes. Let sit in a dark place at room temperature.', 'At 2 days, burp and refrigerate bottle. Allow 24 hours for yeast to fall asleep, then siphon off into another StarSan\'d 2L soda bottle, leaving the flocculated yeast at the bottom of the first bottle. SG check. Keep chilled and drink quickly; the carbonation will not last long -- 3 days is safe', ], fdaIngredients: 'water, sugar, ginger, lemon juice, yeast', };
jkingsman/mead
js/recipes/gingerAle.js
JavaScript
mit
1,638
const murmur = require('murmurhash-native/stream') function createHash () { // algorithm, seed and endianness - do affect the results! return murmur.createHash('murmurHash128x86', { seed: 0, endianness: 'LE' }) } module.exports = createHash
heroqu/hash-through
test/hashes/murmur3_native_128_86_le.js
JavaScript
mit
257
var React = require('react'); var Animation = require('react-addons-css-transition-group'); var NBButton = require('./NBItems').NBButton; var NBTitle = require('./NBItems').NBTitle; var NBEmpty = require('./NBItems').NBEmpty; var Navbar = React.createClass({ render: function() { return ( <div className="navbar"> <div className="navbar-inner"> <NBButton path="/" icon="icon-back" position="left"/> <NBTitle text="Settings"/> <NBEmpty position="right"/> </div> </div> ) } }); var Button = React.createClass({ render: function() { return ( <div> </div> ) } }); var PageContent = React.createClass({ componentWillMount: function() { }, render: function() { return ( <div className="page"> <div className="page-content"> <Navbar/> <Animation transitionName={{ appear: "slideLeft-enter", leave: "slideLeft-leave" }} transitionEnterTimeout={1000} transitionLeaveTimeout={500} transitionAppearTimeout={500} transitionAppear={true} transitionLeave={true}> <div className="content-block"> Content some text alalala ashdihaish uasodj iioash iodhias </div> </Animation> </div> </div> ) } }); module.exports = PageContent;
React-Team-AM/react-template
app/scripts/components/TimerPage.js
JavaScript
mit
1,659
module.exports = { up: (queryInterface, Sequelize) => queryInterface.createTable('Groups', { id: { allowNull: false, autoIncrement: true, primaryKey: true, type: Sequelize.INTEGER }, name: { type: Sequelize.STRING, allowNull: false, }, createdBy: { type: Sequelize.STRING, allowNull: false, }, description: { type: Sequelize.STRING, }, type: { type: Sequelize.STRING, allowNull: false, default: 'public' }, createdAt: { allowNull: false, type: Sequelize.DATE, }, updatedAt: { allowNull: false, type: Sequelize.DATE } }), down: queryInterface => queryInterface.dropTable('Groups'), };
oahray/bc-24-postit
server/migrations/20170710002603-create-group.js
JavaScript
mit
812
var fs = require('fs'); var url = require('url'); var mime = require('mime'); var path = require('path'); exports.css = function(s) { var pathname = url.parse(s.request.url).pathname; var path = 'g' + pathname + '.css'; var locale = s.strings('locale.json'); var errors = s.strings('errors.json'); var content = s.renderText(path, locale, true); if (content == null) { s.response.writeHead(404, { 'Content-Type': 'text/html' }); s.response.end(s.renderText('g/error.html', { errorMessage: errors.stylesheetMissing, errorInfo: pathname })); } else { s.response.writeHead(200, { 'Content-Type': 'text/css' }); s.response.end(content); } } exports.js = function(s) { var pathname = url.parse(s.request.url).pathname; var path = 'g' + pathname + '.js'; var errors = s.strings('errors.json'); var content = s.renderText(path, {}, true); if (content == null) { s.response.writeHead(404, { 'Content-Type': 'text/html' }); s.response.end(s.renderText('g/error.html', { errorMessage: errors.scriptMissing, errorInfo: pathname })); } else { s.response.writeHead(200, { 'Content-Type': 'application/javascript' }); s.response.end(content); } }; exports.static = function(s) { var pathname = url.parse(s.request.url).pathname; var fileDir = path.resolve(__dirname , '..' , pathname.substring(1)); fs.stat(fileDir, function(err, stat) { if (err) { var errors = s.strings('errors.json'); s.response.writeHead(404, { 'Content-Type': 'text/html' }); s.response.end(s.renderText('g/error.html', { errorMessage: errors.staticFileMissing, errorInfo: pathname }, false)); } else { var stream = fs.createReadStream(fileDir); stream.on('open', function() { s.response.writeHead(200, { 'Cache-Control': 'public, max-age=9000000', 'Content-Length': stat.size, 'Content-Type': mime.lookup(fileDir) }); }); stream.on('data', function(data) { s.response.write(data, null); }); stream.on('error', function(err) { console.log(err); var errors = s.strings('errors.json'); s.response.end(errors.streamingError); }); stream.on('end', function(data) { s.response.end(); }); } }); }
Arubaruba/Hayya-Nabnee
routes/resources.js
JavaScript
mit
2,414
import React, { Component } from 'react'; import { SelectField, MenuItem } from 'fusionui-shared-components-react'; import PropTypes from 'prop-types'; import '../../FormField.scss'; import './FormSelectField.scss'; const style = { width: '100%', height: 30, border: 'none', backgroundColor: 'rgb(239, 239, 239)', fontSize: 12, }; class FormSelectField extends Component { constructor(props) { super(props); this.state = { value: props.value }; } componentWillReceiveProps(nextProps) { this.setState({ value: nextProps.value }); } handleChange = (ev, idx, value) => { this.props.onChange(ev, value, this.props.onBlur); this.setState({ value }); } render() { const { label, fchar, options } = this.props; return ( <div className="form-field__wrapper form-select__wrapper"> <label className="form-field__label" htmlFor={ name }>{ label[fchar] || label.DEFAULT }</label> <SelectField style={ style } menuStyle={ style } selectedMenuItemStyle={ { fontWeight: 'bold', color: '#000' } } value={ this.state.value } onChange={ this.handleChange } underlineStyle={ { marginBottom: -8, width: '100%' } } labelStyle={ { paddingLeft: 10, lineHeight: '40px', height: 40 } } > <MenuItem value="" primaryText="Select..." /> { options.map(option => <MenuItem value={ option.value } key={ option.value } primaryText={ option.text } />) } </SelectField> </div> ); } } FormSelectField.propTypes = { fchar: PropTypes.string.isRequired, label: PropTypes.object, options: PropTypes.arrayOf( PropTypes.shape({ text: PropTypes.string, value: PropTypes.string }) ).isRequired, onChange: PropTypes.func.isRequired, onBlur: PropTypes.func.isRequired, value: PropTypes.string }; FormSelectField.defaultProps = { errorText: '', label: {}, value: '' }; export default FormSelectField;
jpgonzalezquinteros/sovos-reactivo-2017
tp-3/juan-pablo-gonzalez/src/shared/components/sovos-dynamic-form/components/formField/components/formSelectField/FormSelectField.js
JavaScript
mit
2,005
// this will build and serve the examples var path = require('path'); var webpack = require('webpack'); module.exports = { entry: { app: './examples/js/app.js', vendors: ['webpack-dev-server/client?http://localhost:3004', 'webpack/hot/only-dev-server'] }, debug: true, devtool: '#eval-source-map', output: { path: path.join(__dirname, 'examples'), filename: '[name].bundle.js' }, serverConfig: { port: '3004',// server port publicPath: '/',// js path contentBase: 'examples/'//web root path }, resolve: { extensions: ['', '.js', '.jsx'], alias: { 'react-bootstrap-table': path.resolve(__dirname, './src') } }, module: { preLoaders: [ { test: /\.js$/, exclude: [ /node_modules/, path.resolve(__dirname, './src/filesaver.js') ], loader: 'eslint' } ], loaders: [ { test: /\.js$/, exclude: /node_modules/, loaders: ['react-hot', 'babel'] }, { test: /\.css$/, loader: 'style-loader!css-loader' } ] }, plugins: [ new webpack.optimize.CommonsChunkPlugin('vendors', 'vendors.js'), new webpack.HotModuleReplacementPlugin(), new webpack.NoErrorsPlugin() ] };
neelvadgama-hailo/react-bootstrap-table
webpack.example.config.js
JavaScript
mit
1,240
'use strict'; var mongoose = require('mongoose'), async = require('async'); var DeleteChildrenPlugin = function(schema, options) { schema.pre('remove', function(done) { var parentField = options.parentField; var childModel = options.childModel; if (!parentField) { var err = new Error('parentField not defined'); return done(err); } if (!childModel) { var err = new Error('childModel not defined'); return done(err); } // must delete all campuses console.log('model::', parentField, '>', childModel, '::pre::remove::enter'); var Model = mongoose.model(childModel); var conditions = {}; conditions[parentField] = this._id; Model.find(conditions).exec(function(err, results) { console.log('model::', parentField, '>', childModel, '::pre::remove::find::enter'); if (err) { return done(err); } async.each(results, function(campus, deleteNextModel) { console.log('model::', parentField, '>', childModel, '::pre::remove::find::each::enter'); campus.remove(deleteNextModel); }, done); }); }); }; var ParentAttachPlugin = function(schema, options) { schema.pre('save', function(doneAttaching) { var doc = this; var parentField = options.parentField; var parentModel = options.parentModel; var childCollection = options.childCollection; if (!doc[parentField]) return doneAttaching(); var Parent = mongoose.model(parentModel); var push = {}; push[childCollection] = doc._id; Parent.findByIdAndUpdate(doc[parentField], { $push: push }).exec(function(err) { if (err) { console.log('plugin::ParentAttachPlugin::schema::pre::save::findByIdAndUpdate::err', err); return doneAttaching(err); } console.log('plugin::ParentAttachPlugin::schema::pre::save::findByIdAndUpdate::exit'); doneAttaching(); }); }); schema.pre('remove', function(doneRemoving) { var doc = this; var parentField = options.parentField; var parentModel = options.parentModel; var childCollection = options.childCollection; if (!doc[parentField]) return doneRemoving(); var Parent = mongoose.model(parentModel); var pull = {}; pull[childCollection] = doc._id; Parent.findByIdAndUpdate(doc[parentField], { $pull: pull }).exec(function(err) { if (err) { console.log('plugin::ParentAttachPlugin::schema::pre::save::findByIdAndUpdate::err', err); return doneRemoving(err); } console.log('plugin::ParentAttachPlugin::schema::pre::save::findByIdAndUpdate::exit'); doneRemoving(); }); }); }; exports.parentAttach = ParentAttachPlugin; exports.deleteChildren = DeleteChildrenPlugin;
icompuiz/pollio
server/components/nesting/index.js
JavaScript
mit
2,628
import CoreClient from './CoreClient'; export default CoreClient;
Picta-it/Jammy
app/components/CoreClient/index.js
JavaScript
mit
67
import merge from 'webpack-merge' import { isString } from '../../utils' export default (config, settings) => { if (isString(settings)) { return merge.smart(config, { entry: [settings] }) } if (Array.isArray(settings)) { return merge.smart(config, { entry: settings }) } throw new Error('Unexpected webpack entry value') }
devdigital/webpack-standards
src/configs/standard/entry.config.js
JavaScript
mit
344
// I am well aware this could be so very much tidier, // we are going fo basic functionality first. // will tidy up later. var boilerplate = function() { this.popup = function(html) { $('#popup').html(html); // add X var close = '<img id="close" src="libs/icons/close.png"></img>'; $('#popup').append(close); $('#close').on('click', function() { $('#magic_positioning_table').hide(); $('#overlay').hide(); }); // add overlay $('#overlay').show(); $('#magic_positioning_table').show(); }; // for ajax popup use: $('#popup').load(URL, function(html) { popup(html); }); }; $(document).ready(function() { // add in hamburger menu to open aside if aside is present if ($('#aside').length>0) { var hamburger = '<img id="hamburger" src="libs/icons/hamburger.png"></img>'; $('#header').append(hamburger); $('#hamburger').on('click', function() { if (!$('#aside').is(':visible')) { $('#aside').show(); $('#header, #footer, #main').transition({ 'left': $('#aside').width() }, 300); } else { $('#header, #footer, #main').transition({ 'left': '0' }, 300, function() { $('#aside').hide(); // in case there is no BG color on the main area's }); } }); // also swipe right to open $$('#main').swipeRight(function(){ if (!$('#aside').is(':visible')) { $('#aside').show(); $('#header, #footer, #main').transition({ 'left': $('#aside').width() }, 300); } }); $$('#main, #aside').swipeLeft(function() { if ($('#aside').is(':visible')) { $('#header, #footer, #main').transition({ 'left': '0' }, 300, function() { $('#aside').hide(); // in case there is no BG color on the main area's }); } }); } // add in the modal popup div (and overlay) var popup = '<div id="popup" class="white"></div>'; var overlay = '<div id="overlay"></div>'; var magic_positioning_table = '<table id="magic_positioning_table">'+ '<tr><td colspan="4"></td></tr>' + '<tr><td></td><td class="popupcell"></td><td></td></tr>' + '<tr><td colspan="4"></td></tr>' + '</table>'; $('body').append(popup); $('body').append(overlay); $('body').append(magic_positioning_table); $('#popup').appendTo('#magic_positioning_table td.popupcell'); // apply the landscape-fullscreen class - removal of which // allows turning off the full screen on rotate behaviour // HAVE TURNED THIS OFF - CONFUSING AND ALSO CAUSES ISSUE WHEN NO ASSIDE - BUT A NEAT IDEA STILL //$('#header, #footer, #main, #aside, #popup').addClass('landscape-fullscreen'); });
krisrandall/boilerplate
libs/boilerplate/js/boilerplate.js
JavaScript
mit
2,582
import React from 'react'; import { render as mount } from 'enzyme'; import { Provider as ContextProvider } from '../common/context'; import Message from './Message'; describe('Message', () => { function render(message, context) { // need the spans otherwise the document has 0 html elements in it. return mount( <span> <ContextProvider value={context}>{message}</ContextProvider> </span>, ); } it('translates the given message', () => { const translateAsParts = jest.fn(() => [ { dangerous: false, value: 'translated ' }, { dangerous: true, value: 'value' }, ]); const context = { translateAsParts }; const component = render(<Message>message.id</Message>, context); expect(translateAsParts).toHaveBeenCalledTimes(1); expect(translateAsParts).toHaveBeenCalledWith('message.id', {}); expect(component.text()).toEqual('translated value'); }); it('translates with parameters', () => { const translateAsParts = jest.fn((key, params) => [ { dangerous: false, value: 'translated value ' }, { dangerous: true, value: params.test }, ]); const context = { translateAsParts }; const component = render(<Message params={{ test: 'hello' }}>message.id</Message>, context); expect(translateAsParts).toHaveBeenCalledTimes(1); expect(translateAsParts).toHaveBeenCalledWith('message.id', { test: 'hello' }); expect(component.text()).toEqual('translated value hello'); }); it('translates with sanitized html', () => { const html = '<h1>this is a heading<b>with bold</b></h1>'; const translateAsParts = jest.fn(() => [{ dangerous: false, value: html }]); const context = { translateAsParts }; const component = render(<Message>message.id</Message>, context); expect(component.html()).toBe( '&lt;h1&gt;this is a heading&lt;b&gt;with bold&lt;/b&gt;&lt;/h1&gt;', ); }); it('allows to translate things as html', () => { const translateAsParts = jest.fn(() => [ { dangerous: false, value: '<h1>some safe html</h1>' }, { dangerous: true, value: '<span>some sketchy user input</span>' }, ]); const context = { translateAsParts }; const component = render(<Message dangerouslyTranslateInnerHTML="message.id" />, context); expect(component.html()).toBe( '<span><h1>some safe html</h1></span>&lt;span&gt;some sketchy user input&lt;/span&gt;', ); }); it('allows to translate into a string', () => { const translateAsParts = jest.fn(() => [ { dangerous: false, value: 'just some ' }, { dangerous: true, value: 'text' }, ]); const context = { translateAsParts }; const component = render(<Message asString>message.id</Message>, context); expect(component.html()).toBe('just some text'); }); });
Tankenstein/retranslate
src/message/Message.spec.js
JavaScript
mit
2,811
/** * @param {number[]} nums * @return {void} Do not return anything, modify nums in-place instead. */ var sortColors = function(nums) { nums.sort(); };
Rhadow/leetcode
leetcode/Medium/075_Sort_Colors.js
JavaScript
mit
160
define(function (require) { 'use strict'; /** * Module dependencies */ var defineComponent = require('flight/lib/component'); var tweetItems = require('component/tweet_items'); var templates = require('templates'); var _ = require('underscore'); /** * Module exports */ return defineComponent(searchColumn); /** * Module function */ function searchColumn() { this.defaultAttrs({ query: null, // selectors titleSelector: '.title', tweetHolderSelector: '.td-tweet-holder' }); this.onTitleChangeRequested = function () { this.trigger('uiShowSearchPrompt'); }; this.onSearchPromptSave = function (ev, data) { console.log('New search query: ', data.query); this.attr.query = data.query; this.update(); }; this.onRemove = function (ev, data) { ev.stopPropagation(); this.teardown(); // Reraise with tag annotation this.trigger('uiRemoveColumnRequested', { tag: this.attr.tag }); }; this.render = function () { this.node.innerHTML = templates.column(); // Not very pretty ... this.select('titleSelector')[0].childNodes[0].bind( 'textContent', this.model, 'title'); this.update(); }; this.update = function () { this.model.title = 'Search: ' + this.attr.query; console.log('Model for', this.node, ':', this.model); this.requestStream(); Platform.performMicrotaskCheckpoint(); }; this.after('initialize', function () { this.tag = _.uniqueId('search-'); this.model = {}; this.requestStream = function () { this.trigger('dataSearchStreamRequested', { tag: this.tag, query: this.attr.query }); }; this.render(); this.on('click', { titleSelector: this.onTitleChangeRequested }); this.on('uiSaveSearchPrompt', this.onSearchPromptSave); this.on('uiRemoveColumnRequested', this.onRemove); tweetItems.attachTo(this.select('tweetHolderSelector'), { tag: this.tag }); }); } });
passy/tweetdock
app/js/component/search_column.js
JavaScript
mit
2,120
({ block : 'page', title : 'bem-components: spin', mods : { theme : 'islands' }, head : [ { elem : 'css', url : 'gemini.css' } ], content : [ { tag : 'h2', content : 'islands' }, ['xs', 's', 'm', 'l', 'xl'].map(function(size){ return { tag : 'p', content : [ size, { tag : 'br' }, { block : 'spin', mods : { paused : true, theme : 'islands', visible : true, size : size }, cls : 'islands-' + size } ] } }) ] });
dima117/devcon-demo
Todo/Bem/libs/bem-components/common.blocks/spin/spin.tests/gemini.bemjson.js
JavaScript
mit
696
'use strict'; /* App Module */ var phonecatApp = angular.module('phonecatApp', [ 'ngRoute', 'phonecatAnimations', 'phonecatControllers', 'phonecatFilters', 'phonecatServices', ]); phonecatApp.config(['$routeProvider', function($routeProvider) { $routeProvider. when('/phones', { templateUrl: 'partials/phone-list.html', controller: 'PhoneListCtrl' }). when('/phones/:phoneId', { templateUrl: 'partials/phone-detail.html', controller: 'PhoneDetailCtrl' }). otherwise({ redirectTo: '/phones' }); }]);
JungyoonChung/cse112Angular
app/js/app.js
JavaScript
mit
601
define('jqueryui/tabs', ['jquery','jqueryui/core','jqueryui/widget'], function (jQuery) { /* * jQuery UI Tabs 1.8.16 * * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about) * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * http://docs.jquery.com/UI/Tabs * * Depends: * jquery.ui.core.js * jquery.ui.widget.js */ (function( $, undefined ) { var tabId = 0, listId = 0; function getNextTabId() { return ++tabId; } function getNextListId() { return ++listId; } $.widget( "ui.tabs", { options: { add: null, ajaxOptions: null, cache: false, cookie: null, // e.g. { expires: 7, path: '/', domain: 'jquery.com', secure: true } collapsible: false, disable: null, disabled: [], enable: null, event: "click", fx: null, // e.g. { height: 'toggle', opacity: 'toggle', duration: 200 } idPrefix: "ui-tabs-", load: null, panelTemplate: "<div></div>", remove: null, select: null, show: null, spinner: "<em>Loading&#8230;</em>", tabTemplate: "<li><a href='#{href}'><span>#{label}</span></a></li>" }, _create: function() { this._tabify( true ); }, _setOption: function( key, value ) { if ( key == "selected" ) { if (this.options.collapsible && value == this.options.selected ) { return; } this.select( value ); } else { this.options[ key ] = value; this._tabify(); } }, _tabId: function( a ) { return a.title && a.title.replace( /\s/g, "_" ).replace( /[^\w\u00c0-\uFFFF-]/g, "" ) || this.options.idPrefix + getNextTabId(); }, _sanitizeSelector: function( hash ) { // we need this because an id may contain a ":" return hash.replace( /:/g, "\\:" ); }, _cookie: function() { var cookie = this.cookie || ( this.cookie = this.options.cookie.name || "ui-tabs-" + getNextListId() ); return $.cookie.apply( null, [ cookie ].concat( $.makeArray( arguments ) ) ); }, _ui: function( tab, panel ) { return { tab: tab, panel: panel, index: this.anchors.index( tab ) }; }, _cleanup: function() { // restore all former loading tabs labels this.lis.filter( ".ui-state-processing" ) .removeClass( "ui-state-processing" ) .find( "span:data(label.tabs)" ) .each(function() { var el = $( this ); el.html( el.data( "label.tabs" ) ).removeData( "label.tabs" ); }); }, _tabify: function( init ) { var self = this, o = this.options, fragmentId = /^#.+/; // Safari 2 reports '#' for an empty hash this.list = this.element.find( "ol,ul" ).eq( 0 ); this.lis = $( " > li:has(a[href])", this.list ); this.anchors = this.lis.map(function() { return $( "a", this )[ 0 ]; }); this.panels = $( [] ); this.anchors.each(function( i, a ) { var href = $( a ).attr( "href" ); // For dynamically created HTML that contains a hash as href IE < 8 expands // such href to the full page url with hash and then misinterprets tab as ajax. // Same consideration applies for an added tab with a fragment identifier // since a[href=#fragment-identifier] does unexpectedly not match. // Thus normalize href attribute... var hrefBase = href.split( "#" )[ 0 ], baseEl; if ( hrefBase && ( hrefBase === location.toString().split( "#" )[ 0 ] || ( baseEl = $( "base" )[ 0 ]) && hrefBase === baseEl.href ) ) { href = a.hash; a.href = href; } // inline tab if ( fragmentId.test( href ) ) { self.panels = self.panels.add( self.element.find( self._sanitizeSelector( href ) ) ); // remote tab // prevent loading the page itself if href is just "#" } else if ( href && href !== "#" ) { // required for restore on destroy $.data( a, "href.tabs", href ); // TODO until #3808 is fixed strip fragment identifier from url // (IE fails to load from such url) $.data( a, "load.tabs", href.replace( /#.*$/, "" ) ); var id = self._tabId( a ); a.href = "#" + id; var $panel = self.element.find( "#" + id ); if ( !$panel.length ) { $panel = $( o.panelTemplate ) .attr( "id", id ) .addClass( "ui-tabs-panel ui-widget-content ui-corner-bottom" ) .insertAfter( self.panels[ i - 1 ] || self.list ); $panel.data( "destroy.tabs", true ); } self.panels = self.panels.add( $panel ); // invalid tab href } else { o.disabled.push( i ); } }); // initialization from scratch if ( init ) { // attach necessary classes for styling this.element.addClass( "ui-tabs ui-widget ui-widget-content ui-corner-all" ); this.list.addClass( "ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all" ); this.lis.addClass( "ui-state-default ui-corner-top" ); this.panels.addClass( "ui-tabs-panel ui-widget-content ui-corner-bottom" ); // Selected tab // use "selected" option or try to retrieve: // 1. from fragment identifier in url // 2. from cookie // 3. from selected class attribute on <li> if ( o.selected === undefined ) { if ( location.hash ) { this.anchors.each(function( i, a ) { if ( a.hash == location.hash ) { o.selected = i; return false; } }); } if ( typeof o.selected !== "number" && o.cookie ) { o.selected = parseInt( self._cookie(), 10 ); } if ( typeof o.selected !== "number" && this.lis.filter( ".ui-tabs-selected" ).length ) { o.selected = this.lis.index( this.lis.filter( ".ui-tabs-selected" ) ); } o.selected = o.selected || ( this.lis.length ? 0 : -1 ); } else if ( o.selected === null ) { // usage of null is deprecated, TODO remove in next release o.selected = -1; } // sanity check - default to first tab... o.selected = ( ( o.selected >= 0 && this.anchors[ o.selected ] ) || o.selected < 0 ) ? o.selected : 0; // Take disabling tabs via class attribute from HTML // into account and update option properly. // A selected tab cannot become disabled. o.disabled = $.unique( o.disabled.concat( $.map( this.lis.filter( ".ui-state-disabled" ), function( n, i ) { return self.lis.index( n ); }) ) ).sort(); if ( $.inArray( o.selected, o.disabled ) != -1 ) { o.disabled.splice( $.inArray( o.selected, o.disabled ), 1 ); } // highlight selected tab this.panels.addClass( "ui-tabs-hide" ); this.lis.removeClass( "ui-tabs-selected ui-state-active" ); // check for length avoids error when initializing empty list if ( o.selected >= 0 && this.anchors.length ) { self.element.find( self._sanitizeSelector( self.anchors[ o.selected ].hash ) ).removeClass( "ui-tabs-hide" ); this.lis.eq( o.selected ).addClass( "ui-tabs-selected ui-state-active" ); // seems to be expected behavior that the show callback is fired self.element.queue( "tabs", function() { self._trigger( "show", null, self._ui( self.anchors[ o.selected ], self.element.find( self._sanitizeSelector( self.anchors[ o.selected ].hash ) )[ 0 ] ) ); }); this.load( o.selected ); } // clean up to avoid memory leaks in certain versions of IE 6 // TODO: namespace this event $( window ).bind( "unload", function() { self.lis.add( self.anchors ).unbind( ".tabs" ); self.lis = self.anchors = self.panels = null; }); // update selected after add/remove } else { o.selected = this.lis.index( this.lis.filter( ".ui-tabs-selected" ) ); } // update collapsible // TODO: use .toggleClass() this.element[ o.collapsible ? "addClass" : "removeClass" ]( "ui-tabs-collapsible" ); // set or update cookie after init and add/remove respectively if ( o.cookie ) { this._cookie( o.selected, o.cookie ); } // disable tabs for ( var i = 0, li; ( li = this.lis[ i ] ); i++ ) { $( li )[ $.inArray( i, o.disabled ) != -1 && // TODO: use .toggleClass() !$( li ).hasClass( "ui-tabs-selected" ) ? "addClass" : "removeClass" ]( "ui-state-disabled" ); } // reset cache if switching from cached to not cached if ( o.cache === false ) { this.anchors.removeData( "cache.tabs" ); } // remove all handlers before, tabify may run on existing tabs after add or option change this.lis.add( this.anchors ).unbind( ".tabs" ); if ( o.event !== "mouseover" ) { var addState = function( state, el ) { if ( el.is( ":not(.ui-state-disabled)" ) ) { el.addClass( "ui-state-" + state ); } }; var removeState = function( state, el ) { el.removeClass( "ui-state-" + state ); }; this.lis.bind( "mouseover.tabs" , function() { addState( "hover", $( this ) ); }); this.lis.bind( "mouseout.tabs", function() { removeState( "hover", $( this ) ); }); this.anchors.bind( "focus.tabs", function() { addState( "focus", $( this ).closest( "li" ) ); }); this.anchors.bind( "blur.tabs", function() { removeState( "focus", $( this ).closest( "li" ) ); }); } // set up animations var hideFx, showFx; if ( o.fx ) { if ( $.isArray( o.fx ) ) { hideFx = o.fx[ 0 ]; showFx = o.fx[ 1 ]; } else { hideFx = showFx = o.fx; } } // Reset certain styles left over from animation // and prevent IE's ClearType bug... function resetStyle( $el, fx ) { $el.css( "display", "" ); if ( !$.support.opacity && fx.opacity ) { $el[ 0 ].style.removeAttribute( "filter" ); } } // Show a tab... var showTab = showFx ? function( clicked, $show ) { $( clicked ).closest( "li" ).addClass( "ui-tabs-selected ui-state-active" ); $show.hide().removeClass( "ui-tabs-hide" ) // avoid flicker that way .animate( showFx, showFx.duration || "normal", function() { resetStyle( $show, showFx ); self._trigger( "show", null, self._ui( clicked, $show[ 0 ] ) ); }); } : function( clicked, $show ) { $( clicked ).closest( "li" ).addClass( "ui-tabs-selected ui-state-active" ); $show.removeClass( "ui-tabs-hide" ); self._trigger( "show", null, self._ui( clicked, $show[ 0 ] ) ); }; // Hide a tab, $show is optional... var hideTab = hideFx ? function( clicked, $hide ) { $hide.animate( hideFx, hideFx.duration || "normal", function() { self.lis.removeClass( "ui-tabs-selected ui-state-active" ); $hide.addClass( "ui-tabs-hide" ); resetStyle( $hide, hideFx ); self.element.dequeue( "tabs" ); }); } : function( clicked, $hide, $show ) { self.lis.removeClass( "ui-tabs-selected ui-state-active" ); $hide.addClass( "ui-tabs-hide" ); self.element.dequeue( "tabs" ); }; // attach tab event handler, unbind to avoid duplicates from former tabifying... this.anchors.bind( o.event + ".tabs", function() { var el = this, $li = $(el).closest( "li" ), $hide = self.panels.filter( ":not(.ui-tabs-hide)" ), $show = self.element.find( self._sanitizeSelector( el.hash ) ); // If tab is already selected and not collapsible or tab disabled or // or is already loading or click callback returns false stop here. // Check if click handler returns false last so that it is not executed // for a disabled or loading tab! if ( ( $li.hasClass( "ui-tabs-selected" ) && !o.collapsible) || $li.hasClass( "ui-state-disabled" ) || $li.hasClass( "ui-state-processing" ) || self.panels.filter( ":animated" ).length || self._trigger( "select", null, self._ui( this, $show[ 0 ] ) ) === false ) { this.blur(); return false; } o.selected = self.anchors.index( this ); self.abort(); // if tab may be closed if ( o.collapsible ) { if ( $li.hasClass( "ui-tabs-selected" ) ) { o.selected = -1; if ( o.cookie ) { self._cookie( o.selected, o.cookie ); } self.element.queue( "tabs", function() { hideTab( el, $hide ); }).dequeue( "tabs" ); this.blur(); return false; } else if ( !$hide.length ) { if ( o.cookie ) { self._cookie( o.selected, o.cookie ); } self.element.queue( "tabs", function() { showTab( el, $show ); }); // TODO make passing in node possible, see also http://dev.jqueryui.com/ticket/3171 self.load( self.anchors.index( this ) ); this.blur(); return false; } } if ( o.cookie ) { self._cookie( o.selected, o.cookie ); } // show new tab if ( $show.length ) { if ( $hide.length ) { self.element.queue( "tabs", function() { hideTab( el, $hide ); }); } self.element.queue( "tabs", function() { showTab( el, $show ); }); self.load( self.anchors.index( this ) ); } else { throw "jQuery UI Tabs: Mismatching fragment identifier."; } // Prevent IE from keeping other link focussed when using the back button // and remove dotted border from clicked link. This is controlled via CSS // in modern browsers; blur() removes focus from address bar in Firefox // which can become a usability and annoying problem with tabs('rotate'). if ( $.browser.msie ) { this.blur(); } }); // disable click in any case this.anchors.bind( "click.tabs", function(){ return false; }); }, _getIndex: function( index ) { // meta-function to give users option to provide a href string instead of a numerical index. // also sanitizes numerical indexes to valid values. if ( typeof index == "string" ) { index = this.anchors.index( this.anchors.filter( "[href$=" + index + "]" ) ); } return index; }, destroy: function() { var o = this.options; this.abort(); this.element .unbind( ".tabs" ) .removeClass( "ui-tabs ui-widget ui-widget-content ui-corner-all ui-tabs-collapsible" ) .removeData( "tabs" ); this.list.removeClass( "ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all" ); this.anchors.each(function() { var href = $.data( this, "href.tabs" ); if ( href ) { this.href = href; } var $this = $( this ).unbind( ".tabs" ); $.each( [ "href", "load", "cache" ], function( i, prefix ) { $this.removeData( prefix + ".tabs" ); }); }); this.lis.unbind( ".tabs" ).add( this.panels ).each(function() { if ( $.data( this, "destroy.tabs" ) ) { $( this ).remove(); } else { $( this ).removeClass([ "ui-state-default", "ui-corner-top", "ui-tabs-selected", "ui-state-active", "ui-state-hover", "ui-state-focus", "ui-state-disabled", "ui-tabs-panel", "ui-widget-content", "ui-corner-bottom", "ui-tabs-hide" ].join( " " ) ); } }); if ( o.cookie ) { this._cookie( null, o.cookie ); } return this; }, add: function( url, label, index ) { if ( index === undefined ) { index = this.anchors.length; } var self = this, o = this.options, $li = $( o.tabTemplate.replace( /#\{href\}/g, url ).replace( /#\{label\}/g, label ) ), id = !url.indexOf( "#" ) ? url.replace( "#", "" ) : this._tabId( $( "a", $li )[ 0 ] ); $li.addClass( "ui-state-default ui-corner-top" ).data( "destroy.tabs", true ); // try to find an existing element before creating a new one var $panel = self.element.find( "#" + id ); if ( !$panel.length ) { $panel = $( o.panelTemplate ) .attr( "id", id ) .data( "destroy.tabs", true ); } $panel.addClass( "ui-tabs-panel ui-widget-content ui-corner-bottom ui-tabs-hide" ); if ( index >= this.lis.length ) { $li.appendTo( this.list ); $panel.appendTo( this.list[ 0 ].parentNode ); } else { $li.insertBefore( this.lis[ index ] ); $panel.insertBefore( this.panels[ index ] ); } o.disabled = $.map( o.disabled, function( n, i ) { return n >= index ? ++n : n; }); this._tabify(); if ( this.anchors.length == 1 ) { o.selected = 0; $li.addClass( "ui-tabs-selected ui-state-active" ); $panel.removeClass( "ui-tabs-hide" ); this.element.queue( "tabs", function() { self._trigger( "show", null, self._ui( self.anchors[ 0 ], self.panels[ 0 ] ) ); }); this.load( 0 ); } this._trigger( "add", null, this._ui( this.anchors[ index ], this.panels[ index ] ) ); return this; }, remove: function( index ) { index = this._getIndex( index ); var o = this.options, $li = this.lis.eq( index ).remove(), $panel = this.panels.eq( index ).remove(); // If selected tab was removed focus tab to the right or // in case the last tab was removed the tab to the left. if ( $li.hasClass( "ui-tabs-selected" ) && this.anchors.length > 1) { this.select( index + ( index + 1 < this.anchors.length ? 1 : -1 ) ); } o.disabled = $.map( $.grep( o.disabled, function(n, i) { return n != index; }), function( n, i ) { return n >= index ? --n : n; }); this._tabify(); this._trigger( "remove", null, this._ui( $li.find( "a" )[ 0 ], $panel[ 0 ] ) ); return this; }, enable: function( index ) { index = this._getIndex( index ); var o = this.options; if ( $.inArray( index, o.disabled ) == -1 ) { return; } this.lis.eq( index ).removeClass( "ui-state-disabled" ); o.disabled = $.grep( o.disabled, function( n, i ) { return n != index; }); this._trigger( "enable", null, this._ui( this.anchors[ index ], this.panels[ index ] ) ); return this; }, disable: function( index ) { index = this._getIndex( index ); var self = this, o = this.options; // cannot disable already selected tab if ( index != o.selected ) { this.lis.eq( index ).addClass( "ui-state-disabled" ); o.disabled.push( index ); o.disabled.sort(); this._trigger( "disable", null, this._ui( this.anchors[ index ], this.panels[ index ] ) ); } return this; }, select: function( index ) { index = this._getIndex( index ); if ( index == -1 ) { if ( this.options.collapsible && this.options.selected != -1 ) { index = this.options.selected; } else { return this; } } this.anchors.eq( index ).trigger( this.options.event + ".tabs" ); return this; }, load: function( index ) { index = this._getIndex( index ); var self = this, o = this.options, a = this.anchors.eq( index )[ 0 ], url = $.data( a, "load.tabs" ); this.abort(); // not remote or from cache if ( !url || this.element.queue( "tabs" ).length !== 0 && $.data( a, "cache.tabs" ) ) { this.element.dequeue( "tabs" ); return; } // load remote from here on this.lis.eq( index ).addClass( "ui-state-processing" ); if ( o.spinner ) { var span = $( "span", a ); span.data( "label.tabs", span.html() ).html( o.spinner ); } this.xhr = $.ajax( $.extend( {}, o.ajaxOptions, { url: url, success: function( r, s ) { self.element.find( self._sanitizeSelector( a.hash ) ).html( r ); // take care of tab labels self._cleanup(); if ( o.cache ) { $.data( a, "cache.tabs", true ); } self._trigger( "load", null, self._ui( self.anchors[ index ], self.panels[ index ] ) ); try { o.ajaxOptions.success( r, s ); } catch ( e ) {} }, error: function( xhr, s, e ) { // take care of tab labels self._cleanup(); self._trigger( "load", null, self._ui( self.anchors[ index ], self.panels[ index ] ) ); try { // Passing index avoid a race condition when this method is // called after the user has selected another tab. // Pass the anchor that initiated this request allows // loadError to manipulate the tab content panel via $(a.hash) o.ajaxOptions.error( xhr, s, index, a ); } catch ( e ) {} } } ) ); // last, so that load event is fired before show... self.element.dequeue( "tabs" ); return this; }, abort: function() { // stop possibly running animations this.element.queue( [] ); this.panels.stop( false, true ); // "tabs" queue must not contain more than two elements, // which are the callbacks for the latest clicked tab... this.element.queue( "tabs", this.element.queue( "tabs" ).splice( -2, 2 ) ); // terminate pending requests from other tabs if ( this.xhr ) { this.xhr.abort(); delete this.xhr; } // take care of tab labels this._cleanup(); return this; }, url: function( index, url ) { this.anchors.eq( index ).removeData( "cache.tabs" ).data( "load.tabs", url ); return this; }, length: function() { return this.anchors.length; } }); $.extend( $.ui.tabs, { version: "1.8.16" }); /* * Tabs Extensions */ /* * Rotate */ $.extend( $.ui.tabs.prototype, { rotation: null, rotate: function( ms, continuing ) { var self = this, o = this.options; var rotate = self._rotate || ( self._rotate = function( e ) { clearTimeout( self.rotation ); self.rotation = setTimeout(function() { var t = o.selected; self.select( ++t < self.anchors.length ? t : 0 ); }, ms ); if ( e ) { e.stopPropagation(); } }); var stop = self._unrotate || ( self._unrotate = !continuing ? function(e) { if (e.clientX) { // in case of a true click self.rotate(null); } } : function( e ) { t = o.selected; rotate(); }); // start rotation if ( ms ) { this.element.bind( "tabsshow", rotate ); this.anchors.bind( o.event + ".tabs", stop ); rotate(); // stop rotation } else { clearTimeout( self.rotation ); this.element.unbind( "tabsshow", rotate ); this.anchors.unbind( o.event + ".tabs", stop ); delete this._rotate; delete this._unrotate; } return this; } }); })( jQuery ); });
ticup/SynerJ
public/libs/jquery-ui-require/jqueryui/tabs.js
JavaScript
mit
21,339
import ApplicationSerializer from './application'; export default ApplicationSerializer.extend({ normalize: function(type, hash) { delete hash['author_email']; delete hash['author_name']; delete hash['branch']; delete hash['committed_at']; delete hash['committer_email']; delete hash['committer_name']; delete hash['compare_url']; delete hash['duration']; delete hash['event_type']; delete hash['finished_at']; delete hash['job_ids']; delete hash['message']; delete hash['number']; delete hash['pull_request']; delete hash['pull_request_number']; delete hash['pull_request_title']; delete hash['started_at']; return this._super(type, hash); } });
IvyApp/ivy-notifier
tests/dummy/app/serializers/build.js
JavaScript
mit
725
const { decode, parse } = require('./response') describe('Protocol > Requests > ListOffsets > v1', () => { test('response', async () => { const data = await decode(Buffer.from(require('../fixtures/v1_response.json'))) expect(data).toEqual({ responses: [ { topic: 'test-topic-16e956902e39874d06f5-91705-2958a472-e582-47a4-86f0-b258630fb3e6', partitions: [{ partition: 0, errorCode: 0, timestamp: '1543343103774', offset: '0' }], }, ], }) await expect(parse(data)).resolves.toBeTruthy() }) })
tulios/kafkajs
src/protocol/requests/listOffsets/v1/response.spec.js
JavaScript
mit
561
import React from 'react' import { Header } from 'components/Header/Header' import { IndexLink, Link } from 'react-router' import { shallow } from 'enzyme' describe('(Component) Header', () => { let _wrapper beforeEach(() => { _wrapper = shallow(<Header />) }) it('Renders a welcome message', () => { const welcome = _wrapper.find('h1') expect(welcome).to.exist expect(welcome.text()).to.match(/React Redux Starter Kit/) }) describe('Navigation links...', () => { it('Should render a Link to home route', () => { expect(_wrapper.contains( <IndexLink activeClassName='route--active' to='/'> Home </IndexLink> )).to.be.true }) it('Should render a Link to Counter route', () => { expect(_wrapper.contains( <Link activeClassName='route--active' to='/counter'> Counter </Link> )).to.be.true }) }) })
gauravnagar1981/ecommerce
tests/components/Header/Header.spec.js
JavaScript
mit
922
define([], function() { 'use strict'; /** * Prints a debugging console message for a shortcut * * @param {Shortcut} shortcut - shortcut object */ var printDebugConsoleMessage = function(shortcut) { console.log('Shortcut "' + shortcut.name + '" triggered with key "' + shortcut.key + '"', shortcut); }; return { printMessage: printDebugConsoleMessage }; });
mitermayer/shortcut-untangler
src/js/lib/debug/Tools.js
JavaScript
mit
419
var game = new Phaser.Game(450, 350, Phaser.CANVAS, '', { preload: preload, create: create, update: update }); function preload(){ game.stage.backgroundColor='#000066'; game.load.image('correct','assets/correct.png'); game.load.image('incorrect','assets/incorrect.png'); game.load.spritesheet('greenbutton','assets/greenbutton.png',186,43); game.load.audio('correct',['assets/correct.mp3','assets/correct.ogg']); game.load.audio('incorrect',['assets/incorrect.mp3','assets/incorrect.ogg']); game.load.audio('button',['assets/buttonclick.mp3','assets/buttonclick.ogg']); game.load.audio('beep',['assets/beep.mp3','assets/beep.ogg']); game.load.audio('pop1',['assets/pop1.mp3','assets/pop1.ogg']); }; var round = []; var sceneIndex = 0; var inScene = false; var inRound = -1; var titleFontStyle = {font:'26px Arial',fill:'#FFFFFF',align:'center'}; var buttonFontStyle= {font:'20px Arial',fill:'#FFFFFF',align:'center'}; var bodyFontStyle = {font:'15px Arial',fill:'#FFFFFF',align:'center'}; var scoreFontStyle = {font:'18px Arial',fill:'#FFFFFF',align:'right'}; var titleText; var bodyText; var goButton; var goButtonText; var timerInterval; var buttonSound; var beepSound; var roundTimerText; var roundTimerValue = 30; var roundTimerInterval; var roundTitleText; var button1; var button2; var button3; var button1Text; var button2Text; var button3Text; var isDisplaying = false; var displayWordObject; var displayWordText; var correctIcon; var incorrectIcon; var correctSound; var incorrectSound; var roundStarted = false; var score=0; var roundScore=0; var resultTimeLeftText; var resultScoreText; var resultTotalText; var nextRoundButton; var nextRoundButtonText; var roundCompleteText; var ul1; var ul2; var questionsRight=0; var questionsWrong=0; var secondsUsed=0; var totalQuestions=0; var finalTitleText; var finalQRightText; var finalQWrongText; var finalSecondsUsedText; var finalAccuracyText; var finalSpeedText; var finalScoreText var finalGroup; var readyForNext = false; var noGuessesLeft= false; var numberOfQuestions=0; var roundsLeft; var resetButton; var resetButtonText; function create(){ Phaser.Canvas.setSmoothingEnabled(game.context, false); buttonSound = game.add.audio('button'); beepSound = game.add.audio('beep'); pop1Sound = game.add.audio('pop1'); correctSound = game.add.audio('correct'); incorrectSound = game.add.audio('incorrect'); }; function introduction(){ titleText = game.add.text(game.world.centerX,((game.world.height/7)*2),'Guess the Category!',titleFontStyle); titleText.anchor.setTo(0.5,0.5); bodyText = game.add.text(game.world.centerX,((game.world.height/7)*3.25),'Instructions: Words and phrases will appear \n on the screen. Guess the category the word\n or phrase belongs to before time runs out!',bodyFontStyle); bodyText.anchor.setTo(0.5,0.5); goButton = game.add.button(game.world.centerX,((game.world.height/7)*5),'greenbutton',nextScene,this,0,1,2); goButton.anchor.setTo(0.5,0.5); goButtonText = game.add.text(goButton.x,goButton.y,'Let\'s Go!',titleFontStyle); goButtonText.anchor.setTo(0.5,0.5); setQuestions(); }; function introductionFadeOut(){ buttonSound.play(); var tw1 = game.add.tween(titleText).to( { alpha: 0 }, 750, Phaser.Easing.Linear.None, true, 0, 0, false); tw1.onCompleteCallback(nextScene); game.add.tween(bodyText).to( { alpha: 0 }, 750, Phaser.Easing.Linear.None, true, 0, 0, false); game.add.tween(goButton).to( { alpha: 0 }, 750, Phaser.Easing.Linear.None, true, 0, 0, false); game.add.tween(goButtonText).to( { alpha: 0 }, 750, Phaser.Easing.Linear.None, true, 0, 0, false); }; function setReady(){ readyForNext = true; }; function roundCountdown(roundText){ readyForNext=false; roundTitleText = game.add.text(game.world.centerX,100,roundText,titleFontStyle); roundTitleText.anchor.setTo(0.5,0.5); var timerValue = 3; var timerText = game.add.text(game.world.centerX,game.world.centerY,timerValue,{font:'50px Arial',fill:'#FFFFFF',align:'center'}); timerText.anchor.setTo(0.5,0.5); this.countdown = function(){ beepSound.play(); timerValue--; timerText.setText(timerValue); if(timerValue<=0){ game.add.tween(roundTitleText).to({x:10,y:20},750,Phaser.Easing.Quadratic.Out,true,0,0,false) game.add.tween(timerText).to({alpha:0},750,Phaser.Easing.Linear.None,true,0,0,false); roundTitleText.anchor.setTo(0,0.5); clearInterval(timerInterval); readyForNext=true; nextScene(); }; }; timerInterval = setInterval(this.countdown,1000); beepSound.play(); }; function nextScene(){ if(!readyForNext){ return; }; sceneIndex++; inScene = false; }; function startRound(roundData){ noGuessesLeft=false; readyForNext=false; roundTimerText = game.add.text(game.world.width-60,20,'Time: '+roundTimerValue,titleFontStyle); roundTimerText.alpha = 0; roundTimerText.anchor.setTo(0.5,0.5); var timerFadeIn = game.add.tween(roundTimerText).to({alpha:1},1000,Phaser.Easing.Linear.None,true,0,0,false); timerFadeIn.onCompleteCallback(function(){roundTimerInterval = setInterval(countDown,1000)}); var categories = []; for(var questions in roundData){ if(categories.indexOf(roundData[questions].category)==-1){ categories.push(roundData[questions].category); }; }; button1 = game.add.button(105,game.world.height-50,'greenbutton',guess,button1,0,1,2); button1.category = categories[0]; button1.anchor.setTo(0.5,0.5); button1Text = game.add.text(button1.x,button1.y,categories[0],buttonFontStyle); button1Text.anchor.setTo(0.5,0.5); button1.alpha = 0; button1Text.alpha = 0; game.add.tween(button1).to({alpha:1},1000,Phaser.Easing.Linear.None,true,0,0,false); game.add.tween(button1Text).to({alpha:1},1000,Phaser.Easing.Linear.None,true,0,0,false); button2 = game.add.button(game.world.width-110,game.world.height-50,'greenbutton',guess,button2,0,1,2); button2.category = categories[1]; button2.anchor.setTo(0.5,0.5); button2Text = game.add.text(button2.x,button2.y,categories[1],buttonFontStyle); button2Text.anchor.setTo(0.5,0.5); button2.alpha = 0; button2Text.alpha=0; game.add.tween(button2).to({alpha:1},1000,Phaser.Easing.Linear.None,true,0,0,false); game.add.tween(button2Text).to({alpha:1},1000,Phaser.Easing.Linear.None,true,0,0,false); if(categories.length===3){ button3 = game.add.button(game.world.centerX,game.world.height-100,'greenbutton',guess,button3,0,1,2); button3.category = categories[2]; button3.anchor.setTo(0.5,0.5); button3Text = game.add.text(button3.x,button3.y,categories[2],buttonFontStyle); button3Text.anchor.setTo(0.5,0.5); button3.alpha=0; button3Text.alpha =0; game.add.tween(button3).to({alpha:1},1000,Phaser.Easing.Linear.None,true,0,0,false); game.add.tween(button3Text).to({alpha:1},1000,Phaser.Easing.Linear.None,true,0,0,false); }; }; function guess(button){ if(noGuessesLeft){ return; }; totalQuestions++; if(button.category === displayWordObject.category){ //console.log("Correct!") questionsRight++; roundScore++; correctIcon = game.add.sprite(game.world.centerX,game.world.centerY-100,'correct'); correctIcon.anchor.setTo(0.5,0.5); correctSound.play(); game.add.tween(correctIcon).to({alpha:0},750,Phaser.Easing.Linear.None,true,0,0,false); }else{ //console.log("Incorrect!") questionsWrong++; incorrectIcon = game.add.sprite(game.world.centerX,game.world.centerY-100,'incorrect'); incorrectIcon.anchor.setTo(0.5,0.5); incorrectSound.play(); game.add.tween(incorrectIcon).to({alpha:0},750,Phaser.Easing.Linear.None,true,0,0,false); }; for(var k=0;k<round[inRound].length;k++){ var obj = round[inRound][k]; if(obj == displayWordObject){ round[inRound].splice(k,1); break; }; }; var dt = game.add.tween(displayWordText).to({alpha:0},500,Phaser.Easing.Linear.None,true,0,0,false); dt.onCompleteCallback(killWord); }; function killWord(){ displayWordText.destroy(); isDisplaying=false; }; function displayWord(roundData){ if(noGuessesLeft){ return; }; //console.log("inRound="+inRound); //console.log(roundData) if(roundData.length==0){ readyForNext=true; noGuessesLeft=true; nextScene(); return; }; pop1Sound.play(); var randomNumber = Math.floor(Math.random()*roundData.length); displayWordObject = roundData[randomNumber]; displayWordText=game.add.text(game.world.centerX,game.world.centerY-25,displayWordObject.text,titleFontStyle); displayWordText.anchor.setTo(0.5,0.5); displayWordText.scale.x = 0; displayWordText.scale.y = 0; game.add.tween(displayWordText.scale).to({x:1,y:1},500,Phaser.Easing.Elastic.Out,true,0,0,false); }; function setQuestions(){ round = []; round.push([{text:"Prosecuted by the state",category:"Crime"}, {text:"Punished by the state",category:"Crime"}, {text:"Violation of a\n written (codified) law",category:"Crime"}, {text:"Violation of social\n norms or expectations",category:"Deviance"}, {text:"Punished by social\n exclusion, stigmatization",category:"Deviance"}]); round.push([{text:"Bad or evil in itself",category:"Mala in Se"}, {text:"Murder, robbery,\n sexual assault",category:"Mala in Se"}, {text:"Most societies have\n criminal prohibitions",category:"Mala in Se"}, {text:"Widespread agreement\n between cultures and societies",category:"Mala in Se"}, {text:"Most people would recognize\n the behaviour as wrong, even \nwithout a law prohibiting it",category:"Mala in Se"}, {text:"Bad because it’s prohibited",category:"Mala Prohibita"}, {text:"Differs from society to\n society and culture to culture",category:"Mala Prohibita"}, {text:"Polygamy",category:"Mala Prohibita"}, {text:"Homosexuality",category:"Mala Prohibita"}, {text:"May be illegal at some\n times, but not at other times",category:"Mala Prohibita"}]); round.push([{text:"Ordered by judge at\n time of sentencing",category:"Probation"}, {text:"Cannot exceed three years",category:"Probation"}, {text:"Is a sentence in itself",category:"Probation"}, {text:"May be combined with\n community service",category:"Probation"}, {text:"Usual eligibility date\n at one-third of sentence",category:"Parole"}, {text:"Granted by parole board",category:"Parole"}, {text:"Imprisoned offender must\n apply for release",category:"Parole"}, {text:"Eligibility date of 10-25\n years for murder",category:"Parole"}, {text:"Automatic at two-thirds\n of sentence",category:"Statuatory Release"}, {text:"Parole board cannot deny\n without a compelling reason",category:"Statuatory Release"}]); roundsLeft = round.length; for(var i=0;i<round.length;i++){ numberOfQuestions+=round[i].length; }; setReady(); }; function countDown(){ if(!roundStarted){ inRound++; roundStarted=true; isDisplaying=false; }; roundTimerValue--; secondsUsed++; if(roundTimerValue>5){ roundTimerText.setText("Time: "+roundTimerValue); }else if(roundTimerValue<=5&&roundTimerValue>=0){ beepSound.play(); roundTimerText.setText("Time: "+roundTimerValue); }; if(roundTimerValue<0){ noGuessesLeft=true; clearInterval(roundTimerInterval); game.add.tween(displayWordText).to({alpha:0},1000,Phaser.Easing.Linear.None,true,0,0,false); readyForNext=true; roundTimerValue=0; nextScene(); }; }; function roundResults(){ readyForNext=false; //console.log("Rounds Left: "+roundsLeft); roundsLeft--; roundCompleteText = game.add.text(game.world.centerX,game.world.centerY,"Round Complete!",titleFontStyle); roundCompleteText.anchor.setTo(0.5,0.5); roundCompleteText.alpha=0; game.add.tween(roundCompleteText).to({alpha:1},1000,Phaser.Easing.Linear.None,true,0,0,false).to({y:100},1000,Phaser.Easing.Quadratic.Out,true,0,0,false); ul1 = game.add.graphics(25,62); ul1.lineStyle(1.5,0xffff00,1); ul1.beginFill(); ul1.moveTo(25,62); ul1.lineTo(375,62); ul1.endFill(); ul1.alpha = 0; game.add.tween(ul1).to({alpha:1},500,Phaser.Easing.Linear.None).delay(1750).start(); resultScoreText = game.add.text(game.world.centerX+160,game.world.centerY-25,"Score: "+roundScore+" answers x 1000 = "+(roundScore*1000)+" points",scoreFontStyle); resultScoreText.anchor.setTo(1,0.5); resultScoreText.alpha=0; game.add.tween(resultScoreText).to({alpha:1},1000,Phaser.Easing.Linear.None).delay(2000).start(); resultTimeLeftText = game.add.text(game.world.centerX+160,game.world.centerY,"Time Left: "+roundTimerValue+' x 100 = '+(roundTimerValue*100)+' points',scoreFontStyle); resultTimeLeftText.anchor.setTo(1,0.5); resultTimeLeftText.alpha=0; game.add.tween(resultTimeLeftText).to({alpha:1},1000,Phaser.Easing.Linear.None).delay(2500).start(); ul2 = game.add.graphics(25,100); ul2.lineStyle(1.5,0xFFFF00,1); ul2.beginFill(); ul2.moveTo(25,100); ul2.lineTo(375,100); ul2.endFill(); ul2.alpha=0; game.add.tween(ul2).to({alpha:1},1000,Phaser.Easing.Linear.None).delay(3000).start(); var roundTotal = (roundScore*1000)+(roundTimerValue*100); score+=roundTotal; resultTotalText = game.add.text(game.world.centerX,game.world.centerY+50,"Round Score: "+roundTotal,titleFontStyle); resultTotalText.anchor.setTo(0.5,0.5); resultTotalText.alpha = 0; game.add.tween(resultTotalText).to({alpha:1},1000,Phaser.Easing.Linear.None).delay(4000).start(); nextRoundButton = game.add.button(game.world.centerX,300,'greenbutton',nextScene,this,0,1,2); nextRoundButton.anchor.setTo(0.5,0.5); nextRoundButton.alpha = 0; if(roundsLeft >1){ nextRoundButtonText = game.add.text(nextRoundButton.x,nextRoundButton.y,"Next Round",titleFontStyle); }else if(roundsLeft == 1){ nextRoundButtonText = game.add.text(nextRoundButton.x,nextRoundButton.y,"Final Round",titleFontStyle); }else if(roundsLeft == 0){ nextRoundButtonText = game.add.text(nextRoundButton.x,nextRoundButton.y,"Get Results",titleFontStyle); }; nextRoundButtonText.anchor.setTo(0.5,0.5); nextRoundButtonText.alpha=0; game.add.tween(nextRoundButton).to({alpha:1},1000,Phaser.Easing.Linear.None).delay(4500).start(); game.add.tween(nextRoundButtonText).to({alpha:1},1000,Phaser.Easing.Linear.None).delay(4500).start(); roundScore=0; roundTimerValue=30; roundStarted=false; setTimeout(setReady,5500); }; function resultsFadeOut(){ buttonSound.play(); game.add.tween(ul1).to({alpha:0},1000,Phaser.Easing.Linear.None,true,0,0,false) game.add.tween(ul2).to({alpha:0},1000,Phaser.Easing.Linear.None,true,0,0,false) game.add.tween(resultScoreText).to({alpha:0},1000,Phaser.Easing.Linear.None,true,0,0,false) game.add.tween(resultTimeLeftText).to({alpha:0},1000,Phaser.Easing.Linear.None,true,0,0,false) game.add.tween(resultTotalText).to({alpha:0},1000,Phaser.Easing.Linear.None,true,0,0,false) game.add.tween(nextRoundButton).to({alpha:0},1000,Phaser.Easing.Linear.None,true,0,0,false) game.add.tween(roundCompleteText).to({alpha:0},1000,Phaser.Easing.Linear.None,true,0,0,false) var nb = game.add.tween(nextRoundButtonText).to({alpha:0},1000,Phaser.Easing.Linear.None,true,0,0,false) nb.onCompleteCallback(nextScene); }; function roundFadeOut(){ noGuessesLeft=true; clearInterval(roundTimerInterval); var t1= game.add.tween(button1).to({alpha:0},1000,Phaser.Easing.Linear.None,true,0,0,false) game.add.tween(button2).to({alpha:0},1000,Phaser.Easing.Linear.None,true,0,0,false) if(button3!=null || button3!=undefined){ game.add.tween(button3).to({alpha:0},1000,Phaser.Easing.Linear.None,true,0,0,false) game.add.tween(button3Text).to({alpha:0},1000,Phaser.Easing.Linear.None,true,0,0,false) }; game.add.tween(button1Text).to({alpha:0},1000,Phaser.Easing.Linear.None,true,0,0,false) game.add.tween(button2Text).to({alpha:0},1000,Phaser.Easing.Linear.None,true,0,0,false) game.add.tween(roundTimerText).to({alpha:0},1000,Phaser.Easing.Linear.None,true,0,0,false) game.add.tween(roundTitleText).to({alpha:0},1000,Phaser.Easing.Linear.None,true,0,0,false) t1.onCompleteCallback(nextScene); }; function finalResults(){ finalGroup = game.add.group(); finalTitleText = game.add.text(game.world.centerX,game.world.centerY,"Your Statistics",titleFontStyle); finalTitleText.anchor.setTo(0.5,0.5); finalTitleText.alpha=0; finalGroup.add(finalTitleText); ul1 = game.add.graphics(25,47); ul1.lineStyle(1.5,0xffff00,1); ul1.beginFill(); ul1.moveTo(25,47); ul1.lineTo(375,47); ul1.endFill(); ul1.alpha = 0; finalGroup.add(ul1); finalQRightText = game.add.text(game.world.centerX,game.world.centerY-50,"Questions Right: "+questionsRight,scoreFontStyle); finalQRightText.anchor.setTo(0.5,0.5); finalQRightText.alpha=0; finalGroup.add(finalQRightText); finalQWrongText = game.add.text(game.world.centerX,game.world.centerY-25,"Questions Wrong: "+questionsWrong,scoreFontStyle); finalQWrongText.anchor.setTo(0.5,0.5); finalQWrongText.alpha=0; finalGroup.add(finalQWrongText); var acc = Math.round((questionsRight/totalQuestions)*100); finalAccuracyText = game.add.text(game.world.centerX,game.world.centerY,"Accuracy: "+acc+"%",scoreFontStyle); finalAccuracyText.anchor.setTo(0.5,0.5); finalAccuracyText.alpha=0; finalGroup.add(finalAccuracyText); ul2 = game.add.graphics(25,115); ul2.lineStyle(1.5,0xFFFF00,1); ul2.beginFill(); ul2.moveTo(25,115); ul2.lineTo(375,115); ul2.endFill(); ul2.alpha=0; finalGroup.add(ul2); finalScoreText = game.add.text(game.world.centerX,game.world.centerY+75,"Final Score: "+score,titleFontStyle); finalScoreText.anchor.setTo(0.5,0.5); finalScoreText.alpha =0; finalGroup.add(finalScoreText); var qps =Math.round((numberOfQuestions/secondsUsed)*100)/100; finalSpeedText = game.add.text(game.world.centerX,game.world.centerY+25,"Speed: "+qps+" questions per second",scoreFontStyle); finalSpeedText.anchor.setTo(0.5,0.5); finalSpeedText.alpha=0; finalGroup.add(finalSpeedText); game.add.tween(finalTitleText).to({alpha:1},1000,Phaser.Easing.Linear.None,true,0,0,false).to({y:75},1000,Phaser.Easing.Quadratic.Out,true,0,0,false); game.add.tween(ul1).to({alpha:1},500,Phaser.Easing.Linear.None).delay(1500).start(); game.add.tween(finalQRightText).to({alpha:1},1000,Phaser.Easing.Linear.None).delay(2000).start(); game.add.tween(finalQWrongText).to({alpha:1},1000,Phaser.Easing.Linear.None).delay(2500).start(); game.add.tween(finalAccuracyText).to({alpha:1},1000,Phaser.Easing.Linear.None).delay(3000).start(); game.add.tween(finalSpeedText).to({alpha:1},1000,Phaser.Easing.Linear.None).delay(3500).start(); game.add.tween(ul2).to({alpha:1},1000,Phaser.Easing.Linear.None).delay(4000).start(); game.add.tween(finalScoreText).to({alpha:1},1000,Phaser.Easing.Linear.None).delay(4500).start(); resetButton = game.add.button(game.world.centerX,game.world.centerY+125,'greenbutton',nextScene,this,0,1,2); resetButton.anchor.setTo(0.5,0.5); resetButton.alpha =0; game.add.tween(resetButton).to({alpha:1},1000,Phaser.Easing.Linear.None).delay(5000).start(); finalGroup.add(resetButton); resetButtonText = game.add.text(resetButton.x,resetButton.y,"Play Again",titleFontStyle); resetButtonText.anchor.setTo(0.5,0.5); resetButtonText.alpha=0; game.add.tween(resetButtonText).to({alpha:1},1000,Phaser.Easing.Linear.None).delay(5000).start(); finalGroup.add(resetButtonText); } function finalResultsFadeOut(){ var finalFade = game.add.tween(finalGroup._container).to({alpha:0},1000,Phaser.Easing.Linear.None).start(); finalFade.onCompleteCallback(resetGame); }; function resetGame(){ //console.log("RESET THE GAME!") sceneIndex = 0; inScene = false; inRound = -1; roundTimerValue = 30; isDisplaying = false; roundStarted = false; questionsRight=0; questionsWrong=0; secondsUsed=0; totalQuestions=0; readyForNext = false; noGuessesLeft= false; numberOfQuestions=0; setQuestions(); }; function update(){ if(!inScene){ inScene = true; switch(sceneIndex){ case 0: introduction(); break; case 1: introductionFadeOut(); break; case 2: roundCountdown("Round 1"); break; case 3: roundTimerValue=30; startRound(round[0]); break; case 4: roundFadeOut(); break; case 5: roundResults(); break; case 6: resultsFadeOut(); break; case 7: roundCountdown("Round 2"); break; case 8: roundTimerValue=60; startRound(round[1]); break; case 9: roundFadeOut(); break; case 10:roundResults(); break; case 11:resultsFadeOut(); break; case 12: roundCountdown("Final Round"); break; case 13: roundTimerValue=90; startRound(round[2]); break; case 14: roundFadeOut(); break; case 15: roundResults(); break; case 16: resultsFadeOut(); break; case 17:finalResults(); break; case 18:finalResultsFadeOut(); break; case 19:resetGame(); break; }; }; if(inRound>-1){ if(!isDisplaying){ isDisplaying=true; displayWord(round[inRound]); }; }; };
bpickard/c9_phaser
tutorials/this_or_that/unit2game_source.js.js
JavaScript
mit
23,780
module.exports = function(app) { var _env = app.get('env'); var _log = app.lib.logger; var _mongoose = app.core.mongo.mongoose; var _group = 'MODEL:oauth.authcodes'; var Schema = { authCode : {type: String, required: true, unique: true, alias: 'authCode'}, clientId : {type: String, alias: 'clientId'}, userId : {type: String, required: true, alias: 'userId'}, expires : {type: Date, alias: 'expires'} }; var AuthCodesSchema = app.core.mongo.db.Schema(Schema); // statics AuthCodesSchema.method('getAuthCode', function(authCode, cb) { var AuthCodes = _mongoose.model('Oauth_AuthCodes'); AuthCodes.findOne({authCode: authCode}, cb); }); AuthCodesSchema.method('saveAuthCode', function(code, clientId, expires, userId, cb) { var AuthCodes = _mongoose.model('Oauth_AuthCodes'); if (userId.id) userId = userId.id; var fields = { clientId : clientId, userId : userId, expires : expires }; AuthCodes.update({authCode: code}, fields, {upsert: true}, function(err) { if (err) _log.error(_group, err); cb(err); }); }); return _mongoose.model('Oauth_AuthCodes', AuthCodesSchema); };
selcukfatihsevinc/app.io
model/oauth/authcodes.js
JavaScript
mit
1,339
/* The MIT License (MIT) Copyright (c) 2017 Adrian Paul Nutiu <nutiuadrianpaul@gmail.com> http://adrianpaulnutiu.me/ */ // ==UserScript== // @name kartwars.io Bot // @namespace https://github.com/kmataru/kartwars.io-bot/raw/pre-release/src/DracoolaArt.Bot.Kartwars/ // @version 0.7.475 // @description kartwars.io Bot // @author Adrian Paul Nutiu // @match http://kartwars.io/ // @icon https://assets-cdn.github.com/images/icons/emoji/unicode/1f697.png // @updateURL https://github.com/kmataru/kartwars.io-bot/raw/pre-release/src/DracoolaArt.Bot.Kartwars/bot.user.js // @downloadURL https://github.com/kmataru/kartwars.io-bot/raw/pre-release/src/DracoolaArt.Bot.Kartwars/bot.user.js // @supportURL https://github.com/kmataru/kartwars.io-bot/issues // @require https://gist.githubusercontent.com/eligrey/384583/raw/96dd5cd2fd6b752aa3ec0630a003e7a920313d1a/object-watch.js // @require https://cdn.rawgit.com/stacktracejs/stacktrace.js/master/dist/stacktrace.min.js // @grant none // ==/UserScript== /// <reference path="lib/_references.ts" /> // tslint:disable-next-line:no-unused-expression !function (window, document) { var baseURL = 'http://scripts.local.com/'; var baseScriptPath = baseURL + "lib/"; var baseStylePath = baseURL + "style/"; window.botSettings = { LOAD_DEBUG_SCRIPTS: false, LOAD_GIT_SCRIPTS: true, }; window.GM_info = GM_info; function initLoader(baseURL, baseScriptPath) { var remoteScript = document.createElement('script'); remoteScript.src = baseScriptPath + "Loader.js?time=" + (+new Date()); remoteScript.onload = function () { setTimeout(function () { (new DracoolaArt.KartwarsBot.Loader(baseURL, baseScriptPath)).boot(); }, 0); }; document.body.appendChild(remoteScript); } function loadStylesheet(fileURL) { fileURL += "?time=" + (+new Date()); var remoteLink = document.createElement('link'); remoteLink.href = fileURL; remoteLink.type = 'text/css'; remoteLink.rel = 'stylesheet'; remoteLink.media = 'screen,print'; remoteLink.onload = function () { var jPlayButton = $('#play-btn'); jPlayButton.addClass('btn-none'); jPlayButton.after("<a href=\"#\" id=\"loading-bot\" class=\"btn btn-play btn-loading-bot\">Loading Bot. Please wait!</a>"); }; document.head.appendChild(remoteLink); } if (window.botSettings.LOAD_GIT_SCRIPTS) { $.ajax({ url: 'https://api.github.com/repos/kmataru/kartwars.io-bot/git/refs/heads/pre-release', cache: false, dataType: 'jsonp' }).done(function (response) { var sha = response['data']['object']['sha']; var baseURL = "https://cdn.rawgit.com/kmataru/kartwars.io-bot/" + sha + "/src/DracoolaArt.Bot.Kartwars/"; var baseScriptPath = baseURL + "lib/"; var baseStylePath = baseURL + "style/"; loadStylesheet(baseStylePath + "Main.min.css"); initLoader(baseURL, baseScriptPath); }).fail(function () { }); } else { loadStylesheet(baseStylePath + "Main.min.css"); initLoader(baseURL, baseScriptPath); } }(window, document);
kmataru/kartwars.io-bot
src/DracoolaArt.Bot.Kartwars/bot.user.js
JavaScript
mit
3,346
import Page from '../Page'; import './news.scss'; import RoomList from "../parts/RoomList"; export default class NewsPage extends Page { indexAction() { this.headerTitle = "新着・おすすめ"; var $switchPanel = $(` <div class="switch-panel"> <div class="switch-btn selected new"> <span class="title">新着</span> <span class="count">--</span> <span class="ken">件</span> </div> <div class="switch-btn pickup"> <span class="title">おすすめ</span> <span class="count">--</span> <span class="ken">件</span> </div> </div> `); this.$main.append($switchPanel); var $newCount = $switchPanel.find(".new .count"); var $pickupCount = $switchPanel.find(".pickup .count"); getPickupCount() .then( count => $pickupCount.html(count) ); RoomList.findAll({new:1}, $newCount) .then( $roomList => { this.$contents.append($roomList); }); var $pickupBtn = $switchPanel.find(".pickup"); var $newBtn = $switchPanel.find(".new"); $pickupBtn.on("click", () => { $newBtn.removeClass("selected"); $pickupBtn.addClass("selected"); RoomList.findAll({pickup:1}) .then( $roomList => { this.$contents.append($roomList); }); }); $newBtn.on("click", () => { $pickupBtn.removeClass("selected"); $newBtn.addClass("selected"); RoomList.findAll({new:1}) .then( $roomList => { this.$contents.append($roomList); }); }); } } function getPickupCount() { return global.APP.api.ietopia.room.count({pickup:1}) }
nakamura-yuta-i7/ietopia-appli
src/pages/news/NewsPage.js
JavaScript
mit
1,666
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } /** * -------------------------------------------------------------------------- * Bootstrap (v4.1.1): scrollspy.js * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * -------------------------------------------------------------------------- */ var ScrollSpy = function ($) { /** * ------------------------------------------------------------------------ * Constants * ------------------------------------------------------------------------ */ var NAME = 'scrollspy'; var VERSION = '4.1.1'; var DATA_KEY = 'bs.scrollspy'; var EVENT_KEY = "." + DATA_KEY; var DATA_API_KEY = '.data-api'; var JQUERY_NO_CONFLICT = $.fn[NAME]; var Default = { offset: 10, method: 'auto', target: '' }; var DefaultType = { offset: 'number', method: 'string', target: '(string|element)' }; var Event = { ACTIVATE: "activate" + EVENT_KEY, SCROLL: "scroll" + EVENT_KEY, LOAD_DATA_API: "load" + EVENT_KEY + DATA_API_KEY }; var ClassName = { DROPDOWN_ITEM: 'dropdown-item', DROPDOWN_MENU: 'dropdown-menu', ACTIVE: 'active' }; var Selector = { DATA_SPY: '[data-spy="scroll"]', ACTIVE: '.active', NAV_LIST_GROUP: '.nav, .list-group', NAV_LINKS: '.nav-link', NAV_ITEMS: '.nav-item', LIST_ITEMS: '.list-group-item', DROPDOWN: '.dropdown', DROPDOWN_ITEMS: '.dropdown-item', DROPDOWN_TOGGLE: '.dropdown-toggle' }; var OffsetMethod = { OFFSET: 'offset', POSITION: 'position' /** * ------------------------------------------------------------------------ * Class Definition * ------------------------------------------------------------------------ */ }; var ScrollSpy = /*#__PURE__*/ function () { function ScrollSpy(element, config) { var _this = this; this._element = element; this._scrollElement = element.tagName === 'BODY' ? window : element; this._config = this._getConfig(config); this._selector = this._config.target + " " + Selector.NAV_LINKS + "," + (this._config.target + " " + Selector.LIST_ITEMS + ",") + (this._config.target + " " + Selector.DROPDOWN_ITEMS); this._offsets = []; this._targets = []; this._activeTarget = null; this._scrollHeight = 0; $(this._scrollElement).on(Event.SCROLL, function (event) { return _this._process(event); }); this.refresh(); this._process(); } // Getters var _proto = ScrollSpy.prototype; // Public _proto.refresh = function refresh() { var _this2 = this; var autoMethod = this._scrollElement === this._scrollElement.window ? OffsetMethod.OFFSET : OffsetMethod.POSITION; var offsetMethod = this._config.method === 'auto' ? autoMethod : this._config.method; var offsetBase = offsetMethod === OffsetMethod.POSITION ? this._getScrollTop() : 0; this._offsets = []; this._targets = []; this._scrollHeight = this._getScrollHeight(); var targets = [].slice.call(document.querySelectorAll(this._selector)); targets.map(function (element) { var target; var targetSelector = Util.getSelectorFromElement(element); if (targetSelector) { target = document.querySelector(targetSelector); } if (target) { var targetBCR = target.getBoundingClientRect(); if (targetBCR.width || targetBCR.height) { // TODO (fat): remove sketch reliance on jQuery position/offset return [$(target)[offsetMethod]().top + offsetBase, targetSelector]; } } return null; }).filter(function (item) { return item; }).sort(function (a, b) { return a[0] - b[0]; }).forEach(function (item) { _this2._offsets.push(item[0]); _this2._targets.push(item[1]); }); }; _proto.dispose = function dispose() { $.removeData(this._element, DATA_KEY); $(this._scrollElement).off(EVENT_KEY); this._element = null; this._scrollElement = null; this._config = null; this._selector = null; this._offsets = null; this._targets = null; this._activeTarget = null; this._scrollHeight = null; }; // Private _proto._getConfig = function _getConfig(config) { config = _objectSpread({}, Default, typeof config === 'object' && config ? config : {}); if (typeof config.target !== 'string') { var id = $(config.target).attr('id'); if (!id) { id = Util.getUID(NAME); $(config.target).attr('id', id); } config.target = "#" + id; } Util.typeCheckConfig(NAME, config, DefaultType); return config; }; _proto._getScrollTop = function _getScrollTop() { return this._scrollElement === window ? this._scrollElement.pageYOffset : this._scrollElement.scrollTop; }; _proto._getScrollHeight = function _getScrollHeight() { return this._scrollElement.scrollHeight || Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); }; _proto._getOffsetHeight = function _getOffsetHeight() { return this._scrollElement === window ? window.innerHeight : this._scrollElement.getBoundingClientRect().height; }; _proto._process = function _process() { var scrollTop = this._getScrollTop() + this._config.offset; var scrollHeight = this._getScrollHeight(); var maxScroll = this._config.offset + scrollHeight - this._getOffsetHeight(); if (this._scrollHeight !== scrollHeight) { this.refresh(); } if (scrollTop >= maxScroll) { var target = this._targets[this._targets.length - 1]; if (this._activeTarget !== target) { this._activate(target); } return; } if (this._activeTarget && scrollTop < this._offsets[0] && this._offsets[0] > 0) { this._activeTarget = null; this._clear(); return; } var offsetLength = this._offsets.length; for (var i = offsetLength; i--;) { var isActiveTarget = this._activeTarget !== this._targets[i] && scrollTop >= this._offsets[i] && (typeof this._offsets[i + 1] === 'undefined' || scrollTop < this._offsets[i + 1]); if (isActiveTarget) { this._activate(this._targets[i]); } } }; _proto._activate = function _activate(target) { this._activeTarget = target; this._clear(); var queries = this._selector.split(','); // eslint-disable-next-line arrow-body-style queries = queries.map(function (selector) { return selector + "[data-target=\"" + target + "\"]," + (selector + "[href=\"" + target + "\"]"); }); var $link = $([].slice.call(document.querySelectorAll(queries.join(',')))); if ($link.hasClass(ClassName.DROPDOWN_ITEM)) { $link.closest(Selector.DROPDOWN).find(Selector.DROPDOWN_TOGGLE).addClass(ClassName.ACTIVE); $link.addClass(ClassName.ACTIVE); } else { // Set triggered link as active $link.addClass(ClassName.ACTIVE); // Set triggered links parents as active // With both <ul> and <nav> markup a parent is the previous sibling of any nav ancestor $link.parents(Selector.NAV_LIST_GROUP).prev(Selector.NAV_LINKS + ", " + Selector.LIST_ITEMS).addClass(ClassName.ACTIVE); // Handle special case when .nav-link is inside .nav-item $link.parents(Selector.NAV_LIST_GROUP).prev(Selector.NAV_ITEMS).children(Selector.NAV_LINKS).addClass(ClassName.ACTIVE); } $(this._scrollElement).trigger(Event.ACTIVATE, { relatedTarget: target }); }; _proto._clear = function _clear() { var nodes = [].slice.call(document.querySelectorAll(this._selector)); $(nodes).filter(Selector.ACTIVE).removeClass(ClassName.ACTIVE); }; // Static ScrollSpy._jQueryInterface = function _jQueryInterface(config) { return this.each(function () { var data = $(this).data(DATA_KEY); var _config = typeof config === 'object' && config; if (!data) { data = new ScrollSpy(this, _config); $(this).data(DATA_KEY, data); } if (typeof config === 'string') { if (typeof data[config] === 'undefined') { throw new TypeError("No method named \"" + config + "\""); } data[config](); } }); }; _createClass(ScrollSpy, null, [{ key: "VERSION", get: function get() { return VERSION; } }, { key: "Default", get: function get() { return Default; } }]); return ScrollSpy; }(); /** * ------------------------------------------------------------------------ * Data Api implementation * ------------------------------------------------------------------------ */ $(window).on(Event.LOAD_DATA_API, function () { var scrollSpys = [].slice.call(document.querySelectorAll(Selector.DATA_SPY)); var scrollSpysLength = scrollSpys.length; for (var i = scrollSpysLength; i--;) { var $spy = $(scrollSpys[i]); ScrollSpy._jQueryInterface.call($spy, $spy.data()); } }); /** * ------------------------------------------------------------------------ * jQuery * ------------------------------------------------------------------------ */ $.fn[NAME] = ScrollSpy._jQueryInterface; $.fn[NAME].Constructor = ScrollSpy; $.fn[NAME].noConflict = function () { $.fn[NAME] = JQUERY_NO_CONFLICT; return ScrollSpy._jQueryInterface; }; return ScrollSpy; }($); //# sourceMappingURL=scrollspy.js.map
Lyricalz/bootstrap
js/dist/scrollspy.js
JavaScript
mit
10,942
/* WebGL Renderer*/ var WebGLRenderer, __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; WebGLRenderer = (function(_super) { __extends(WebGLRenderer, _super); WebGLRenderer.PARTICLE_VS = '\nuniform vec2 viewport;\nattribute vec3 position;\nattribute float radius;\nattribute vec4 colour;\nvarying vec4 tint;\n\nvoid main() {\n\n // convert the rectangle from pixels to 0.0 to 1.0\n vec2 zeroToOne = position.xy / viewport;\n zeroToOne.y = 1.0 - zeroToOne.y;\n\n // convert from 0->1 to 0->2\n vec2 zeroToTwo = zeroToOne * 2.0;\n\n // convert from 0->2 to -1->+1 (clipspace)\n vec2 clipSpace = zeroToTwo - 1.0;\n\n tint = colour;\n\n gl_Position = vec4(clipSpace, 0, 1);\n gl_PointSize = radius * 2.0;\n}'; WebGLRenderer.PARTICLE_FS = '\nprecision mediump float;\n\nuniform sampler2D texture;\nvarying vec4 tint;\n\nvoid main() {\n gl_FragColor = texture2D(texture, gl_PointCoord) * tint;\n}'; WebGLRenderer.SPRING_VS = '\nuniform vec2 viewport;\nattribute vec3 position;\n\nvoid main() {\n\n // convert the rectangle from pixels to 0.0 to 1.0\n vec2 zeroToOne = position.xy / viewport;\n zeroToOne.y = 1.0 - zeroToOne.y;\n\n // convert from 0->1 to 0->2\n vec2 zeroToTwo = zeroToOne * 2.0;\n\n // convert from 0->2 to -1->+1 (clipspace)\n vec2 clipSpace = zeroToTwo - 1.0;\n\n gl_Position = vec4(clipSpace, 0, 1);\n}'; WebGLRenderer.SPRING_FS = '\nvoid main() {\n gl_FragColor = vec4(1.0, 1.0, 1.0, 0.1);\n}'; function WebGLRenderer(usePointSprites) { var error; this.usePointSprites = usePointSprites != null ? usePointSprites : true; this.setSize = __bind(this.setSize, this); WebGLRenderer.__super__.constructor.apply(this, arguments); this.particlePositionBuffer = null; this.particleRadiusBuffer = null; this.particleColourBuffer = null; this.particleTexture = null; this.particleShader = null; this.springPositionBuffer = null; this.springShader = null; this.canvas = document.createElement('canvas'); try { this.gl = this.canvas.getContext('experimental-webgl'); } catch (_error) { error = _error; } finally { if (!this.gl) { return new CanvasRenderer(); } } this.domElement = this.canvas; } WebGLRenderer.prototype.init = function(physics) { WebGLRenderer.__super__.init.call(this, physics); this.initShaders(); this.initBuffers(physics); this.particleTexture = this.createParticleTextureData(); this.gl.blendFunc(this.gl.SRC_ALPHA, this.gl.ONE); return this.gl.enable(this.gl.BLEND); }; WebGLRenderer.prototype.initShaders = function() { this.particleShader = this.createShaderProgram(WebGLRenderer.PARTICLE_VS, WebGLRenderer.PARTICLE_FS); this.springShader = this.createShaderProgram(WebGLRenderer.SPRING_VS, WebGLRenderer.SPRING_FS); this.particleShader.uniforms = { viewport: this.gl.getUniformLocation(this.particleShader, 'viewport') }; this.springShader.uniforms = { viewport: this.gl.getUniformLocation(this.springShader, 'viewport') }; this.particleShader.attributes = { position: this.gl.getAttribLocation(this.particleShader, 'position'), radius: this.gl.getAttribLocation(this.particleShader, 'radius'), colour: this.gl.getAttribLocation(this.particleShader, 'colour') }; this.springShader.attributes = { position: this.gl.getAttribLocation(this.springShader, 'position') }; return console.log(this.particleShader); }; WebGLRenderer.prototype.initBuffers = function(physics) { var a, b, colours, g, particle, r, radii, rgba, _i, _len, _ref; colours = []; radii = []; this.particlePositionBuffer = this.gl.createBuffer(); this.springPositionBuffer = this.gl.createBuffer(); this.particleColourBuffer = this.gl.createBuffer(); this.particleRadiusBuffer = this.gl.createBuffer(); _ref = physics.particles; for (_i = 0, _len = _ref.length; _i < _len; _i++) { particle = _ref[_i]; rgba = (particle.colour || '#FFFFFF').match(/[\dA-F]{2}/gi); r = (parseInt(rgba[0], 16)) || 255; g = (parseInt(rgba[1], 16)) || 255; b = (parseInt(rgba[2], 16)) || 255; a = (parseInt(rgba[3], 16)) || 255; colours.push(r / 255, g / 255, b / 255, a / 255); radii.push(particle.radius || 32); } this.gl.bindBuffer(this.gl.ARRAY_BUFFER, this.particleColourBuffer); this.gl.bufferData(this.gl.ARRAY_BUFFER, new Float32Array(colours), this.gl.STATIC_DRAW); this.gl.bindBuffer(this.gl.ARRAY_BUFFER, this.particleRadiusBuffer); return this.gl.bufferData(this.gl.ARRAY_BUFFER, new Float32Array(radii), this.gl.STATIC_DRAW); }; WebGLRenderer.prototype.createParticleTextureData = function(size) { var canvas, ctx, rad, texture; if (size == null) { size = 128; } canvas = document.createElement('canvas'); canvas.width = canvas.height = size; ctx = canvas.getContext('2d'); rad = size * 0.5; ctx.beginPath(); ctx.arc(rad, rad, rad, 0, Math.PI * 2, false); ctx.closePath(); ctx.fillStyle = '#FFF'; ctx.fill(); texture = this.gl.createTexture(); this.setupTexture(texture, canvas); return texture; }; WebGLRenderer.prototype.loadTexture = function(source) { var texture, _this = this; texture = this.gl.createTexture(); texture.image = new Image(); texture.image.onload = function() { return _this.setupTexture(texture, texture.image); }; texture.image.src = source; return texture; }; WebGLRenderer.prototype.setupTexture = function(texture, data) { this.gl.bindTexture(this.gl.TEXTURE_2D, texture); this.gl.texImage2D(this.gl.TEXTURE_2D, 0, this.gl.RGBA, this.gl.RGBA, this.gl.UNSIGNED_BYTE, data); this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_MIN_FILTER, this.gl.LINEAR); this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_MAG_FILTER, this.gl.LINEAR); this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_WRAP_S, this.gl.CLAMP_TO_EDGE); this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_WRAP_T, this.gl.CLAMP_TO_EDGE); this.gl.generateMipmap(this.gl.TEXTURE_2D); this.gl.bindTexture(this.gl.TEXTURE_2D, null); return texture; }; WebGLRenderer.prototype.createShaderProgram = function(_vs, _fs) { var fs, prog, vs; vs = this.gl.createShader(this.gl.VERTEX_SHADER); fs = this.gl.createShader(this.gl.FRAGMENT_SHADER); this.gl.shaderSource(vs, _vs); this.gl.shaderSource(fs, _fs); this.gl.compileShader(vs); this.gl.compileShader(fs); if (!this.gl.getShaderParameter(vs, this.gl.COMPILE_STATUS)) { alert(this.gl.getShaderInfoLog(vs)); null; } if (!this.gl.getShaderParameter(fs, this.gl.COMPILE_STATUS)) { alert(this.gl.getShaderInfoLog(fs)); null; } prog = this.gl.createProgram(); this.gl.attachShader(prog, vs); this.gl.attachShader(prog, fs); this.gl.linkProgram(prog); return prog; }; WebGLRenderer.prototype.setSize = function(width, height) { this.width = width; this.height = height; WebGLRenderer.__super__.setSize.call(this, this.width, this.height); this.canvas.width = this.width; this.canvas.height = this.height; this.gl.viewport(0, 0, this.width, this.height); this.gl.useProgram(this.particleShader); this.gl.uniform2fv(this.particleShader.uniforms.viewport, new Float32Array([this.width, this.height])); this.gl.useProgram(this.springShader); return this.gl.uniform2fv(this.springShader.uniforms.viewport, new Float32Array([this.width, this.height])); }; WebGLRenderer.prototype.render = function(physics) { var p, s, vertices, _i, _j, _len, _len1, _ref, _ref1; WebGLRenderer.__super__.render.apply(this, arguments); this.gl.clear(this.gl.COLOR_BUFFER_BIT | this.gl.DEPTH_BUFFER_BIT); if (this.renderParticles) { vertices = []; _ref = physics.particles; for (_i = 0, _len = _ref.length; _i < _len; _i++) { p = _ref[_i]; vertices.push(p.pos.x, p.pos.y, 0.0); } this.gl.activeTexture(this.gl.TEXTURE0); this.gl.bindTexture(this.gl.TEXTURE_2D, this.particleTexture); this.gl.useProgram(this.particleShader); this.gl.bindBuffer(this.gl.ARRAY_BUFFER, this.particlePositionBuffer); this.gl.bufferData(this.gl.ARRAY_BUFFER, new Float32Array(vertices), this.gl.STATIC_DRAW); this.gl.vertexAttribPointer(this.particleShader.attributes.position, 3, this.gl.FLOAT, false, 0, 0); this.gl.enableVertexAttribArray(this.particleShader.attributes.position); this.gl.bindBuffer(this.gl.ARRAY_BUFFER, this.particleColourBuffer); this.gl.enableVertexAttribArray(this.particleShader.attributes.colour); this.gl.vertexAttribPointer(this.particleShader.attributes.colour, 4, this.gl.FLOAT, false, 0, 0); this.gl.bindBuffer(this.gl.ARRAY_BUFFER, this.particleRadiusBuffer); this.gl.enableVertexAttribArray(this.particleShader.attributes.radius); this.gl.vertexAttribPointer(this.particleShader.attributes.radius, 1, this.gl.FLOAT, false, 0, 0); this.gl.drawArrays(this.gl.POINTS, 0, vertices.length / 3); } if (this.renderSprings && physics.springs.length > 0) { vertices = []; _ref1 = physics.springs; for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) { s = _ref1[_j]; vertices.push(s.p1.pos.x, s.p1.pos.y, 0.0); vertices.push(s.p2.pos.x, s.p2.pos.y, 0.0); } this.gl.useProgram(this.springShader); this.gl.bindBuffer(this.gl.ARRAY_BUFFER, this.springPositionBuffer); this.gl.bufferData(this.gl.ARRAY_BUFFER, new Float32Array(vertices), this.gl.STATIC_DRAW); this.gl.vertexAttribPointer(this.springShader.attributes.position, 3, this.gl.FLOAT, false, 0, 0); this.gl.enableVertexAttribArray(this.springShader.attributes.position); return this.gl.drawArrays(this.gl.LINES, 0, vertices.length / 3); } }; WebGLRenderer.prototype.destroy = function() {}; return WebGLRenderer; })(Renderer);
codio/tutorial_grunt_watch_coffee
compiled/demos/renderer/WebGLRenderer.js
JavaScript
mit
10,506
"use strict"; const test = require("tape"); const aceyDeuceyGameEngine = require("../"); const getInitialGameState = aceyDeuceyGameEngine.getInitialGameState; test("getInitialGameState", t => { t.plan(1); const gameState = { board: [ {isPlayerOne: null, numPieces: 0}, {isPlayerOne: null, numPieces: 0}, {isPlayerOne: null, numPieces: 0}, {isPlayerOne: null, numPieces: 0}, {isPlayerOne: null, numPieces: 0}, {isPlayerOne: null, numPieces: 0}, {isPlayerOne: null, numPieces: 0}, {isPlayerOne: null, numPieces: 0}, {isPlayerOne: null, numPieces: 0}, {isPlayerOne: null, numPieces: 0}, {isPlayerOne: null, numPieces: 0}, {isPlayerOne: null, numPieces: 0}, {isPlayerOne: null, numPieces: 0}, {isPlayerOne: null, numPieces: 0}, {isPlayerOne: null, numPieces: 0}, {isPlayerOne: null, numPieces: 0}, {isPlayerOne: null, numPieces: 0}, {isPlayerOne: null, numPieces: 0}, {isPlayerOne: null, numPieces: 0}, {isPlayerOne: null, numPieces: 0}, {isPlayerOne: null, numPieces: 0}, {isPlayerOne: null, numPieces: 0}, {isPlayerOne: null, numPieces: 0}, {isPlayerOne: null, numPieces: 0} ], isPlayerOne: true, playerOne: { initialPieces: 15, barPieces: 0, winningPieces: 0 }, playerTwo: { initialPieces: 15, barPieces: 0, winningPieces:0 } }; t.deepEqual(getInitialGameState(), gameState, "returns the correct gameState object"); });
KatherineThompson/acey-deucey-game-engine
tests/get-initial-game-state.test.js
JavaScript
mit
1,758
'use strict'; (function(module) { const splashView = {}; splashView.defaultView = function(){ $('#about').hide(); $('#map').css('z-index', -500); $('form').fadeIn(); $('#splash-page').fadeIn(); } module.splashView = splashView; })(window); $(function(){ $('#home').on('click', function(){ splashView.defaultView(); }); });
glenrage/soundsgood
public/scripts/views/splashview.js
JavaScript
mit
358
import Vue from 'vue' import Router from 'vue-router' import Resource from'vue-resource' import { sync } from 'vuex-router-sync' Vue.use(Router) Vue.use(Resource) // components import App from './components/App.vue' import Login from './components/Login/Login.vue' import Dashboard from './components/Dashboard/Dashboard.vue' import Counter from './components/Counter/Counter.vue' // model import store from './vuex/store.js' // routing var router = new Router() router.map({ '/login': { component: Login }, '/dashboard': { component: Dashboard }, '/counter': { component: Counter } }) router.beforeEach(function() { window.scrollTo(0, 0) }) router.redirect({ '*': '/login' }) sync(store, router) router.start(App, 'body') Vue.config.debug = true Vue.http.interceptors.push({ request: function(request) { Vue.http.headers.common['Authorization'] = 'JWT' + sessionStorage.getItem('token') return request }, response: function(response) { if (response.status === 401) { router.go('/login') } return response } });
vianvio/babyMoveCounter
app/index.js
JavaScript
mit
1,081
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ /* Latitude/longitude spherical geodesy formulae & scripts (c) Chris Veness 2002-2015 */ /* - www.movable-type.co.uk/scripts/latlong.html MIT Licence */ /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ 'use strict'; /** * Creates a LatLon point on the earth's surface at the specified latitude / longitude. * * @classdesc Tools for geodetic calculations * @requires Dms from 'dms.js' * * @constructor * @param {number} lat - Latitude in degrees. * @param {number} lon - Longitude in degrees. * * @example * var p1 = new LatLon(52.205, 0.119); */ function LatLon(lat, lon) { // allow instantiation without 'new' if (!(this instanceof LatLon)) return new LatLon(lat, lon); this.lat = Number(lat); this.lon = Number(lon); } /** * Returns the distance from 'this' point to destination point (using haversine formula). * * @param {LatLon} point - Latitude/longitude of destination point. * @param {number} [radius=6371e3] - (Mean) radius of earth (defaults to radius in metres). * @returns {number} Distance between this point and destination point, in same units as radius. * * @example * var p1 = new LatLon(52.205, 0.119), p2 = new LatLon(48.857, 2.351); * var d = p1.distanceTo(p2); // Number(d.toPrecision(4)): 404300 */ LatLon.prototype.distanceTo = function(point, radius) { if (!(point instanceof LatLon)) throw new TypeError('point is not LatLon object'); radius = (radius === undefined) ? 6371e3 : Number(radius); var R = radius; var φ1 = this.lat.toRadians(), λ1 = this.lon.toRadians(); var φ2 = point.lat.toRadians(), λ2 = point.lon.toRadians(); var Δφ = φ2 - φ1; var Δλ = λ2 - λ1; var a = Math.sin(Δφ/2) * Math.sin(Δφ/2) + Math.cos(φ1) * Math.cos(φ2) * Math.sin(Δλ/2) * Math.sin(Δλ/2); var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); var d = R * c; return d; }; /** * Returns the (initial) bearing from 'this' point to destination point. * * @param {LatLon} point - Latitude/longitude of destination point. * @returns {number} Initial bearing in degrees from north. * * @example * var p1 = new LatLon(52.205, 0.119), p2 = new LatLon(48.857, 2.351); * var b1 = p1.bearingTo(p2); // b1.toFixed(1): 156.2 */ LatLon.prototype.bearingTo = function(point) { if (!(point instanceof LatLon)) throw new TypeError('point is not LatLon object'); var φ1 = this.lat.toRadians(), φ2 = point.lat.toRadians(); var Δλ = (point.lon-this.lon).toRadians(); // see http://mathforum.org/library/drmath/view/55417.html var y = Math.sin(Δλ) * Math.cos(φ2); var x = Math.cos(φ1)*Math.sin(φ2) - Math.sin(φ1)*Math.cos(φ2)*Math.cos(Δλ); var θ = Math.atan2(y, x); return (θ.toDegrees()+360) % 360; }; /** * Returns final bearing arriving at destination destination point from 'this' point; the final bearing * will differ from the initial bearing by varying degrees according to distance and latitude. * * @param {LatLon} point - Latitude/longitude of destination point. * @returns {number} Final bearing in degrees from north. * * @example * var p1 = new LatLon(52.205, 0.119), p2 = new LatLon(48.857, 2.351); * var b2 = p1.finalBearingTo(p2); // b2.toFixed(1): 157.9 */ LatLon.prototype.finalBearingTo = function(point) { if (!(point instanceof LatLon)) throw new TypeError('point is not LatLon object'); // get initial bearing from destination point to this point & reverse it by adding 180° return ( point.bearingTo(this)+180 ) % 360; }; /** * Returns the midpoint between 'this' point and the supplied point. * * @param {LatLon} point - Latitude/longitude of destination point. * @returns {LatLon} Midpoint between this point and the supplied point. * * @example * var p1 = new LatLon(52.205, 0.119), p2 = new LatLon(48.857, 2.351); * var pMid = p1.midpointTo(p2); // pMid.toString(): 50.5363°N, 001.2746°E */ LatLon.prototype.midpointTo = function(point) { if (!(point instanceof LatLon)) throw new TypeError('point is not LatLon object'); // see http://mathforum.org/library/drmath/view/51822.html for derivation var φ1 = this.lat.toRadians(), λ1 = this.lon.toRadians(); var φ2 = point.lat.toRadians(); var Δλ = (point.lon-this.lon).toRadians(); var Bx = Math.cos(φ2) * Math.cos(Δλ); var By = Math.cos(φ2) * Math.sin(Δλ); var φ3 = Math.atan2(Math.sin(φ1)+Math.sin(φ2), Math.sqrt( (Math.cos(φ1)+Bx)*(Math.cos(φ1)+Bx) + By*By) ); var λ3 = λ1 + Math.atan2(By, Math.cos(φ1) + Bx); λ3 = (λ3+3*Math.PI) % (2*Math.PI) - Math.PI; // normalise to -180..+180° return new LatLon(φ3.toDegrees(), λ3.toDegrees()); }; /** * Returns the destination point from 'this' point having travelled the given distance on the * given initial bearing (bearing normally varies around path followed). * * @param {number} distance - Distance travelled, in same units as earth radius (default: metres). * @param {number} bearing - Initial bearing in degrees from north. * @param {number} [radius=6371e3] - (Mean) radius of earth (defaults to radius in metres). * @returns {LatLon} Destination point. * * @example * var p1 = new LatLon(51.4778, -0.0015); * var p2 = p1.destinationPoint(7794, 300.7); // p2.toString(): 51.5135°N, 000.0983°W */ LatLon.prototype.destinationPoint = function(distance, bearing, radius) { radius = (radius === undefined) ? 6371e3 : Number(radius); // see http://williams.best.vwh.net/avform.htm#LL var δ = Number(distance) / radius; // angular distance in radians var θ = Number(bearing).toRadians(); var φ1 = this.lat.toRadians(); var λ1 = this.lon.toRadians(); var φ2 = Math.asin( Math.sin(φ1)*Math.cos(δ) + Math.cos(φ1)*Math.sin(δ)*Math.cos(θ) ); var λ2 = λ1 + Math.atan2(Math.sin(θ)*Math.sin(δ)*Math.cos(φ1), Math.cos(δ)-Math.sin(φ1)*Math.sin(φ2)); λ2 = (λ2+3*Math.PI) % (2*Math.PI) - Math.PI; // normalise to -180..+180° return new LatLon(φ2.toDegrees(), λ2.toDegrees()); }; /** * Returns the point of intersection of two paths defined by point and bearing. * * @param {LatLon} p1 - First point. * @param {number} brng1 - Initial bearing from first point. * @param {LatLon} p2 - Second point. * @param {number} brng2 - Initial bearing from second point. * @returns {LatLon} Destination point (null if no unique intersection defined). * * @example * var p1 = LatLon(51.8853, 0.2545), brng1 = 108.547; * var p2 = LatLon(49.0034, 2.5735), brng2 = 32.435; * var pInt = LatLon.intersection(p1, brng1, p2, brng2); // pInt.toString(): 50.9078°N, 004.5084°E */ LatLon.intersection = function(p1, brng1, p2, brng2) { if (!(p1 instanceof LatLon)) throw new TypeError('p1 is not LatLon object'); if (!(p2 instanceof LatLon)) throw new TypeError('p2 is not LatLon object'); // see http://williams.best.vwh.net/avform.htm#Intersection var φ1 = p1.lat.toRadians(), λ1 = p1.lon.toRadians(); var φ2 = p2.lat.toRadians(), λ2 = p2.lon.toRadians(); var θ13 = Number(brng1).toRadians(), θ23 = Number(brng2).toRadians(); var Δφ = φ2-φ1, Δλ = λ2-λ1; var δ12 = 2*Math.asin( Math.sqrt( Math.sin(Δφ/2)*Math.sin(Δφ/2) + Math.cos(φ1)*Math.cos(φ2)*Math.sin(Δλ/2)*Math.sin(Δλ/2) ) ); if (δ12 == 0) return null; // initial/final bearings between points var θ1 = Math.acos( ( Math.sin(φ2) - Math.sin(φ1)*Math.cos(δ12) ) / ( Math.sin(δ12)*Math.cos(φ1) ) ); if (isNaN(θ1)) θ1 = 0; // protect against rounding var θ2 = Math.acos( ( Math.sin(φ1) - Math.sin(φ2)*Math.cos(δ12) ) / ( Math.sin(δ12)*Math.cos(φ2) ) ); var θ12, θ21; if (Math.sin(λ2-λ1) > 0) { θ12 = θ1; θ21 = 2*Math.PI - θ2; } else { θ12 = 2*Math.PI - θ1; θ21 = θ2; } var α1 = (θ13 - θ12 + Math.PI) % (2*Math.PI) - Math.PI; // angle 2-1-3 var α2 = (θ21 - θ23 + Math.PI) % (2*Math.PI) - Math.PI; // angle 1-2-3 if (Math.sin(α1)==0 && Math.sin(α2)==0) return null; // infinite intersections if (Math.sin(α1)*Math.sin(α2) < 0) return null; // ambiguous intersection //α1 = Math.abs(α1); //α2 = Math.abs(α2); // ... Ed Williams takes abs of α1/α2, but seems to break calculation? var α3 = Math.acos( -Math.cos(α1)*Math.cos(α2) + Math.sin(α1)*Math.sin(α2)*Math.cos(δ12) ); var δ13 = Math.atan2( Math.sin(δ12)*Math.sin(α1)*Math.sin(α2), Math.cos(α2)+Math.cos(α1)*Math.cos(α3) ); var φ3 = Math.asin( Math.sin(φ1)*Math.cos(δ13) + Math.cos(φ1)*Math.sin(δ13)*Math.cos(θ13) ); var Δλ13 = Math.atan2( Math.sin(θ13)*Math.sin(δ13)*Math.cos(φ1), Math.cos(δ13)-Math.sin(φ1)*Math.sin(φ3) ); var λ3 = λ1 + Δλ13; λ3 = (λ3+3*Math.PI) % (2*Math.PI) - Math.PI; // normalise to -180..+180° return new LatLon(φ3.toDegrees(), λ3.toDegrees()); }; /** * Returns (signed) distance from ‘this’ point to great circle defined by start-point and end-point. * * @param {LatLon} pathStart - Start point of great circle path. * @param {LatLon} pathEnd - End point of great circle path. * @param {number} [radius=6371e3] - (Mean) radius of earth (defaults to radius in metres). * @returns {number} Distance to great circle (-ve if to left, +ve if to right of path). * * @example * var pCurrent = new LatLon(53.2611, -0.7972); * var p1 = new LatLon(53.3206, -1.7297), p2 = new LatLon(53.1887, 0.1334); * var d = pCurrent.crossTrackDistanceTo(p1, p2); // Number(d.toPrecision(4)): -307.5 */ LatLon.prototype.crossTrackDistanceTo = function(pathStart, pathEnd, radius) { if (!(pathStart instanceof LatLon)) throw new TypeError('pathStart is not LatLon object'); if (!(pathEnd instanceof LatLon)) throw new TypeError('pathEnd is not LatLon object'); radius = (radius === undefined) ? 6371e3 : Number(radius); var δ13 = pathStart.distanceTo(this, radius)/radius; var θ13 = pathStart.bearingTo(this).toRadians(); var θ12 = pathStart.bearingTo(pathEnd).toRadians(); var dxt = Math.asin( Math.sin(δ13) * Math.sin(θ13-θ12) ) * radius; return dxt; }; /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ /** * Returns the distance travelling from 'this' point to destination point along a rhumb line. * * @param {LatLon} point - Latitude/longitude of destination point. * @param {number} [radius=6371e3] - (Mean) radius of earth (defaults to radius in metres). * @returns {number} Distance in km between this point and destination point (same units as radius). * * @example * var p1 = new LatLon(51.127, 1.338), p2 = new LatLon(50.964, 1.853); * var d = p1.distanceTo(p2); // Number(d.toPrecision(4)): 40310 */ LatLon.prototype.rhumbDistanceTo = function(point, radius) { if (!(point instanceof LatLon)) throw new TypeError('point is not LatLon object'); radius = (radius === undefined) ? 6371e3 : Number(radius); // see http://williams.best.vwh.net/avform.htm#Rhumb var R = radius; var φ1 = this.lat.toRadians(), φ2 = point.lat.toRadians(); var Δφ = φ2 - φ1; var Δλ = Math.abs(point.lon-this.lon).toRadians(); // if dLon over 180° take shorter rhumb line across the anti-meridian: if (Math.abs(Δλ) > Math.PI) Δλ = Δλ>0 ? -(2*Math.PI-Δλ) : (2*Math.PI+Δλ); // on Mercator projection, longitude distances shrink by latitude; q is the 'stretch factor' // q becomes ill-conditioned along E-W line (0/0); use empirical tolerance to avoid it var Δψ = Math.log(Math.tan(φ2/2+Math.PI/4)/Math.tan(φ1/2+Math.PI/4)); var q = Math.abs(Δψ) > 10e-12 ? Δφ/Δψ : Math.cos(φ1); // distance is pythagoras on 'stretched' Mercator projection var δ = Math.sqrt(Δφ*Δφ + q*q*Δλ*Δλ); // angular distance in radians var dist = δ * R; return dist; }; /** * Returns the bearing from 'this' point to destination point along a rhumb line. * * @param {LatLon} point - Latitude/longitude of destination point. * @returns {number} Bearing in degrees from north. * * @example * var p1 = new LatLon(51.127, 1.338), p2 = new LatLon(50.964, 1.853); * var d = p1.rhumbBearingTo(p2); // d.toFixed(1): 116.7 */ LatLon.prototype.rhumbBearingTo = function(point) { if (!(point instanceof LatLon)) throw new TypeError('point is not LatLon object'); var φ1 = this.lat.toRadians(), φ2 = point.lat.toRadians(); var Δλ = (point.lon-this.lon).toRadians(); // if dLon over 180° take shorter rhumb line across the anti-meridian: if (Math.abs(Δλ) > Math.PI) Δλ = Δλ>0 ? -(2*Math.PI-Δλ) : (2*Math.PI+Δλ); var Δψ = Math.log(Math.tan(φ2/2+Math.PI/4)/Math.tan(φ1/2+Math.PI/4)); var θ = Math.atan2(Δλ, Δψ); return (θ.toDegrees()+360) % 360; }; /** * Returns the destination point having travelled along a rhumb line from 'this' point the given * distance on the given bearing. * * @param {number} distance - Distance travelled, in same units as earth radius (default: metres). * @param {number} bearing - Bearing in degrees from north. * @param {number} [radius=6371e3] - (Mean) radius of earth (defaults to radius in metres). * @returns {LatLon} Destination point. * * @example * var p1 = new LatLon(51.127, 1.338); * var p2 = p1.rhumbDestinationPoint(40300, 116.7); // p2.toString(): 50.9642°N, 001.8530°E */ LatLon.prototype.rhumbDestinationPoint = function(distance, bearing, radius) { radius = (radius === undefined) ? 6371e3 : Number(radius); var δ = Number(distance) / radius; // angular distance in radians var φ1 = this.lat.toRadians(), λ1 = this.lon.toRadians(); var θ = Number(bearing).toRadians(); var Δφ = δ * Math.cos(θ); var φ2 = φ1 + Δφ; // check for some daft bugger going past the pole, normalise latitude if so if (Math.abs(φ2) > Math.PI/2) φ2 = φ2>0 ? Math.PI-φ2 : -Math.PI-φ2; var Δψ = Math.log(Math.tan(φ2/2+Math.PI/4)/Math.tan(φ1/2+Math.PI/4)); var q = Math.abs(Δψ) > 10e-12 ? Δφ / Δψ : Math.cos(φ1); // E-W course becomes ill-conditioned with 0/0 var Δλ = δ*Math.sin(θ)/q; var λ2 = λ1 + Δλ; λ2 = (λ2 + 3*Math.PI) % (2*Math.PI) - Math.PI; // normalise to -180..+180° return new LatLon(φ2.toDegrees(), λ2.toDegrees()); }; /** * Returns the loxodromic midpoint (along a rhumb line) between 'this' point and second point. * * @param {LatLon} point - Latitude/longitude of second point. * @returns {LatLon} Midpoint between this point and second point. * * @example * var p1 = new LatLon(51.127, 1.338), p2 = new LatLon(50.964, 1.853); * var p2 = p1.rhumbMidpointTo(p2); // p2.toString(): 51.0455°N, 001.5957°E */ LatLon.prototype.rhumbMidpointTo = function(point) { if (!(point instanceof LatLon)) throw new TypeError('point is not LatLon object'); // http://mathforum.org/kb/message.jspa?messageID=148837 var φ1 = this.lat.toRadians(), λ1 = this.lon.toRadians(); var φ2 = point.lat.toRadians(), λ2 = point.lon.toRadians(); if (Math.abs(λ2-λ1) > Math.PI) λ1 += 2*Math.PI; // crossing anti-meridian var φ3 = (φ1+φ2)/2; var f1 = Math.tan(Math.PI/4 + φ1/2); var f2 = Math.tan(Math.PI/4 + φ2/2); var f3 = Math.tan(Math.PI/4 + φ3/2); var λ3 = ( (λ2-λ1)*Math.log(f3) + λ1*Math.log(f2) - λ2*Math.log(f1) ) / Math.log(f2/f1); if (!isFinite(λ3)) λ3 = (λ1+λ2)/2; // parallel of latitude λ3 = (λ3 + 3*Math.PI) % (2*Math.PI) - Math.PI; // normalise to -180..+180° return new LatLon(φ3.toDegrees(), λ3.toDegrees()); }; /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ /** * Returns a string representation of 'this' point, formatted as degrees, degrees+minutes, or * degrees+minutes+seconds. * * @param {string} [format=dms] - Format point as 'd', 'dm', 'dms'. * @param {number} [dp=0|2|4] - Number of decimal places to use - default 0 for dms, 2 for dm, 4 for d. * @returns {string} Comma-separated latitude/longitude. */ LatLon.prototype.toString = function(format, dp) { if (format === undefined) format = 'dms'; return Dms.toLat(this.lat, format, dp) + ', ' + Dms.toLon(this.lon, format, dp); }; /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ /** Extend Number object with method to convert numeric degrees to radians */ if (Number.prototype.toRadians === undefined) { Number.prototype.toRadians = function() { return this * Math.PI / 180; }; } /** Extend Number object with method to convert radians to numeric (signed) degrees */ if (Number.prototype.toDegrees === undefined) { Number.prototype.toDegrees = function() { return this * 180 / Math.PI; }; }
jdpearce/snowthorn-flightvisualiser
src/js/latlon-spherical.js
JavaScript
mit
17,418
/* @flow */ /* eslint-disable */ import * as React from 'react'; jest.autoMockOff(); jest.clearAllMocks(); jest.resetAllMocks(); // $FlowExpectedError[prop-missing] property `atoMockOff` not found in object type jest.atoMockOff(); const mockFn = jest.fn(); mockFn.mock.calls.map(String).map((a) => a + a); type Foo = { doStuff: string => number, ... }; const foo: Foo = { doStuff(str: string): number { return 5; } }; foo.doStuff = jest.fn().mockImplementation((str) => 10); foo.doStuff = jest.fn().mockImplementation((str) => parseInt(str, 10)); foo.doStuff = jest.fn().mockImplementation((str) => str.indexOf('a')); // $FlowExpectedError[prop-missing] function `doesntExist` not found in string. foo.doStuff = jest.fn().mockImplementation((str) => str.doesntExist()); // $FlowExpectedError[incompatible-call] Mock function expected to return number, not string. foo.doStuff = jest.fn().mockImplementation((str) => '10'); foo.doStuff = jest.fn().mockImplementationOnce((str) => 10); foo.doStuff = jest.fn().mockImplementationOnce((str) => parseInt(str, 10)); foo.doStuff = jest.fn().mockImplementationOnce((str) => str.indexOf('a')); // $FlowExpectedError[prop-missing] function `doesntExist` not found in string. foo.doStuff = jest.fn().mockImplementationOnce((str) => str.doesntExist()); // $FlowExpectedError[incompatible-call] Mock function expected to return number, not string. foo.doStuff = jest.fn().mockImplementationOnce((str) => '10'); foo.doStuff = jest.fn().mockReturnValue(10); // $FlowExpectedError[incompatible-call] Mock function expected to return number, not string. foo.doStuff = jest.fn().mockReturnValue('10'); foo.doStuff = jest.fn().mockReturnValueOnce(10); // $FlowExpectedError[incompatible-call] Mock function expected to return number, not string. foo.doStuff = jest.fn().mockReturnValueOnce('10'); const mockedDoStuff = (foo.doStuff = jest.fn().mockImplementation((str) => 10)); mockedDoStuff.mock.calls[0][0].indexOf('a'); // $FlowExpectedError[prop-missing] function `doesntExist` not found in string. mockedDoStuff.mock.calls[0][0].doesntExist('a'); mockedDoStuff.mock.instances[0] > 5; // $FlowExpectedError[prop-missing] function `doesntExist` not found in number. mockedDoStuff.mock.instances[0].indexOf('a'); expect(1).toEqual(1); expect(true).toBe(true); expect(5).toBeGreaterThan(3); expect(5).toBeLessThan(8); expect("jester").toContain("jest"); expect({ foo: "bar" }).toHaveProperty("foo"); expect({ foo: "bar" }).toHaveProperty("foo", "bar"); expect("foo").toMatchSnapshot("snapshot name"); expect({ foo: "bar" }).toMatchObject({ baz: "qux" }); expect("foobar").toMatch(/foo/); expect("foobar").toMatch("foo"); mockFn("a"); expect("someVal").toBeCalled(); expect("someVal").toBeCalledWith("a"); // $FlowExpectedError[incompatible-call] property `toHaveBeeenCalledWith` not found in object type expect("someVal").toHaveBeeenCalledWith("a"); // $FlowExpectedError[prop-missing] property `fn` not found in Array mockFn.mock.calls.fn(); describe('name', () => {}); describe.only('name', () => {}); describe.skip('name', () => {}); test("test", () => expect("foo").toMatchSnapshot()); test.only("test", () => expect("foo").toMatchSnapshot()); test.skip("test", () => expect("foo").toMatchSnapshot()); // $FlowExpectedError[prop-missing] property `fonly` not found in object type test.fonly('test', () => expect('foo').toMatchSnapshot()); test('name', (done) => { done(); }); test.only('name', (done) => { done(); }); test.skip('name', (done) => { done(); }); // $FlowExpectedError[incompatible-call] tests should return void or Promise. test('name', () => 5); test('name', async () => {}); test('name', () => new Promise((resolve, reject) => {})); // $FlowExpectedError[incompatible-call] describe does not support Promises. describe('name', () => new Promise((resolve, reject) => {})); beforeEach(() => {}); beforeEach(() => new Promise((resolve, reject) => {})); // $FlowExpectedError[incompatible-call] Lifecycle methods should return void or Promise. beforeEach(() => 5); beforeAll(() => {}); beforeAll(() => new Promise((resolve, reject) => {})); // $FlowExpectedError[incompatible-call] Lifecycle methods should return void or Promise. beforeAll(() => 5); afterEach(() => {}); afterEach(() => new Promise((resolve, reject) => {})); // $FlowExpectedError[incompatible-call] Lifecycle methods should return void or Promise. afterEach(() => 5); afterAll(() => {}); afterAll(() => new Promise((resolve, reject) => {})); // $FlowExpectedError[incompatible-call] Lifecycle methods should return void or Promise. afterAll(() => 5); xtest('test', () => {}); // $FlowExpectedError[prop-missing] property `bar` not found in object type expect.bar(); expect.extend({ blah(actual, expected) { return { message: () => 'blah fail', pass: false, }; }, }); expect.extend({ foo(actual, expected) { // $FlowExpectedError[prop-missing] property `pass` not found in object literal return {}; }, }); const err = new Error('err'); expect(() => { throw err; }).toThrowError('err'); expect(() => { throw err; }).toThrowError(/err/); expect(() => { throw err; }).toThrowError(err); expect(() => {}).toThrow('err'); expect(() => {}).toThrow(/err/); expect(() => {}).toThrow(err); // Test method chaining fixes jest.doMock('testModule1', () => {}).doMock('testModule2', () => {}); jest.dontMock('testModule1').dontMock('testModule2'); jest.resetModules().resetModules(); jest.spyOn({}, 'foo'); expect.addSnapshotSerializer({ print: (val, serialize) => `Foo: ${serialize(val.foo)}`, test: (val) => val && val.hasOwnProperty('foo'), }); // $FlowExpectedError[incompatible-call] expect.addSnapshotSerializer(JSON.stringify); expect.assertions(1); expect.hasAssertions(); expect.anything(); expect.any(Error); expect.objectContaining({ foo: 'bar', }); expect.arrayContaining(['red', 'blue']); expect.stringMatching('*this part*'); test.concurrent('test', () => {}); expect([1, 2, 3]).toHaveLength(3); (async () => { await expect(Promise.reject('ok')).rejects.toBe('ok'); await expect(Promise.resolve('ok')).resolves.toBe('ok'); })(); /** * Plugin: jest-enzyme */ // $FlowExpectedError[cannot-resolve-module] import { shallow } from 'enzyme'; const Dummy = () => <div />; const wrapper = shallow(<Dummy />); expect(wrapper).toBeChecked(); expect(wrapper).toBeDisabled(); expect(wrapper).toBeEmpty(); expect(wrapper).toBeEmptyRender(); expect(wrapper).toBePresent(); expect(wrapper).toContainReact(<Dummy />); // $FlowExpectedError[incompatible-call] expect(wrapper).toContainReact(); // $FlowExpectedError[incompatible-call] expect(wrapper).toContainReact('string'); expect(wrapper).toExist(); expect(wrapper).toHaveClassName('class'); // $FlowExpectedError[incompatible-call] expect(wrapper).toHaveClassName(); // $FlowExpectedError[incompatible-call] expect(wrapper).toHaveClassName(true); expect(wrapper).toHaveHTML('<span>test</span>'); // $FlowExpectedError[incompatible-call] expect(wrapper).toHaveHTML(); // $FlowExpectedError[incompatible-call] expect(wrapper).toHaveHTML(true); expect(wrapper).toHaveProp('test'); expect(wrapper).toHaveProp('test', 'test'); // $FlowExpectedError[incompatible-call] expect(wrapper).toHaveProp(); // $FlowExpectedError[incompatible-call] expect(wrapper).toHaveProp(true); expect(wrapper).toHaveProp({ test: "test" }); // $FlowExpectedError[incompatible-call] expect(wrapper).toHaveProp({ test: "test" }, "test"); expect(wrapper).toHaveRef('test'); // $FlowExpectedError[incompatible-call] expect(wrapper).toHaveRef(); // $FlowExpectedError[incompatible-call] expect(wrapper).toHaveRef(true); expect(wrapper).toHaveState('test'); expect(wrapper).toHaveState('test', 'test'); expect(wrapper).toHaveState({ test: "test" }); // $FlowExpectedError[incompatible-call] expect(wrapper).toHaveState({ test: "test" }, "test"); // $FlowExpectedError[incompatible-call] expect(wrapper).toHaveState(); // $FlowExpectedError[incompatible-call] expect(wrapper).toHaveState(true); expect(wrapper).toHaveStyle('color'); expect(wrapper).toHaveStyle('color', '#ccc'); expect(wrapper).toHaveStyle({ color: "#ccc" }); // $FlowExpectedError[incompatible-call] expect(wrapper).toHaveStyle({ color: "#ccc" }, "test"); // $FlowExpectedError[incompatible-call] expect(wrapper).toHaveStyle(); // $FlowExpectedError[incompatible-call] expect(wrapper).toHaveStyle(true); expect(wrapper).toHaveTagName('marquee'); // $FlowExpectedError[incompatible-call] expect(wrapper).toHaveTagName(); // $FlowExpectedError[incompatible-call] expect(wrapper).toHaveTagName(true); expect(wrapper).toHaveText('test'); // $FlowExpectedError[incompatible-call] expect(wrapper).toHaveText(); // $FlowExpectedError[incompatible-call] expect(wrapper).toHaveText(true); expect(wrapper).toIncludeText("test"); // $FlowExpectedError[incompatible-call] expect(wrapper).toIncludeText(); // $FlowExpectedError[incompatible-call] expect(wrapper).toIncludeText(true); expect(wrapper).toHaveValue("test"); expect(wrapper).toMatchElement(<Dummy />); // $FlowExpectedError[incompatible-call] expect(wrapper).toMatchElement(); // $FlowExpectedError[incompatible-call] expect(wrapper).toMatchElement(true); expect(wrapper).toMatchSelector('span'); // $FlowExpectedError[incompatible-call] expect(wrapper).toMatchSelector(); // $FlowExpectedError[incompatible-call] expect(wrapper).toMatchSelector(true); // dom-testing-library { const element = document.createElement('div'); expect(element).toHaveTextContent('123'); // $FlowExpectedError[incompatible-call]: expected text content should be present expect(element).toHaveTextContent(); // $FlowExpectedError[incompatible-call]: expected text content should be a string expect(element).toHaveTextContent(1); expect(element).toBeInTheDOM(); expect(element).toHaveAttribute('foo'); expect(element).toHaveAttribute('foo', 'bar'); // $FlowExpectedError[incompatible-call]: attribute name should be present expect(element).toHaveAttribute(); // $FlowExpectedError[incompatible-call]: attribute name should be a string expect(element).toHaveAttribute(1); // $FlowExpectedError[incompatible-call]: expected attribute value should be a string expect(element).toHaveAttribute('foo', 1); }
splodingsocks/FlowTyped
definitions/npm/jest_v20.x.x/flow_v0.134.x-/test_jest-v20.x.x.js
JavaScript
mit
10,282
/** * Dependencies * @type {exports} */ var fs = require('fs') , q = require('q') , _ = require('underscore') , path = require('path') , natural = require('natural') , nounInflector = new natural.NounInflector() , argv = require('optimist').argv , path = require('path') , generator = require('./model.generator'); /** * Arguments */ var directory = path.resolve(process.argv[2]) , dest = path.resolve(process.argv[3]); var host = "" , version = "1.0" , rel = ""; /** * Functions */ var resourceName = function(model) { return nounInflector.pluralize(model.modelName).toLowerCase(); }; /** * load a model * @param modelPath * @returns {*} */ var loadModel = function(modelPath) { return require(directory + '/' + modelPath); }; /** * Write the schema file * @param modelPath */ var profileModel = function(modelPath) { var model = loadModel(modelPath); var schema = generator(host, version, model, rel); mkdir(dest) fs.writeFile(dest + '/' + resourceName(model) + '.json', JSON.stringify(schema, false, 2), function(err) { }); }; /** * Read models from directory */ fs.readdir(directory, function(err, files) { _.each(files, profileModel); }); /** * Make a directory * @param path * @param root * @returns {boolean|*} */ function mkdir(path, root) { var dirs = path.split('/') , dir = dirs.shift() , root = (root || '') + dir + '/'; try { fs.mkdirSync(root); } catch(e) { if (!fs.statSync(root).isDirectory()) { throw new Error(e); } } return !dirs.length || mkdir(dirs.join('/'), root); }
bpanahij/restgoose
tools/json-schema-generator/index.js
JavaScript
mit
1,586
'use strict' const path = require('path') const Generator = require('yeoman-generator') const chalk = require('chalk') const _ = require('lodash') _.templateSettings.interpolate = /<%=([\s\S]+?)%>/g module.exports = Generator.extend({ initializing: function () { this.props = {} }, paths: function () { this.sourceRoot(path.normalize(path.join(__dirname, '/../../templates'))) }, writing: function () { const props = this.config.getAll() const newVersion = require('../../package.json').version if (!this.fs.exists(this.destinationPath('.yo-rc.json'))) { this.log(chalk.red('Refusing to update, a .yo-rc.json file is required.')) return } const cpTpl = (from, to) => { this.fs.copyTpl( this.templatePath(from), this.destinationPath(to), props ) } const cp = (from, to) => { this.fs.copy( this.templatePath(from), this.destinationPath(to) ) } const rm = (p) => { this.fs.delete(this.destinationPath(p)) } const pkgTpl = _.template( this.fs.read(this.templatePath('_package.json')) ) const pkg = JSON.parse(pkgTpl(props)) // No longer using eslint pkg.dependencies['eslint'] = undefined pkg.dependencies['eslint-config-ivantage'] = undefined pkg.dependencies['eslint-loader'] = undefined pkg.devDependencies['eslint'] = undefined pkg.devDependencies['eslint-config-ivantage'] = undefined pkg.devDependencies['eslint-loader'] = undefined // React update 15.4 --> 15.5 pkg.devDependencies['react-addons-shallow-compare'] = undefined pkg.devDependencies['react-addons-test-utils'] = undefined pkg.devDependencies['prop-types'] = undefined // Removed postcss plugins pkg.devDependencies['postcss-custom-properties'] = undefined // @todo - extendJSON will merge properties, for some things // (devDependencies) we probably just want to set them so as to not carry // forward cruft we don't need anymore. this.fs.extendJSON(this.destinationPath('package.json'), _.pick(pkg, [ 'name', 'main', 'description', 'scripts', 'license', 'jest', 'peerDependencies', 'devDependencies' ])) cpTpl('webpack.config.js', 'webpack.config.js') if (props.useDotFiles) { cp('_editorconfig', '.editorconfig') cp('_gitignore', '.gitignore') cp('_babelrc', '.babelrc') } else { [ '.editorconfig', '.gitignore', '.babelrc' ].forEach(rm) } // Standard over eslint! rm('.eslintrc.js') // No longer using explicit mock files rm('src/mocks') this.config.set('generatorVersion', newVersion) }, end: function () { const msg = chalk.green('Done.') this.log(msg) } })
iVantage/generator-ivh-react-component
generators/update/index.js
JavaScript
mit
2,829
'use strict' /* libraries */ var Sequelize = require('sequelize') /* own code */ var Attribute = require('./attribute') /** * Parse DEM entity and create Sequelize definition for the table itself. * @constructor */ function Entity() { this._parserAttr = new Attribute() } /** * Input JSON (DEM entity): { "id": "Person", "alias": "person", "comment": "Person basic entity with 2 attributes.", "attributes": [...] } * * Result data: { table: "NameFirst", columns: {...}, options: {...} } * * See http://sequelize.readthedocs.org/en/latest/docs/models-definition/#configuration * * @param jsDem * @param seqModel * @return {{}} * @private */ Entity.prototype.parseJson = function _parseJson(jsDem, seqModel) { var result = {table: '', columns: {}, options: {}}; /* process common properties */ result.table = jsDem.id var options = result.options /* parse columns */ if (jsDem.attributes) { var demAttrs = jsDem.attributes var columns = result.columns var i, len, parsedAttr; for (i = 0, len = demAttrs.length; i < len; ++i) { parsedAttr = this._parserAttr.parseJson(demAttrs[i]) columns[parsedAttr.column] = parsedAttr.definition } } return result } module.exports = Entity
flancer32/dbear
src/inc/generate/model/entity.js
JavaScript
mit
1,327
/** * Copyright 2016-present Tuan Le. * * Licensed under the MIT License. * You may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://opensource.org/licenses/mit-license.html * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *------------------------------------------------------------------------ * * @module SubtitleText * @description - Subtitle text component. * * @author Tuan Le (tuan.t.lei@gmail.com) * * * @flow */ 'use strict'; // eslint-disable-line import React from 'react'; import ReactNative from 'react-native'; // eslint-disable-line import PropTypes from 'prop-types'; import { Text as AnimatedText } from 'react-native-animatable'; import { DefaultTheme, DefaultThemeContext } from '../../themes/default-theme'; const DEFAULT_ANIMATION_DURATION_MS = 300; const DEFAULT_SUBTITLE_TEXT_STYLE = DefaultTheme.text.font.subtitle; const readjustStyle = (newStyle = { shade: `themed`, alignment: `left`, decoration: `none`, font: `themed`, indentation: 0, color: `themed` }, prevAdjustedStyle = DEFAULT_SUBTITLE_TEXT_STYLE, Theme = DefaultTheme) => { const { shade, alignment, decoration, font, indentation, color, style } = newStyle; const themedShade = shade === `themed` ? Theme.text.subtitle.shade : shade; let themedColor; if (color === `themed`) { if (Theme.text.color.subtitle.hasOwnProperty(Theme.text.subtitle.color)) { themedColor = Theme.text.color.subtitle[Theme.text.subtitle.color][themedShade]; } else { themedColor = Theme.text.subtitle.color; } } else if (Theme.text.color.subtitle.hasOwnProperty(color)) { themedColor = Theme.text.color.subtitle[color][themedShade]; } else { themedColor = color; } return { small: { ...prevAdjustedStyle.small, ...Theme.text.font.subtitle.small, fontFamily: font === `themed` ? Theme.text.font.subtitle.small.fontFamily : font, textAlign: alignment, textDecorationLine: decoration, paddingLeft: indentation > 0 ? indentation : 0, paddingRight: indentation < 0 ? -indentation : 0, color: themedColor, ...(typeof style === `object` ? style : {}) }, normal: { ...prevAdjustedStyle.normal, ...Theme.text.font.subtitle.normal, fontFamily: font === `themed` ? Theme.text.font.subtitle.normal.fontFamily : font, textAlign: alignment, textDecorationLine: decoration, paddingLeft: indentation > 0 ? indentation : 0, paddingRight: indentation < 0 ? -indentation : 0, color: themedColor, ...(typeof style === `object` ? style : {}) }, large: { ...prevAdjustedStyle.large, ...Theme.text.font.subtitle.large, fontFamily: font === `themed` ? Theme.text.font.subtitle.large.fontFamily : font, textAlign: alignment, textDecorationLine: decoration, paddingLeft: indentation > 0 ? indentation : 0, paddingRight: indentation < 0 ? -indentation : 0, color: themedColor, ...(typeof style === `object` ? style : {}) } }; }; export default class SubtitleText extends React.Component { static contextType = DefaultThemeContext static propTypes = { exclusions: PropTypes.arrayOf(PropTypes.string), room: PropTypes.oneOf([ `none`, `content-left`, `content-middle`, `content-right`, `content-bottom`, `content-top`, `media`, `activity-indicator` ]), shade: PropTypes.oneOf([ `themed`, `light`, `dark` ]), alignment: PropTypes.oneOf([ `left`, `center`, `right` ]), decoration: PropTypes.oneOf([ `none`, `underline`, `line-through` ]), size: PropTypes.oneOf([ `themed`, `small`, `normal`, `large` ]), font: PropTypes.string, indentation: PropTypes.number, uppercased: PropTypes.bool, lowercased: PropTypes.bool, color: PropTypes.string, initialAnimation: PropTypes.oneOfType([ PropTypes.string, PropTypes.shape({ refName: PropTypes.string, transitions: PropTypes.arrayOf(PropTypes.shape({ to: PropTypes.oneOfType([ PropTypes.func, PropTypes.object ]), from: PropTypes.oneOfType([ PropTypes.func, PropTypes.object ]), option: PropTypes.shape({ duration: PropTypes.number, delay: PropTypes.number, easing: PropTypes.string }) })), onTransitionBegin: PropTypes.func, onTransitionEnd: PropTypes.func, onAnimationBegin: PropTypes.func, onAnimationEnd: PropTypes.func }) ]) } static defaultProps = { exclusions: [ `` ], room: `none`, shade: `themed`, alignment: `left`, decoration: `none`, font: `themed`, size: `themed`, indentation: 0, uppercased: false, lowercased: false, color: `themed`, initialAnimation: `themed` } static getDerivedStateFromProps (props, state) { const { shade, alignment, decoration, font, indentation, color, style } = props; const { Theme } = state.context; return { adjustedStyle: readjustStyle({ shade, alignment, decoration, font, indentation, color, style }, state.adjustedStyle, Theme) }; } constructor (props) { super(props); const component = this; component.refCache = {}; component.state = { context: { Theme: DefaultTheme }, adjustedStyle: DEFAULT_SUBTITLE_TEXT_STYLE }; } animate (animation = { onTransitionBegin: () => null, onTransitionEnd: () => null, onAnimationBegin: () => null, onAnimationEnd: () => null }) { const component = this; const { Theme } = component.context; if (typeof animation === `string` && animation !== `none`) { const animationName = animation.replace(/-([a-z])/g, (match, word) => word.toUpperCase()); if (Theme.text.animation.subtitle.hasOwnProperty(animationName)) { animation = Theme.text.animation.subtitle[animationName]; } } if (typeof animation === `object`) { const { refName, transitions, onTransitionBegin, onTransitionEnd, onAnimationBegin, onAnimationEnd } = animation; const componentRef = component.refCache[refName]; if (componentRef !== undefined && Array.isArray(transitions)) { let transitionDuration = 0; const transitionPromises = transitions.map((transition, transitionIndex) => { let transitionBeginPromise; let transitionEndPromise; if (typeof transition === `object`) { let transitionType; let componentRefTransition = { from: {}, to: {} }; let componentRefTransitionOption = { duration: DEFAULT_ANIMATION_DURATION_MS, delay: 0, easing: `linear` }; if (transition.hasOwnProperty(`from`)) { let from = typeof transition.from === `function` ? transition.from(component.props, component.state, component.context) : transition.from; componentRefTransition.from = typeof from === `object` ? from : {}; transitionType = `from`; } if (transition.hasOwnProperty(`to`)) { let to = typeof transition.to === `function` ? transition.to(component.props, component.state, component.context) : transition.to; componentRefTransition.to = typeof to === `object` ? to : {}; transitionType = transitionType === `from` ? `from-to` : `to`; } if (transition.hasOwnProperty(`option`) && typeof transition.option === `object`) { componentRefTransitionOption = { ...componentRefTransitionOption, ...transition.option }; } transitionBeginPromise = new Promise((resolve) => { setTimeout(() => { if (transitionType === `to`) { componentRef.transitionTo( componentRefTransition.to, componentRefTransitionOption.duration, componentRefTransitionOption.easing, componentRefTransitionOption.delay ); } else if (transitionType === `from-to`) { setTimeout(() => { componentRef.transition( componentRefTransition.from, componentRefTransition.to, componentRefTransitionOption.duration, componentRefTransitionOption.easing ); }, componentRefTransitionOption.delay); } (typeof onTransitionBegin === `function` ? onTransitionBegin : () => null)(transitionIndex); resolve((_onTransitionBegin) => (typeof _onTransitionBegin === `function` ? _onTransitionBegin : () => null)(_onTransitionBegin)); }, transitionDuration + 5); }); transitionDuration += componentRefTransitionOption.duration + componentRefTransitionOption.delay; transitionEndPromise = new Promise((resolve) => { setTimeout(() => { (typeof onTransitionEnd === `function` ? onTransitionEnd : () => null)(transitionIndex); resolve((_onTransitionEnd) => (typeof _onTransitionEnd === `function` ? _onTransitionEnd : () => null)(transitionIndex)); }, transitionDuration); }); } return [ transitionBeginPromise, transitionEndPromise ]; }); const animationBeginPromise = new Promise((resolve) => { (typeof onAnimationBegin === `function` ? onAnimationBegin : () => null)(); resolve((_onAnimationBegin) => (typeof _onAnimationBegin === `function` ? _onAnimationBegin : () => null)()); }); const animationEndPromise = new Promise((resolve) => { setTimeout(() => { (typeof onAnimationEnd === `function` ? onAnimationEnd : () => null)(); resolve((_onAnimationEnd) => (typeof _onAnimationEnd === `function` ? _onAnimationEnd : () => null)()); }, transitionDuration + 5); }); return Promise.all([ animationBeginPromise, ...transitionPromises.flat(), animationEndPromise ].filter((animationPromise) => animationPromise !== undefined)); } } } componentDidMount () { const component = this; const { shade, alignment, decoration, font, indentation, color, initialAnimation, style } = component.props; const { Theme } = component.context; component.setState((prevState) => { return { context: { Theme }, adjustedStyle: readjustStyle({ shade, alignment, decoration, font, indentation, color, style }, prevState.adjustedStyle, Theme) }; }, () => { if ((typeof initialAnimation === `string` && initialAnimation !== `none`) || typeof initialAnimation === `object`) { component.animate(initialAnimation); } }); } componentWillUnMount () { const component = this; component.refCache = {}; } render () { const component = this; const { size, uppercased, lowercased, children } = component.props; const { adjustedStyle } = component.state; const { Theme } = component.context; const themedSize = size === `themed` ? Theme.text.subtitle.size : size; let contentChildren = null; if (React.Children.count(children) > 0) { contentChildren = React.Children.toArray(React.Children.map(children, (child) => { if (uppercased) { return child.toUpperCase(); } else if (lowercased) { return child.toLowerCase(); } return child; })); } return ( <AnimatedText ref = {(componentRef) => { component.refCache[`animated-text`] = componentRef; }} style = { adjustedStyle[themedSize] } ellipsizeMode = 'tail' numberOfLines = { 1 } useNativeDriver = { true } > { contentChildren } </AnimatedText> ); } }
tuantle/hypertoxin
src/components/texts/subtitle-text.js
JavaScript
mit
15,513
const pageIcon = require('./../lib/index'); const helpers = require('./helpers'); const fs = require('fs'); const chai = require('chai'); const path = require('path'); const url = require('url'); const expect = chai.expect; const {isIconValid, saveToFile} = helpers; const SITE_URLS = [ 'https://www.facebook.com/', 'http://stackoverflow.com/questions/16301503/can-i-use-requirepath-join-to-safely-concatenate-urls', 'https://web.whatsapp.com' ]; const HTTP_TEST_URL = 'http://web.whatsapp.com'; const ICON_TYPE_URL = 'https://web.whatsapp.com'; describe('Page Icon', function() { this.timeout(10000); it('Can download all icons', function(done) { const downloadTests = SITE_URLS.map(function(siteUrl) { return new Promise(function(resolve, reject) { pageIcon(siteUrl) .then(function(icon) { if (!icon) { throw `No icon found for url: ${siteUrl}`; } return icon; }) .then(function(icon) { expect(isIconValid(icon)).to.be.true; return icon; }) .then(saveToFile) .then(() => { resolve(); }) .catch(reject); }); }); Promise.all(downloadTests) .then(function() { done(); }) .catch(done); }); it('Can try to https if nothing is found at http', function(done) { pageIcon(HTTP_TEST_URL) .then(function(icon) { if (!icon) { throw `No icon found for url: ${siteUrl}`; } return icon; }) .then(function(icon) { expect(isIconValid(icon)).to.be.true; done() }) .catch(done); }); describe('Specification of preferred icon ext', function () { it('Type .png', function(done) { iconTypeTest('.png', done); }); it('Type .ico', function (done) { iconTypeTest('.ico', done); }); }); }); function iconTypeTest(ext, callback) { pageIcon(ICON_TYPE_URL, {ext: ext}) .then(function(icon) { if (!icon) { throw `No icon found for url: ${ICON_TYPE_URL}`; } return icon; }) .then(function(icon) { expect(icon.ext).to.equal(ext, `Should get a ${ext} from WhatsApp`); return icon; }) .then(() => { callback(); }) .catch(callback); }
jiahaog/page-icon
test/test.js
JavaScript
mit
2,773
// // This is only a SKELETON file for the 'Rectangles' exercise. It's been provided as a // convenience to get you started writing code faster. // export function count() { throw new Error('Remove this statement and implement this function'); }
exercism/xecmascript
exercises/practice/rectangles/rectangles.js
JavaScript
mit
249
var async = require('async'), awsSDK = require('aws-sdk'), uuid = require('node-uuid'); function client() { return new awsSDK.DynamoDB().client; } function putItem(done) { var item = { TableName: "test.performance.ssl", Item: { id: { S: uuid.v1() } } }; client().putItem(item, done); }; function put10(done) { var i = 10; var t = process.hrtime(); async.whilst(function() { return i > 0; }, function(cb) { --i; return putItem(cb); }, function(e) { t = process.hrtime(t); console.log('%d seconds', t[0] + t[1] / 1000000000); return done(e); }); }; describe('ssl tests', function() { this.timeout(10000); describe('with ssl', function() { before(function() { awsSDK.config.update({ accessKeyId: process.env.AWS_ACCESS_KEY, secretAccessKey: process.env.AWS_SECRET_KEY, sslEnabled: true, region: 'us-east-1' }); }); it('can put 10 items', put10); }); describe('without ssl', function() { before(function() { awsSDK.config.update({ accessKeyId: process.env.AWS_ACCESS_KEY, secretAccessKey: process.env.AWS_SECRET_KEY, sslEnabled: false, region: 'us-east-1' }); }); it('can put 10 items', put10); }); });
B2MSolutions/performance-tests
dynamodb/ssl-test.js
JavaScript
mit
1,308
'use strict'; var _ = require("lodash-node") ,parserlib = require("parserlib") // for linting CSS ,fse = require("fs-extra") ,cwd = process.cwd() describe("test 4 - check css is valid", function() { var originalTimeout; beforeEach(function() { originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL; jasmine.DEFAULT_TIMEOUT_INTERVAL = 4000; }); afterEach(function() { jasmine.DEFAULT_TIMEOUT_INTERVAL = originalTimeout; }); /** * Lodash template used just for converting path vars */ var rootDirObj = { rootDir: "./" } ,config = require("./grunt_configs/test4.js").test ,DEST = _.template( config.dest, rootDirObj ); it("should have created a css file for icons which should no longer contains any template syntax, then lint the styles.", function(done) { expect( fse.existsSync(DEST+"icons.css") ).toBe( true ); var css = fse.readFileSync(DEST+"icons.css").toString(); expect( css.indexOf("<%=") ).toEqual(-1); lintCSS( done, css ); }); it("should have copied the `svgloader.js` file into dist.", function() { expect( fse.existsSync(DEST+"svgloader.js") ).toBe( true ); }); it("should have NOT generated sprite and placed it into dist.", function() { expect( fse.existsSync(DEST + "sprite.png") ).toBe( false ); }); }); function lintCSS( done, returnedStr ) { // Now we lint the CSS var parser = new parserlib.css.Parser(); // will get changed to true in error handler if errors detected var errorsFound = false; parser.addListener("error", function(event){ console.log("Parse error: " + event.message + " (" + event.line + "," + event.col + ")", "error"); errorsFound = true; }); parser.addListener("endstylesheet", function(){ console.log("Finished parsing style sheet"); expect( errorsFound ).toBe( false ); // finish the test done(); }); parser.parse( returnedStr ); }
digitor/grunt-badass
tests/test4_grunt_spec.js
JavaScript
mit
1,880
'use strict'; import angular from 'angular'; import NavbarTpl from './navbar.html'; import NavbarService from './navbar-service'; import NavbarCtrl from './navbar-ctrl'; function navbar(NavbarService) { return { restrict: 'E', scope: { name: '@', version: '@', linkTo: '@' }, templateUrl: NavbarTpl, link: (scope, el, attr) => { scope.navbar = NavbarService.getNavbar(); } } } export default angular.module('directives.navbar', [NavbarService]) .directive('navbar', ['NavbarService', navbar]) .controller('NavbarCtrl', ['$scope', '$document', NavbarCtrl]) .name;
hegdeashwin/aw-stack
src/app/components/navbar/navbar-directive.js
JavaScript
mit
623
'use strict' require('should') const DummyTransport = require('chix-transport/dummy') const ProcessManager = require('chix-flow/src/process/manager') const RuntimeHandler = require('../lib/handler/runtime') const pkg = require('../package') const schemas = require('../schemas') // TODO: this just loads the definitions from the live webserver. // Doesn't matter that much I think.. describe('Runtime Handler:', () => { it('Should respond to getruntime', (done) => { const pm = new ProcessManager() const transport = new DummyTransport({ // logger: console, bail: true, schemas: schemas }) RuntimeHandler.handle(pm, transport /*, console*/) transport.capabilities = ['my-capabilities'] transport.once('send', (data, conn) => { data.protocol.should.eql('runtime') data.command.should.eql('runtime') data.payload.version.should.eql(pkg.version) data.payload.capabilities.should.eql([ 'my-capabilities' ]) conn.should.eql('test-connection') // assume the data from the server is ok done() }) // trigger component action transport.receive({ protocol: 'runtime', command: 'getruntime' }, 'test-connection') }) })
psichi/chix
packages/chix-runtime/test/runtime.js
JavaScript
mit
1,249
/*! PhotoSwipe Default UI - 4.1.2 - 2017-04-05 * http://photoswipe.com * Copyright (c) 2017 Dmitry Semenov; */ /** * * UI on top of main sliding area (caption, arrows, close button, etc.). * Built just using public methods/properties of PhotoSwipe. * */ (function (root, factory) { if (typeof define === 'function' && define.amd) { define(factory); } else if (typeof exports === 'object') { module.exports = factory(); } else { root.PhotoSwipeUI_Default = factory(); } })(this, function () { 'use strict'; var PhotoSwipeUI_Default = function(pswp, framework) { var ui = this; var _overlayUIUpdated = false, _controlsVisible = true, _fullscrenAPI, _controls, _captionContainer, _fakeCaptionContainer, _indexIndicator, _shareButton, _shareModal, _shareModalHidden = true, _initalCloseOnScrollValue, _isIdle, _listen, _loadingIndicator, _loadingIndicatorHidden, _loadingIndicatorTimeout, _galleryHasOneSlide, _options, _defaultUIOptions = { barsSize: {top:44, bottom:'auto'}, closeElClasses: ['item', 'caption', 'zoom-wrap', 'ui', 'top-bar'], timeToIdle: 4000, timeToIdleOutside: 1000, loadingIndicatorDelay: 1000, // 2s addCaptionHTMLFn: function(item, captionEl /*, isFake */) { if(!item.title) { captionEl.children[0].innerHTML = ''; return false; } captionEl.children[0].innerHTML = item.title; return true; }, closeEl:true, captionEl: true, fullscreenEl: true, zoomEl: true, shareEl: true, counterEl: true, arrowEl: true, preloaderEl: true, tapToClose: false, tapToToggleControls: true, clickToCloseNonZoomable: true, shareButtons: [ {id:'facebook', label:'Share on Facebook', url:'https://www.facebook.com/dialog/share?app_id=248996855307000&amp;href={{url}}&amp;picture=https://stuti1995.github.io{{raw_image_url}}&description={{text}}'}, {id:'twitter', label:'Tweet', url:'https://twitter.com/intent/tweet?text={{text}}&url={{url}}'}, {id:'pinterest', label:'Pin it', url:'http://www.pinterest.com/pin/create/button/'+ '?url={{url}}&media={{image_url}}&description={{text}}'}, {id:'download', label:'Download image', url:'https://stuti1995.github.io{{raw_image_url}}', download:true} ], getImageURLForShare: function( /* shareButtonData */ ) { return pswp.currItem.src || ''; }, getPageURLForShare: function( /* shareButtonData */ ) { return window.location.href; }, getTextForShare: function( /* shareButtonData */ ) { return pswp.currItem.title || ''; }, indexIndicatorSep: ' / ', fitControlsWidth: 1200 }, _blockControlsTap, _blockControlsTapTimeout; var _onControlsTap = function(e) { if(_blockControlsTap) { return true; } e = e || window.event; if(_options.timeToIdle && _options.mouseUsed && !_isIdle) { // reset idle timer _onIdleMouseMove(); } var target = e.target || e.srcElement, uiElement, clickedClass = target.getAttribute('class') || '', found; for(var i = 0; i < _uiElements.length; i++) { uiElement = _uiElements[i]; if(uiElement.onTap && clickedClass.indexOf('pswp__' + uiElement.name ) > -1 ) { uiElement.onTap(); found = true; } } if(found) { if(e.stopPropagation) { e.stopPropagation(); } _blockControlsTap = true; // Some versions of Android don't prevent ghost click event // when preventDefault() was called on touchstart and/or touchend. // // This happens on v4.3, 4.2, 4.1, // older versions strangely work correctly, // but just in case we add delay on all of them) var tapDelay = framework.features.isOldAndroid ? 600 : 30; _blockControlsTapTimeout = setTimeout(function() { _blockControlsTap = false; }, tapDelay); } }, _fitControlsInViewport = function() { return !pswp.likelyTouchDevice || _options.mouseUsed || screen.width > _options.fitControlsWidth; }, _togglePswpClass = function(el, cName, add) { framework[ (add ? 'add' : 'remove') + 'Class' ](el, 'pswp__' + cName); }, // add class when there is just one item in the gallery // (by default it hides left/right arrows and 1ofX counter) _countNumItems = function() { var hasOneSlide = (_options.getNumItemsFn() === 1); if(hasOneSlide !== _galleryHasOneSlide) { _togglePswpClass(_controls, 'ui--one-slide', hasOneSlide); _galleryHasOneSlide = hasOneSlide; } }, _toggleShareModalClass = function() { _togglePswpClass(_shareModal, 'share-modal--hidden', _shareModalHidden); }, _toggleShareModal = function() { _shareModalHidden = !_shareModalHidden; if(!_shareModalHidden) { _toggleShareModalClass(); setTimeout(function() { if(!_shareModalHidden) { framework.addClass(_shareModal, 'pswp__share-modal--fade-in'); } }, 30); } else { framework.removeClass(_shareModal, 'pswp__share-modal--fade-in'); setTimeout(function() { if(_shareModalHidden) { _toggleShareModalClass(); } }, 300); } if(!_shareModalHidden) { _updateShareURLs(); } return false; }, _openWindowPopup = function(e) { e = e || window.event; var target = e.target || e.srcElement; pswp.shout('shareLinkClick', e, target); if(!target.href) { return false; } if( target.hasAttribute('download') ) { return true; } window.open(target.href, 'pswp_share', 'scrollbars=yes,resizable=yes,toolbar=no,'+ 'location=yes,width=550,height=420,top=100,left=' + (window.screen ? Math.round(screen.width / 2 - 275) : 100) ); if(!_shareModalHidden) { _toggleShareModal(); } return false; }, _updateShareURLs = function() { var shareButtonOut = '', shareButtonData, shareURL, image_url, page_url, share_text; for(var i = 0; i < _options.shareButtons.length; i++) { shareButtonData = _options.shareButtons[i]; image_url = _options.getImageURLForShare(shareButtonData); page_url = _options.getPageURLForShare(shareButtonData); share_text = _options.getTextForShare(shareButtonData); shareURL = shareButtonData.url.replace('{{url}}', encodeURIComponent(page_url) ) .replace('{{image_url}}', encodeURIComponent(image_url) ) .replace('{{raw_image_url}}', image_url ) .replace('{{text}}', encodeURIComponent(share_text) ); shareButtonOut += '<a href="' + shareURL + '" target="_blank" '+ 'class="pswp__share--' + shareButtonData.id + '"' + (shareButtonData.download ? 'download' : '') + '>' + shareButtonData.label + '</a>'; if(_options.parseShareButtonOut) { shareButtonOut = _options.parseShareButtonOut(shareButtonData, shareButtonOut); } } _shareModal.children[0].innerHTML = shareButtonOut; _shareModal.children[0].onclick = _openWindowPopup; }, _hasCloseClass = function(target) { for(var i = 0; i < _options.closeElClasses.length; i++) { if( framework.hasClass(target, 'pswp__' + _options.closeElClasses[i]) ) { return true; } } }, _idleInterval, _idleTimer, _idleIncrement = 0, _onIdleMouseMove = function() { clearTimeout(_idleTimer); _idleIncrement = 0; if(_isIdle) { ui.setIdle(false); } }, _onMouseLeaveWindow = function(e) { e = e ? e : window.event; var from = e.relatedTarget || e.toElement; if (!from || from.nodeName === 'HTML') { clearTimeout(_idleTimer); _idleTimer = setTimeout(function() { ui.setIdle(true); }, _options.timeToIdleOutside); } }, _setupFullscreenAPI = function() { if(_options.fullscreenEl && !framework.features.isOldAndroid) { if(!_fullscrenAPI) { _fullscrenAPI = ui.getFullscreenAPI(); } if(_fullscrenAPI) { framework.bind(document, _fullscrenAPI.eventK, ui.updateFullscreen); ui.updateFullscreen(); framework.addClass(pswp.template, 'pswp--supports-fs'); } else { framework.removeClass(pswp.template, 'pswp--supports-fs'); } } }, _setupLoadingIndicator = function() { // Setup loading indicator if(_options.preloaderEl) { _toggleLoadingIndicator(true); _listen('beforeChange', function() { clearTimeout(_loadingIndicatorTimeout); // display loading indicator with delay _loadingIndicatorTimeout = setTimeout(function() { if(pswp.currItem && pswp.currItem.loading) { if( !pswp.allowProgressiveImg() || (pswp.currItem.img && !pswp.currItem.img.naturalWidth) ) { // show preloader if progressive loading is not enabled, // or image width is not defined yet (because of slow connection) _toggleLoadingIndicator(false); // items-controller.js function allowProgressiveImg } } else { _toggleLoadingIndicator(true); // hide preloader } }, _options.loadingIndicatorDelay); }); _listen('imageLoadComplete', function(index, item) { if(pswp.currItem === item) { _toggleLoadingIndicator(true); } }); } }, _toggleLoadingIndicator = function(hide) { if( _loadingIndicatorHidden !== hide ) { _togglePswpClass(_loadingIndicator, 'preloader--active', !hide); _loadingIndicatorHidden = hide; } }, _applyNavBarGaps = function(item) { var gap = item.vGap; if( _fitControlsInViewport() ) { var bars = _options.barsSize; if(_options.captionEl && bars.bottom === 'auto') { if(!_fakeCaptionContainer) { _fakeCaptionContainer = framework.createEl('pswp__caption pswp__caption--fake'); _fakeCaptionContainer.appendChild( framework.createEl('pswp__caption__center') ); _controls.insertBefore(_fakeCaptionContainer, _captionContainer); framework.addClass(_controls, 'pswp__ui--fit'); } if( _options.addCaptionHTMLFn(item, _fakeCaptionContainer, true) ) { var captionSize = _fakeCaptionContainer.clientHeight; gap.bottom = parseInt(captionSize,10) || 44; } else { gap.bottom = bars.top; // if no caption, set size of bottom gap to size of top } } else { gap.bottom = bars.bottom === 'auto' ? 0 : bars.bottom; } // height of top bar is static, no need to calculate it gap.top = bars.top; } else { gap.top = gap.bottom = 0; } }, _setupIdle = function() { // Hide controls when mouse is used if(_options.timeToIdle) { _listen('mouseUsed', function() { framework.bind(document, 'mousemove', _onIdleMouseMove); framework.bind(document, 'mouseout', _onMouseLeaveWindow); _idleInterval = setInterval(function() { _idleIncrement++; if(_idleIncrement === 2) { ui.setIdle(true); } }, _options.timeToIdle / 2); }); } }, _setupHidingControlsDuringGestures = function() { // Hide controls on vertical drag _listen('onVerticalDrag', function(now) { if(_controlsVisible && now < 0.95) { ui.hideControls(); } else if(!_controlsVisible && now >= 0.95) { ui.showControls(); } }); // Hide controls when pinching to close var pinchControlsHidden; _listen('onPinchClose' , function(now) { if(_controlsVisible && now < 0.9) { ui.hideControls(); pinchControlsHidden = true; } else if(pinchControlsHidden && !_controlsVisible && now > 0.9) { ui.showControls(); } }); _listen('zoomGestureEnded', function() { pinchControlsHidden = false; if(pinchControlsHidden && !_controlsVisible) { ui.showControls(); } }); }; var _uiElements = [ { name: 'caption', option: 'captionEl', onInit: function(el) { _captionContainer = el; } }, { name: 'share-modal', option: 'shareEl', onInit: function(el) { _shareModal = el; }, onTap: function() { _toggleShareModal(); } }, { name: 'button--share', option: 'shareEl', onInit: function(el) { _shareButton = el; }, onTap: function() { _toggleShareModal(); } }, { name: 'button--zoom', option: 'zoomEl', onTap: pswp.toggleDesktopZoom }, { name: 'counter', option: 'counterEl', onInit: function(el) { _indexIndicator = el; } }, { name: 'button--close', option: 'closeEl', onTap: pswp.close }, { name: 'button--arrow--left', option: 'arrowEl', onTap: pswp.prev }, { name: 'button--arrow--right', option: 'arrowEl', onTap: pswp.next }, { name: 'button--fs', option: 'fullscreenEl', onTap: function() { if(_fullscrenAPI.isFullscreen()) { _fullscrenAPI.exit(); } else { _fullscrenAPI.enter(); } } }, { name: 'preloader', option: 'preloaderEl', onInit: function(el) { _loadingIndicator = el; } } ]; var _setupUIElements = function() { var item, classAttr, uiElement; var loopThroughChildElements = function(sChildren) { if(!sChildren) { return; } var l = sChildren.length; for(var i = 0; i < l; i++) { item = sChildren[i]; classAttr = item.className; for(var a = 0; a < _uiElements.length; a++) { uiElement = _uiElements[a]; if(classAttr.indexOf('pswp__' + uiElement.name) > -1 ) { if( _options[uiElement.option] ) { // if element is not disabled from options framework.removeClass(item, 'pswp__element--disabled'); if(uiElement.onInit) { uiElement.onInit(item); } //item.style.display = 'block'; } else { framework.addClass(item, 'pswp__element--disabled'); //item.style.display = 'none'; } } } } }; loopThroughChildElements(_controls.children); var topBar = framework.getChildByClass(_controls, 'pswp__top-bar'); if(topBar) { loopThroughChildElements( topBar.children ); } }; ui.init = function() { // extend options framework.extend(pswp.options, _defaultUIOptions, true); // create local link for fast access _options = pswp.options; // find pswp__ui element _controls = framework.getChildByClass(pswp.scrollWrap, 'pswp__ui'); // create local link _listen = pswp.listen; _setupHidingControlsDuringGestures(); // update controls when slides change _listen('beforeChange', ui.update); // toggle zoom on double-tap _listen('doubleTap', function(point) { var initialZoomLevel = pswp.currItem.initialZoomLevel; if(pswp.getZoomLevel() !== initialZoomLevel) { pswp.zoomTo(initialZoomLevel, point, 333); } else { pswp.zoomTo(_options.getDoubleTapZoom(false, pswp.currItem), point, 333); } }); // Allow text selection in caption _listen('preventDragEvent', function(e, isDown, preventObj) { var t = e.target || e.srcElement; if( t && t.getAttribute('class') && e.type.indexOf('mouse') > -1 && ( t.getAttribute('class').indexOf('__caption') > 0 || (/(SMALL|STRONG|EM)/i).test(t.tagName) ) ) { preventObj.prevent = false; } }); // bind events for UI _listen('bindEvents', function() { framework.bind(_controls, 'pswpTap click', _onControlsTap); framework.bind(pswp.scrollWrap, 'pswpTap', ui.onGlobalTap); if(!pswp.likelyTouchDevice) { framework.bind(pswp.scrollWrap, 'mouseover', ui.onMouseOver); } }); // unbind events for UI _listen('unbindEvents', function() { if(!_shareModalHidden) { _toggleShareModal(); } if(_idleInterval) { clearInterval(_idleInterval); } framework.unbind(document, 'mouseout', _onMouseLeaveWindow); framework.unbind(document, 'mousemove', _onIdleMouseMove); framework.unbind(_controls, 'pswpTap click', _onControlsTap); framework.unbind(pswp.scrollWrap, 'pswpTap', ui.onGlobalTap); framework.unbind(pswp.scrollWrap, 'mouseover', ui.onMouseOver); if(_fullscrenAPI) { framework.unbind(document, _fullscrenAPI.eventK, ui.updateFullscreen); if(_fullscrenAPI.isFullscreen()) { _options.hideAnimationDuration = 0; _fullscrenAPI.exit(); } _fullscrenAPI = null; } }); // clean up things when gallery is destroyed _listen('destroy', function() { if(_options.captionEl) { if(_fakeCaptionContainer) { _controls.removeChild(_fakeCaptionContainer); } framework.removeClass(_captionContainer, 'pswp__caption--empty'); } if(_shareModal) { _shareModal.children[0].onclick = null; } framework.removeClass(_controls, 'pswp__ui--over-close'); framework.addClass( _controls, 'pswp__ui--hidden'); ui.setIdle(false); }); if(!_options.showAnimationDuration) { framework.removeClass( _controls, 'pswp__ui--hidden'); } _listen('initialZoomIn', function() { if(_options.showAnimationDuration) { framework.removeClass( _controls, 'pswp__ui--hidden'); } }); _listen('initialZoomOut', function() { framework.addClass( _controls, 'pswp__ui--hidden'); }); _listen('parseVerticalMargin', _applyNavBarGaps); _setupUIElements(); if(_options.shareEl && _shareButton && _shareModal) { _shareModalHidden = true; } _countNumItems(); _setupIdle(); _setupFullscreenAPI(); _setupLoadingIndicator(); }; ui.setIdle = function(isIdle) { _isIdle = isIdle; _togglePswpClass(_controls, 'ui--idle', isIdle); }; ui.update = function() { // Don't update UI if it's hidden if(_controlsVisible && pswp.currItem) { ui.updateIndexIndicator(); if(_options.captionEl) { _options.addCaptionHTMLFn(pswp.currItem, _captionContainer); _togglePswpClass(_captionContainer, 'caption--empty', !pswp.currItem.title); } _overlayUIUpdated = true; } else { _overlayUIUpdated = false; } if(!_shareModalHidden) { _toggleShareModal(); } _countNumItems(); }; ui.updateFullscreen = function(e) { if(e) { // some browsers change window scroll position during the fullscreen // so PhotoSwipe updates it just in case setTimeout(function() { pswp.setScrollOffset( 0, framework.getScrollY() ); }, 50); } // toogle pswp--fs class on root element framework[ (_fullscrenAPI.isFullscreen() ? 'add' : 'remove') + 'Class' ](pswp.template, 'pswp--fs'); }; ui.updateIndexIndicator = function() { if(_options.counterEl) { _indexIndicator.innerHTML = (pswp.getCurrentIndex()+1) + _options.indexIndicatorSep + _options.getNumItemsFn(); } }; ui.onGlobalTap = function(e) { e = e || window.event; var target = e.target || e.srcElement; if(_blockControlsTap) { return; } if(e.detail && e.detail.pointerType === 'mouse') { // close gallery if clicked outside of the image if(_hasCloseClass(target)) { pswp.close(); return; } if(framework.hasClass(target, 'pswp__img')) { if(pswp.getZoomLevel() === 1 && pswp.getZoomLevel() <= pswp.currItem.fitRatio) { if(_options.clickToCloseNonZoomable) { pswp.close(); } } else { pswp.toggleDesktopZoom(e.detail.releasePoint); } } } else { // tap anywhere (except buttons) to toggle visibility of controls if(_options.tapToToggleControls) { if(_controlsVisible) { ui.hideControls(); } else { ui.showControls(); } } // tap to close gallery if(_options.tapToClose && (framework.hasClass(target, 'pswp__img') || _hasCloseClass(target)) ) { pswp.close(); return; } } }; ui.onMouseOver = function(e) { e = e || window.event; var target = e.target || e.srcElement; // add class when mouse is over an element that should close the gallery _togglePswpClass(_controls, 'ui--over-close', _hasCloseClass(target)); }; ui.hideControls = function() { framework.addClass(_controls,'pswp__ui--hidden'); _controlsVisible = false; }; ui.showControls = function() { _controlsVisible = true; if(!_overlayUIUpdated) { ui.update(); } framework.removeClass(_controls,'pswp__ui--hidden'); }; ui.supportsFullscreen = function() { var d = document; return !!(d.exitFullscreen || d.mozCancelFullScreen || d.webkitExitFullscreen || d.msExitFullscreen); }; ui.getFullscreenAPI = function() { var dE = document.documentElement, api, tF = 'fullscreenchange'; if (dE.requestFullscreen) { api = { enterK: 'requestFullscreen', exitK: 'exitFullscreen', elementK: 'fullscreenElement', eventK: tF }; } else if(dE.mozRequestFullScreen ) { api = { enterK: 'mozRequestFullScreen', exitK: 'mozCancelFullScreen', elementK: 'mozFullScreenElement', eventK: 'moz' + tF }; } else if(dE.webkitRequestFullscreen) { api = { enterK: 'webkitRequestFullscreen', exitK: 'webkitExitFullscreen', elementK: 'webkitFullscreenElement', eventK: 'webkit' + tF }; } else if(dE.msRequestFullscreen) { api = { enterK: 'msRequestFullscreen', exitK: 'msExitFullscreen', elementK: 'msFullscreenElement', eventK: 'MSFullscreenChange' }; } if(api) { api.enter = function() { // disable close-on-scroll in fullscreen _initalCloseOnScrollValue = _options.closeOnScroll; _options.closeOnScroll = false; if(this.enterK === 'webkitRequestFullscreen') { pswp.template[this.enterK]( Element.ALLOW_KEYBOARD_INPUT ); } else { return pswp.template[this.enterK](); } }; api.exit = function() { _options.closeOnScroll = _initalCloseOnScrollValue; return document[this.exitK](); }; api.isFullscreen = function() { return document[this.elementK]; }; } return api; }; }; return PhotoSwipeUI_Default; });
stuti1995/stuti1995.github.io
js/photoswipe-ui-default.js
JavaScript
mit
21,634
/** * Clase que permite trabajar con la plantilla del profesor. * * @param {String} id ID de la etiqueta HTML asociada. * @param {Boolean revisor ¿Sólo se buscarán revisores? * @returns {Profesor} */ function Profesor(id, revisor) { /** * Establece la etiqueta HTML asociada a esta plantilla. */ this.id = id; /** * Establece si la plantilla de búsqueda sólo buscará revisores en * el servidor o no. */ this.revisor = false; if (typeof revisor !== 'undefined') { this.revisor = revisor; } /** * Devuelve la etiqueta HTML asociada. * * @returns {jQuery} */ this.objeto = function () { return $('input#' + this.id); }; /** * Inicializa el INPUT como un objeto Select2. */ this.inicializar = function () { revisor = this.revisor; this.objeto().select2( { placeholder: 'Elija un profesor', minimumInputLength: 1, minimumResultsForSearch: 1, formatSearching: 'Buscando...', formatAjaxError: 'Ha habido un error en la petición', dropdownCssClass: 'bigdrop', dropdownAutoWidth: true, ajax: { url: '/index/select2Profesor', dataType: 'json', type: 'POST', async: false, data: function (cadena) { var input = new Formulario().objeto().children("input[type = 'hidden']"); var datos = establecerDatosSelect2(input.prop('name'), input.prop('value'), cadena, 2); if (revisor) { datos['NkWQ0yGKJFJ6U4WS7yRS'] = true; } console.log(this.revisor); console.log(datos); return datos; }, results: function (datos) { return {results: obtenerDatosSelect2(datos)}; } }, formatResult: function (objeto) { return objeto['nombreCompleto']; }, formatSelection: function (objeto) { return objeto['nombreCompleto']; }, initSelection: function (elemento, callback) { var id = $(elemento).val(); if (id !== '') { var input = new Formulario().objeto().children("input[type = 'hidden']"); var datos = establecerDatosSelect2(input.prop('name'), input.prop('value'), id, 1); if (revisor) { datos['NkWQ0yGKJFJ6U4WS7yRS'] = true; } $.ajax('/index/select2Profesor', { dataType: 'json', type: 'POST', async: false, data: datos }).done(function (datos) { callback(obtenerDatosSelect2(datos)[0]); }); } } }); }; /** * Desplaza las etiquetas HTML Select2 que se usan para este profesor. */ this.moverSelect2 = function () { this.objeto().parent().append($('div#s2id_' + this.id)); }; }
RompePC/gconves
aplicacion/publico/js/campoFormulario/profesor.js
JavaScript
mit
4,241
import React from 'react' function LoadingIndicator () { return ( <div> Loading <div className='sk-fading-circle'> <div className='sk-circle1 sk-circle'></div> <div className='sk-circle2 sk-circle'></div> <div className='sk-circle3 sk-circle'></div> <div className='sk-circle4 sk-circle'></div> <div className='sk-circle5 sk-circle'></div> <div className='sk-circle6 sk-circle'></div> <div className='sk-circle7 sk-circle'></div> <div className='sk-circle8 sk-circle'></div> <div className='sk-circle9 sk-circle'></div> <div className='sk-circle10 sk-circle'></div> <div className='sk-circle11 sk-circle'></div> <div className='sk-circle12 sk-circle'></div> </div> </div> ) } export default LoadingIndicator
seannives/solid-react-login
app/components/common/LoadingIndicator.js
JavaScript
mit
836
const c = require('ansi-colors') const glob = require('glob') const path = require('path') const terserVersion = require('terser/package.json').version const TerserWebpackPlugin = require('terser-webpack-plugin') const webpack = require('webpack') const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin const { argv } = require('yargs') const config = require('../config') // Ensures that production settings for Babel are used process.env.NODE_ENV = 'build-es' /* eslint-disable no-await-in-loop */ /* eslint-disable no-console */ /* eslint-disable no-restricted-syntax */ // // Webpack config // const makeWebpackConfig = (entry) => ({ devtool: false, mode: 'production', target: 'web', entry, output: { filename: path.basename(entry), path: config.paths.base('bundle-size', 'dist'), ...(argv.debug && { pathinfo: true, }), }, module: { rules: [ { test: /\.(js|ts)$/, loader: 'babel-loader', exclude: /node_modules/, options: { cacheDirectory: true, }, }, ], }, externals: { react: 'react', 'react-dom': 'reactDOM', }, ...(argv.debug && { optimization: { minimizer: [ new TerserWebpackPlugin({ cache: true, parallel: true, sourceMap: false, terserOptions: { mangle: false, output: { beautify: true, comments: true, preserve_annotations: true, }, }, }), ], }, }), performance: { hints: false, }, plugins: [ argv.debug && new BundleAnalyzerPlugin({ analyzerMode: 'static', logLevel: 'warn', openAnalyzer: false, reportFilename: `${path.basename(entry, '.js')}.html`, }), ].filter(Boolean), resolve: { alias: { 'semantic-ui-react': config.paths.dist('es', 'index.js'), }, }, }) function webpackAsync(webpackConfig) { return new Promise((resolve, reject) => { const compiler = webpack(webpackConfig) compiler.run((err, stats) => { if (err) { reject(err) } const info = stats.toJson() if (stats.hasErrors()) { reject(new Error(info.errors.toString())) } if (stats.hasWarnings()) { reject(new Error(info.warnings.toString())) } resolve(info) }) }) } // // // ;(async () => { const fixtures = glob.sync('fixtures/*.size.js', { cwd: __dirname, }) console.log(c.cyan(`ℹ Using Webpack ${webpack.version} & Terser ${terserVersion}`)) console.log(c.cyan('ℹ Running following fixtures:')) console.log(c.cyan(fixtures.map((fixture) => ` - ${fixture}`).join('\n'))) for (const fixture of fixtures) { const fixturePath = config.paths.base('bundle-size', fixture) await webpackAsync(makeWebpackConfig(fixturePath)) console.log(c.green(`✔ Completed: ${fixture}`)) } })()
Semantic-Org/Semantic-UI-React
bundle-size/bundle.js
JavaScript
mit
2,998
LearnosityAmd.define([ 'jquery-v1.10.2', 'underscore-v1.5.2', 'vendor/mathcore' ], function ($, _, mathcore) { 'use strict'; var padding = 10, defaults = { "is_math": true, "response_id": "custom-mathcore-response-<?php echo $session_id; ?>", "type": "custom", "js": "//docs.vg.learnosity.com/demos/products/questionsapi/questiontypes/assets/mathcore/mathcore.js", "css": "//docs.vg.learnosity.com/demos/products/questionsapi/questiontypes/assets/mathcore/mathcore.css", "stimulus": "Simplify following expression: <b>\\(2x^2 + 3x - 5 + 5x - 4x^2 + 20\\)</b>", "score": 1, "specs": [{ "method": "isSimplified" }, { "method": "equivSymbolic", "value": "2x^2 + 3x - 5 + 5x - 4x^2 + 20" }] }, template = _.template('<div class="response_wrapper"><input type="text" /></div>'); var Question = function(options) { var $response, $input, self = this, triggerChanged = function () { self.clear(); setTimeout(function () { options.events.trigger('changed', $input.val()); }, 500); }; self.clear = function () { $response.removeClass('valid'); $response.removeClass('notValid'); }; self.validate = function () { var scorer = new Scorer(options.question, $input.val()), isValid = scorer.isValid(); self.clear(); if (isValid) { $response.addClass('valid'); } else { $response.addClass('notValid'); } }; options.events.on('validate', function () { self.validate(); }); if (options.state === 'review') { self.validate(); } if (options.response) { $input.val(options.response); } options.$el.html(template()); options.events.trigger('ready'); $response = options.$el.find('.response_wrapper'); $input = $response.find('input'); $input.on('change keydown', triggerChanged); triggerChanged(); }; var Scorer = function (question, response) { this.question = question; this.response = response; }; Scorer.prototype.isValid = function() { var i, temp, isValid = true; for(i = 0; i < this.question.specs.length; i ++) { temp = mathcore.validate(this.question.specs[i], this.response); isValid = isValid && temp.result; } return isValid; }; Scorer.prototype.score = function() { return this.isValid() ? this.maxScore() : 0; }; Scorer.prototype.maxScore = function() { return this.question.score || 1; }; return { Question: Question, Scorer: Scorer }; });
danielyoun82/bootcamp2017
www/casestudies/customquestions/custom_mathcore.js
JavaScript
mit
3,034
/* eslint-disable no-cond-assign, no-param-reassign */ import voidElements from "void-elements"; function isVoidElement(tag) { const tagName = tag.match(/<([^\s>]+)/); return Boolean(tagName) && voidElements[tagName[1].toLowerCase()] === true; } export default { strip(str) { return str.replace(/(<([^>]+)>)/gi, ""); }, map(str) { const regexp = /<[^>]+>/gi; const tags = []; const openers = []; let result; let tag; while ((result = regexp.exec(str))) { tag = { tagName: result[0], position: result.index }; if (tag.tagName.charAt(1) === "/") { tag.opener = openers.pop(); } else if ( tag.tagName.charAt(tag.tagName.length - 2) !== "/" && !isVoidElement(tag.tagName) ) { openers.push(tag); } tags.push(tag); } return tags; }, inject(str, map) { for (let i = 0, tag; i < map.length; i += 1) { tag = map[i]; if (str.length > 0 && tag.position <= str.length) { str = str.substr(0, tag.position) + tag.tagName + str.substr(tag.position); } else if (tag.opener && tag.opener.position < str.length) { str += tag.tagName; } } return str; } };
Zhouzi/TheaterJS
src/html.js
JavaScript
mit
1,251
var superagent = require('superagent') var env = process.env /** * put_doc * initialize with the couchdb to save to * * expects that the url, port, username, password are in environment * variables. If not, add these to the options object. * * var cuser = env.COUCHDB_USER ; * var cpass = env.COUCHDB_PASS ; * var chost = env.COUCHDB_HOST || '127.0.0.1'; * var cport = env.COUCHDB_PORT || 5984; * * Options: * * {"cuser":"somerthineg", * "cpass":"password", * "chost":"couchdb host", * "cport":"couchdb port", // must be a number * "cdb" :"the%2fcouchdb%2fto%2fuse" // be sure to properly escape your db names * } * * If you don't need user/pass to create docs, feel free to skip * these. I only try to use credentials if these are truthy * * returns a function that will save new entries * * to create a new doc in couchdb, call with the * object that is the doc, plus a callback * * The object should be a couchdb doc, but th _id field is optional. * * but highly recommended * * The first argument to the callback is whether there is an error in * the requqest, the second is the json object returned from couchdb, * whcih should have the save state of the document (ok or rejected) * */ function put_doc(opts){ if(opts.cdb === undefined) throw new Error('must define the {"cdb":"dbname"} option') var cuser = env.COUCHDB_USER var cpass = env.COUCHDB_PASS var chost = env.COUCHDB_HOST || '127.0.0.1' var cport = env.COUCHDB_PORT || 5984 // override env. vars if(opts.cuser !== undefined) cuser = opts.cuser if(opts.cpass !== undefined) cpass = opts.cpass if(opts.chost !== undefined) chost = opts.chost if(opts.cport !== undefined) cport = +opts.cport var couch = 'http://'+chost+':'+cport if(/http/.test(chost)) couch = chost+':'+cport var overwrite = false function put(doc,next){ var uri = couch+'/'+opts.cdb var req if(overwrite && doc._id !== undefined){ uri += '/'+doc._id superagent.head(uri) .end(function(err,res){ if(res.header.etag){ doc._rev=JSON.parse(res.headers.etag) } var req = superagent.put(uri) .type('json') .set('accept','application/json') if(cuser && cpass){ req.auth(cuser,cpass) } req.send(doc) req.end(function(e,r){ if(e) return next(e) return next(null,r.body) }) }) }else{ if(doc._id !== undefined){ uri += '/'+doc._id req = superagent.put(uri) }else{ req = superagent.post(uri) } req.type('json') .set('accept','application/json') if(cuser && cpass){ req.auth(cuser,cpass) } req.send(doc) req.end(function(e,r){ if(e) return next(e) return next(null,r.body) }) } return null } put.overwrite = function(setting){ if(setting === undefined){ return overwrite } overwrite = setting return overwrite } return put } module.exports=put_doc
jmarca/couchdb_put_doc
lib/put_doc.js
JavaScript
mit
3,419
(function() { // Creating application var app = {}; var parseData = function(data) { var result = {}; // TODO: Get better performance here var years = _.groupBy(data, 'year'); for (var key in years) { result[key] = _.groupBy(years[key], 'cartodb_id'); } return result; }; var MapView = function() { this.options = { map: { center: [0, 0], zoom: 2, minZoom: 2, maxZoom: 16 }, tiles: { url: 'http://server.arcgisonline.com/ArcGIS/rest/services/Canvas/World_Light_Gray_Base/MapServer/tile/{z}/{y}/{x}', options: { attribution: 'Tiles &copy; Esri &mdash; Esri, DeLorme, NAVTEQ', maxZoom: 16 } }, featureStyle: { fillColor: '#999', color: '#060', weight: 1, opacity: 1, fillOpacity: 0.7 } }; this.createMap = function() { this.map = L.map(this.el, this.options.map); // Adding tiles // L.tileLayer(this.options.tiles.url, this.options.tiles.options) // .addTo(this.map); }; this.createLayer = function(topojson) { // The problem is here var geojson = omnivore.topojson.parse(topojson); // it takes 500ms var style = this.options.featureStyle; this.layer = L.geoJson(geojson, { style: function() { return style; } }); // it takes 750ms this.map.addLayer(this.layer); // it takes 600ms }; this.setYear = function(year) { var self = this; var data = app.groupedData[year]; var style = _.clone(this.options.featureStyle); if (!this.getColor) { console.error('first set colors'); } else { this.layer.setStyle(function(feature) { var cartodbId = feature.properties.cartodb_id; var country = data[cartodbId]; if (country && country[0].total) { style.fillColor = self.getColor(country[0].total); } else { style.fillColor = self.options.featureStyle.fillColor; } return style; }); } }; this.setColors = function(min, max, buckets) { this.getColor = d3.scale.quantize() .domain([min, max]) .range(colorbrewer.GnBu[buckets]); }; this.init = (function() { this.el = document.getElementById('map'); this.createMap(); }).bind(this)(); return this; }; var SliderView = function() { this.options = { velocity: 100 }; this.setEvents = function() { var self = this; var changeYearEvent = new Event('ChangeYear'); this.input.oninput = function() { self.setText(self.input.value); self.el.dispatchEvent(changeYearEvent); }; this.startBtn.onclick = this.start.bind(this); this.stopBtn.onclick = this.stop.bind(this); }; this.start = function() { this.timer = setInterval((function() { var value = parseInt(this.input.value); var current = value + 1; if (this.max === current) { this.stop(); } this.setValue(current); }).bind(this), this.options.velocity) }; this.stop = function() { if (this.timer) { clearInterval(this.timer); } }; this.show = function() { this.el.className = ''; }; this.hide = function() { this.el.className = 'is-hidden'; }; this.setRange = function(min, max) { this.min = min; this.max = max; this.input.setAttribute('min', min); this.input.setAttribute('max', max); }; this.setValue = function(value) { this.input.value = value; this.input.oninput(); }; this.setText = function(text) { this.label.textContent = text; }; this.init = (function() { this.timer = null; this.el = document.getElementById('slider'); this.input = document.getElementById('sliderRange'); this.label = document.getElementById('sliderLabel'); this.startBtn = document.getElementById('sliderPlay'); this.stopBtn = document.getElementById('sliderStop'); this.setEvents(); }).bind(this)(); return this; }; // Document ready document.addEventListener('DOMContentLoaded', function() { app.loader = document.getElementById('loader'); app.map = new MapView(); app.slider = new SliderView(); // When all data is loaded document.addEventListener('DataLoaded', function() { var data = responses[1]; var years = utils.getMinMax(data, 'year'); var totals = utils.getMinMax(data, 'total'); var minData = totals[0]; var maxData = totals[1]; var minYear = years[0]; var maxYear = years[1]; app.map.createLayer(responses[0]); app.groupedData = parseData(data); app.map.setColors(minData, maxData, 9); app.slider.el.addEventListener('ChangeYear', function() { app.map.setYear(parseInt(app.slider.input.value)); }); app.slider.setRange(minYear, maxYear); app.slider.setValue(minYear); app.slider.show(); app.loader.className = 'loader is-hidden'; }); }); })();
Vizzuality/sandbox
src/world-svg-layers/main.js
JavaScript
mit
5,201
/** * #config * * Copyright (c)2011, by Branko Vukelic * * Configuration methods and settings for Postfinance. All startup configuration * settings are set using the `config.configure()` and `config.option()` * methods. Most options can only be set once, and subsequent attempts to set * them will result in an error. To avoid this, pass the * `allowMultipleSetOption` option to `config.configure()` and set it to * `true`. (The option has a long name to prevent accidental usage.) * * Copyright (c)2014, by Olivier Evalet <evaleto@gmail.com> * Copyright (c)2011, by Branko Vukelic <branko@herdhound.com> * Licensed under GPL license (see LICENSE) */ var config = exports; var util = require('util'); var PostFinanceError = require('./error'); var samurayKeyRe = /^[0-9a-f]{4}$/; var isConfigured = false; config.POSTFINANCE_VERSION = '0.0.1'; /** * ## settings * *Master configuration settings for Postfinance* * * The `settings` object contains all the core configuration options that * affect the way certain things work (or not), and the Postfinance gateway * credentials. You should _not_ access this object directly. The correct way * to access and set the settings is through either ``configure()`` or * ``option()`` methods. * * Settings are expected to contain following keys with their default values: * * + _pspid_: Postfinance gateway Merchant Key (default: `''`) * + _apiPassword_: Postfinance gateway API Password (default: `''`) * + _apiUser_: Processor (gateway) ID; be sure to set this to a sandbox * ID for testing (default: `''`) * + _currency_: Default currency for all transactions (can be overriden by * specifying the appropriate options in transaction objects) * + _allowedCurrencies_: Array containing the currencies that can be used * in transactions. (default: ['USD']) * + _sandbox_: All new payment methods will be sandbox payment methods * (default: false) * + _enabled_: Whether to actually make requests to gateway (default: true) * + _debug_: Whether to log to STDOUT; it is highly recommended that * you disable this in production, to remain PCI comliant, and to * avoid performance issues (default: true) * * Only `currency` option can be set multiple times. All other options can only * be set once using the ``config.configure()`` method. * * The ``apiVersion`` setting is present for conveinence and is should be * treated as a constant (i.e., read-only). */ var settings = {}; settings.pmlist=['creditcart','postfinance card','paypal'] settings.pspid = ''; settings.apiPassword = ''; settings.apiUser = ''; settings.currency = 'CHF'; settings.allowedCurrencies = ['CHF']; settings.shaWithSecret=true; // do not append secret in sha string (this is a postfinance configuration) settings.operation='RES' settings.path = { ecommerce:'/ncol/test/orderstandard_utf8.asp', order:'/ncol/test/orderdirect_utf8.asp', maintenance:'/ncol/test/maintenancedirect.asp', query:'/ncol/test/querydirect_utf8.asp', }; settings.host = 'e-payment.postfinance.ch'; settings.allowMaxAmount=400.00; // block payment above settings.sandbox = false; settings.enabled = true; // Does not make any actual API calls if false settings.debug = false; // Enables *blocking* debug output to STDOUT settings.apiVersion = 1; // Don't change this... unless you need to settings.allowMultipleSetOption = false; config.reset=function(){ if(process.env.NODE_ENV=='test'){ settings.sandbox = false; settings.enabled = true; settings.pspid = ''; settings.apiPassword = ''; settings.apiUser = ''; settings.currency = 'CHF'; settings.allowedCurrencies = ['CHF']; settings.shaWithSecret=true; settings.operation='RES' isConfigured=false; } else throw new Error('Reset is not possible here') } /** * ## config.debug(message) * *Wrapper around `util.debug` to log items in debug mode* * * This method is typically used by Postfinance implementation to output debug * messages. There is no need to call this method outside of Postfinance. * * Note that any debug messages output using this function will block * execution temporarily. It is advised to disable debug setting in production * to prevent this logger from running. * * @param {Object} message Object to be output as a message * @private */ config.debug = debug = function(message) { if (settings.debug) { util.debug(message); } }; /** * ## config.configure(opts) * *Set global Postfinance configuration options* * * This method should be used before using any of the Postfinance's functions. It * sets the options in the `settings` object, and performs basic validation * of the options before doing so. * * Unless you also pass it the `allowMultipleSetOption` option with value set * to `true`, you will only be able to call this method once. This is done to * prevent accidental calls to this method to modify critical options that may * affect the security and/or correct operation of your system. * * This method depends on ``config.option()`` method to set the individual * options. * * If an invalid option is passed, it will throw an error. * * @param {Object} Configuration options */ config.configure = function(opts) { debug('Configuring Postfinance with: \n' + util.inspect(opts)); if (!opts.pspid || (opts.apiUser&&!opts.apiPassword)) { throw new PostFinanceError('system', 'Incomplete Postfinance API credentials', opts); } Object.keys(opts).forEach(function(key) { config.option(key, opts[key]); }); isConfigured = true; if(config.option('shaWithSecret')) debug("append sha with secret") //print settings? //debug("settings "+util.inspect(settings)) }; /** * ## config.option(name, [value]) * *Returns or sets a single configuration option* * * If value is not provided this method returns the value of the named * configuration option key. Otherwise, it sets the value and returns it. * * Setting values can only be set once for most options. An error will be * thrown if you try to set an option more than once. This restriction exist * to prevent accidental and/or malicious manipulation of critical Postfinance * configuration options. * * During testing, you may set the `allowMultipleSetOption` to `true` in order * to enable multiple setting of protected options. Note that once this option * is set to `false` it can no longer be set to true. * * Postfinance API credentials are additionally checked for consistency. If they * do not appear to be valid keys, an error will be thrown. * * @param {String} option Name of the option key * @param {Object} value New value of the option * @returns {Object} Value of the `option` key */ config.option = function(option, value) { if (typeof value !== 'undefined') { debug('Setting Postfinance key `' + option + '` to `' + value.toString() + '`'); // Do not allow an option to be set twice unless it's `currency` if (isConfigured && !settings.allowMultipleSetOption && option !== 'currency') { throw new PostFinanceError( 'system', 'Option ' + option + ' is already locked', option); } switch (option) { case 'pspid': case 'apiPassword': case 'apiUser': case 'currency': case 'shaSecret': case 'host': case 'path': case 'operation': case 'acceptUrl': case 'declineUrl': case 'exceptionUrl': case 'cancelUrl': case 'backUrl': settings[option] = value; break; case 'allowMaxAmount': settings[option] = parseFloat(value) break; case 'sandbox': case 'enabled': case 'debug': case 'shaWithSecret': case 'allowMultipleSetOption': settings[option] = Boolean(value); break; case 'allowedCurrencies': if (!Array.isArray(value)) { throw new PostFinanceError('system', 'Allowed currencies must be an array', null); } if (value.indexOf(settings.currency) < 0) { value.push(settings.currency); } settings.allowedCurrencies = value; break; default: // Do not allow unknown options to be set throw new PostFinanceError('system', 'Unrecognized configuration option', option); } } return settings[option]; };
evaletolab/node-postfinance
lib/config.js
JavaScript
mit
8,332
var EffectsList = [ ['复古效果', 'sketch', 'dorsy', '2013-10-12'], ['黄色调效果', 'yellowStyle', 'dorsy', '2013-10-12'], ['缩小', 'mini', 'dorsy', '2013-10-12'] ]; var EffectTmp = ' <li data-ename="{name}">\ <img src="style/image/effect/{name}.png" />\ <h3>{cnname}</h3>\ <div class="itemInfo">\ <span class="author lightFont">{author}</span>\ <span class="date lightFont">{date}</span>\ </div>\ </li>\ ';
hangfang/ihelper.since.love
static/public/js/photo/effectsList.js
JavaScript
mit
475
//= require ../bower_components/jquery/dist/jquery.js 'use strict'; var APP = {}; $(function() { console.log('Hello from your jQuery application!'); });
alvik48/fmp
templates/js/jquery/app.js
JavaScript
mit
159
const userDao = require('../dao/user'), tokenDao = require('../dao/token'), appDao = require('../dao/app'), tokenRedisDao = require('../dao/redis/token'), userRedisDao = require('../dao/redis/user'), passport = require('../service/passport'), STATUS = require('../common/const').STATUS, ERROR = require('../common/error.map'); var create = async function(ctx, next) { var body = ctx.request.body; var app = ctx.get('app'); var user = await userDao.findUserByMobile(body.mobile); if (user && user.apps && user.apps.length !== 0 && user.apps.indexOf(app) !== -1) { throw ERROR.USER.EXIST; } else if (user) { await userDao.addApp(user._id, app); } else { user = await userDao.createUserByMobile(body.mobile, app); } var results = await Promise.all([ passport.encrypt(body.password), userRedisDao.incTotal(app) ]); var password = results[0]; var shortId = results[1]; await appDao.create(app, user._id, password, shortId); ctx.user = user.toJSON() ctx.user.user_short_id = shortId; ctx.logger.info(`用户 ${body.mobile} 注册app ${app}`) await next() }; var getInfo = async function(ctx, next) { var user = await userDao.getInfo(ctx.oauth.user_id, ctx.oauth.app); ctx.result = { user_id: user._id, mobile: user.mobile, chance: user.chance }; }; var updatePassword = async function(ctx, next) { var body = ctx.request.body; var appInfo = await appDao.find(ctx.oauth.app, ctx.oauth.user_id); if (!appInfo || !appInfo.password) { throw ERROR.USER.NOT_EXIST; } if (appInfo.status !== STATUS.USER.ACTIVE) { throw ERROR.USER.NOT_ACTIVE; } var result = await passport.validate(body.old_password, appInfo.password); if (!result) { throw ERROR.OAUTH.PASSWORD_ERROR; } var newPasswordHash = await passport.encrypt(body.new_password); await appDao.updatePassword(appInfo._id, newPasswordHash); ctx.logger.info(`用户 ${ctx.oauth.user_id} 修改密码`); await next(); }; var resetPassword = async function(ctx, next) { var body = ctx.request.body; var app = ctx.get('app'); var userInfo = await userDao.findUserByMobile(body.mobile); if (!userInfo) { throw ERROR.USER.NOT_EXIST; } var appInfo = await appDao.find(app, userInfo._id); if (!appInfo || !appInfo.password) { throw ERROR.USER.NOT_EXIST; } if (appInfo.status !== STATUS.USER.ACTIVE) { throw ERROR.USER.NOT_ACTIVE; } var passwordHash = await passport.encrypt(body.password); await appDao.updatePassword(appInfo._id, passwordHash); ctx.logger.info(`用户 ${body.mobile} 重置密码 app ${app}`); await next(); //强制用户登出 var expiredToken = await tokenDao.delToken(app, userInfo._id); tokenRedisDao.delToken(expiredToken.access_token); tokenRedisDao.delToken(expiredToken.refresh_token); }; module.exports = { create, getInfo, updatePassword, resetPassword }
mane115/ucenter
controller/user.js
JavaScript
mit
3,072
// ga.addEventBehavior(ga.gameEvents.MouseDown, undefined, undefined, undefined, function (e) { // var spriteClick = ga.CheckEventPosition(e.offsetX, e.offsetY); // if (spriteClick != undefined) { // if (this.lastClick != undefined) { // this.lastClick.unHighLight(); // } // this.lastClick = spriteClick; // spriteClick.highLight(0, 0, 0, 0, 255, 0, 0, 0); // var parentObj = this; // setTimeout(function () { // var seeker = new Seeker("walking", "attacking", 100); // ga.addEventBehavior(ga.gameEvents.MouseDown, "", spriteClick, "walking", function (e, sprite, engine) { // if (sprite == parentObj.lastClick) { // seeker.execute(e, sprite, engine); // } // }, -1); // seeker.setFoundCallback(function (sprite) { // sprite.unHighLight(); // ga.removeEventBehavior(ga.gameEvents.MouseDown, sprite); // }); // }, 100); // } // }, 1);
j03m/trafficcone
public/tccore/behaviors/ClickAndSeek.js
JavaScript
mit
1,338
/** * modal api */ export default { methods: { /** * 点击 Full 的导航按钮 */ clickFullNav() { if (this.commit) { this.no() } else { this.hide() } }, /** * 显示pop * * @param {Number} - 当前页码 * @return {Object} */ show() { this.modalDisplay = true return this.$nextTick(() => { this.$refs.fadeTransition.enter() this.$refs.pop.show() return this }) }, /** * 隐藏pop * * @return {Object} */ hide() { this.$refs.fadeTransition.leave() this.$refs.pop.hide({ cb: () => { this.modalDisplay = false this.isMousedown = false } }) return this }, /** * 鼠标mouseDown 弹窗头部触发的事件 * * @return {Object} */ mouseDown(event) { this.isMousedown = true this.pointStart = { x: event.clientX, y: event.clientY } return this }, /** * 鼠标mouseMove 弹窗头部触发的事件 * * @return {Object, Boolean} */ mouseMove(event) { event.preventDefault() if (!this.isMousedown) { return false } this.$refs.pop.computePosition() this.pointStart = { x: event.clientX, y: event.clientY } return this }, /** * 鼠标mouseUp 弹窗头部触发的事件 * * @return {Object, Boolean} */ mouseUp(event) { event.preventDefault() if (!this.isMousedown) { return false } this.isMousedown = false return this }, /** * 弹窗点击确定触发的函数 * * @return {Object} */ ok() { this.$emit('ok') if (this.okCbFun) { if (typeof this.okCbFun === 'function') { this.okCbFun(this) } return this } return this.hide() }, /** * 弹窗点击取消触发的函数 * * @return {Object} */ no() { this.$emit('no') if (this.noCbFun) { if (typeof this.noCbFun === 'function') { this.noCbFun(this) } return this } this.hide() }, /** * 获取 / 设置 弹窗的title名 * * @return {Object, Boolean} */ title(text) { if (text === '' || text) { this.stateHeader = text } return this }, /** * alert, confirm 弹窗的文字信息 * * @param {String} - 需要设置的值 * @return {Object, String} */ info(text) { if (text === '' || text) { this.stateMessage = text } return this }, /** * 设置各个组件的配置数据 * * @param {Object} opt - 选项 * {Function} okCb - 点击的回调函数 * {Function} noCb - 取消的回调函数 * {Function} showCb - 显示之后的回调函数 * {Function} hideCb - 隐藏之后的回调函数 * {String} title - 模态框标题 * {Function} message - 需要展示的信息 */ set({ okCb, noCb, showCb, hideCb, title = '', message = '', ui = this.ui, theme = this.theme } = {}) { this.okCbFun = okCb this.noCbFun = noCb this.showCb = showCb this.hideCb = hideCb this.stateHeader = title this.stateMessage = message this.stateUI = ui this.stateTheme = theme return this } } }
zen0822/vue2do
package/component/module/Modal/Modal.api.js
JavaScript
mit
3,719
(function() { 'use strict'; /** * @ngdoc function * @name app.service:badgesService * @description * # badgesService * Service of the app */ angular .module('badges') .factory('BadgesService', Badges); // Inject your dependencies as .$inject = ['$http', 'someSevide']; // function Name ($http, someSevide) {...} Badges.$inject = ['$http', '$rootScope']; function Badges ($http, $rootScope) { return { getBadges:getBadges }; function getBadges(vm) { var badges = []; var url = "https://raw.githubusercontent.com/ltouroumov/amt-g4mify/master/client/app/assets/images/"; var req = { method: 'GET', url: 'http://localhost:8080/api/users/' + $rootScope.username +'/badges', headers: { 'Content-Type': 'application/json', 'Identity': '1:secret' } }; $http(req).then(function(res){ console.log("Badges: OK"); for(var i = 0; i < res.data.length; i++){ var badge = { level: res.data[i].level, name: res.data[i].type.name, image: url + res.data[i].type.image }; console.log(badges); badges.push(badge); } vm.badges = badges; }, function(err){ console.log("Badges: ERROR"); vm.msg = "- An error occurred posting the event to the gamification platform"; vm.success = false; }); } } })();
ltouroumov/amt-g4mify
client/app/modules/badges/badgesService.js
JavaScript
mit
1,377
import React from 'react'; import renderer from 'react-test-renderer'; import { data, renderers, expectors } from '../../test-utils'; import ImmutableVirtualizedList from '../ImmutableVirtualizedList'; describe('ImmutableVirtualizedList', () => { it('renders with empty data', () => { expectors.expectVirtualizedToMatchSnapshotWithData(data.EMPTY_DATA); }); it('renders basic List', () => { expectors.expectVirtualizedToMatchSnapshotWithData(data.LIST_DATA); }); it('renders nested List', () => { expectors.expectVirtualizedToMatchSnapshotWithData(data.LIST_DATA_NESTED); }); it('renders basic Range', () => { expectors.expectVirtualizedToMatchSnapshotWithData(data.RANGE_DATA); }); }); describe('ImmutableVirtualizedList with renderEmpty', () => { it('renders normally when there are some items', () => { const tree = renderer.create( <ImmutableVirtualizedList immutableData={data.LIST_DATA} renderItem={renderers.renderRow} renderEmpty={() => renderers.renderRow('No items')} />, ); expect(tree.toJSON()).toMatchSnapshot(); }); it('renders empty with a function', () => { const tree = renderer.create( <ImmutableVirtualizedList immutableData={data.EMPTY_DATA} renderItem={renderers.renderRow} renderEmpty={() => renderers.renderRow('No items')} />, ); expect(tree.toJSON()).toMatchSnapshot(); }); it('renders empty with a string', () => { const color = 'red'; const tree = renderer.create( <ImmutableVirtualizedList immutableData={data.EMPTY_DATA} renderItem={renderers.renderRow} renderEmpty="No items" contentContainerStyle={{ color }} />, ); expect(tree.toJSON()).toMatchSnapshot(); }); it('doesn\'t render empty with null', () => { const tree = renderer.create( <ImmutableVirtualizedList immutableData={data.EMPTY_DATA} renderItem={renderers.renderRow} renderEmpty={null} renderEmptyInList={null} />, ); expect(tree.toJSON()).toMatchSnapshot(); }); }); describe('ImmutableVirtualizedList with renderEmptyInList', () => { it('renders normally when there are some items', () => { const tree = renderer.create( <ImmutableVirtualizedList immutableData={data.LIST_DATA} renderItem={renderers.renderRow} renderEmptyInList={() => renderers.renderRow('No items')} />, ); expect(tree.toJSON()).toMatchSnapshot(); }); it('renders empty with a function', () => { const tree = renderer.create( <ImmutableVirtualizedList immutableData={data.EMPTY_DATA} renderItem={renderers.renderRow} renderEmptyInList={() => renderers.renderRow('No items')} />, ); expect(tree.toJSON()).toMatchSnapshot(); }); it('renders empty with a string', () => { const color = 'red'; const tree = renderer.create( <ImmutableVirtualizedList immutableData={data.EMPTY_DATA} renderItem={renderers.renderRow} renderEmptyInList="No items" contentContainerStyle={{ color }} />, ); expect(tree.toJSON()).toMatchSnapshot(); }); it('doesn\'t render empty with null', () => { const tree = renderer.create( <ImmutableVirtualizedList immutableData={data.EMPTY_DATA} renderItem={renderers.renderRow} renderEmpty={null} renderEmptyInList={null} />, ); expect(tree.toJSON()).toMatchSnapshot(); }); });
cooperka/react-native-immutable-list-view
src/ImmutableVirtualizedList/__tests__/ImmutableVirtualizedList.test.js
JavaScript
mit
3,559
describe("Quiz API Tests", function() { var api; var mock; beforeAll(function(done) { api = Playbasis.quizApi; mock = window.mock; window.acquireBuiltPlaybasis(); done(); }); describe("List Active Quizzes test", function() { beforeAll(function(done) { done(); }); it("should return success", function(done) { api.listOfActiveQuizzes() .then((result) => { done(); }, (e) => { console.log(e.message);}) }); }); describe("Detail of Quiz test", function() { var quizId = "57f5d72ab350cf67308b81c6"; //pre-existing quiz 1 beforeAll(function(done) { done(); }); it("should return success", function(done) { api.detailOfQuiz(quizId) .then((result) => { expect(result.response.result).not.toBe(null); expect(result.response.result.quiz_id).toEqual(quizId); done(); }, (e) => { console.log(e.message);}); }); }); describe("Random Get a Quiz for Player test", function() { beforeAll(function(done) { done(); }); it("should return success", function(done) { api.randomQuizForPlayer(mock.env.playerId) .then((result) => { expect(result.response.result).not.toBe(null); expect(result.response.result.quiz_id).not.toBe(null); done(); }, (e) => { console.log(e.message);}); }); }); describe("List Quiz Done by Player test", function() { beforeAll(function(done) { done(); }); it("should return success", function(done) { api.listQuizDone(mock.env.playerId, 5) .then((result) => { done(); }, (e) => { console.log(e.message);}); }); }); describe("List Pending Quiz by Player test", function() { beforeAll(function(done) { done(); }); it("should return success", function(done) { api.listPendingQuiz(mock.env.playerId, 5) .then((result) => { done(); }, (e) => { console.log(e.message);}); }); }); describe("Get Question from Quiz for Player test", function() { var quizId = "57f5d72ab350cf67308b81c6"; //pre-existing quiz 1 beforeAll(function(done) { done(); }); it("should return success", function(done) { api.getQuestionFromQuiz(quizId, mock.env.playerId) .then((result) => { done(); }, (e) => { console.log(e.message);}); }); }); describe("Get Question (with reset timestamp) from Quiz for Player test", function() { var quizId = "57f5d72ab350cf67308b81c6"; //pre-existing quiz 1 beforeAll(function(done) { done(); }); it("should return success", function(done) { api.getQuestionFromQuiz_resetTimeStamp(quizId, mock.env.playerId) .then((result) => { done(); }, (e) => { console.log(e.message);}); }); }); describe("Answer a Question for Quiz test", function() { var quizId = "57f5d72ab350cf67308b81c6"; // pre-existing quiz 1 var optionId = "1521751f31748deab6333a87"; // pre-existing option 1 for quiz 1 var questionId = "138003ef42931448ab4b02e2"; // pre-existing question for quiz 1 beforeAll(function(done) { done(); }); // ensure to reset progress of quiz after answering question afterAll(function(done) { api.resetQuiz(mock.env.playerId, quizId) .then((result) => { done(); }, (e) => { console.log(e.message);}); }); it("should return success", function(done) { api.answerQuestion(quizId, mock.env.playerId, questionId, optionId) .then((result) => { expect(result.response.result).not.toBe(null); expect(result.response.result.score).toEqual(10); // pre-set done(); }, (e) => { console.log(e.message);}); }); }); describe("Rank Player by Score test", function() { var quizId = "57f5d72ab350cf67308b81c6"; // pre-existing quiz 1 beforeAll(function(done) { done(); }); it("should return success", function(done) { api.rankPlayersByScore(quizId, 10) .then((result) => { done(); }, (e) => { console.log(e.message);}); }); }); describe("Query for Quiz's Statistics test", function() { var quizId = "57f5d72ab350cf67308b81c6"; // pre-existing quiz 1 beforeAll(function(done) { done(); }); it("should return success", function(done) { api.quizStatistics(quizId) .then((result) => { done(); }, (e) => { console.log(e.message);}); }); }); describe("Reset Quiz test", function() { var quizId = "57f5d72ab350cf67308b81c6"; // pre-existing quiz 1 beforeAll(function(done) { done(); }); it("should return success", function(done) { api.resetQuiz(mock.env.playerId, quizId) .then((result) => { done(); }, (e) => { console.log(e.message);}); }); }); });
playbasis/native-sdk-js
test/api.quiz.test.js
JavaScript
mit
4,574
'use babel' export default function destroySession(self, sharedSession) { // Checks if shared session in the stack let shareStackIndex = self.shareStack.indexOf(sharedSession) if (shareStackIndex !== -1) { // Removes share session from the stack and updates UI self.shareStack.splice(shareStackIndex, 1) self.updateShareView() } else { // Logs an error message console.error(sharedSession, 'not found') } }
lightbulb-softworks/atom-realtime-collaboration
lib/helpers/destroySession.js
JavaScript
mit
438
version https://git-lfs.github.com/spec/v1 oid sha256:7998c9520ed14ac4fc2dcf6956c1dcbd36b02d6dfe63b0e4ec15a1635b951e08 size 4403
yogeshsaroya/new-cdnjs
ajax/libs/yui/3.17.2/queue-promote/queue-promote-coverage.js
JavaScript
mit
129
version https://git-lfs.github.com/spec/v1 oid sha256:6f71532f9445b6d65fbaecee3fa6944aa804f3a8f7364028a6d8c71261adc0e5 size 3643
yogeshsaroya/new-cdnjs
ajax/libs/angular.js/1.3.4/angular-touch.min.js
JavaScript
mit
129
version https://git-lfs.github.com/spec/v1 oid sha256:b519d8c53881da3ce32f92a5c9f583c67d563ea9d7c5cacd3bf2503726443654 size 3420
yogeshsaroya/new-cdnjs
ajax/libs/uikit/2.15.0/js/components/upload.min.js
JavaScript
mit
129
/*! 一叶孤舟 | qq:28701884 | 欢迎指教 */ var bill = bill || {}; //初始化 bill.init = function (){ if (com.store){ clearInterval(bill.timer); bill.setBillList(com.arr2Clone(com.initMap)); //写入棋谱列表 play.isPlay=false; com.show(); }else { bill.timer = setInterval("bill.init()",300); } } //把所有棋谱写入棋谱列表 bill.setBillList = function (map){ var list=com.get("billList") for (var i=0; i < com.store.length ; i++){ var option = document.createElement('option'); option.text='棋谱'+(i+1); option.value=i; list.add(option , null); } list.addEventListener("change", function(e) { bill.setBox (com.store[this.value], map) }) bill.setBox (com.store[0], map) } //棋谱分析 写入 bill.setMove = function (bl,inx,map){ var map = com.arr2Clone(map); for (var i=0; i<map.length; i++){ for (var n=0; n<map[i].length; n++){ var key = map[i][n]; if (key){ com.mans[key].x=n; com.mans[key].y=i; com.mans[key].isShow = true; } } } for (var i=0; i<= inx ; i++){ var n = i*4 var y = bl[n+1] var newX = bl[n+2] var x = bl[n+0] var newY = bl[n+3] if (com.mans[map[newY][newX]]) { com.mans[map[newY][newX]].isShow = false; } com.mans[map[y][x]].x = newX; com.mans[map[y][x]].y = newY; if (i == inx) { com.showPane(x ,y,newX,newY); } map[newY][newX] = map[y][x]; delete map[y][x]; } return map; } //写入棋谱 bill.setBox = function (bl,initMap){ var map = com.arr2Clone(initMap); var bl= bl.split(""); var h=''; for (var i=0; i< bl.length ; i+=4){ h +='<li id="move_'+(i/4)+'">'; var x = bl[i+0]; var y = bl[i+1]; var newX = bl[i+2]; var newY = bl[i+3]; h += com.createMove(map,x,y,newX,newY); h +='</li>\n\r'; } com.get("billBox").innerHTML = h; var doms=com.get("billBox").getElementsByTagName("li"); for (var i=0; i<doms.length; i++){ doms[i].addEventListener("click", function(e) { var inx = this.getAttribute("id").split("_")[1]; bill.setMove (bl , inx , initMap) com.show(); }) } }
xuchanggui/website
games/web_chess/js/bill.js
JavaScript
mit
2,075
"use strict"; var now = Date.now; var CircleQueue = require("../../misc/CircleQueue.js"); function TransCommandQueue(mainQueue, object) { CircleQueue.call(this); this.object = object; this.mainQueue = mainQueue; } TransCommandQueue.prototype = { __name__ : "TransCommandQueue", "__proto__" : CircleQueue.prototype, constructor : TransCommandQueue, isClosed : false, isExecuted : false, execute : function () { if (this.isExecuted || !this.length || this.isClosed) { return; } var self = this; var task = this.shift(); this.object.query(task.sql, task.options, function (err, result) { self.isExecuted = false; task.callback(err, result); self.execute(); }); this.isExecuted = true; }, destroy : function () { if (this.isClosed) { return; } this.isClosed = true; this.clear(); this.mainQueue.pool.returnObject(this.object); this.mainQueue.execute(); } }; module.exports = TransCommandQueue;
majianxiong/beejs
lib/data/mysql/TransCommandQueue.js
JavaScript
mit
955
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); 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 _react = require('react'); var _react2 = _interopRequireDefault(_react); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } // (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP var STATUS_ICON = "_CSSClassnames2.default.STATUS_ICON"; var Label = function (_Component) { (0, _inherits3.default)(Label, _Component); function Label() { (0, _classCallCheck3.default)(this, Label); return (0, _possibleConstructorReturn3.default)(this, (Label.__proto__ || (0, _getPrototypeOf2.default)(Label)).apply(this, arguments)); } (0, _createClass3.default)(Label, [{ key: 'render', value: function render() { var className = STATUS_ICON + ' ' + STATUS_ICON + '-label'; if (this.props.className) { className += ' ' + this.props.className; } return _react2.default.createElement( 'svg', { className: className, viewBox: '0 0 24 24', version: '1.1' }, _react2.default.createElement( 'g', { className: STATUS_ICON + '__base' }, _react2.default.createElement('circle', { cx: '12', cy: '12', r: '12', stroke: 'none' }) ) ); } }]); return Label; }(_react.Component); Label.displayName = 'Label'; exports.default = Label; module.exports = exports['default'];
abzfarah/Pearson.NAPLAN.GnomeH
src/components/common/icons/status/Label.js
JavaScript
mit
2,134
module.exports = { // meta /** * The banner is the comment that is placed at the top of our compiled * source files. It is first processed as a Grunt template, where the `<%=` * pairs are evaluated based on this very configuration object. */ banner: '/**\n' + ' * <%= pkg.name %> - v<%= pkg.version %> - <%= grunt.template.today("yyyy-mm-dd") %>\n' + ' * <%= pkg.homepage %>\n' + ' *\n' + ' * Copyright (c) <%= grunt.template.today("yyyy") %> <%= pkg.author %>\n' + ' * Licensed <%= pkg.licenses.type %> <<%= pkg.licenses.url %>>\n' + ' */\n' };
csterwa/ng-matrix-component
config/grunt/config/meta.js
JavaScript
mit
621
function DashboardController($scope, $state, $stateParams, dashboardFactory) { var dc = this; dc.playerStats = {}; dc.itemForAuction = {}; dc.auctionStarted = false; // Called on page load to retrieve player data dashboardFactory.getData(dashboardFactory.getName()).then(function(response) { dc.playerStats = response.data; }); var unbindLogout = $scope.$on('logout', function() { dashboardFactory.logout().then(function(response) { if (response.status === 200) { $state.go('login'); } }); }); var unbindStart = $scope.$on('startAuction', function(evt, data) { dc.auctionStarted = true; dc.itemForAuction = data; $scope.$broadcast('roll it'); }); var unbindClose = $scope.$on('auction closed', function(evt, data) { updateData(dc.playerStats, data); dashboardFactory.processBid(data).then(function(response) { if (response.data === 200) { dashboardFactory.getData(dashboardFactory.getName()).then(function(res) { dc.playerStats = res.data; }); } }); }); // Clear events $scope.$on('$destroy', function() { unbindLogout(); unbindStart(); unbindClose(); }); /** * @desc function that updates player dashboard in real-time * @param {Object} playerData - logged in player's data * @param {Object} newData - contains player's recent transaction */ function updateData(playerData, newData) { playerData.coins = playerData.coins - newData.value; angular.forEach(playerData.inventoryItems, function(item) { if (item.name === newData.itemName) { item.quantity = item.quantity - newData.qty; } }); } } module.exports = DashboardController;
juliuscalahi/crossover
public/src/components/dashboard/dashboard-controller.js
JavaScript
mit
1,912
export default class Paths { /* url, path, relative path... anything */ static normalizePath(path, base, root=lively4url) { base = base.replace(/[^/]*$/,"") // if it is not a dir var normalized = path if (path.match(/^[A-Za-z]+:/)) { // do nothing } else if (path.match(/^\//)) { normalized = path.replace(/^\//, root + "/") } else { normalized = base + path } return Paths.normalizeURL(normalized) } static normalizeURL(urlString) { var url = new URL(urlString); url.pathname = this.normalize(url.pathname); return "" + url; } /* normalize only the "path" part of an URL */ static normalize(path) { let source = path.split(/\/+/) let target = [] for(let token of source) { if(token === '..') { target.pop() } else if(token !== '' && token !== '.') { target.push(token) } } if(path.charAt(0) === '/') return '/' + target.join('/') else return target.join('/') } static join(a, b) { if(b[0] === '/') { return this.normalize(b) } else { return this.normalize(a + '/' + b) } } }
LivelyKernel/lively4-core
src/client/paths.js
JavaScript
mit
1,198
/** * Copyright (c) 2014 brian@bevey.org * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ /** * @author brian@bevey.org * @fileoverview Prevent an air filter or other device from being turned off if * air quality is bad. The main intent of this is to prevent * automated macros or machine learning from turning off a filter * if air quality (PM 2.5) is really bad. */ module.exports = (function () { 'use strict'; return { version : 20180822, airFilterWhenSmoggy : function (deviceId, command, controllers, config) { var deviceState = require(__dirname + '/../../lib/deviceState'), commandParts = command.split('-'), filter = config.filter, maxLevel = config.maxLevel || 34.4, commandSubdevice = '', checkState, status; checkState = function () { var currDevice, currentDevice = {}, status = {}, subdeviceId, i = 0; for (currDevice in controllers) { if (controllers[currDevice].config) { switch (controllers[currDevice].config.typeClass) { // Look for bad PM 2.5 values in Air Quality case 'airQuality' : currentDevice = deviceState.getDeviceState(currDevice); if (currentDevice.value && currentDevice.value.report) { for (i; i < currentDevice.value.report.length; i += 1) { if (currentDevice.value.report[i].type === 'pm25') { status.value = currentDevice.value.report[i].value; } } } break; case 'nest' : case 'smartthings' : case 'wemo' : currentDevice = deviceState.getDeviceState(currDevice); if (currentDevice.value) { for (subdeviceId in currentDevice.value.devices) { if (currentDevice.value.devices[subdeviceId].label === filter) { status.filter = currentDevice.value.devices[subdeviceId]; status.newState = currentDevice.value; } } } break; } } } return status; }; if (commandParts.length === 3) { commandSubdevice = commandParts[1]; // We only care if it's the given subdevice AND we're trying to // potentially turn it off. if ((filter === commandSubdevice) && ((commandParts[2] === 'toggle') || (commandParts[2] === 'off'))) { status = checkState(); // Air quality is beyond it's determined safe bounds and the chosen // filter is currently on - abort this off or toggle command. if ((status.value >= maxLevel) && (status.filter.state === 'on')) { return false; } } } } }; }());
imbrianj/switchBoard
apps/conditional/airFilterWhenSmoggy.js
JavaScript
mit
4,094
import {stats} from './stats.js'; import {core} from './core.js'; import {tasks} from './tasks.js'; const scenesRenderInfo = {}; // Used for throttling FPS for each Scene const tickEvent = { sceneId: null, time: null, startTime: null, prevTime: null, deltaTime: null }; const taskBudget = 10; // Millisecs we're allowed to spend on tasks in each frame const fpsSamples = []; const numFPSSamples = 30; let lastTime = 0; let elapsedTime; let totalFPS = 0; const frame = function () { let time = Date.now(); if (lastTime > 0) { // Log FPS stats elapsedTime = time - lastTime; var newFPS = 1000 / elapsedTime; // Moving average of FPS totalFPS += newFPS; fpsSamples.push(newFPS); if (fpsSamples.length >= numFPSSamples) { totalFPS -= fpsSamples.shift(); } stats.frame.fps = Math.round(totalFPS / fpsSamples.length); } runTasks(time); fireTickEvents(time); renderScenes(); lastTime = time; window.requestAnimationFrame(frame); }; function runTasks(time) { // Process as many enqueued tasks as we can within the per-frame task budget const tasksRun = tasks.runTasks(time + taskBudget); const tasksScheduled = tasks.getNumTasks(); stats.frame.tasksRun = tasksRun; stats.frame.tasksScheduled = tasksScheduled; stats.frame.tasksBudget = taskBudget; } function fireTickEvents(time) { // Fire tick event on each Scene tickEvent.time = time; for (var id in core.scenes) { if (core.scenes.hasOwnProperty(id)) { var scene = core.scenes[id]; tickEvent.sceneId = id; tickEvent.startTime = scene.startTime; tickEvent.deltaTime = tickEvent.prevTime != null ? tickEvent.time - tickEvent.prevTime : 0; /** * Fired on each game loop iteration. * * @event tick * @param {String} sceneID The ID of this Scene. * @param {Number} startTime The time in seconds since 1970 that this Scene was instantiated. * @param {Number} time The time in seconds since 1970 of this "tick" event. * @param {Number} prevTime The time of the previous "tick" event from this Scene. * @param {Number} deltaTime The time in seconds since the previous "tick" event from this Scene. */ scene.fire("tick", tickEvent, true); } } tickEvent.prevTime = time; } function renderScenes() { const scenes = core.scenes; const forceRender = false; let scene; let renderInfo; let ticksPerRender; let id; for (id in scenes) { if (scenes.hasOwnProperty(id)) { scene = scenes[id]; renderInfo = scenesRenderInfo[id]; if (!renderInfo) { renderInfo = scenesRenderInfo[id] = {}; // FIXME } ticksPerRender = scene.ticksPerRender; if (renderInfo.ticksPerRender !== ticksPerRender) { renderInfo.ticksPerRender = ticksPerRender; renderInfo.renderCountdown = ticksPerRender; } if (--renderInfo.renderCountdown === 0) { scene.render(forceRender); renderInfo.renderCountdown = ticksPerRender; } } } } window.requestAnimationFrame(frame); const loop = {}; export{loop};
xeolabs/xeoengine
src/loop.js
JavaScript
mit
3,405
import BaseStatementNode from './BaseStatementNode'; import * as symbols from '../symbols'; export default class BaseBlockNode extends BaseStatementNode { packBlock(bitstr, propName) { var prop = this[propName] if (!prop) { bitstr.writebits(0, 1); return; } bitstr.writebits(1, 1); bitstr.writebits(prop.length, 32); prop.forEach(p => p.pack(bitstr)); } [symbols.FMAKEHLIRBLOCK](builder, arr, expectedType) { return arr.map(a => a[symbols.FMAKEHLIR](builder, expectedType)) .map(a => Array.isArray(a) ? a : [a]) .reduce((a, b) => a.concat(b), []); } };
mattbasta/btype
src/astNodes/BaseBlockNode.js
JavaScript
mit
689
"use strict"; //////////////////////////////////////////////////////////////////////////////// // ニコニコ動画再生 //////////////////////////////////////////////////////////////////////////////// Contents.nicovideo = function( cp ) { var p = $( '#' + cp.id ); var cont = p.find( 'div.contents' ); cp.SetIcon( null ); //////////////////////////////////////////////////////////// // 開始処理 //////////////////////////////////////////////////////////// this.start = function() { cont.activity( { color: '#ffffff' } ); cont.addClass( 'nicovideo' ) .html( OutputTPL( 'nicovideo', { id: cp.param.id } ) ); cp.SetTitle( 'Nicovideo - ' + cp.param['url'], false ); cont.activity( false ); }; //////////////////////////////////////////////////////////// // 終了処理 //////////////////////////////////////////////////////////// this.stop = function() { }; }
oken1/kurotwi
js/contents/nicovideo.js
JavaScript
mit
894
var prependChar = '#'; var util = require('util'); function convertToLines(str) { return str.split('\n').map(function(newStr) { return prependChar + newStr; }); } var newConsole = { log : function log() { convertToLines(util.format.apply(this, arguments)).forEach(function(line) { console.log(line); }); }, error : function error() { convertToLines(util.format.apply(this, arguments)).forEach(function(line) { console.error(line); }); } }; module.exports = newConsole;
ryanstevens/taplog
index.js
JavaScript
mit
515
var page = require('page'), csp = require('js-csp'); class Router { constructor(routes){ this.routes = routes; this.chan = csp.chan(); this.nextTransition = null; this.nextEl = null; // Setup channel listening for(var r in routes) this.listenToRoute(r); // Start listening page(); } /** * Go to route */ go(route, transition){ this.nextTransition = transition; page(route || '/'); return this; } loc(){ return location.pathname.substr(1); } listenToRoute(routeName){ var chan = this.chan; page(this.routes[routeName].path, function(){ csp.go(function*(){ yield csp.put(chan, routeName); }); }); } }; module.exports = Router;
gcao/weiqi-app
client/router/Router.js
JavaScript
mit
771
//= require phaser
macbury/ninja
app/assets/javascripts/macbury_ninja/game.js
JavaScript
mit
19
$(function() { function cellValue(val) { return { sortValue: val, displayValue: val.toString() }; } var yAxis = [{ id: 'store', name: 'Store' }, { id: 'clerk', name: 'Clerk' }]; var keyfigures = [{ id: 'nocustomers', name: 'Customers' }, { id: 'turnover', name: 'Turnover' }]; // normally one would request data here from the server using yAxis and keyfigures // but to keep things simple, we type in the result below var reportState = new ReportState({ useExpandCollapse: true }); reportState.dimensionsY = _.map(yAxis, function(e) { return e.id; }); reportState.serverData = [ { type: 'row', values: [cellValue('Copenhagen'), cellValue(''), cellValue(210), cellValue(43100)] }, { type: 'row', values: [cellValue('Stockholm'), cellValue(''), cellValue(120), cellValue(22100)] }, { type: 'row', values: [cellValue('Berlin'), cellValue(''), cellValue(743), cellValue(50032)] }, { type: 'grandtotal', values: [cellValue('Grand total'), cellValue(''), cellValue(1073), cellValue(115232)] } ]; var allYAxisValues = reportBuilder.getYAxisValues(reportState.serverData, yAxis); reportState.drawNewData = function(data) { // this also simulates a server backend returning new results reportState.serverData = []; if (_.any(reportState.expandedCells['store'], function(e) { return e == 'store:Copenhagen'; })) { reportState.serverData.push({ type: 'row', values: [cellValue('Copenhagen'), cellValue('Stine'), cellValue(110), cellValue(33100)] }); reportState.serverData.push({ type: 'row', values: [cellValue('Copenhagen'), cellValue('Dorthe'), cellValue(100), cellValue(10000)] }); reportState.serverData.push({ type: 'subtotal', values: [cellValue('Copenhagen'), cellValue(''), cellValue(210), cellValue(43100)] }); } else reportState.serverData.push({ type: 'row', values: [cellValue('Copenhagen'), cellValue(''), cellValue(210), cellValue(43100)] }); if (_.any(reportState.expandedCells['store'], function(e) { return e == 'store:Stockholm'; })) { reportState.serverData.push({ type: 'row', values: [cellValue('Stockholm'), cellValue('Emma'), cellValue(30), cellValue(2100)] }); reportState.serverData.push({ type: 'row', values: [cellValue('Stockholm'), cellValue('Anne'), cellValue(70), cellValue(18000)] }); reportState.serverData.push({ type: 'row', values: [cellValue('Stockholm'), cellValue('Julia'), cellValue(20), cellValue(2000)] }); reportState.serverData.push({ type: 'subtotal', values: [cellValue('Stockholm'), cellValue(''), cellValue(120), cellValue(22100)] }); } else reportState.serverData.push({ type: 'row', values: [cellValue('Stockholm'), cellValue(''), cellValue(120), cellValue(22100)] }); if (_.any(reportState.expandedCells['store'], function(e) { return e == 'store:Berlin'; })) { reportState.serverData.push({ type: 'row', values: [cellValue('Berlin'), cellValue('Sandra'), cellValue(93), cellValue(1182)] }); reportState.serverData.push({ type: 'row', values: [cellValue('Berlin'), cellValue('Katharina'), cellValue(100), cellValue(6700)] }); reportState.serverData.push({ type: 'row', values: [cellValue('Berlin'), cellValue('Nadine'), cellValue(120), cellValue(10030)] }); reportState.serverData.push({ type: 'row', values: [cellValue('Berlin'), cellValue('Julia'), cellValue(430), cellValue(30200)] }); reportState.serverData.push({ type: 'subtotal', values: [cellValue('Berlin'), cellValue(''), cellValue(743), cellValue(50032)] }); } else reportState.serverData.push({ type: 'row', values: [cellValue('Berlin'), cellValue(''), cellValue(743), cellValue(50032)] }); reportState.serverData.push({ type: 'grandtotal', values: [cellValue('Grand total'), cellValue(''), cellValue(1073), cellValue(115232)] }); if (reportState.sortRowIndex != -1) reportState.drawData(reportBuilder.sortExpandedData(reportState.serverData, reportState.dimensionsY, reportState.sortRowIndex, reportState.sortDirection, reportState.expandedCells)); else reportState.drawData(reportState.serverData); }; reportState.drawData = function(data) { reportInterface.drawTable("data", reportState, allYAxisValues, data, yAxis, keyfigures); reportInterface.addSortHeaders("data", reportState); reportInterface.addExpandCollapseHeaders("data", reportState); }; reportState.drawData(reportState.serverData); });
arj03/datagrid
examples/simple-expand/example.js
JavaScript
mit
4,693
var socketio = require('socket.io'), dotProp = require('dot-prop'); /** * Constructs a Socket. * Socket manager powered by Socket.IO. * * @constructor */ function Socket(){ this.port = null; this.io = null; this.scope = {}; } Socket.prototype.start = function () { var self = this; var settings = self.scope.settings(); self.io = socketio(settings.socket.port); self.io.on('connection', function (socket) { socket.emit('structure', {key: self.scope.key, title: self.scope.title, sub: self.scope.sub}); socket.on('call', function(data){ dotProp.get(self.scope, data.path).job.call(data); }); }); return self; }; module.exports = new Socket();
mateuscalza/master-of-puppets
controllers/Socket.js
JavaScript
mit
724
import TestUtils from 'react-dom/test-utils'; import React from 'react'; import ReactDOM from 'react-dom'; import Textarea from '../'; const { findRenderedDOMComponentWithClass, renderIntoDocument, Simulate } = TestUtils; function fake() { return () => { return 'fake function'; } } describe('The input textarea', () => { describe('when mounted with no props', () => { let reactComponent; let domNode; let inputNode; beforeEach(() => { reactComponent = renderIntoDocument(<Textarea name='myTextArea' onChange={fake} />); domNode = ReactDOM.findDOMNode(reactComponent); inputNode = ReactDOM.findDOMNode(reactComponent.refs.htmlInput); }); it('should render a node with data-focus attribute', () => { expect(reactComponent).toBeDefined(); expect(reactComponent).toBeInstanceOf(Object); expect(domNode.tagName).toBe('DIV'); expect(domNode.getAttribute('data-focus')).toBe('input-textarea'); }); it('should be material designed', () => { const divMdl = domNode.firstChild; expect(divMdl).toBeDefined(); expect(divMdl.tagName).toBe('DIV'); expect(divMdl.className).toMatch('mdl-textfield mdl-js-textfield'); }); it('should have a material designed textarea', () => { expect(inputNode.getAttribute('class')).toBe('mdl-textfield__input'); }); it('should render an empty textarea', () => { expect(inputNode).toBeDefined(); expect(inputNode.type).toBe('textarea'); expect(inputNode.value).toBe(''); expect(() => findRenderedDOMComponentWithClass(reactComponent, 'label-error')).toThrow('Did not find exactly one match (found: 0) for class:label-error'); }); }); describe('when mounted with onChange props defined', () => { let component, domNode, onChangeSpy; const testValue = 'CHANGED_VALUE'; beforeEach(() => { onChangeSpy = jest.fn(); // test that the method in props onChange is called component = renderIntoDocument(<Textarea name='myTextArea' onChange={onChangeSpy} />); }); it('should call the onChange function defined in props when textarea is changed', () => { expect(onChangeSpy).not.toHaveBeenCalled(); Simulate.change(ReactDOM.findDOMNode(component.refs.htmlInput), { target: { value: testValue } }); expect(onChangeSpy).toHaveBeenCalledTimes(1); }); }); describe('when an error is declared in props', () => { let component, errorComponent, inputNode; const errorLabel = 'this is an error'; beforeEach(() => { component = renderIntoDocument(<Textarea error={errorLabel} name='myTextArea' onChange={fake} />); inputNode = ReactDOM.findDOMNode(component.refs.htmlInput); errorComponent = findRenderedDOMComponentWithClass(component, 'label-error'); }); it('should display the input textarea', () => { expect(inputNode).toBeDefined(); expect(inputNode.getAttribute('pattern')).toBe('hasError'); }); it('should display the error', () => { expect(errorComponent).toBeDefined(); expect(errorComponent.innerHTML).toBe(errorLabel); }); }); });
KleeGroup/focus-components
src/components/input/textarea/__tests__/index.js
JavaScript
mit
3,437
System.register([], function (_export, _context) { "use strict"; _export("default", function () { return 'test'; }); return { setters: [], execute: function () {} }; });
systemjs/systemjs
test/fixtures/register-modules/export-default.js
JavaScript
mit
193
var arrayOfInts = [1, 10, -5, 1, -100]; function maxProduct(arr) { var smallest = 0; var almostSmallest = 0; var largest = 0; var second = 0; var third = 0; for(var i = 0; i < arr.length; i++ ) { if(arr[i] > largest){ third = second second = largest largest = arr[i] } else if(arr[i] > second) { third = second second = arr[i] } else if(arr[i] > third){ third = arr[i] } else if( arr[i] < 0) { if(arr[i] < smallest) { almostSmallest = smallest smallest = arr[i]; } else { if( arr[i] < almostSmallest) { almostSmallest = arr[i] } } } } if(smallest * almostSmallest > second * third) { return largest * almostSmallest * smallest } return largest * second * third } maxProduct(arrayOfInts)
15chrjef/Interview-Cake
3.js
JavaScript
mit
901
export default function isJavascript(scriptTag) { // TODO: add a console warning if the script tag doesn't have an attribute? // seems like it's required for some parts of ember consumption let type = scriptTag.attributes.type ? scriptTag.attributes.type.value : 'text/javascript'; return /(?:application|text)\/javascript/i.test(type); }
ef4/ember-handoff
addon/lib/is-js.js
JavaScript
mit
347
'use strict'; function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } (function () { function pushComponent(array, component) { if (!array) { array = []; } array.push({ name: component.getAttribute('name'), source: '' + component.textContent }); return array; } function getComponents() { var components = document.getElementsByClassName('component-template'); var componentTree = {}; [].concat(_toConsumableArray(components)).forEach(function (component) { var componentType = component.getAttribute('data-type'); componentTree[componentType] = pushComponent(componentTree[componentType], component); }); return componentTree; } function createFragment() { return document.createDocumentFragment(); } function listElementComponent() {} function addToElement(source, destination) { destination.innerHTML = source; } /* rewrite this */ function buildComponentList(tree) { var fragment = createFragment(); var components = getComponents(); var keys = Object.keys(components); var list = document.createElement('ul'); keys.forEach(function (key) { var listItem = document.createElement('li'); var subList = document.createElement('ul'); var title = document.createElement('p'); title.textContent = key; listItem.appendChild(title); components[key].forEach(function (component) { var item = document.createElement('li'); item.textContent = component.name; subList.appendChild(item); }); listItem.appendChild(subList); list.appendChild(listItem); }); fragment.appendChild(list); document.getElementById('container').appendChild(fragment); } /* end */ // temp stuff for demo buildComponentList(getComponents()); document.getElementById('addBanner').addEventListener('click', function () { addToElement(getComponents().information[0].source, document.querySelector('.container')); }); })();
WillsonSmith/PageBuilderPrototype
js/build.js
JavaScript
mit
2,147
(function(){ angular.module('nbTodos') .component('todoEditor', { templateUrl: '/app/todos/todo-editor/todo-editor.component.html', controller: TodoEditorController, controllerAs: 'vm' }); TodoEditorController.$inject = ['todosStore']; function TodoEditorController(todosStore) { this.text = ''; this.create = function () { if( this.text.trim().length === 0) { this.error = true; return; } todosStore.create(this.text); this.text = ''; } } })();
lean-stack/ngjs-notebook
src/app/todos/todo-editor/todo-editor.component.js
JavaScript
mit
534
import { UPDATE_BOMB_LOCATIONS, REMOVE_PLAYER_BOMBS } from './constants' const initialState = { } //the bombs are stored in an 'allBombs' object within the state, that has keys of the user's socket ID, each with a property of an array of that user's bomb objects export const bombs = (state = initialState, action) => { let newState; switch (action.type) { case UPDATE_BOMB_LOCATIONS: newState = Object.assign({}, state); for (let key in action.allBombs) { newState[key] = action.allBombs[key] } return newState; case REMOVE_PLAYER_BOMBS: newState = Object.assign({}, state) delete newState[action.id] return newState; default: return state; } }
Bombanauts/Bombanauts
browser/redux/bombs/reducer.js
JavaScript
mit
722
$('.counter').countTo({ formatter: function (value, options) { return value.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,').slice(0,-3); } }); function updateCount(to) { $('.counter').countTo({ from: parseInt($('.counter').html().replace(/,/g, '')), to: to, formatter: function (value, options) { return value.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,').slice(0,-3); } }); } function getUpdatedCount() { $.getJSON("https://petition.parliament.uk/petitions/131215.json", function (data){ updateCount(data.data.attributes.signature_count); console.log("+" + (data.data.attributes.signature_count - parseInt($('.counter').html().replace(/,/g, ''))) ); }); } function getCountryData() { $.getJSON("https://petition.parliament.uk/petitions/131215.json", function (data){ data.data.attributes.signatures_by_country.sort(function(a,b){ if (a.signature_count > b.signature_count){ return -1; } else if (a.signature_count < b.signature_count){ return 1; } return 0; }); $("#counties").html(""); data.data.attributes.signatures_by_country.slice(0, 10).forEach(function(item, index){ html = '<img class="flag flag-' + item.code.toLowerCase() + '"> <b>' + item.name + ':</b> ' + item.signature_count.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,').slice(0,-3) + '</p>'; $("#counties").append(html); }); }); }
aaranmcguire/aaranmcguire.github.io
js/app.js
JavaScript
mit
1,513