code
stringlengths
2
1.05M
repo_name
stringlengths
5
114
path
stringlengths
4
991
language
stringclasses
1 value
license
stringclasses
15 values
size
int32
2
1.05M
'use strict' const sprockets = require( __dirname + '/../../src/sprockets' ) const mkdir = require( __dirname + '/../../utils/mkdir' ) const fs = require( 'fs' ) let input = './src/index.html' let output = './build/index.html' sprockets.add( 'index', ( done ) => { mkdir( output ) fs.createReadStream( input ) .on( 'end', function () { done() } ) .pipe( fs.createWriteStream( output ) ) } )
vladfilipro/sprockets
tasks/compile/index.js
JavaScript
mit
417
const create = require('./create') const geom2 = require('../geometry/geom2') const fromPoints = points => { const geometry = geom2.fromPoints(points) const newShape = create() newShape.geometry = geometry return newShape } module.exports = fromPoints
jscad/csg.js
src/core/shape2/fromPoints.js
JavaScript
mit
262
'use strict'; var users = require('../../app/controllers/users.server.controller'), streams = require('../../app/controllers/streams.server.controller'); module.exports = function(app){ app.route('/api/streams') .get(streams.list) .post(users.requiresLogin, streams.create); app.route('/api/streams/:streamId') .get(streams.read) .put(users.requiresLogin, streams.hasAuthorization, streams.update) .delete(users.requiresLogin, streams.hasAuthorization, streams.delete); app.param('streamId', streams.streamByID); };
plonsker/onetwo
app/routes/streams.server.routes.js
JavaScript
mit
599
import Reflux from 'reflux'; //TODO: recheck the flow of these actions 'cause it doesn't seem to be OK export default Reflux.createActions([ 'eventPartsReady', 'eventPartsUpdate' ]);
fk1blow/repeak
src/client/actions/event-part-actions.js
JavaScript
mit
188
/** * @license Angular v5.2.2 * (c) 2010-2018 Google, Inc. https://angular.io/ * License: MIT */ import { EventEmitter, Injectable } from '@angular/core'; import { __extends } from 'tslib'; import { LocationStrategy } from '@angular/common'; /** * @fileoverview added by tsickle * @suppress {checkTypes} checked by tsc */ /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * A spy for {\@link Location} that allows tests to fire simulated location events. * * \@experimental */ var SpyLocation = /** @class */ (function () { function SpyLocation() { this.urlChanges = []; this._history = [new LocationState('', '')]; this._historyIndex = 0; /** * \@internal */ this._subject = new EventEmitter(); /** * \@internal */ this._baseHref = ''; /** * \@internal */ this._platformStrategy = /** @type {?} */ ((null)); } /** * @param {?} url * @return {?} */ SpyLocation.prototype.setInitialPath = /** * @param {?} url * @return {?} */ function (url) { this._history[this._historyIndex].path = url; }; /** * @param {?} url * @return {?} */ SpyLocation.prototype.setBaseHref = /** * @param {?} url * @return {?} */ function (url) { this._baseHref = url; }; /** * @return {?} */ SpyLocation.prototype.path = /** * @return {?} */ function () { return this._history[this._historyIndex].path; }; /** * @param {?} path * @param {?=} query * @return {?} */ SpyLocation.prototype.isCurrentPathEqualTo = /** * @param {?} path * @param {?=} query * @return {?} */ function (path, query) { if (query === void 0) { query = ''; } var /** @type {?} */ givenPath = path.endsWith('/') ? path.substring(0, path.length - 1) : path; var /** @type {?} */ currPath = this.path().endsWith('/') ? this.path().substring(0, this.path().length - 1) : this.path(); return currPath == givenPath + (query.length > 0 ? ('?' + query) : ''); }; /** * @param {?} pathname * @return {?} */ SpyLocation.prototype.simulateUrlPop = /** * @param {?} pathname * @return {?} */ function (pathname) { this._subject.emit({ 'url': pathname, 'pop': true, 'type': 'popstate' }); }; /** * @param {?} pathname * @return {?} */ SpyLocation.prototype.simulateHashChange = /** * @param {?} pathname * @return {?} */ function (pathname) { // Because we don't prevent the native event, the browser will independently update the path this.setInitialPath(pathname); this.urlChanges.push('hash: ' + pathname); this._subject.emit({ 'url': pathname, 'pop': true, 'type': 'hashchange' }); }; /** * @param {?} url * @return {?} */ SpyLocation.prototype.prepareExternalUrl = /** * @param {?} url * @return {?} */ function (url) { if (url.length > 0 && !url.startsWith('/')) { url = '/' + url; } return this._baseHref + url; }; /** * @param {?} path * @param {?=} query * @return {?} */ SpyLocation.prototype.go = /** * @param {?} path * @param {?=} query * @return {?} */ function (path, query) { if (query === void 0) { query = ''; } path = this.prepareExternalUrl(path); if (this._historyIndex > 0) { this._history.splice(this._historyIndex + 1); } this._history.push(new LocationState(path, query)); this._historyIndex = this._history.length - 1; var /** @type {?} */ locationState = this._history[this._historyIndex - 1]; if (locationState.path == path && locationState.query == query) { return; } var /** @type {?} */ url = path + (query.length > 0 ? ('?' + query) : ''); this.urlChanges.push(url); this._subject.emit({ 'url': url, 'pop': false }); }; /** * @param {?} path * @param {?=} query * @return {?} */ SpyLocation.prototype.replaceState = /** * @param {?} path * @param {?=} query * @return {?} */ function (path, query) { if (query === void 0) { query = ''; } path = this.prepareExternalUrl(path); var /** @type {?} */ history = this._history[this._historyIndex]; if (history.path == path && history.query == query) { return; } history.path = path; history.query = query; var /** @type {?} */ url = path + (query.length > 0 ? ('?' + query) : ''); this.urlChanges.push('replace: ' + url); }; /** * @return {?} */ SpyLocation.prototype.forward = /** * @return {?} */ function () { if (this._historyIndex < (this._history.length - 1)) { this._historyIndex++; this._subject.emit({ 'url': this.path(), 'pop': true }); } }; /** * @return {?} */ SpyLocation.prototype.back = /** * @return {?} */ function () { if (this._historyIndex > 0) { this._historyIndex--; this._subject.emit({ 'url': this.path(), 'pop': true }); } }; /** * @param {?} onNext * @param {?=} onThrow * @param {?=} onReturn * @return {?} */ SpyLocation.prototype.subscribe = /** * @param {?} onNext * @param {?=} onThrow * @param {?=} onReturn * @return {?} */ function (onNext, onThrow, onReturn) { return this._subject.subscribe({ next: onNext, error: onThrow, complete: onReturn }); }; /** * @param {?} url * @return {?} */ SpyLocation.prototype.normalize = /** * @param {?} url * @return {?} */ function (url) { return /** @type {?} */ ((null)); }; SpyLocation.decorators = [ { type: Injectable }, ]; /** @nocollapse */ SpyLocation.ctorParameters = function () { return []; }; return SpyLocation; }()); var LocationState = /** @class */ (function () { function LocationState(path, query) { this.path = path; this.query = query; } return LocationState; }()); /** * @fileoverview added by tsickle * @suppress {checkTypes} checked by tsc */ /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * A mock implementation of {\@link LocationStrategy} that allows tests to fire simulated * location events. * * \@stable */ var MockLocationStrategy = /** @class */ (function (_super) { __extends(MockLocationStrategy, _super); function MockLocationStrategy() { var _this = _super.call(this) || this; _this.internalBaseHref = '/'; _this.internalPath = '/'; _this.internalTitle = ''; _this.urlChanges = []; /** * \@internal */ _this._subject = new EventEmitter(); return _this; } /** * @param {?} url * @return {?} */ MockLocationStrategy.prototype.simulatePopState = /** * @param {?} url * @return {?} */ function (url) { this.internalPath = url; this._subject.emit(new _MockPopStateEvent(this.path())); }; /** * @param {?=} includeHash * @return {?} */ MockLocationStrategy.prototype.path = /** * @param {?=} includeHash * @return {?} */ function (includeHash) { if (includeHash === void 0) { includeHash = false; } return this.internalPath; }; /** * @param {?} internal * @return {?} */ MockLocationStrategy.prototype.prepareExternalUrl = /** * @param {?} internal * @return {?} */ function (internal) { if (internal.startsWith('/') && this.internalBaseHref.endsWith('/')) { return this.internalBaseHref + internal.substring(1); } return this.internalBaseHref + internal; }; /** * @param {?} ctx * @param {?} title * @param {?} path * @param {?} query * @return {?} */ MockLocationStrategy.prototype.pushState = /** * @param {?} ctx * @param {?} title * @param {?} path * @param {?} query * @return {?} */ function (ctx, title, path, query) { this.internalTitle = title; var /** @type {?} */ url = path + (query.length > 0 ? ('?' + query) : ''); this.internalPath = url; var /** @type {?} */ externalUrl = this.prepareExternalUrl(url); this.urlChanges.push(externalUrl); }; /** * @param {?} ctx * @param {?} title * @param {?} path * @param {?} query * @return {?} */ MockLocationStrategy.prototype.replaceState = /** * @param {?} ctx * @param {?} title * @param {?} path * @param {?} query * @return {?} */ function (ctx, title, path, query) { this.internalTitle = title; var /** @type {?} */ url = path + (query.length > 0 ? ('?' + query) : ''); this.internalPath = url; var /** @type {?} */ externalUrl = this.prepareExternalUrl(url); this.urlChanges.push('replace: ' + externalUrl); }; /** * @param {?} fn * @return {?} */ MockLocationStrategy.prototype.onPopState = /** * @param {?} fn * @return {?} */ function (fn) { this._subject.subscribe({ next: fn }); }; /** * @return {?} */ MockLocationStrategy.prototype.getBaseHref = /** * @return {?} */ function () { return this.internalBaseHref; }; /** * @return {?} */ MockLocationStrategy.prototype.back = /** * @return {?} */ function () { if (this.urlChanges.length > 0) { this.urlChanges.pop(); var /** @type {?} */ nextUrl = this.urlChanges.length > 0 ? this.urlChanges[this.urlChanges.length - 1] : ''; this.simulatePopState(nextUrl); } }; /** * @return {?} */ MockLocationStrategy.prototype.forward = /** * @return {?} */ function () { throw 'not implemented'; }; MockLocationStrategy.decorators = [ { type: Injectable }, ]; /** @nocollapse */ MockLocationStrategy.ctorParameters = function () { return []; }; return MockLocationStrategy; }(LocationStrategy)); var _MockPopStateEvent = /** @class */ (function () { function _MockPopStateEvent(newUrl) { this.newUrl = newUrl; this.pop = true; this.type = 'popstate'; } return _MockPopStateEvent; }()); /** * @fileoverview added by tsickle * @suppress {checkTypes} checked by tsc */ /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * @fileoverview added by tsickle * @suppress {checkTypes} checked by tsc */ /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * @module * @description * Entry point for all public APIs of this package. */ // This file only reexports content of the `src` folder. Keep it that way. /** * @fileoverview added by tsickle * @suppress {checkTypes} checked by tsc */ /** * Generated bundle index. Do not edit. */ export { SpyLocation, MockLocationStrategy }; //# sourceMappingURL=testing.js.map
RJ15/FixIt
badminton/node_modules/@angular/common/esm5/testing.js
JavaScript
mit
11,979
function router(handle, pathname, res, postdata) { console.log('into the router request for->'+pathname); // var newpathname = pathname; // var newpostdata = postdata; // console.log(pathname.lastIndexOf('.')); var extendNM = pathname.substr(pathname.lastIndexOf('.')+1); // console.log(extendNM); // var cssFileRegex = new RegExp('^/css/.*css?$'); // if (cssFileRegex.test(pathname)) { // newpathname = 'css'; // newpostdata = pathname; // } if (typeof handle[extendNM] === 'function') { handle[extendNM](res, postdata, pathname); } else { console.log('no request handle found for->'+pathname); res.writeHead(404, {'Content-Type':'text/plain'}); res.write('404 not found!'); res.end(); } } exports.router = router;
noprettyboy/my_portal_page
serverjs/router.js
JavaScript
mit
744
$(function(){$(".btn-restaurant-status").click(function(){$(".popup-shadow").show();$(".popup-restaurant-status").fadeIn()});$("#popup-restaurant-status-yes").click(function(){$("#form-restaurant-status").submit()});$("#popup-restaurant-status-no").click(function(){$(".popup-shadow").hide();$(".popup-restaurant-status").hide()})});
PersonalLinyang/o2h
public/assets/js/pc/admin/service/restaurant/restaurant_detail.js
JavaScript
mit
333
"use strict" class Compress extends R.Compressor{ /** * * */ run(R,compressor){ this.compressBackbone(true); } } module.exports=Compress;
williamamed/Raptor.js
@raptorjs-development/raptor-panel/Compressor/Compress.js
JavaScript
mit
154
var parserx = require('parse-regexp') var EventEmitter = require('events').EventEmitter var MuxDemux = require('mux-demux') var remember = require('remember') var idle = require('idle') var timestamp = require('monotonic-timestamp') var from = require('from') var sync = require('./state-sync') module.exports = Rumours //THIS IS STRICTLY FOR DEBUGGING var ids = 'ABCDEFHIJKLMNOP' function createId () { var id = ids[0] ids = ids.substring(1) return id } function Rumours (schema) { var emitter = new EventEmitter() //DEBUG emitter.id = createId() var rules = [] var live = {} var locals = {} /* schema must be of form : { '/regexp/g': function (key) { //must return a scuttlebutt instance //regexes must match from the first character. //[else madness would ensue] } } */ for (var p in schema) { rules.push({rx: parserx(p) || p, fn: schema[p]}) } function match (key) { for (var i in rules) { var r = rules[i] var m = key.match(r.rx) if(m && m.index === 0) return r.fn } } //OPEN is a much better verb than TRANSCIEVE emitter.open = emitter.transceive = emitter.trx = function (key, local, cb) { if(!cb && 'function' === typeof local) cb = local, local = true local = (local !== false) //default to true if(local) locals[key] = true if(live[key]) return live[key] //if we havn't emitted ready, emit it now, //can deal with the rest of the updates later... if(!emitter.ready) { emitter.ready = true emitter.emit('ready') } var fn = match(key) if(!fn) throw new Error('no schema for:'+key) var doc = fn(key) //create instance. doc.key = key live[key] = doc //remeber what is open. emitter.emit('open', doc, local) //attach to any open streams. emitter.emit('trx', doc, local) doc.once('dispose', function () { delete locals[doc.key] delete live[doc.key] }) if(cb) doc.once('sync', cb) return doc } //CLOSE(doc) emitter.close = emitter.untransceive = emitter.untrx = function (doc) { doc.dispose() emitter.emit('untrx', doc) emitter.emit('close', doc) return this } /* so the logic here: if open a doc, RTR over stream; if idle close stream if change reopen stream */ function activations (listen) { emitter.on('open', onActive) for(var key in live) { (onActive)(live[key]) } function onActive (doc, local) { local = (local !== false) var up = true function onUpdate (u) { if(up) return up = true listen(doc, true) } function onIdle () { up = false listen(doc, false) } //call onIdle when _update hasn't occured within ms... idle(doc, '_update', 1e3, onIdle) doc.once('dispose', function () { if(up) { up = false listen(doc, false) } doc.removeListener('_update', onIdle) doc.removeListener('_update', onUpdate) }) doc.on('_update', onUpdate) listen(doc, true) } } var state = {} var syncState = sync(emitter, state) //a better name for this? function onReadyOrNow (cb) { process.nextTick(function () { if(emitter.ready) return cb() emitter.once('ready', cb) }) } emitter.createStream = function (mode) { var streams = {} var mx = MuxDemux(function (stream) { if(/^__state/.test(stream.meta.key)) { return stateStream(stream) } if(_stream = streams[stream.meta.key]) { if(_stream.meta.ts > stream.meta.ts) return _stream.end() else stream.end(), stream = _stream } streams[stream.meta.key] = stream //this will trigger connectIf emitter.open(stream.meta.key, false) }) function connectIf(doc) { var stream = streams[doc.key] if(!stream) { streams[doc.key] = stream = mx.createStream({key: doc.key, ts: timestamp()}) } stream.pipe(doc.createStream({wrapper:'raw', tail: true})).pipe(stream) stream.once('close', function () { delete streams[doc.key] }) } //replicate all live documents. process.nextTick(function () { activations(function (doc, up) { if(up) { process.nextTick(function () { connectIf(doc) }) } else { if(streams[doc.key]) streams[doc.key].end() if(!locals[doc.key]) doc.dispose() } }) }) function stateStream (stream) { stream.on('data', function (ary) { var key = ary.shift() var hash = ary.shift() if(state[key] !== hash && !live[key]) { //(_, false) means close this again after it stops changing... emitter.open(key, false) } }) } //wait untill is ready, if not yet ready... onReadyOrNow(function () { from( Object.keys(state).map(function (k) { return [k, state[k]] }) ) .pipe(mx.createStream({key: '__state'})) /*.on('data', function (data) { var key = data.shift() var hash = data.shift() //just have to open the document, //and it will be replicated to the remote. if(state[key] !== hash) emitter.open(key) })*/ }) return mx } //inject kv object used to persist everything. emitter.persist = function (kv) { var sync = remember(kv) function onActive (doc) { sync(doc) } //check if any docs are already active. //start persisting them. for (var k in live) { onActive(live[k]) } emitter.on('trx', onActive) //load the state - this is the hash of the documents! syncState(kv) return emitter } return emitter }
dominictarr/rumours_
index.js
JavaScript
mit
6,007
'use strict'; var xpath = require('xpath'); var dom = require('xmldom').DOMParser; module.exports = function (grunt) { var xml = grunt.file.read(__dirname + '/../pom.xml'); var doc = new dom().parseFromString(xml); var select = xpath.useNamespaces({"xmlns": "http://maven.apache.org/POM/4.0.0"}); var version = select("/xmlns:project/xmlns:version/text()", doc).toString().split( /-/ )[0]; var repository = select("/xmlns:project/xmlns:url/text()", doc).toString(); require('load-grunt-tasks')(grunt); grunt.initConfig({ changelog: { options: { version: version, repository: repository, dest: '../CHANGELOG.md' } }, }); grunt.registerTask('default', ['changelog']); };
bheiskell/HungerRain
changelog/Gruntfile.js
JavaScript
mit
800
import Class from '../mixin/class'; import Media from '../mixin/media'; import {$, addClass, after, Animation, assign, attr, css, fastdom, hasClass, isNumeric, isString, isVisible, noop, offset, offsetPosition, query, remove, removeClass, replaceClass, scrollTop, toFloat, toggleClass, toPx, trigger, within} from 'uikit-util'; export default { mixins: [Class, Media], props: { top: null, bottom: Boolean, offset: String, animation: String, clsActive: String, clsInactive: String, clsFixed: String, clsBelow: String, selTarget: String, widthElement: Boolean, showOnUp: Boolean, targetOffset: Number }, data: { top: 0, bottom: false, offset: 0, animation: '', clsActive: 'uk-active', clsInactive: '', clsFixed: 'uk-sticky-fixed', clsBelow: 'uk-sticky-below', selTarget: '', widthElement: false, showOnUp: false, targetOffset: false }, computed: { offset({offset}) { return toPx(offset); }, selTarget({selTarget}, $el) { return selTarget && $(selTarget, $el) || $el; }, widthElement({widthElement}, $el) { return query(widthElement, $el) || this.placeholder; }, isActive: { get() { return hasClass(this.selTarget, this.clsActive); }, set(value) { if (value && !this.isActive) { replaceClass(this.selTarget, this.clsInactive, this.clsActive); trigger(this.$el, 'active'); } else if (!value && !hasClass(this.selTarget, this.clsInactive)) { replaceClass(this.selTarget, this.clsActive, this.clsInactive); trigger(this.$el, 'inactive'); } } } }, connected() { this.placeholder = $('+ .uk-sticky-placeholder', this.$el) || $('<div class="uk-sticky-placeholder"></div>'); this.isFixed = false; this.isActive = false; }, disconnected() { if (this.isFixed) { this.hide(); removeClass(this.selTarget, this.clsInactive); } remove(this.placeholder); this.placeholder = null; this.widthElement = null; }, events: [ { name: 'load hashchange popstate', el: window, handler() { if (!(this.targetOffset !== false && location.hash && window.pageYOffset > 0)) { return; } const target = $(location.hash); if (target) { fastdom.read(() => { const {top} = offset(target); const elTop = offset(this.$el).top; const elHeight = this.$el.offsetHeight; if (this.isFixed && elTop + elHeight >= top && elTop <= top + target.offsetHeight) { scrollTop(window, top - elHeight - (isNumeric(this.targetOffset) ? this.targetOffset : 0) - this.offset); } }); } } } ], update: [ { read({height}, type) { if (this.isActive && type !== 'update') { this.hide(); height = this.$el.offsetHeight; this.show(); } height = !this.isActive ? this.$el.offsetHeight : height; this.topOffset = offset(this.isFixed ? this.placeholder : this.$el).top; this.bottomOffset = this.topOffset + height; const bottom = parseProp('bottom', this); this.top = Math.max(toFloat(parseProp('top', this)), this.topOffset) - this.offset; this.bottom = bottom && bottom - height; this.inactive = !this.matchMedia; return { lastScroll: false, height, margins: css(this.$el, ['marginTop', 'marginBottom', 'marginLeft', 'marginRight']) }; }, write({height, margins}) { const {placeholder} = this; css(placeholder, assign({height}, margins)); if (!within(placeholder, document)) { after(this.$el, placeholder); attr(placeholder, 'hidden', ''); } // ensure active/inactive classes are applied this.isActive = this.isActive; }, events: ['resize'] }, { read({scroll = 0}) { this.width = (isVisible(this.widthElement) ? this.widthElement : this.$el).offsetWidth; this.scroll = window.pageYOffset; return { dir: scroll <= this.scroll ? 'down' : 'up', scroll: this.scroll, visible: isVisible(this.$el), top: offsetPosition(this.placeholder)[0] }; }, write(data, type) { const {initTimestamp = 0, dir, lastDir, lastScroll, scroll, top, visible} = data; const now = performance.now(); data.lastScroll = scroll; if (scroll < 0 || scroll === lastScroll || !visible || this.disabled || this.showOnUp && type !== 'scroll') { return; } if (now - initTimestamp > 300 || dir !== lastDir) { data.initScroll = scroll; data.initTimestamp = now; } data.lastDir = dir; if (this.showOnUp && Math.abs(data.initScroll - scroll) <= 30 && Math.abs(lastScroll - scroll) <= 10) { return; } if (this.inactive || scroll < this.top || this.showOnUp && (scroll <= this.top || dir === 'down' || dir === 'up' && !this.isFixed && scroll <= this.bottomOffset) ) { if (!this.isFixed) { if (Animation.inProgress(this.$el) && top > scroll) { Animation.cancel(this.$el); this.hide(); } return; } this.isFixed = false; if (this.animation && scroll > this.topOffset) { Animation.cancel(this.$el); Animation.out(this.$el, this.animation).then(() => this.hide(), noop); } else { this.hide(); } } else if (this.isFixed) { this.update(); } else if (this.animation) { Animation.cancel(this.$el); this.show(); Animation.in(this.$el, this.animation).catch(noop); } else { this.show(); } }, events: ['resize', 'scroll'] } ], methods: { show() { this.isFixed = true; this.update(); attr(this.placeholder, 'hidden', null); }, hide() { this.isActive = false; removeClass(this.$el, this.clsFixed, this.clsBelow); css(this.$el, {position: '', top: '', width: ''}); attr(this.placeholder, 'hidden', ''); }, update() { const active = this.top !== 0 || this.scroll > this.top; let top = Math.max(0, this.offset); if (this.bottom && this.scroll > this.bottom - this.offset) { top = this.bottom - this.scroll; } css(this.$el, { position: 'fixed', top: `${top}px`, width: this.width }); this.isActive = active; toggleClass(this.$el, this.clsBelow, this.scroll > this.bottomOffset); addClass(this.$el, this.clsFixed); } } }; function parseProp(prop, {$props, $el, [`${prop}Offset`]: propOffset}) { const value = $props[prop]; if (!value) { return; } if (isNumeric(value) && isString(value) && value.match(/^-?\d/)) { return propOffset + toPx(value); } else { return offset(value === true ? $el.parentNode : query(value, $el)).bottom; } }
RadialDevGroup/rails-uikit-sass
vendor/assets/js/core/sticky.js
JavaScript
mit
8,774
const fs = require('fs') const getLanguages = require('./private/getLanguages') const checkExistance = require('./private/checkExistance') const getThisDir = require('./private/getThisDir') const thisDir = getThisDir(module.parent.filename) const configDir = thisDir + '/i18n-tracker.config.json' const config = JSON.parse(fs.readFileSync(configDir, 'utf8')) function getTranslations() { const translations = getLanguages(config.translations) const baseExist = checkExistance(thisDir,[config.base]) const allExist = checkExistance(thisDir, translations) let returnObj = {} if(allExist && baseExist){ const base = require(`${thisDir}\\${config.base[0]}`) returnObj[config.base[0]] = base translations.forEach((translation) => { const thisTrans = require(`${thisDir}\\${translation[0]}`) returnObj[translation[0]] = thisTrans }) } return returnObj } module.exports = { getTranslations: getTranslations }
kesupile/I18n-tracker
index.js
JavaScript
mit
953
// app/models/article.js var Mongoose = require('mongoose'); // define article schema var articleSchema = Mongoose.Schema({ url: { type: String, required: true }, tags: [String], userId: { type: String, required: true }, meta: { title: String, author: String, readTime: String, summary: String, domain: String, createdAt: { type: Date, default: Date.now }, starred: { type: Boolean, default: false }, archived: { type: Boolean, default: false } }, content: { html: String, text: String } }); module.exports = Mongoose.model('Article', articleSchema);
isaacev/Ink
app/models/article.js
JavaScript
mit
615
const webModel = require('../webModel'); const webModelFunctions = require('../webModelFunctions'); const robotModel = require('../robotModel'); const getCmdVelIdleTime = require('../getCmdVelIdleTime'); const WayPoints = require('../WayPoints.js'); const wayPointEditor = new WayPoints(); function pickRandomWaypoint() { if (webModel.debugging && webModel.logBehaviorMessages) { const message = ' - Checking: Random Waypoint Picker'; console.log(message); webModelFunctions.scrollingStatusUpdate(message); } if ( webModel.ROSisRunning && webModel.wayPoints.length > 1 && // If we only have 1, it hardly works. webModel.mapName !== '' && !webModel.pluggedIn && !webModel.wayPointNavigator.goToWaypoint && !robotModel.goToWaypointProcess.started && getCmdVelIdleTime() > 2 // TODO: Set this time in a config or something. // TODO: Also make it 5 once we are done debugging. ) { if (webModel.debugging && webModel.logBehaviorMessages) { console.log(` - Picking a random waypoint!`); } if (robotModel.randomWaypointList.length === 0) { robotModel.randomWaypointList = [...webModel.wayPoints]; } // Remove most recent waypoint from list in case this was a list reload. if (robotModel.randomWaypointList.length > 1) { const lastWaypointEntry = robotModel.randomWaypointList.indexOf( webModel.wayPointNavigator.wayPointName, ); if (lastWaypointEntry > -1) { robotModel.randomWaypointList.splice(lastWaypointEntry, 1); } } // Pick a random entry from the list. const randomEntryIndex = Math.floor( Math.random() * robotModel.randomWaypointList.length, ); // Set this as the new waypoint, just like user would via web site, // and remove it from our list. if (webModel.debugging && webModel.logBehaviorMessages) { console.log(` - ${robotModel.randomWaypointList[randomEntryIndex]}`); } wayPointEditor.goToWaypoint( robotModel.randomWaypointList[randomEntryIndex], ); robotModel.randomWaypointList.splice(randomEntryIndex, 1); // Preempt remaining functions, as we have an action to take now. return false; } // This behavior is idle, allow behave loop to continue to next entry. return true; } module.exports = pickRandomWaypoint;
chrisl8/ArloBot
node/behaviors/pickRandomWaypoint.js
JavaScript
mit
2,341
/** * Created by zhibo on 15-8-20. */ /* * 上传图片插件改写 * @author: * @data: 2013年2月17日 * @version: 1.0 * @rely: jQuery */ $(function(){ /* * 参数说明 * baseUrl: 【字符串】表情路径的基地址 */ var lee_pic = { uploadTotal : 0, uploadLimit : 8, //最多传多少张 uploadify:function(){ //文件上传测试 $('#file').uploadify({ swf : 'http://ln.localhost.com/static/uploadify/uploadify.swf', uploader : '', width : 120, height : 30, fileTypeDesc : '图片类型', buttonCursor:'pointer', buttonText:'上传图片', fileTypeExts : '*.jpeg; *.jpg; *.png; *.gif', fileSizeLimit : '1MB', overrideEvents : ['onSelectError','onSelect','onDialogClose'], //错误替代 onSelectError : function (file, errorCode, errorMsg) { switch (errorCode) { case -110 : $('#error').dialog('open').html('超过1024KB...'); setTimeout(function () { $('#error').dialog('close').html('...'); }, 1000); break; } }, //开始上传前 onUploadStart : function () { if (lee_pic.uploadTotal == 8) { $('#file').uploadify('stop'); $('#file').uploadify('cancel'); $('#error').dialog('open').html('限制为8张...'); setTimeout(function () { $('#error').dialog('close').html('...'); }, 1000); } else { $('.weibo_pic_list').append('<div class="weibo_pic_content"><span class="remove"></span><span class="text">删除</span><img src="' + ThinkPHP['IMG'] + '/loading_100.png" class="weibo_pic_img"></div>'); } }, //上传成功后的函数 onUploadSuccess : function (file, data, response) { // alert(data); //打印出返回的数据 $('.weibo_pic_list').append('<input type="hidden" name="images" value='+ data +'> ') var imageUrl= $.parseJSON(data); /* data是返回的回调信息alert file上传的图片信息 用console.log(file);测试 response上传成功与否 alert alert(response); alert(data); $('.weibo_pic_list').append('<div class="weibo_pic_content"><span class="remove"></span><span class="text">删除</span><img src="' + ThinkPHP['IMG'] + '/loading_100.png" class="weibo_pic_img"></div>'); //把上传的图片返回的缩略图结果写入html页面中 */ lee_pic.thumb(imageUrl['thumb']); //执行缩略图显示问题 lee_pic.hover(); lee_pic.remove(); //共 0 张,还能上传 8 张(按住ctrl可选择多张 lee_pic.uploadTotal++; lee_pic.uploadLimit--; $('.weibo_pic_total').text(lee_pic.uploadTotal); $('.weibo_pic_limit').text(lee_pic.uploadLimit); } }); }, hover:function(){ //上传图片鼠标经过显示删除按扭 var content=$('.weibo_pic_content'); var len=content.length; $(content[len - 1]).hover(function(){ $(this).find('.remove').show(); $(this).find('.text').show(); },function(){ $(this).find('.remove').hide(); $(this).find('.text').hide(); }); }, remove:function(){ //删除上传的图片操作 var remove=$('.weibo_pic_content .text'); var removelen=remove.length; $(remove[removelen-1]).on('click',function(){ $(this).parent('.weibo_pic_content').next('input[name="images"]').remove(); $(this).parents('.weibo_pic_content').remove(); //共 0 张,还能上传 8 张(按住ctrl可选择多张 lee_pic.uploadTotal--; lee_pic.uploadLimit++; $('.weibo_pic_total').text(lee_pic.uploadTotal); $('.weibo_pic_limit').text(lee_pic.uploadLimit); }); }, thumb : function (src) { /*调节缩略图显示问题-即不以中心点为起点显示*/ var img = $('.weibo_pic_img'); var len = img.length; //alert(src); $(img[len - 1]).attr('src', ThinkPHP['LOCALNAME']+src).hide(); setTimeout(function () { if ($(img[len - 1]).width() > 100) { $(img[len - 1]).css('left', -($(img[len - 1]).width() - 100) / 2); } if ($(img[len - 1]).height() > 100) { $(img[len - 1]).css('top', -($(img[len - 1]).height() - 100) / 2); } //记图片淡入淡出 $(img[len - 1]).attr('src', ThinkPHP['LOCALNAME']+src).fadeIn(); }, 50); }, init:function(){ /*绑定上传图片弹出按钮响应,初始化。*/ //绑定uploadify函数 lee_pic.uploadify(); /*绑定关闭按钮*/ $('#pic_box a.close').on('click',function(){ $('#pic_box').hide(); $('.pic_arrow_top').hide(); }); /*绑定document点击事件,对target不在上传图片弹出框上时执行引藏事件 //由于鼠标离开窗口就会关闭,影响使用,所以取消 $(document).on('click',function(e){ var target = $(e.target); if( target.closest("#pic_btn").length == 1 || target.closest(".weibo_pic_content .text").length == 1) return; if( target.closest("#pic_box").length == 0 ){ $('#pic_box').hide(); $('.pic_arrow_top').hide(); } }); */ } }; lee_pic.init(); //调用初始化函数。 window.uploadCount = { clear : function () { lee_pic.uploadTotal = 0; lee_pic.uploadLimit = 8; } }; });
zl0314/ruida
static/js/lee_pic.js
JavaScript
mit
6,916
'use strict'; $(function() { $('a.page-scroll').bind('click', function(event) { var $anchor = $(this); $('html, body').stop().animate({ scrollTop: $($anchor.attr('href')).offset().top }, 1750, 'easeInOutSine'); event.preventDefault(); }); });
mskalandunas/parcel
app/js/lib/smooth_scroll.js
JavaScript
mit
270
// @flow import React, { Component } from 'react' import Carousel, { Modal, ModalGateway } from '../../../../src/components' import { videos } from './data' import { Poster, Posters } from './Poster' import View from './View' import { Code, Heading } from '../../components' type Props = {} type State = { currentModal: number | null } export default class AlternativeMedia extends Component<Props, State> { state = { currentModal: null } toggleModal = (index: number | null = null) => { this.setState({ currentModal: index }) } render() { const { currentModal } = this.state return ( <div> <Heading source="/CustomComponents/AlternativeMedia/index.js">Alternative Media</Heading> <p> In this example the data passed to <Code>views</Code> contains source and poster information. The <Code>&lt;View /&gt;</Code> component has been replaced to render an HTML5 video tag and custom controls. </p> <p> Videos courtesy of{' '} <a href="https://peach.blender.org/" target="_blank"> "Big Buck Bunny" </a>{' '} and{' '} <a href="https://durian.blender.org/" target="_blank"> "Sintel" </a> </p> <Posters> {videos.map((vid, idx) => ( <Poster key={idx} data={vid} onClick={() => this.toggleModal(idx)} /> ))} </Posters> <ModalGateway> {Number.isInteger(currentModal) ? ( <Modal allowFullscreen={false} closeOnBackdropClick={false} onClose={this.toggleModal}> <Carousel currentIndex={currentModal} components={{ Footer: null, View }} views={videos} /> </Modal> ) : null} </ModalGateway> </div> ) } }
jossmac/react-images
docs/pages/CustomComponents/AlternativeMedia/index.js
JavaScript
mit
1,796
define(['react', 'lodash', './searchView.rt'], function (React, _, template) { 'use strict'; var exactMatchFieldNames = ['type', 'topic']; var partialMatchFieldNames = ['title']; return React.createClass({ displayName: 'searchView', propTypes: { configData: React.PropTypes.object.isRequired, bricksData: React.PropTypes.array.isRequired }, getInitialState: function(){ return { type: '', title: '', topic: '' }; }, getSearchResults: function(){ var bricks = this.props.bricksData; var exactMatchFields = _.pick(this.state, function(value, key){ return _.includes(exactMatchFieldNames, key) && value; }); var partialMatchFields = _.pick(this.state, partialMatchFieldNames); var results = _.filter(bricks, function(brick){ var result = true; _.forEach(exactMatchFields, function(value, key){ if (brick[key] !== value){ result = false; } }); _.forEach(partialMatchFields, function(value, key){ if (!_.includes(brick[key], value)){ result = false; } }); return result; }); return results; }, linkState: function (propName) { return { value: this.state[propName], requestChange: function (value) { var newState = _.clone(this.state); newState[propName] = value; if (this.state[propName] !== value){ this.setState(newState); } }.bind(this) }; }, getResultWrapperClasses: function(result){ return { 'result-wrapper': true, 'selected': result.selected }; }, render: template }); });
rommguy/merkaz-hadraha
src/main/webapp/client/views/searchView.js
JavaScript
mit
2,152
// Karma configuration file, see link for more information // https://karma-runner.github.io/1.0/config/configuration-file.html module.exports = function (config) { config.set({ basePath: '', frameworks: ['jasmine', '@angular-devkit/build-angular'], plugins: [ require('karma-jasmine'), require('karma-chrome-launcher'), require('karma-jasmine-html-reporter'), require('karma-coverage-istanbul-reporter'), require('@angular-devkit/build-angular/plugins/karma') ], client: { clearContext: false // leave Jasmine Spec Runner output visible in browser }, coverageIstanbulReporter: { dir: require('path').join(__dirname, '../../coverage/test-app'), reports: ['html', 'lcovonly', 'text-summary'], fixWebpackSourcePaths: true }, reporters: ['progress', 'kjhtml'], port: 9876, colors: true, logLevel: config.LOG_INFO, autoWatch: true, browsers: ['ChromeHeadless'], singleRun: false, restartOnFileChange: true }); };
salemdar/ngx-cookie
projects/test-app/karma.conf.js
JavaScript
mit
1,032
import Ember from 'ember'; export default Ember.Route.extend({ model(params) { let zipcode = params.zipcode || '97212'; let zipcode2 = params.zipcode2 || '98074'; return Ember.RSVP.hash({ first_location: $.getJSON(`https://api.wunderground.com/api/13fcb02d16148708/conditions/forecast/q/${zipcode}.json`).then(function(data) { data.forecast.days = data.forecast.simpleforecast.forecastday.slice(1,4); return data; }), second_location: $.getJSON(`https://api.wunderground.com/api/13fcb02d16148708/conditions/forecast/q/${zipcode2}.json`).then(function(data) { data.forecast.days = data.forecast.simpleforecast.forecastday.slice(1,4); return data; }) }); }, afterModel: function(model) { model.temperature_difference = Math.abs(parseFloat(model.second_location.current_observation.temp_f - model.first_location.current_observation.temp_f).toFixed(2)); }, actions: { updateZip(model) { this.transitionTo('index', model.first_location.current_observation.display_location.zip, model.second_location.current_observation.display_location.zip); } } });
gpxl/simple-weather-ember
app/routes/index.js
JavaScript
mit
1,151
/* The MIT License Copyright (c) 2010-2011 Ibon Tolosana [@hyperandroid] 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. Version: 0.1 build: 54 Created on: DATE: 2011-10-27 TIME: 23:44:43 */ (function(){CAAT.B2DBodyActor=function(){CAAT.B2DBodyActor.superclass.constructor.call(this);return this};CAAT.B2DBodyActor.prototype={restitution:0.5,friction:0.5,density:1,bodyType:Box2D.Dynamics.b2Body.b2_dynamicBody,worldBody:null,world:null,worldBodyFixture:null,bodyDef:null,fixtureDef:null,bodyData:null,recycle:false,setRecycle:function(){this.recycle=true;return this},destroy:function(){CAAT.B2DBodyActor.superclass.destroy.call(this);if(this.recycle)this.setLocation(-Number.MAX_VALUE,-Number.MAX_VALUE), this.setAwake(false);else{var c=this.worldBody;c.DestroyFixture(this.worldBodyFixture);this.world.DestroyBody(c)}return this},setAwake:function(c){this.worldBody.SetAwake(c);return this},setSleepingAllowed:function(c){this.worldBody.SetSleepingAllowed(c);return this},setLocation:function(c,a){this.worldBody.SetPosition(new Box2D.Common.Math.b2Vec2((c+this.width/2)/CAAT.PMR,(a+this.height/2)/CAAT.PMR));return this},setDensity:function(c){this.density=c;return this},setFriction:function(c){this.friction= c;return this},setRestitution:function(c){this.restitution=c;return this},setBodyType:function(c){this.bodyType=c;return this},check:function(c,a,b){c[a]||(c[a]=b)},createBody:function(c,a){if(a)this.check(a,"density",1),this.check(a,"friction",0.5),this.check(a,"restitution",0.2),this.check(a,"bodyType",Box2D.Dynamics.b2Body.b2_staticBody),this.check(a,"userData",{}),this.check(a,"image",null),this.density=a.density,this.friction=a.friction,this.restitution=a.restitution,this.bodyType=a.bodyType, this.image=a.image;this.world=c;return this},getCenter:function(){return{x:0,y:0}},getDistanceJointLocalAnchor:function(){return{x:0,y:0}}};extend(CAAT.B2DBodyActor,CAAT.Actor)})(); (function(){CAAT.B2DPolygonBody=function(){CAAT.B2DPolygonBody.superclass.constructor.call(this);return this};CAAT.B2DPolygonBody.Type={EDGE:"edge",BOX:"box",POLYGON:"polygon"};CAAT.B2DPolygonBody.prototype={boundingBox:null,getDistanceJointLocalAnchor:function(){return this.worldBody.GetFixtureList().GetShape().m_centroid},getCenter:function(){var c=this.worldBody,a=c.m_xf,c=c.GetFixtureList().GetShape();return Box2D.Common.Math.b2Math.MulX(a,c.m_centroid)},animate:function(c,a){var b=this.worldBody, d=b.m_xf,e=this.worldBodyFixture.GetShape();e&&(d=Box2D.Common.Math.b2Math.MulX(d,e.m_centroid),CAAT.Actor.prototype.setLocation.call(this,d.x*CAAT.PMR-this.width/2,d.y*CAAT.PMR-this.height/2),this.setRotation(b.GetAngle()));return CAAT.B2DPolygonBody.superclass.animate.call(this,c,a)},createBody:function(c,a){CAAT.B2DPolygonBody.superclass.createBody.call(this,c,a);var b=CAAT.B2DPolygonBody.createPolygonBody(c,a);a.userData.actor=this;this.worldBody=b.worldBody;this.worldBodyFixture=b.worldBodyFixture; this.fixtureDef=b.fixDef;this.bodyDef=b.bodyDef;this.bodyData=a;this.boundingBox=b.boundingBox;this.setBackgroundImage(a.image).setSize(b.boundingBox[1].x-b.boundingBox[0].x+1,b.boundingBox[1].y-b.boundingBox[0].y+1).setFillStyle(b.worldBodyFixture.IsSensor()?"red":"green").setImageTransformation(CAAT.ImageActor.prototype.TR_FIXED_TO_SIZE);return this}};CAAT.B2DPolygonBody.createPolygonBody=function(c,a){var b=new Box2D.Dynamics.b2FixtureDef;b.density=a.density;b.friction=a.friction;b.restitution= a.restitution;b.shape=new Box2D.Collision.Shapes.b2PolygonShape;var d=Number.MAX_VALUE,e=-Number.MAX_VALUE,g=Number.MAX_VALUE,j=-Number.MAX_VALUE,k=[],l=a.bodyDefScale||1;l+=(a.bodyDefScaleTolerance||0)*Math.random();for(var f=0;f<a.bodyDef.length;f++){var h=a.bodyDef[f].x*l,i=a.bodyDef[f].y*l;h<d&&(d=h);h>e&&(e=h);i<g&&(g=i);i>j&&(j=i);h+=a.x||0;i+=a.y||0;k.push(new Box2D.Common.Math.b2Vec2(h/CAAT.PMR,i/CAAT.PMR))}l=[{x:d,y:g},{x:e,y:j}];f=new Box2D.Dynamics.b2BodyDef;f.type=a.bodyType;if(a.polygonType=== CAAT.B2DPolygonBody.Type.EDGE)b.shape.SetAsEdge(k[0],k[1]);else if(a.polygonType===CAAT.B2DPolygonBody.Type.BOX)b.shape.SetAsBox((e-d)/2/CAAT.PMR,(j-g)/2/CAAT.PMR),f.position.x=((e-d)/2+(a.x||0))/CAAT.PMR,f.position.y=((j-g)/2+(a.y||0))/CAAT.PMR;else if(a.polygonType===CAAT.B2DPolygonBody.Type.POLYGON)b.shape.SetAsArray(k,k.length);else throw"Unkown bodyData polygonType: "+a.polygonType;b.userData=a.userData;f.userData=a.userData;d=c.CreateBody(f);e=d.CreateFixture(b);a.isSensor&&e.SetSensor(true); return{worldBody:d,worldBodyFixture:e,fixDef:b,bodyDef:f,boundingBox:l}};extend(CAAT.B2DPolygonBody,CAAT.B2DBodyActor)})(); (function(){CAAT.B2DCircularBody=function(){CAAT.B2DCircularBody.superclass.constructor.call(this);return this};CAAT.B2DCircularBody.prototype={radius:1,getDistanceJointLocalAnchor:function(){return new Box2D.Common.Math.b2Vec2(0,0)},getCenter:function(){return this.worldBody.m_xf.position},animate:function(c,a){var b=this.worldBody,d=b.m_xf;CAAT.Actor.prototype.setLocation.call(this,CAAT.PMR*d.position.x-this.width/2,CAAT.PMR*d.position.y-this.height/2);this.setRotation(b.GetAngle());return CAAT.B2DCircularBody.superclass.animate.call(this, c,a)},createBody:function(c,a){var b=a.radius||1;b+=(a.bodyDefScaleTolerance||0)*Math.random();a.radius=b;CAAT.B2DCircularBody.superclass.createBody.call(this,c,a);if(a.radius)this.radius=a.radius;b=new Box2D.Dynamics.b2FixtureDef;b.density=this.density;b.friction=this.friction;b.restitution=this.restitution;b.shape=new Box2D.Collision.Shapes.b2CircleShape(this.radius/CAAT.PMR);var d=new Box2D.Dynamics.b2BodyDef;d.type=this.bodyType;d.position.x=a.x/CAAT.PMR;d.position.y=a.y/CAAT.PMR;a.userData.actor= this;b.userData=a.userData;d.userData=a.userData;var e=c.CreateBody(d),g=e.CreateFixture(b);a.isSensor&&g.SetSensor(true);this.worldBody=e;this.worldBodyFixture=g;this.fixtureDef=b;this.bodyDef=d;this.bodyData=a;this.setFillStyle(this.worldBodyFixture.IsSensor()?"red":"blue").setBackgroundImage(this.image).setSize(2*this.radius,2*this.radius).setImageTransformation(CAAT.ImageActor.prototype.TR_FIXED_TO_SIZE);return this}};extend(CAAT.B2DCircularBody,CAAT.B2DBodyActor)})();
Irrelon/CAAT
build/caat-box2d-min.js
JavaScript
mit
7,074
(function () { 'use strict'; angular .module('starter-app') .run(['$window', function ($window) { $window.proj4 = require('proj4'); }]); })();
OrdnanceSurvey/web-elements-starter
src/app/app.constants.js
JavaScript
mit
187
"use strict"; define([ 'lodash', 'jquery', 'jquery-ui/ui/autocomplete', 'deckslots/cardstore' ], function(_, $, autocomplete, CardStore) { var CardSelector = function (conf) { this.domNode = conf.domNode; this.onSelectCallback = conf.onSelect; this.cardSource = []; var that = this; this.loadCards(function () { that.domNode.autocomplete({ source: that.cardSource, focus: function(event, ui) { that.domNode.val(ui.item.label); return false; }, select: function(event, ui) { that.onSelectCallback(event, ui); that.domNode.val(''); return false; } }); }) }; CardSelector.prototype.loadCards = function (callback) { var that = this; _.forEach(CardStore.cards, function(card) { that.cardSource.push({ label : card.name, value : card.id, card: card }); }); callback(); }; return CardSelector; });
hodavidhara/deckslots
static/js/deckslots/cardselector.js
JavaScript
mit
1,188
for(_="taz'+qadd@=a.Z0,Wre!SCALE6void(~trans%[1]+'$=\"qc`.map(_',^0 K!turnJ){JIentRdelzQ/)&&(QPelmSvgO),100W5K75,^'fill: # 1075function+)/g,(,K5W0zngramZpagepolygon[0]ate(a){mousevar 25 25,25Zzrget touch points c!SVG( W 5W5000c.match(/'],['.!place(/szrtetAttribute('active%l aI'<svg viewBox=\"KKK800\">qa_(cI'< `+'\" style`$\"/>'}).join('')+'</svg>'}=null,Q,,=rot='^m=window.m=cZtype,dX,eY,g=1;J''=.zgName&&r|w/)?(,~=[d,e])):~&&(vP=[d-,e-[1]],='(qQ+^qQ$)'p|ndP?(='^.s ^.g ')([\\d.]hI+h+Q[g?g=0:g=1]})Q==0):console.log('click')a.p!vRDefault(.s%form^+'qrot||(=0)))},6=2.5,=[['WK1f3fW 1074D9,7FDBFF,5K39CCCC5253D997052ECC400 75,01FF70']]_J a=a(\\dcI c*6}a}); @(a,c,d){e=documR.c!ElemR(a);J e.innerHTML=c,d.p!pend(ee}O=@('div^ b);'down move up  end move'\\w+/g,O.@EvRListener(a,m)});";G=/[-O-RI-K^-`$%~6!WZ@qz]/.exec(_);)with(_.split(G))_=join(shift());eval(_)
ripter/js1k
2017/dragdrop/914_code_babili_rp.js
JavaScript
mit
986
/** * Code derived from Leaflet.heat by Vladimir Agafonkin (2-clause BSD License) * https://github.com/Leaflet/Leaflet.heat/blob/gh-pages/src/HeatLayer.js */ L.CanvasLayer = (L.Layer ? L.Layer : L.Class).extend({ redraw: function () { if (this._heat && !this._frame && !this._map._animating) { this._frame = L.Util.requestAnimFrame(this._redraw, this); } this._redraw(); return this; }, _redraw: function () { throw 'implement in subclass'; this._frame = null; }, onAdd: function (map) { this._map = map; if (!this._canvas) { this._initCanvas(); } map._panes.overlayPane.appendChild(this._canvas); map.on('moveend', this._reset, this); if (map.options.zoomAnimation && L.Browser.any3d) { map.on('zoomanim', this._animateZoom, this); } this._reset(); }, onRemove: function (map) { map.getPanes().overlayPane.removeChild(this._canvas); map.off('moveend', this._reset, this); if (map.options.zoomAnimation) { map.off('zoomanim', this._animateZoom, this); } }, addTo: function (map) { map.addLayer(this); return this; }, _initCanvas: function () { var canvas = this._canvas = L.DomUtil.create('canvas', 'leaflet-bil-layer leaflet-layer'); var size = this._map.getSize(); canvas.width = size.x; canvas.height = size.y; // TODO subclass L.DomUtil.setOpacity(canvas, this.options.opacity); var animated = this._map.options.zoomAnimation && L.Browser.any3d; L.DomUtil.addClass(canvas, 'leaflet-zoom-' + (animated ? 'animated' : 'hide')); }, _reset: function () { var topLeft = this._map.containerPointToLayerPoint([0, 0]); L.DomUtil.setPosition(this._canvas, topLeft); var size = this._map.getSize(); if (this._canvas.width !== size.x) { this._canvas.width = size.x; } if (this._canvas.height !== size.y) { this._canvas.height = size.y; } this._redraw(); }, _animateZoom: function (e) { var scale = this._map.getZoomScale(e.zoom), offset = this._map._getCenterOffset(e.center)._multiplyBy(-scale).subtract(this._map._getMapPanePos()); if (L.DomUtil.setTransform) { L.DomUtil.setTransform(this._canvas, offset, scale); } else { this._canvas.style[L.DomUtil.TRANSFORM] = L.DomUtil.getTranslateString(offset) + ' scale(' + scale + ')'; } } });
nrenner/leaflet-raw-dem
js/CanvasLayer.js
JavaScript
mit
2,656
import Ember from 'ember'; export default Ember.Route.extend({ model() { const eventRecord = this.store.createRecord('event'); const openingTier = this.store.createRecord('opening-tier'); eventRecord.set('openingTier', openingTier); return eventRecord; }, actions: { didTransition() { this.set('title', 'Create new Event'); return true; } } });
NullVoxPopuli/aeonvera-ui
app/pods/events/new/route.js
JavaScript
mit
392
$(document).ready( function () { var Counter = Backbone.Model.extend({ defaults : {"value" : 0}, inc : function () { var val = this.get("value"); this.set("value", val+1); } }); var CounterView = Backbone.View.extend({ render: function () { var val = this.model.get("value"); var btn = '<button>Increment</button>'; this.$el.html('<p>'+val+'</p>' + btn); }, initialize: function () { this.model.on("change", this.render, this); }, events : { 'click button' : 'increment' }, increment : function () { this.model.inc(); } }); var counterModel = new Counter(); var counterView1 = new CounterView({model : counterModel}); var counterView2 = new CounterView({model : counterModel}); counterView1.render(); counterView2.render(); $("#counterdiv").append(counterView1.$el); $("#counterdiv").append(counterView2.$el); });
clarissalittler/backbone-tutorials
counterMulti.js
JavaScript
mit
1,026
"use strict"; var Client_1 = require('./src/helpers/Client'); exports.Client = Client_1.Client; //# sourceMappingURL=index.js.map
alormil/put.io-node
js/ts/index.js
JavaScript
mit
129
(function() { angular.module('signup', [ 'userServiceMod' ]) .controller('SignupCtrl', ['$location', 'userService', 'validator', function($location, userService, validator) { var signup = this; signup.buttonEnabled = true; signup.err = { username: "", email: "", password: "", server: "" }; signup.data = { username: "", email: "", password: "" }; signup.submit = function() { if (!signup.buttonEnabled) { return; } var errors = null; // reset err messages signup.err.username = ""; signup.err.email = ""; signup.err.password = ""; signup.err.server = ""; // check validity of data errors = validator('user', signup.data, ['username', 'email', 'password']); if (errors) { signup.err = errors; return; } // disable submit button signup.buttonEnabled = false; userService.signup(signup.data, function(err, data) { if (err) { // enable submit button signup.buttonEnabled = true; if (err.status === 400) { // email or username already in use signup.err.server = err.data.error; } else { signup.err.server = "There was a problem with the server. Please try again."; } return; } // redirect to user's page $location.path('/' + userService.getUser().username); }); }; }]); })();
BYossarian/focus
public/js/controllers/signup.js
JavaScript
mit
2,063
'use strict'; angular.module('spc') .factory('Auth', function Auth($location, $rootScope, $http, User, CremaAuth, spcServerUrl, apiKey, $cookieStore, $q) { var currentMetaData = {}; if ($cookieStore.get('access_token')) { currentMetaData = CremaAuth.get(); } return { /** * Authenticate user and save token * * @param {Object} user - login info * @param {Function} callback - optional * @return {Promise} */ login: function (user) { var deferred = $q.defer(); $http.post(spcServerUrl + '/api/auth/login', { apikey: apiKey, email: user.email, password: user.password }). success(function (data) { if (data.secondFactor) { currentMetaData = data; deferred.resolve(data); } else { $cookieStore.put('access_token', data.access_token); currentMetaData = CremaAuth.get(null, function () { deferred.resolve(data); }, function (error) { deferred.reject(error.data); }); } }). error(function (err) { this.logout(); deferred.reject(err); }.bind(this)); return deferred.promise; }, loginLdap: function (user) { var deferred = $q.defer(); $http.post(spcServerUrl + '/api/auth/ldap', { email: user.email, password: user.password }). success(function (data) { if (data.secondFactor) { currentMetaData = data; deferred.resolve(data); } else { $cookieStore.put('access_token', data.access_token); currentMetaData = CremaAuth.get(null, function () { deferred.resolve(data); }, function (error) { deferred.reject(error.data); }); } }). error(function (err) { this.logout(); deferred.reject(err); }.bind(this)); return deferred.promise; }, loginGoogle: function (accessToken, user) { var deferred = $q.defer(); if (user.secondFactor) { currentMetaData = user; currentMetaData.$promise = '&promise'; deferred.resolve(currentMetaData); } else { $cookieStore.put('access_token', accessToken); currentMetaData = CremaAuth.get(null, function() { deferred.resolve(); }, function (error) { deferred.reject(error.data); }); } return deferred.promise; }, /** * Delete access token and user info * * @param {Function} */ logout: function () { $cookieStore.remove('access_token'); currentMetaData = {}; }, /** * Create a new user * * @param {Object} user - user info * @param {Function} callback - optional * @return {Promise} */ createUser: function (user) { var deferred = $q.defer(); console.debug("client auth.service.js createUser", "userData", user); User.save(user).$promise.then(function (data) { console.debug("client auth.service.js.createUser", "success", data); $cookieStore.put('access_token', data.access_token); return CremaAuth.get({id: currentMetaData._id}).$promise; }).then(function (cremaUser) { currentMetaData = cremaUser; deferred.resolve(cremaUser) }).catch(function (err) { console.debug("client auth.service.js createUser", "failed", err); deferred.reject(err); } ); return deferred.promise; }, /** * Change password * * @param {String} oldPassword * @param {String} newPassword * @param {Function} callback - optional * @return {Promise} */ changePassword: function (oldPassword, newPassword, callback) { var cb = callback || angular.noop; return User.changePassword({id: currentMetaData._id}, { oldPassword: oldPassword, newPassword: newPassword }, function (user) { return cb(user); }, function (err) { return cb(err); }).$promise; }, /** * Gets all available info on authenticated user / entity * * @return {Object} user */ getCurrentMetaData: function () { return currentMetaData; }, setCurrentMetaData: function (metaData) { currentMetaData = metaData; }, /** * Check if a user is logged in * * @return {Boolean} */ isLoggedIn: function () { return $cookieStore.get('access_token'); }, /** * Waits for currentMetaData to resolve before checking if user is logged in */ isLoggedInAsync: function (cb) { if (currentMetaData.hasOwnProperty('$promise')) { currentMetaData.$promise.then(function () { cb(true); }).catch(function () { cb(false); }); } else if (currentMetaData.hasOwnProperty('secondFactor')) { cb(true); } else { cb(false); } }, /** * Check if a user is an admin * * @return {Boolean} */ isAdmin: function () { var isAdmin = false; if (currentMetaData && currentMetaData.entity !== undefined) { var roles = currentMetaData.entity.roles; roles.forEach(function(role, index, roles) { if (role === 'admin') { isAdmin = true; } }); } return isAdmin; }, /** * Check if user needs two-factor auth */ isTwoFactor: function() { return currentMetaData.secondFactor; }, /** * Get auth token */ getToken: function () { return $cookieStore.get('access_token'); } }; });
tobistw/spc-web-client
client/components/auth/auth.service.js
JavaScript
mit
6,192
const WEEKDAYS_LONG = { ru: [ 'Воскресенье', 'Понедельник', 'Вторник', 'Среда', 'Четверг', 'Пятница', 'Суббота', ], it: [ 'Domenica', 'Lunedì', 'Martedì', 'Mercoledì', 'Giovedì', 'Venerdì', 'Sabato', ], }; const WEEKDAYS_SHORT = { ru: ['Вс', 'Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб'], it: ['Do', 'Lu', 'Ma', 'Me', 'Gi', 'Ve', 'Sa'], }; const MONTHS = { ru: [ 'Январь', 'Февраль', 'Март', 'Апрель', 'Май', 'Июнь', 'Июль', 'Август', 'Сентябрь', 'Октябрь', 'Ноябрь', 'Декабрь', ], it: [ 'Gennaio', 'Febbraio', 'Marzo', 'Aprile', 'Maggio', 'Giugno', 'Luglio', 'Agosto', 'Settembre', 'Ottobre', 'Novembre', 'Dicembre', ], }; const FIRST_DAY_OF_WEEK = { ru: 1, it: 1, }; // Translate aria-labels const LABELS = { ru: { nextMonth: 'следующий месяц', previousMonth: 'предыдущий месяц' }, it: { nextMonth: 'Prossimo mese', previousMonth: 'Mese precedente' }, }; export default class Example extends React.Component { state = { locale: 'en', }; switchLocale = e => { const locale = e.target.value || 'en'; this.setState({ locale }); }; render() { const { locale } = this.state; return ( <div> <p> <select value={locale} onChange={this.switchLocale}> <option value="en">English</option> <option value="ru">Русский (Russian)</option> <option value="it">Italian</option> </select> </p> <DayPicker locale={locale} months={MONTHS[locale]} weekdaysLong={WEEKDAYS_LONG[locale]} weekdaysShort={WEEKDAYS_SHORT[locale]} firstDayOfWeek={FIRST_DAY_OF_WEEK[locale]} labels={LABELS[locale]} /> </div> ); } }
saenglert/react-day-picker
docs/examples/src/localization.js
JavaScript
mit
2,036
{ TITLE : 'HiddenColony', API : 'API', USED_BY : 'Used by', LAS_MOD : 'Last update', EXPIRES : 'Next update', SER_TIM : 'Server time', LOC_TIM : 'Local time', REM_TIM : 'Remaining time' }
EliasGrande/OGameHiddenColony
dist/locale/en_GB.js
JavaScript
mit
202
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _utils = require('./utils'); var metaFactory = function metaFactory(_ref) { var name = _ref.name; var checker = _ref.checker; var types = _ref.types; var meta = { name: name, checker: checker, types: types, isGeneric: false }; meta.map = (0, _utils.functor)(function () { return [{ 'name': name }, { 'checker': checker }, { 'types': types }, { 'isGeneric': !!types }]; }); return meta; }; var extend = function extend(checker) { return function (name, newChecker) { return typeFactory(name, function () { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return checker.apply(null, args) && newChecker.apply(null, args); }, [checker, newChecker]); }; }; var typeFactory = function typeFactory(name, checker, types) { checker.map = (0, _utils.functor)(function () { return metaFactory({ name: name, checker: checker, types: types }); }); checker.extend = extend(checker); return checker; }; exports.default = typeFactory;
Gwash3189/stronganator
dist/type.js
JavaScript
mit
1,152
module.exports = { "level": [ { "level": "1", "name": "trick" }, { "level": "1", "name": "destiny-bond" }, { "level": "1", "name": "ally-switch" }, { "level": "1", "name": "hyperspace-hole" }, { "level": "1", "name": "confusion" }, { "level": "6", "name": "astonish" }, { "level": "10", "name": "magic-coat" }, { "level": "15", "name": "psybeam" }, { "level": "19", "name": "light-screen" }, { "level": "25", "name": "skill-swap" }, { "level": "29", "name": "power-split" }, { "level": "35", "name": "guard-split" }, { "level": "46", "name": "phantom-force" }, { "level": "50", "name": "wonder-room" }, { "level": "55", "name": "trick-room" }, { "level": "68", "name": "shadow-ball" }, { "level": "75", "name": "psychic" }, { "level": "85", "name": "hyperspace-hole" } ], "tutor": [], "machine": [ "psyshock", "calm-mind", "toxic", "hidden-power", "sunny-day", "taunt", "hyper-beam", "light-screen", "protect", "rain-dance", "safeguard", "frustration", "thunderbolt", "return", "psychic", "shadow-ball", "brick-break", "double-team", "reflect", "torment", "facade", "rest", "thief", "round", "focus-blast", "energy-ball", "fling", "charge-beam", "quash", "embargo", "giga-impact", "flash", "thunder-wave", "psych-up", "dream-eater", "grass-knot", "swagger", "sleep-talk", "substitute", "trick-room", "power-up-punch", "confide" ], "egg": [] };
leader22/simple-pokedex-v2
_scraping/XYmoves/720.js
JavaScript
mit
2,423
var url = require('url') var gitHead = require('git-head') var GitHubApi = require('github') var parseSlug = require('parse-github-repo-url') module.exports = function (config, cb) { var pkg = config.pkg var options = config.options var plugins = config.plugins var ghConfig = options.githubUrl ? url.parse(options.githubUrl) : {} var github = new GitHubApi({ port: ghConfig.port, protocol: (ghConfig.protocol || '').split(':')[0] || null, host: ghConfig.hostname, pathPrefix: options.githubApiPathPrefix || null }) plugins.generateNotes(config, function (err, log) { if (err) return cb(err) gitHead(function (err, hash) { if (err) return cb(err) var ghRepo = parseSlug(pkg.repository.url) var release = { owner: ghRepo[0], repo: ghRepo[1], name: 'v' + pkg.version, tag_name: 'v' + pkg.version, target_commitish: hash, draft: !!options.debug, body: log } if (options.debug && !options.githubToken) { return cb(null, false, release) } github.authenticate({ type: 'token', token: options.githubToken }) github.repos.createRelease(release, function (err) { if (err) return cb(err) cb(null, true, release) }) }) }) }
MakiCode/Enchilada
crawlkit-2/node_modules/semantic-release/src/post.js
JavaScript
mit
1,323
const ROOT_PATH = process.cwd() module.exports = { bail: false, cache: false, devtool: 'eval', devServer: { compress: true, contentBase: `${ROOT_PATH}/public/`, historyApiFallback: true, hot: true, port: 8000, stats: { colors: true } }, entry: require('./__entry'), output: { path: `${ROOT_PATH}/public/scripts`, filename: '[name].js', publicPath: 'scripts/' }, module: require('./__module'), plugins: require('./plugins'), resolve: require('./__resolve') }
jbarinas/cake-hub
_configs/webpack.config.dev.js
JavaScript
mit
600
(function( $, SocialCount ) { SocialCount.selectors.facebook = '.facebook'; SocialCount.getFacebookAction = function( $el ) { return ( $el.attr('data-facebook-action' ) || 'like' ).toLowerCase(); }; SocialCount.plugins.init.push(function() { var $el = this; $el.addClass( SocialCount.getFacebookAction( $el ) ); }); SocialCount.plugins.bind.push(function(bind, url) { var $el = this, facebookAction = SocialCount.getFacebookAction( $el ); bind( $el.find( SocialCount.selectors.facebook + ' a' ), '<div class="fb-like" data-href="' + url + '" data-layout="button"' + ' data-action="' + facebookAction + '" data-show-faces="false"' + ' data-share="false"></div>', '//connect.facebook.net/' + ( SocialCount.locale || 'en_US' ) + '/sdk.js#xfbml=1&version=v2.0', function( el ) { FB.XFBML.parse( el ); }); }); })( jQuery, window.SocialCount );
filamentgroup/SocialCount
src/networks/facebook.js
JavaScript
mit
937
/** * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ import Flax from '../../../../'; import TodoActions from '../actions/TodoActions'; const TodoStore = Flax.createStore({ displayName: 'TodoStore', getInitialState: function () { return { todos: {}, id: 0 } }, getActionBinds() { return [ [TodoActions.create, this._handleCreate], [TodoActions.updateText, this._handleUpdateText], [TodoActions.destroy, this._handleDestroy], [TodoActions.toggleComplete, this._handleToggleComplete], [TodoActions.toggleCompleteAll, this._handleToggleCompleteAll] ]; }, events: { CHANGE_EVENT: null }, getters: { areAllComplete() { var todos = this.state.todos; for (var id in todos) { if (!todos[id].complete) { return false; } } return true; }, getAll() { return this.state.todos; } }, // Helpers _update(id, update) { if (this.state.todos.hasOwnProperty(id)) this.state.todos[id] = Object.assign({}, this.state.todos[id], update); }, _destroy(id) { delete this.state.todos[id]; }, // Handlers _handleCreate(payload) { var text = payload.text.trim(); if (text !== '') { // var id = (+new Date() + Math.floor(Math.random() * 999999)).toString(36); var id = this.state.id++; this.state.todos[id] = { id: id, complete: false, text: text }; this.emitChange(this.CHANGE_EVENT); } }, _handleToggleComplete(payload) { this._update(payload.id, {complete: payload.complete}); this.emitChange(this.CHANGE_EVENT); }, _handleUpdateText(payload) { var id = payload.id; var text = payload.text.trim(); if (text !== '') { this._update(id, {text: text}); this.emitChange(this.CHANGE_EVENT); } }, _handleToggleCompleteAll() { var updates; if (this.areAllComplete()) { updates = {complete: false}; } else { updates = {complete: true}; } for (var id in this.state.todos) { this._update(id, updates); } this.emitChange(this.CHANGE_EVENT); }, _handleDestroy(payload) { var id = payload.id; this._destroy(id); this.emitChange(this.CHANGE_EVENT); }, _handleDestroyCompleted() { var todos = this.state.todos; for (var id in todos) { if (todos[id].complete) { this._destroy(id); } } this.emitChange(this.CHANGE_EVENT); } }); export default TodoStore;
osmanpontes/flax
examples/todos/src/stores/TodoStore.js
JavaScript
mit
2,773
module.exports = { update: function(data) { var _ = this; _.dom.update(data || _._data); }, dispose: function dispose() { var _ = this; _.$element.innerHTML = ''; }, render: function render() { var _ = this; _.dispose(); _.dom = _.bars.compile(_.template); _.dom.update(_._data); _.dom.appendTo(_.$element); _.emit('render'); } };
Mike96Angelo/Custom-Element
lib/events.js
JavaScript
mit
438
import { createStore, applyMiddleware, compose } from 'redux' import { autoRehydrate } from 'redux-persist' import createLogger from 'redux-logger' import rootReducer from '../reducers/' import Config from '../../config/debug_settings' import createSagaMiddleware from 'redux-saga' import sagas from '../sagas' import R from 'ramda' import devTools from 'remote-redux-devtools' import ReduxPersist from '../../config/redux_persist' import RehydrationServices from '../services/rehydration_services' import Types from '@actions/types' var Fabric = require('react-native-fabric'); var { Answers } = Fabric; // the logger master switch const USE_LOGGING = Config.reduxLogging // silence these saga-based messages const SAGA_LOGGING_BLACKLIST = ['EFFECT_TRIGGERED', 'EFFECT_RESOLVED', 'EFFECT_REJECTED', 'persist/REHYDRATE'] const actionTransformer = action => { console.log('log action') // All log functions take an optional array of custom attributes as the last parameter Answers.logCustom('User action', { action }); return action } // create the logger const logger = createLogger({ predicate: ( getState, { type } ) => USE_LOGGING && R.not(R.contains(type, SAGA_LOGGING_BLACKLIST)), actionTransformer }) let middleware = [] const sagaMiddleware = createSagaMiddleware() const answersLogger = store => next => action => { switch(action.type){ case Types.LOGIN_SUCCESS: Answers.logLogin('Login Success', true) break case Types.LOGIN_FAILURE: Answers.logLogin('Login Success', false) break case Types.REGISTER_SUCCESS: Answers.logSignUp('SignUp Success', false) break } return next(action) } const crashLogger = store => next => action => { try { return next(action) } catch (err) { console.error('Caught an exception!', err) Answers.logCustom('Redux error', { extra: { action, state: store.getState() } }); throw err } } middleware.push(sagaMiddleware) middleware.push(answersLogger) middleware.push(crashLogger) // Don't ship these if (__DEV__) { middleware.push(logger) } // a function which can create our store and auto-persist the data export default () => { let store = {} // Add rehydrate enhancer if ReduxPersist is active if (ReduxPersist.active) { const enhancers = compose( applyMiddleware(...middleware), autoRehydrate(), devTools() ) store = createStore( rootReducer, enhancers ) // configure persistStore and check reducer version number RehydrationServices.updateReducers(store) } else { const enhancers = compose( applyMiddleware(...middleware), ) store = createStore( rootReducer, enhancers ) } // run sagas sagaMiddleware.run(sagas) devTools.updateStore(store) return store }
igorlimansky/react-native-redux-boilerplate
src/core/store/store.js
JavaScript
mit
2,872
/* * 根据贝塞尔曲线获取两个经纬度之间的曲线 */ 'use strict'; var PI = Math.PI; /* * 初始贝塞尔曲线值 * params: * start: {lat:112,lng:22} 起点 * end: {lat:112,lng:22} 终点 * isClockWise: bool 是否顺时针 */ var BezierPath = function(start,end,isClockWise){ this.geometries = []; this.start = start; this.end = end; this.clockWise = isClockWise; } /* * 绘制曲线 * * params: * angle: 绘制角度 范围:0~90 */ BezierPath.prototype.MakePath = function(angle) { this.angle = angle; var auxiliaryPoint = this.AuxiliaryPoint(); var bezier1x; var bezier1y; var bezier2x; var bezier2y; var bezier_x; var bezier_y; var t = 0; while ( this.geometries.length <= 100 ) { bezier1x = this.start.lng + ( auxiliaryPoint.lng - this.start.lng ) * t; bezier1y = this.start.lat + ( auxiliaryPoint.lat - this.start.lat ) * t; bezier2x = auxiliaryPoint.lng + ( this.end.lng - auxiliaryPoint.lng ) * t; bezier2y = auxiliaryPoint.lat + ( this.end.lat - auxiliaryPoint.lat ) * t; bezier_x = bezier1x + ( bezier2x - bezier1x ) * t; bezier_y = bezier1y + ( bezier2y - bezier1y ) * t; this.geometries.push({lat:bezier_y,lng:bezier_x}); t += 0.01; } } /* * 获取辅助点 * */ BezierPath.prototype.AuxiliaryPoint = function() { if (this.angle < 0) { this.angle = 0; }else if(this.angle > 90){ this.angle = 90; } var target = {lat:0,lng:0}; // 两点之间的角度 var btpAngle = Math.atan2(this.start.lat-this.end.lat,this.start.lng-this.end.lng)*180/PI; // 中间点 var center = {lat:(this.start.lat+this.end.lat)/2,lng:(this.start.lng+this.end.lng)/2}; // 距离 var distance = Math.sqrt((this.start.lat-this.end.lat)*(this.start.lat-this.end.lat)+(this.start.lng-this.end.lng)*(this.start.lng-this.end.lng)) // 中间点到辅助点的距离 var adis = (distance/2.0)*Math.tan(this.angle*PI/180.0); // 辅助点的经纬度 var auxAngle = Math.abs(btpAngle) > 90 ? 180 - Math.abs(btpAngle):Math.abs(btpAngle); var lat = adis*Math.sin((90 - auxAngle)*PI/180); var lng = adis*Math.cos((90 - auxAngle)*PI/180); if (this.start.lat>this.end.lat) { this.isClockWise = !this.isClockWise; } if (btpAngle >= 90) { target.lat = center.lat + (this.isClockWise?lat:-1*lat); target.lng = center.lng + (this.isClockWise?lng:-1*lng); }else{ target.lat = center.lat + (this.isClockWise?lat:-1*lat); target.lng = center.lng - (this.isClockWise?lng:-1*lng); } if (target.lat > 90) { target.lat = 90.0; }else if (target.lat <- 90){ target.lat = -90.0; } if (target.lng > 180) { target.lng = target.lng-360.0; }else if (target.lng <- 180){ target.lng = 360.0 + target.lng; } return target; } /* * 转化 mapbox feature data */ BezierPath.prototype.toMapBoxFeature = function(properties) { properties = properties || {}; if (this.geometries.length <= 0) { return {'geometry': { 'type': 'LineString', 'coordinates': null }, 'type': 'Feature', 'properties': properties }; } else { var multiline = []; for (var i = 0; i < this.geometries.length ; i++) { multiline.push([this.geometries[i].lng,this.geometries[i].lat]); } return {'geometry': { 'type': 'LineString', 'coordinates': multiline }, 'type': 'Feature', 'properties': properties}; } };
ZacksTsang/BezierPath
bezierpath.js
JavaScript
mit
3,579
import './adventure_status_bar.html'; import { Template } from 'meteor/templating'; /** * Template Helpers */ Template.AdventureStatusBar.helpers({ getHeaderMargin(){ return Template.instance().headerMargin.get(); }, adventureStatus(){ return this.adventure.get().status } }); /** * Template Event Handlers */ Template.AdventureStatusBar.events({}); /** * Template Created */ Template.AdventureStatusBar.onCreated(() => { let instance = Template.instance(); instance.headerMargin = new ReactiveVar(); }); /** * Template Rendered */ Template.AdventureStatusBar.onRendered(() => { let instance = Template.instance(); instance.autorun(() => { let viewport = instance.data.viewport.get(), header = instance.$(".adventure-status-header"), offset = $(".roba-accordion-content").first().offset(), currentMargin = parseInt(header.css("margin-top")); if(currentMargin >= 0 && viewport && viewport.offset){ instance.headerMargin.set(currentMargin + viewport.offset.top - offset.top); } }) }); /** * Template Destroyed */ Template.AdventureStatusBar.onDestroyed(() => { });
austinsand/doc-roba
meteor/client/ui/pages/adventure_console/adventure_status_bar.js
JavaScript
mit
1,164
// Copyright (c) 2012 Titanium I.T. LLC. All rights reserved. See LICENSE.txt for details. /*global desc, task, jake, fail, complete, directory, require, console, process */ (function () { "use strict"; var REQUIRED_BROWSERS = [ // "IE 8.0", // "IE 9.0", // "Firefox 17.0", // "Chrome 23.0", // "Safari 6.0" ]; var lint = require("./build/util/lint_runner.js"); var nodeunit = require("./build/util/nodeunit_runner.js"); var karma = require("./build/util/karma_runner.js"); desc("Lint and test"); task("default", ["lint", "test"], function() { console.log("\n\nOK"); }); desc("Start Karma server -- run this first"); task("karma", function() { karma.serve(complete, fail); }, {async: true}); desc("Lint everything"); task("lint", [], function () { var passed = lint.validateFileList(nodeFilesToLint(), nodeLintOptions(), {}); passed = lint.validateFileList(browserFilesToLint(), browserLintOptions(), {}) && passed; if (!passed) fail("Lint failed"); }); desc("Test everything"); task("test", ["testServer", "testClient"]); desc("Test node.js code"); task("testServer", function() { nodeunit.runTests(nodeFilesToTest(), complete, fail); }, {async: true}); desc("Test browser code"); task("testClient", function() { karma.runTests(REQUIRED_BROWSERS, complete, fail); }, {async: true}); function nodeFilesToTest() { var testFiles = new jake.FileList(); testFiles.include("src/_*_test.js"); testFiles.include("src/server/**/_*_test.js"); testFiles.exclude("node_modules"); var tests = testFiles.toArray(); return tests; } function nodeFilesToLint() { var files = new jake.FileList(); files.include("src/*.js"); files.include("src/server/**/*.js"); files.include("build/util/**/*.js"); files.include("Jakefile.js"); return files.toArray(); } function browserFilesToLint() { var files = new jake.FileList(); files.include("src/client/**/*.js"); return files.toArray(); } function globalLintOptions() { return { bitwise:true, curly:false, eqeqeq:true, forin:true, immed:true, latedef:false, newcap:true, noarg:true, noempty:true, nonew:true, regexp:true, undef:true, strict:true, trailing:true }; } function nodeLintOptions() { var options = globalLintOptions(); options.node = true; return options; } function browserLintOptions() { var options = globalLintOptions(); options.browser = true; return options; } }());
DarthStrom/poker-plus
Jakefile.js
JavaScript
mit
2,466
import DOMExporter from './DOMExporter' import DefaultDOMElement from '../ui/DefaultDOMElement' import { isBoolean } from 'lodash-es' import forEach from '../util/forEach' import isNumber from '../util/isNumber' import isString from '../util/isString' var defaultAnnotationConverter = { tagName: 'span', export: function(node, el) { el.tagName = 'span' el.attr('data-type', node.type) var properties = node.toJSON() forEach(properties, function(value, name) { if (name === 'id' || name === 'type') return if (isString(value) || isNumber(value) || isBoolean(value)) { el.attr('data-'+name, value) } }) } } var defaultBlockConverter = { export: function(node, el, converter) { el.attr('data-type', node.type) var properties = node.toJSON() forEach(properties, function(value, name) { if (name === 'id' || name === 'type') { return } var prop = converter.$$('div').attr('property', name) if (node.getPropertyType(name) === 'string' && value) { prop.append(converter.annotatedText([node.id, name])) } else { prop.text(value) } el.append(prop) }) } } /* @class @abstract Base class for custom HTML exporters. If you want to use XML as your exchange format see {@link model/XMLExporter}. */ class HTMLExporter extends DOMExporter { constructor(config) { super(Object.assign({ idAttribute: 'data-id' }, config)) // used internally for creating elements this._el = DefaultDOMElement.parseHTML('<html></html>') } exportDocument(doc) { var htmlEl = DefaultDOMElement.parseHTML('<html><head></head><body></body></html>') return this.convertDocument(doc, htmlEl) } getDefaultBlockConverter() { return defaultBlockConverter } getDefaultPropertyAnnotationConverter() { return defaultAnnotationConverter } } export default HTMLExporter
stencila/substance
model/HTMLExporter.js
JavaScript
mit
1,923
'use strict'; var tomasi = require('..'); var fs = require('fs'); var path = require('path'); var join = path.join; var test = require('tape'); var RELATIVE_PATH = path.relative(process.cwd(), __dirname); var FIXTURES_DIR = join(RELATIVE_PATH, 'fixtures'); var FIXTURES_ABS_DIR = join(__dirname, 'fixtures'); test('without `$preProcess` or `$views` pipelines', function(t) { var inPath = join(FIXTURES_DIR, '*.txt'); var config = { blog: { $inPath: inPath } }; tomasi(config).build(function(err, dataTypes) { t.false(err); t.looseEquals(dataTypes.blog, [ { $inPath: join(FIXTURES_DIR, '1-foo.txt'), $content: 'foo' }, { $inPath: join(FIXTURES_DIR, '2-bar.txt'), $content: 'bar' }, { $inPath: join(FIXTURES_DIR, '3-baz.txt'), $content: 'baz' } ]); t.end(); }); }); test('calls the build `cb` with an `err` if no files match an `$inPath`', function(t) { var calls = []; var x = function(cb) { calls.push(1); cb(); }; var y = function(cb) { calls.push(2); cb(); }; var inPath = join('invalid', '*.txt'); var config = { blog: { $inPath: inPath, $preProcess: [ x ], $views: { single: [ [ y ] ] } } }; t.false(fs.existsSync('invalid')); tomasi(config).build(function(err) { t.true(err); t.looseEqual(calls, []); t.end(); }); }); test('calls plugins in a single `$preProcess` pipeline in series', function(t) { var calls = []; var x = function(cb, files, dataTypeName, viewName, dataTypes) { calls.push(1); t.equal(arguments.length, 6); var expectedFiles = [ { $inPath: join(FIXTURES_DIR, '1-foo.txt'), $content: 'foo' }, { $inPath: join(FIXTURES_DIR, '2-bar.txt'), $content: 'bar' }, { $inPath: join(FIXTURES_DIR, '3-baz.txt'), $content: 'baz' } ]; t.deepEqual(files, expectedFiles); t.equal(dataTypeName, 'blog'); t.equal(viewName, null); t.deepEqual(dataTypes, { blog: expectedFiles }); t.true(files === dataTypes.blog); cb(null, ['tomasi']); }; var y = function(cb, files, dataTypeName, viewName, dataTypes) { calls.push(2); t.equal(arguments.length, 6); t.deepEqual(files, ['tomasi']); t.equal(dataTypeName, 'blog'); t.equal(viewName, null); t.deepEqual(dataTypes.blog, ['tomasi']); t.true(files === dataTypes.blog); cb(); }; var inPath = join(FIXTURES_DIR, '*.txt'); var config = { blog: { $inPath: inPath, $preProcess: [ x, y ] } }; tomasi(config).build(function(err) { t.false(err); t.looseEquals(calls, [ 1, 2 ]); t.end(); }); }); test('calls the build `cb` with the `err` if a plugin in a `$preProcess` pipeline has an error', function(t) { var calls = []; var x = function(cb) { calls.push(1); cb(); }; var y = function(cb) { calls.push(2); cb('error'); }; var z = function(cb) { calls.push(3); cb(); }; var inPath = join(FIXTURES_DIR, '*.txt'); var config = { blog: { $inPath: inPath, $preProcess: [ x, y, z ] } }; tomasi(config).build(function(err) { t.equal(err, 'error'); t.looseEquals(calls, [ 1, 2 ]); t.end(); }); }); test('runs parallel `$preProcess` pipelines in parallel', function(t) { var calls = []; var x = function(cb) { calls.push(1); setTimeout(function() { calls.push(4); cb(); }, 10); }; var y = function(cb) { calls.push(2); setTimeout(function() { calls.push(3); cb(); }, 0); }; var inPath = join(FIXTURES_DIR, '*.txt'); var config = { blog: { $inPath: inPath, $preProcess: [ x ] }, news: { $inPath: inPath, $preProcess: [ y ] } }; tomasi(config).build(function(err) { t.false(err); t.looseEquals(calls, [ 1, 2, 3, 4 ]); t.end(); }); }); test('calls plugins in a single `$view` pipeline in series', function(t) { var calls = []; var x = function(cb, files, dataTypeName, viewName, dataTypes) { calls.push(1); t.equal(arguments.length, 6); var expectedFiles = [ { $inPath: join(FIXTURES_DIR, '1-foo.txt'), $content: 'foo' }, { $inPath: join(FIXTURES_DIR, '2-bar.txt'), $content: 'bar' }, { $inPath: join(FIXTURES_DIR, '3-baz.txt'), $content: 'baz' } ]; t.deepEqual(files, expectedFiles); t.equal(dataTypeName, 'blog'); t.equal(viewName, 'single'); t.deepEqual(dataTypes, { blog: { single: expectedFiles } }); t.true(files === dataTypes.blog.single); cb(null, ['tomasi']); }; var y = function(cb, files, dataTypeName, viewName, dataTypes) { calls.push(2); t.equal(arguments.length, 6); var expectedFiles = ['tomasi']; t.deepEquals(files, expectedFiles); t.equal(dataTypeName, 'blog'); t.equal(viewName, 'single'); t.deepEqual(dataTypes, { blog: { single: expectedFiles } }); t.true(files === dataTypes.blog.single); cb(); }; var config = { blog: { $inPath: join(FIXTURES_DIR, '*.txt'), $views: { single: [ [ x, y ] ] } } }; tomasi(config).build(function(err) { t.false(err); t.looseEquals(calls, [ 1, 2 ]); t.end(); }); }); test('calls the build `cb` with the `err` if a plugin in a `$preProcess` pipeline has an error', function(t) { var calls = []; var x = function(cb) { calls.push(1); cb(); }; var y = function(cb) { calls.push(2); cb('error'); }; var z = function(cb) { calls.push(3); cb(); }; var inPath = join(FIXTURES_DIR, '*.txt'); var config = { blog: { $inPath: inPath, $views: { single: [ [ x, y, z ] ] } } }; tomasi(config).build(function(err) { t.equal(err, 'error'); t.looseEquals(calls, [ 1, 2 ]); t.end(); }); }); test('runs consecutive `$view` pipelines in series', function(t) { var calls = []; var x = function(cb) { calls.push(1); cb(null, ['tomasi']); }; var y = function(cb, files, dataTypeName, viewName, dataTypes) { calls.push(2); t.deepEquals(files, ['tomasi']); t.deepEquals(dataTypes.blog.single, ['tomasi']); cb(); }; var inPath = join(FIXTURES_DIR, '*.txt'); var config = { blog: { $inPath: inPath, $views: { single: [ [ x ], [ y ] ] } } }; tomasi(config).build(function(err) { t.false(err); t.looseEquals(calls, [ 1, 2 ]); t.end(); }); }); test('runs parallel `$view` pipelines in parallel', function(t) { t.test('same data type', function() { var calls = []; var x = function(cb) { calls.push(1); setTimeout(function() { calls.push(3); cb(); }, 10); }; var y = function(cb) { calls.push(5); setTimeout(function() { calls.push(6); cb(); }, 0); }; var z = function(cb) { calls.push(2); setTimeout(function() { calls.push(4); cb(); }, 20); }; var inPath = join(FIXTURES_DIR, '*.txt'); var config = { blog: { $inPath: inPath, $views: { single: [ [ x ], [ y ] ], archive: [ [ z ] ] } } }; tomasi(config).build(function(err) { t.false(err); t.looseEquals(calls, [ 1, 2, 3, 4, 5, 6 ]); t.end(); }); }); t.test('different data types', function(t) { var calls = []; var x = function(cb) { calls.push(1); setTimeout(function() { calls.push(3); cb(); }, 10); }; var y = function(cb) { calls.push(5); setTimeout(function() { calls.push(6); cb(); }, 0); }; var z = function(cb) { calls.push(2); setTimeout(function() { calls.push(4); cb(); }, 20); }; var inPath = join(FIXTURES_DIR, '*.txt'); var config = { blog: { $inPath: inPath, $views: { single: [ [ x ], [ y ] ] } }, news: { $inPath: inPath, $views: { single: [ [ z ] ] } } }; tomasi(config).build(function(err) { t.false(err); t.looseEquals(calls, [ 1, 2, 3, 4, 5, 6 ]); t.end(); }); }); }); test('uses settings in the specified `config` file', function(t) { var config = join(FIXTURES_ABS_DIR, 'tomasi.js'); t.true(fs.existsSync(config)); tomasi(config).build(function(err, dataTypes) { t.false(err); t.looseEquals(dataTypes.blog, [ { $inPath: join(FIXTURES_ABS_DIR, '1-foo.txt'), $content: 'foo' }, { $inPath: join(FIXTURES_ABS_DIR, '2-bar.txt'), $content: 'bar' }, { $inPath: join(FIXTURES_ABS_DIR, '3-baz.txt'), $content: 'baz' } ]); t.end(); }); }); test('throws if the specified `config` file does not exist', function(t) { t.throws(function() { var config = 'invalid'; t.false(fs.existsSync(config)); tomasi(config); }); t.end(); }); test('prepends `$dirs.$inDir` to each `$inPath`', function(t) { var config = { $dirs: { $inDir: FIXTURES_ABS_DIR }, $dataTypes: { blog: { $inPath: '*.txt' } } }; tomasi(config).build(function(err, dataTypes) { t.false(err); t.looseEquals(dataTypes.blog, [ { $inPath: join(FIXTURES_ABS_DIR, '1-foo.txt'), $content: 'foo' }, { $inPath: join(FIXTURES_ABS_DIR, '2-bar.txt'), $content: 'bar' }, { $inPath: join(FIXTURES_ABS_DIR, '3-baz.txt'), $content: 'baz' } ]); t.end(); }); }); test('can handle non-utf8 files', function(t) { var calls = []; var inPath = join(FIXTURES_DIR, 'heart.png'); var content = fs.readFileSync(inPath); var expectedFiles = [ { $inPath: inPath, $content: content } ]; var x = function(cb, files, dataTypeName, viewName, dataTypes) { calls.push(1); t.equal(arguments.length, 6); t.deepEqual(files, expectedFiles); t.equal(dataTypeName, 'images'); t.equal(viewName, null); t.deepEqual(dataTypes, { images: expectedFiles }); t.equal(files, dataTypes.images); cb(); }; var y = function(cb, files, dataTypeName, viewName, dataTypes) { calls.push(2); t.equal(arguments.length, 6); t.deepEqual(files, expectedFiles); t.equal(dataTypeName, 'images'); t.equal(viewName, 'single'); t.deepEqual(dataTypes, { images: { single: expectedFiles } }); t.equal(files, dataTypes.images.single); cb(); }; var config = { images: { $inPath: join(FIXTURES_DIR, '*.png'), $preProcess: [ x ], $views: { single: [ [ y ] ] } } }; tomasi(config).build(function(err) { t.false(err); t.looseEquals(calls, [ 1, 2 ]); t.end(); }); });
yuanqing/tomasi
test/build.js
JavaScript
mit
11,000
/* This script generates mock data for local development. This way you don't have to point to an actual API, but you can enjoy realistic, but randomized data, and rapid page loads due to local, static data. */ /* eslint-disable no-console */ import jsf from 'json-schema-faker'; import {schema} from './mockDataSchema'; import fs from 'fs'; import chalk from 'chalk'; const json = JSON.stringify(jsf.resolve(schema)); fs.writeFile("./src/api/db.json", json, function(err) { if (err) { console.log(chalk.red(err)); } else { console.log(chalk.green("Mock data generated.")); } });
davefud/js-dev-env
buildScripts/generateMockData.js
JavaScript
mit
604
/* global describe,it */ var getSlug = require('../lib/speakingurl'); describe('getSlug symbols', function () { 'use strict'; it('should convert symbols', function (done) { getSlug('Foo & Bar | Baz') .should.eql('foo-and-bar-or-baz'); getSlug('Foo & Bar | Baz', { lang: 'cs' }) .should.eql('foo-a-bar-nebo-baz'); getSlug('Foo & Bar | Baz', { lang: 'en' }) .should.eql('foo-and-bar-or-baz'); getSlug('Foo & Bar | Baz', { lang: 'de' }) .should.eql('foo-und-bar-oder-baz'); getSlug('Foo & Bar | Baz', { lang: 'fr' }) .should.eql('foo-et-bar-ou-baz'); getSlug('Foo & Bar | Baz', { lang: 'es' }) .should.eql('foo-y-bar-u-baz'); getSlug('Foo & Bar | Baz', { lang: 'ru' }) .should.eql('foo-i-bar-ili-baz'); getSlug('Foo & Bar | Baz', { lang: 'ro' }) .should.eql('foo-si-bar-sau-baz'); getSlug('Foo & Bar | Baz', { lang: 'sk' }) .should.eql('foo-a-bar-alebo-baz'); done(); }); it('shouldn\'t convert symbols', function (done) { getSlug('Foo & Bar | Baz', { symbols: false }) .should.eql('foo-bar-baz'); getSlug('Foo & Bar | Baz', { lang: 'en', symbols: false }) .should.eql('foo-bar-baz'); getSlug('Foo & Bar | Baz', { lang: 'de', symbols: false }) .should.eql('foo-bar-baz'); getSlug('Foo & Bar | Baz', { lang: 'fr', symbols: false }) .should.eql('foo-bar-baz'); getSlug('Foo & Bar | Baz', { lang: 'es', symbols: false }) .should.eql('foo-bar-baz'); getSlug('Foo & Bar | Baz', { lang: 'ru', symbols: false }) .should.eql('foo-bar-baz'); getSlug('Foo & Bar | Baz', { lang: 'cs', symbols: false }) .should.eql('foo-bar-baz'); getSlug('Foo & Bar | Baz', { lang: 'sk', symbols: false }) .should.eql('foo-bar-baz'); done(); }); it('should not convert symbols with uric flag true', function (done) { getSlug('Foo & Bar | Baz', { uric: true }) .should.eql('foo-&-bar-or-baz'); getSlug('Foo & Bar | Baz', { lang: 'en', uric: true }) .should.eql('foo-&-bar-or-baz'); getSlug('Foo & Bar | Baz', { lang: 'de', uric: true }) .should.eql('foo-&-bar-oder-baz'); getSlug('Foo & Bar | Baz', { lang: 'fr', uric: true }) .should.eql('foo-&-bar-ou-baz'); getSlug('Foo & Bar | Baz', { lang: 'es', uric: true }) .should.eql('foo-&-bar-u-baz'); getSlug('Foo & Bar | Baz', { lang: 'ru', uric: true }) .should.eql('foo-&-bar-ili-baz'); getSlug('Foo & Bar | Baz', { lang: 'cs', uric: true }) .should.eql('foo-&-bar-nebo-baz'); getSlug('Foo & Bar | Baz', { lang: 'sk', uric: true }) .should.eql('foo-&-bar-alebo-baz'); done(); }); it('should not convert symbols with uricNoSlash flag true', function (done) { getSlug('Foo & Bar | Baz', { uricNoSlash: true }) .should.eql('foo-&-bar-or-baz'); getSlug('Foo & Bar | Baz', { lang: 'en', uricNoSlash: true }) .should.eql('foo-&-bar-or-baz'); getSlug('Foo & Bar | Baz', { lang: 'de', uricNoSlash: true }) .should.eql('foo-&-bar-oder-baz'); getSlug('Foo & Bar | Baz', { lang: 'fr', uricNoSlash: true }) .should.eql('foo-&-bar-ou-baz'); getSlug('Foo & Bar | Baz', { lang: 'es', uricNoSlash: true }) .should.eql('foo-&-bar-u-baz'); getSlug('Foo & Bar | Baz', { lang: 'ru', uricNoSlash: true }) .should.eql('foo-&-bar-ili-baz'); getSlug('Foo & Bar | Baz', { lang: 'cs', uricNoSlash: true }) .should.eql('foo-&-bar-nebo-baz'); getSlug('Foo & Bar | Baz', { lang: 'sk', uricNoSlash: true }) .should.eql('foo-&-bar-alebo-baz'); done(); }); it('should not convert symbols with mark flag true', function (done) { getSlug('Foo (Bar) . Baz', { mark: true }) .should.eql('foo-(bar)-.-baz'); getSlug('Foo (Bar) . Baz', { lang: 'en', mark: true }) .should.eql('foo-(bar)-.-baz'); getSlug('Foo (Bar) . Baz', { lang: 'de', mark: true }) .should.eql('foo-(bar)-.-baz'); getSlug('Foo (Bar) . Baz', { lang: 'fr', mark: true }) .should.eql('foo-(bar)-.-baz'); getSlug('Foo (Bar) . Baz', { lang: 'es', mark: true }) .should.eql('foo-(bar)-.-baz'); getSlug('Foo (Bar) . Baz', { lang: 'ru', mark: true }) .should.eql('foo-(bar)-.-baz'); getSlug('Foo (Bar) . Baz', { lang: 'cs', mark: true }) .should.eql('foo-(bar)-.-baz'); getSlug('Foo (Bar) . Baz', { lang: 'sk', mark: true }) .should.eql('foo-(bar)-.-baz'); done(); }); it('should convert symbols with flags true', function (done) { getSlug('Foo (♥) ; Baz=Bar', { lang: 'en', uric: true, uricNoSlash: true, mark: true }) .should.eql('foo-(love)-;-baz=bar'); getSlug('Foo (♥) ; Baz=Bar', { lang: 'de', uric: true, uricNoSlash: true, mark: true }) .should.eql('foo-(liebe)-;-baz=bar'); getSlug('Foo (♥) ; Baz=Bar', { lang: 'fr', uric: true, uricNoSlash: true, mark: true }) .should.eql('foo-(amour)-;-baz=bar'); getSlug('Foo (♥) ; Baz=Bar', { lang: 'es', uric: true, uricNoSlash: true, mark: true }) .should.eql('foo-(amor)-;-baz=bar'); getSlug('Foo (♥) ; Baz=Bar', { lang: 'ru', uric: true, uricNoSlash: true, mark: true }) .should.eql('foo-(lubov)-;-baz=bar'); getSlug('Foo (♥) ; Baz=Bar', { lang: 'cs', uric: true, uricNoSlash: true, mark: true }) .should.eql('foo-(laska)-;-baz=bar'); getSlug('Foo (♥) ; Baz=Bar', { lang: 'sk', uric: true, uricNoSlash: true, mark: true }) .should.eql('foo-(laska)-;-baz=bar'); getSlug(' Sch(* )ner (♥)Ti♥tel ♥läßt grüßen!? Bel♥♥ été !', { lang: 'en', uric: true, uricNoSlash: true, mark: true, maintainCase: true }) .should.eql( 'Sch(*-)ner-(love)Ti-love-tel-love-laesst-gruessen!?-Bel-love-love-ete-!' ); done(); }); it('should replace symbols (de)', function (done) { getSlug('Äpfel & Birnen', { lang: 'de' }) .should.eql('aepfel-und-birnen'); getSlug('ÄÖÜäöüß', { lang: 'de', maintainCase: true }) .should.eql('AeOeUeaeoeuess'); done(); }); it('should replace chars by cs language standards', function (done) { getSlug( 'AaÁáBbCcČčDdĎďEeÉéĚěFfGgHhChchIiÍíJjKkLlMmNnŇňOoÓóPpQqRrŘřSsŠšTtŤťUuÚúŮůVvWwXxYyÝýZzŽž', { lang: 'cs' }) .should.eql( 'aaaabbccccddddeeeeeeffgghhchchiiiijjkkllmmnnnnooooppqqrrrrssssttttuuuuuuvvwwxxyyyyzzzz' ); getSlug( 'AaÁáBbCcČčDdĎďEeÉéĚěFfGgHhChchIiÍíJjKkLlMmNnŇňOoÓóPpQqRrŘřSsŠšTtŤťUuÚúŮůVvWwXxYyÝýZzŽž', { lang: 'cs', maintainCase: true }) .should.eql( 'AaAaBbCcCcDdDdEeEeEeFfGgHhChchIiIiJjKkLlMmNnNnOoOoPpQqRrRrSsSsTtTtUuUuUuVvWwXxYyYyZzZz' ); done(); }); it('should replace chars by fi language standards', function (done) { getSlug( 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZzÅåÄäÖö', { lang: 'fi', maintainCase: true }) .should.eql( 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZzAaAaOo' ); done(); }); it('should replace chars by sk language standards', function (done) { getSlug( 'AaÁaÄäBbCcČčDdĎďDzdzDždžEeÉéFfGgHhChchIiÍíJjKkLlĹ弾MmNnŇňOoÓóÔôPpQqRrŔŕSsŠšTtŤťUuÚúVvWwXxYyÝýZzŽž', { lang: 'sk' }) .should.eql( 'aaaaaabbccccdddddzdzdzdzeeeeffgghhchchiiiijjkkllllllmmnnnnooooooppqqrrrrssssttttuuuuvvwwxxyyyyzzzz' ); getSlug( 'AaÁaÄäBbCcČčDdĎďDzdzDždžEeÉéFfGgHhChchIiÍíJjKkLlĹ弾MmNnŇňOoÓóÔôPpQqRrŔŕSsŠšTtŤťUuÚúVvWwXxYyÝýZzŽž', { lang: 'sk', maintainCase: true }) .should.eql( 'AaAaAaBbCcCcDdDdDzdzDzdzEeEeFfGgHhChchIiIiJjKkLlLlLlMmNnNnOoOoOoPpQqRrRrSsSsTtTtUuUuVvWwXxYyYyZzZz' ); done(); }); it('should ignore not available language param', function (done) { getSlug('Äpfel & Birnen', { lang: 'xx' }) .should.eql('aepfel-and-birnen'); done(); }); it('should convert currency symbols to lowercase', function (done) { getSlug('NEXUS4 only €199!', { maintainCase: false }) .should.eql('nexus4-only-eur199'); getSlug('NEXUS4 only €299.93', { maintainCase: false }) .should.eql('nexus4-only-eur299-93'); getSlug('NEXUS4 only 円399.73', { maintainCase: false }) .should.eql('nexus4-only-yen399-73'); done(); }); it('should convert currency symbols to uppercase', function (done) { getSlug('NEXUS4 only €199!', { maintainCase: true }) .should.eql('NEXUS4-only-EUR199'); getSlug('NEXUS4 only €299.93', { maintainCase: true }) .should.eql('NEXUS4-only-EUR299-93'); getSlug('NEXUS4 only 円399.73', { maintainCase: true }) .should.eql('NEXUS4-only-YEN399-73'); done(); }); });
jotamaggi/react-calendar-app
node_modules/speakingurl/test/test-lang.js
JavaScript
mit
12,387
/*global module:false*/ module.exports = function(grunt) { // Project configuration. grunt.initConfig({ // Metadata. pkg: grunt.file.readJSON('package.json'), banner: '/*! <%= pkg.title || pkg.name %> - v<%= pkg.version %> - ' + '<%= grunt.template.today("yyyy-mm-dd") %>\n' + '<%= pkg.homepage ? "* " + pkg.homepage + "\\n" : "" %>' + '* Copyright (c) <%= grunt.template.today("yyyy") %> <%= pkg.author.name %>;' + ' Licensed <%= _.pluck(pkg.licenses, "type").join(", ") %> */\n', // Task configuration. watch: { compass: { files: ['app/styles/{,*/}*.{scss,sass}'], tasks: ['compass:server'] } }, open: { server: { path: 'http://localhost:<%= connect.options.port %>' } }, clean: { dist: { files: [{ dot: true, src: [ '.tmp', 'dist/*', '!dist/.git*' ] }] }, server: '.tmp' }, compass: { options: { sassDir: 'app/styles', cssDir: 'app/styles', generatedImagesDir: '.tmp/images/generated', imagesDir: 'app/images', javascriptsDir: 'app/scripts', fontsDir: 'app/styles/fonts', importPath: 'app/bower_components', httpImagesPath: '/images', httpGeneratedImagesPath: '/images/generated', httpFontsPath: '/styles/fonts', relativeAssets: false }, dist: {}, server: { options: { debugInfo: false } } }, }); // These plugins provide necessary tasks. grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-contrib-compass'); grunt.registerTask('server', function (target) { if (target === 'dist') { return grunt.task.run(['build', 'open', 'connect:dist:keepalive']); } grunt.task.run([ 'clean:server', 'concurrent:server', 'connect:livereload', 'open', 'watch' ]); }); // Default task. grunt.registerTask('default', ['watch']); };
jussiip/wamefork
Gruntfile.js
JavaScript
mit
2,290
/** * Using Rails-like standard naming convention for endpoints. * GET /things -> index * POST /things -> create * GET /things/:id -> show * PUT /things/:id -> update * DELETE /things/:id -> destroy */ import {notFound, invalidData} from './errors'; import awaitify from 'awaitify'; import _ from 'lodash'; import {loadGroupUsers} from './api-utils'; import UserGroup from './models/user-group.model'; import User from './models/user.model'; export const index = awaitify(function *(req, res, next) { try { const userGroups = yield UserGroup.find({}).exec(); res.status(200).json(userGroups); } catch (err) { return next(err); } }); export const show = awaitify(function *(req, res, next) { try { const {params:{id}} = req; const userGroup = yield UserGroup.findById(id).exec(); if (!userGroup) { return notFound(req, res); } res.status(200).json(userGroup); } catch (err) { return next(err); } }); export const create = awaitify(function *(req, res, next) { try { const {body:{name}} = req; if (!name) { return invalidData(req, res); } let userGroup = new UserGroup(); userGroup.name = name; userGroup.users = []; const result = yield userGroup.save(); res.status(200).json(result); } catch (err) { return next(err); } }); export const update = awaitify(function *(req, res, next) { try { const {body:{name}, params:{id}} = req; if (!name || !id) { return invalidData(req, res); } const userGroup = yield UserGroup.findById(id).exec(); if (!userGroup) { return notFound(req, res); } userGroup.name = name; const result = yield userGroup.save().exec(); res.status(200).json(result); } catch (err) { return next(err); } }); export const users = awaitify(function *(req, res, next) { try { const {params:{name}} = req; if (!name) { return invalidData(req, res); } const result = yield loadGroupUsers(name); if (!result) { return notFound(req, res); } res.status(200).json(result); } catch (err) { return next(err); } }); export const assignUsersToGroup = awaitify(function *(req, res, next) { try { const {body, params:{name}} = req; if (!name || !_.isArray(body)) { return invalidData(req, res); } const userGroup = yield UserGroup.findOne({name}).exec(); if (!userGroup) { return notFound(req, res); } userGroup.users = _.uniq(userGroup.users.concat(body)); userGroup.markModified('users'); const result = yield userGroup.save(); res.status(200).json(result); } catch (err) { return next(err); } }); export const unassignUsersFromGroup = awaitify(function *(req, res, next) { try { const {body, params:{name}} = req; if (!name || !_.isArray(body)) { return invalidData(req, res); } const userGroup = yield UserGroup.findOne({name}).exec(); if (!userGroup) { return notFound(req, res); } _.remove(userGroup.users, id => _.includes(body, String(id))); userGroup.markModified('users'); const result = yield userGroup.save(); res.status(200).json(result); } catch (err) { return next(err); } }); export const destroy = awaitify(function *(req, res, next) { try { const userGroup = yield UserGroup.findById(req.params.id).exec(); if (!userGroup || userGroup.users.length) { return invalidData(req, res); } const result = yield UserGroup.findByIdAndRemove(req.params.id).exec(); res.status(200).json(result); } catch (err) { return next(err); } });
fixjs/user-management-app
src/apis/user-group.api.js
JavaScript
mit
3,703
var express = require('express'); var app = express(); var uid = require('uid'); var databaseUrl = 'mongodb://dev:[email protected]:47107/getitrightdev'; var collections = ['active_users']; var db = require('mongojs').connect(databaseUrl, collections); app.use(express.static('public')); app.use(express.json()); //Getting Data app.get('/api/active-users', function(req, res) { var now = new Date().valueOf(), criteria = new Date(now - 5 * 60 * 60000); db.active_users.find({'last_updated': {'$gte': criteria}}).toArray(function(err, results) { res.send(results.map(function(item, i) { return {long: item.coords.long, lat: item.coords.lat}; })); }); }); //Storing DATA app.post('/api/heartbeat', function(req, res) { var data = { id: req.body.id, coords: { long: req.query.long, lat: req.query.lat }, last_updated: new Date() }; console.log(data.id); if (data.id) { db.active_users.update({id: data.id}, data, callback); } else { data.id = uid(); db.active_users.save(data, callback); } function callback(err, saved) { if (err || !saved) { res.send('Couldnt proceed'); } else { res.send(data.id); } } }); var server = app.listen(3030, function() { console.log('Listening on port %d', server.address().port); });
getitrightio/getitright-server
app/server.js
JavaScript
mit
1,356
// 74: String - `endsWith()` // To do: make all tests pass, leave the assert lines unchanged! var assert = require("assert"); describe('`str.endsWith(searchString)` determines whether `str` ends with `searchString`.', function() { const s = 'el fin'; describe('1st parameter, the string to search for', function() { it('works with just a character', function() { const doesEndWith = s.endsWith('n'); assert.equal(doesEndWith, true); }); it('works with a string', function() { const expected = true; assert.equal(s.endsWith('fin'), expected); }); it('works with unicode characters', function() { const nuclear = '☢'; assert.equal(nuclear.endsWith('☢'), true); }); it('a regular expression throws a TypeError', function() { const aRegExp = /the/; assert.throws(() => {''.endsWith(aRegExp)}, TypeError); }); }); describe('2nd parameter, searches within this string as if this string were only this long', function() { it('find "el" at a substring of the length 2', function() { const endPos = 2; assert.equal(s.endsWith('el', endPos), true); }); it('`undefined` uses the entire string', function() { const _undefined_ = undefined; assert.equal(s.endsWith('fin', _undefined_), true); }); it('the parameter gets coerced to an int', function() { const position = '5'; assert.equal(s.endsWith('fi', position), true); }); describe('value less than 0', function() { it('returns `true`, when searching for an empty string', function() { const emptyString = ''; assert.equal('1'.endsWith(emptyString, -1), true); }); it('return `false`, when searching for a non-empty string', function() { const notEmpty = '??'; assert.equal('1'.endsWith(notEmpty, -1), false); }); }); }); describe('transfer the functionality to other objects', function() { const endsWith = (...args) => String.prototype.endsWith.call(...args); it('e.g. a boolean', function() { let aBool = true; assert.equal(endsWith(!aBool, 'lse'), true); }); it('e.g. a number', function() { let aNumber = 84; assert.equal(endsWith(aNumber + 1900, 84), true); }); it('also using the position works', function() { const position = 3; assert.equal(endsWith(1994, '99', position), true); }); }); });
jostw/es6-katas
tests/74-string-ends-with.js
JavaScript
mit
2,438
var merge = require('merge'); var clone = require('clone'); var Field = require('./field'); var maxCounter = require('../mixins/max-counter'); module.exports = function() { return merge.recursive(Field(), { props: { placeholder: { type:String, required:false, default:'' }, disabled: { type: Boolean }, tinymce:{ default: false }, debounce:{ type:Number, default:300 }, lazy:{ type:Boolean }, toggler:{ type:Boolean }, togglerButton:{ type:Object, default:function() { return { expand:'Expand', minimize:'Minimize' } } } }, data: function() { return { editor: null, expanded:false, fieldType:'textarea', tagName:'textarea' } }, methods:{ toggle: function() { this.expanded=!this.expanded; var textarea = $(this.$el).find("textarea"); height = this.expanded?textarea.get(0).scrollHeight:"auto"; textarea.height(height); this.$dispatch('vue-formular.textarea-was-toggled', {expanded:this.expanded}); } }, computed:merge(maxCounter, { togglerText: function() { return this.expanded?this.togglerButton.minimize:this.togglerButton.expand; } }), ready: function() { if (this.tinymce===false) return; var that = this; var setup = that.tinymce && that.tinymce.hasOwnProperty('setup')? that.tinymce.setup: function() {}; var parentSetup = that.getForm().options.tinymceOptions.hasOwnProperty('setup')? that.getForm().options.tinymceOptions.setup: function(){}; var options = typeof this.tinymce=='object'? merge.recursive(clone(this.getForm().options.tinymceOptions), this.tinymce): this.getForm().options.tinymceOptions; options = merge.recursive(options, { selector:'textarea[name=' + this.name +']', setup : function(ed) { that.editor = ed; parentSetup(ed); setup(ed); ed.on('change',function(e) { that.value = ed.getContent(); }.bind(this)); } }); tinymce.init(options); this.$watch('value', function(val) { if(val != tinymce.get("textarea_" + this.name).getContent()) { tinymce.get("textarea_" + this.name).setContent(val); } }); } }); }
matfish2/vue-formular
lib/components/fields/textarea.js
JavaScript
mit
2,395
import i18n from 'mi18n' import Sortable from 'sortablejs' import h, { indexOfNode } from '../common/helpers' import dom from '../common/dom' import { ANIMATION_SPEED_SLOW, ANIMATION_SPEED_FAST } from '../constants' import { merge } from '../common/utils' const defaults = Object.freeze({ type: 'field', displayType: 'slider', }) const getTransition = val => ({ transform: `translateX(${val ? `${val}px` : 0})` }) /** * Edit and control sliding panels */ export default class Panels { /** * Panels initial setup * @param {Object} options Panels config * @return {Object} Panels */ constructor(options) { this.opts = merge(defaults, options) this.panelDisplay = this.opts.displayType this.activePanelIndex = 0 this.panelNav = this.createPanelNav() const panelsWrap = this.createPanelsWrap() this.nav = this.navActions() const resizeObserver = new window.ResizeObserver(([{ contentRect: { width } }]) => { if (this.currentWidth !== width) { this.toggleTabbedLayout() this.currentWidth = width this.nav.setTranslateX(this.activePanelIndex, false) } }) const observeTimeout = window.setTimeout(() => { resizeObserver.observe(panelsWrap) window.clearTimeout(observeTimeout) }, ANIMATION_SPEED_SLOW) } getPanelDisplay() { const column = this.panelsWrap const width = parseInt(dom.getStyle(column, 'width')) const autoDisplayType = width > 390 ? 'tabbed' : 'slider' const isAuto = this.opts.displayType === 'auto' this.panelDisplay = isAuto ? autoDisplayType : this.opts.displayType || defaults.displayType return this.panelDisplay } toggleTabbedLayout = () => { this.getPanelDisplay() const isTabbed = this.isTabbed this.panelsWrap.parentElement.classList.toggle('tabbed-panels', isTabbed) if (isTabbed) { this.panelNav.removeAttribute('style') } return isTabbed } /** * Resize the panel after its contents change in height * @return {String} panel's height in pixels */ resizePanels = () => { this.toggleTabbedLayout() const panelStyle = this.panelsWrap.style const activePanelHeight = dom.getStyle(this.currentPanel, 'height') panelStyle.height = activePanelHeight return activePanelHeight } /** * Wrap a panel and make properties sortable * if the panel belongs to a field * @return {Object} DOM element */ createPanelsWrap() { const panelsWrap = dom.create({ className: 'panels', content: this.opts.panels.map(({ config: { label }, ...panel }) => panel), }) if (this.opts.type === 'field') { this.sortableProperties(panelsWrap) } this.panelsWrap = panelsWrap this.panels = panelsWrap.children this.currentPanel = this.panels[this.activePanelIndex] return panelsWrap } /** * Sortable panel properties * @param {Array} panels * @return {Array} panel groups */ sortableProperties(panels) { const _this = this const groups = panels.getElementsByClassName('field-edit-group') return h.forEach(groups, (group, index) => { group.fieldId = _this.opts.id if (group.isSortable) { Sortable.create(group, { animation: 150, group: { name: 'edit-' + group.editGroup, pull: true, put: ['properties'], }, sort: true, handle: '.prop-order', onSort: evt => { _this.propertySave(evt.to) _this.resizePanels() }, }) } }) } createPanelNavLabels() { const labels = this.opts.panels.map(panel => ({ tag: 'h5', action: { click: evt => { const index = indexOfNode(evt.target, evt.target.parentElement) this.currentPanel = this.panels[index] const labels = evt.target.parentElement.childNodes this.nav.refresh(index) dom.removeClasses(labels, 'active-tab') evt.target.classList.add('active-tab') }, }, content: panel.config.label, })) const panelLabels = { className: 'panel-labels', content: { content: labels, }, } const [firstLabel] = labels firstLabel.className = 'active-tab' return dom.create(panelLabels) } /** * Panel navigation, tabs and arrow buttons for slider * @return {Object} DOM object for panel navigation wrapper */ createPanelNav() { this.labels = this.createPanelNavLabels() const next = { tag: 'button', attrs: { className: 'next-group', title: i18n.get('controlGroups.nextGroup'), type: 'button', }, dataset: { toggle: 'tooltip', placement: 'top', }, action: { click: e => this.nav.nextGroup(e), }, content: dom.icon('triangle-right'), } const prev = { tag: 'button', attrs: { className: 'prev-group', title: i18n.get('controlGroups.prevGroup'), type: 'button', }, dataset: { toggle: 'tooltip', placement: 'top', }, action: { click: e => this.nav.prevGroup(e), }, content: dom.icon('triangle-left'), } return dom.create({ tag: 'nav', attrs: { className: 'panel-nav', }, content: [prev, this.labels, next], }) } get isTabbed() { return this.panelDisplay === 'tabbed' } /** * Handlers for navigating between panel groups * @todo refactor to use requestAnimationFrame instead of css transitions * @return {Object} actions that control panel groups */ navActions() { const action = {} const groupParent = this.currentPanel.parentElement const labelWrap = this.labels.firstChild const siblingGroups = this.currentPanel.parentElement.childNodes this.activePanelIndex = indexOfNode(this.currentPanel, groupParent) let offset = { nav: 0, panel: 0 } let lastOffset = { ...offset } const groupChange = newIndex => { const labels = labelWrap.children dom.removeClasses(siblingGroups, 'active-panel') dom.removeClasses(labels, 'active-tab') this.currentPanel = siblingGroups[newIndex] this.currentPanel.classList.add('active-panel') labels[newIndex].classList.add('active-tab') return this.currentPanel } const getOffset = index => { return { nav: -labelWrap.offsetWidth * index, panel: -groupParent.offsetWidth * index, } } const translateX = ({ offset, reset, duration = ANIMATION_SPEED_FAST, animate = !this.isTabbed }) => { const panelQueue = [getTransition(lastOffset.panel), getTransition(offset.panel)] const navQueue = [getTransition(lastOffset.nav), getTransition(this.isTabbed ? 0 : offset.nav)] if (reset) { const [panelStart] = panelQueue const [navStart] = navQueue panelQueue.push(panelStart) navQueue.push(navStart) } const animationOptions = { easing: 'ease-in-out', duration: animate ? duration : 0, fill: 'forwards', } const panelTransition = groupParent.animate(panelQueue, animationOptions) labelWrap.animate(navQueue, animationOptions) const handleFinish = () => { this.panelsWrap.style.height = dom.getStyle(this.currentPanel, 'height') panelTransition.removeEventListener('finish', handleFinish) if (!reset) { lastOffset = offset } } panelTransition.addEventListener('finish', handleFinish) } action.setTranslateX = (panelIndex, animate = true) => { offset = getOffset(panelIndex || this.activePanelIndex) translateX({ offset, animate }) } action.refresh = newIndex => { if (newIndex !== undefined) { this.activePanelIndex = newIndex groupChange(newIndex) } this.resizePanels() action.setTranslateX(this.activePanelIndex, false) } /** * Slides panel to the next group * @return {Object} current group after navigation */ action.nextGroup = () => { const newIndex = this.activePanelIndex + 1 if (newIndex !== siblingGroups.length) { const curPanel = groupChange(newIndex) offset = { nav: -labelWrap.offsetWidth * newIndex, panel: -curPanel.offsetLeft, } translateX({ offset }) this.activePanelIndex++ } else { offset = { nav: lastOffset.nav - 8, panel: lastOffset.panel - 8, } translateX({ offset, reset: true }) } return this.currentPanel } action.prevGroup = () => { if (this.activePanelIndex !== 0) { const newIndex = this.activePanelIndex - 1 const curPanel = groupChange(newIndex) offset = { nav: -labelWrap.offsetWidth * newIndex, panel: -curPanel.offsetLeft, } translateX({ offset }) this.activePanelIndex-- } else { offset = { nav: 8, panel: 8, } translateX({ offset, reset: true }) } } return action } }
Draggable/formeo
src/js/components/panels.js
JavaScript
mit
9,240
/* * Copyright (c) 2012 VMware, Inc. All Rights Reserved. * * 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. */ (function (buster, define) { "use strict"; var assert, refute, undef; assert = buster.assert; refute = buster.refute; define('probe/stats/mean-test', function (require) { var mean, counter; mean = require('probe/stats/mean'); counter = require('probe/stats/counter'); buster.testCase('probe/stats/mean', { 'update the mean for each new value': function () { var m = mean(); assert.same(1, m(1)); assert.same(2, m(3)); assert.same(2, m(2)); assert.same(4, m(10)); assert.same(0, m(-16)); assert.same(1 / 6, m(1)); }, 'allow counter to be injected': function () { var m, c; c = counter(); m = mean(c); c.inc(); assert.same(1, m(1)); c.inc(); assert.same(2, m(3)); c.inc(); assert.same(2, m(2)); c.inc(); assert.same(4, m(10)); c.inc(); assert.same(0, m(-16)); c.inc(); assert.same(1 / 6, m(1)); }, 'injected counters must be incremented manually': function () { var m = mean(counter()); assert.same(Number.POSITIVE_INFINITY, m(1)); }, 'not passing a value returns the most recent mean': function () { var m = mean(); assert.same(1, m(1)); assert.same(1, m()); assert.same(1, m()); }, 'should restart from NaN when reset': function () { var m = mean(); assert.same(NaN, m()); assert.same(1, m(1)); assert.same(2, m(3)); m.reset(); assert.same(NaN, m()); assert.same(1, m(1)); assert.same(2, m(3)); }, 'should not update the readOnly stat': function () { var m, ro; m = mean(); ro = m.readOnly(); assert.same(NaN, m()); assert.same(NaN, ro()); assert.same(1, m(1)); assert.same(1, ro(2)); ro.reset(); assert.same(1, m()); m.reset(); assert.same(NaN, m()); assert.same(NaN, ro()); assert.same(ro, ro.readOnly()); } }); }); }( this.buster || require('buster'), typeof define === 'function' && define.amd ? define : function (id, factory) { var packageName = id.split(/[\/\-]/)[0], pathToRoot = id.replace(/[^\/]+/g, '..'); pathToRoot = pathToRoot.length > 2 ? pathToRoot.substr(3) : pathToRoot; factory(function (moduleId) { return require(moduleId.indexOf(packageName) === 0 ? pathToRoot + moduleId.substr(packageName.length) : moduleId); }); } // Boilerplate for AMD and Node ));
s2js/probes
test/stats/mean-test.js
JavaScript
mit
3,493
/** * Copyright (c) 2010 by Gabriel Birke * * 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. */ function Sanitize(){ var i, e, options; options = arguments[0] || {} this.config = {} this.config.elements = options.elements ? options.elements : []; this.config.attributes = options.attributes ? options.attributes : {}; this.config.attributes[Sanitize.ALL] = this.config.attributes[Sanitize.ALL] ? this.config.attributes[Sanitize.ALL] : []; this.config.allow_comments = options.allow_comments ? options.allow_comments : false; this.allowed_elements = {}; this.config.protocols = options.protocols ? options.protocols : {}; this.config.add_attributes = options.add_attributes ? options.add_attributes : {}; this.dom = options.dom ? options.dom : document; for(i=0;i<this.config.elements.length;i++) { this.allowed_elements[this.config.elements[i]] = true; } this.config.remove_element_contents = {}; this.config.remove_all_contents = false; if(options.remove_contents) { if(options.remove_contents instanceof Array) { for(i=0;i<options.remove_contents.length;i++) { this.config.remove_element_contents[options.remove_contents[i]] = true; } } else { this.config.remove_all_contents = true; } } this.transformers = options.transformers ? options.transformers : []; } Sanitize.REGEX_PROTOCOL = /^([A-Za-z0-9\+\-\.\&\;\*\s]*?)(?:\:|&*0*58|&*x0*3a)/i Sanitize.RELATIVE = '__relative__'; // emulate Ruby symbol with string constant Sanitize.prototype.clean_node = function(container) { var fragment = this.dom.createDocumentFragment(); this.current_element = fragment; this.whitelist_nodes = []; /** * Utility function to check if an element exists in an array */ function _array_index(needle, haystack) { var i; for(i=0; i < haystack.length; i++) { if(haystack[i] == needle) return i; } return -1; } function _merge_arrays_uniq() { var result = []; var uniq_hash = {} var i,j; for(i=0;i<arguments.length;i++) { if(!arguments[i] || !arguments[i].length) continue; for(j=0;j<arguments[i].length;j++) { if(uniq_hash[arguments[i][j]]) continue; uniq_hash[arguments[i][j]] = true; result.push(arguments[i][j]); } } return result; } /** * Clean function that checks the different node types and cleans them up accordingly * @param elem DOM Node to clean */ function _clean(elem) { var clone; switch(elem.nodeType) { // Element case 1: _clean_element.call(this, elem) break; // Text case 3: var clone = elem.cloneNode(false); this.current_element.appendChild(clone); break; // Entity-Reference (normally not used) case 5: var clone = elem.cloneNode(false); this.current_element.appendChild(clone); break; // Comment case 8: if(this.config.allow_comments) { var clone = elem.cloneNode(false); this.current_element.appendChild(clone); } default: //console.log("unknown node type", elem.nodeType) } } function _clean_element(elem) { var i, j, clone, parent_element, name, allowed_attributes, attr, attr_name, attr_node, protocols, del, attr_ok; var transform = _transform_element.call(this, elem); elem = transform.node; name = elem.nodeName.toLowerCase(); // check if element itself is allowed parent_element = this.current_element; if(this.allowed_elements[name] || transform.whitelist) { this.current_element = this.dom.createElement(elem.nodeName); parent_element.appendChild(this.current_element); // clean attributes allowed_attributes = _merge_arrays_uniq( this.config.attributes[name], this.config.attributes['__ALL__'], transform.attr_whitelist ); for(i=0;i<allowed_attributes.length;i++) { attr_name = allowed_attributes[i]; attr = elem.attributes[attr_name]; if(attr) { attr_ok = true; // Check protocol attributes for valid protocol if(this.config.protocols[name] && this.config.protocols[name][attr_name]) { protocols = this.config.protocols[name][attr_name]; del = attr.nodeValue.toLowerCase().match(Sanitize.REGEX_PROTOCOL); if(del) { attr_ok = (_array_index(del[1], protocols) != -1); } else { attr_ok = (_array_index(Sanitize.RELATIVE, protocols) != -1); } } if(attr_ok) { attr_node = document.createAttribute(attr_name); attr_node.value = attr.nodeValue; this.current_element.setAttributeNode(attr_node); } } } // Add attributes if(this.config.add_attributes[name]) { for(attr_name in this.config.add_attributes[name]) { attr_node = document.createAttribute(attr_name); attr_node.value = this.config.add_attributes[name][attr_name]; this.current_element.setAttributeNode(attr_node); } } } // End checking if element is allowed // If this node is in the dynamic whitelist array (built at runtime by // transformers), let it live with all of its attributes intact. else if(_array_index(elem, this.whitelist_nodes) != -1) { this.current_element = elem.cloneNode(true); // Remove child nodes, they will be sanitiazied and added by other code while(this.current_element.childNodes.length > 0) { this.current_element.removeChild(this.current_element.firstChild); } parent_element.appendChild(this.current_element); } // iterate over child nodes if(!this.config.remove_all_contents && !this.config.remove_element_contents[name]) { for(i=0;i<elem.childNodes.length;i++) { _clean.call(this, elem.childNodes[i]); } } // some versions of IE don't support normalize. if(this.current_element.normalize) { this.current_element.normalize(); } this.current_element = parent_element; } // END clean_element function function _transform_element(node) { var output = { attr_whitelist:[], node: node, whitelist: false } var i, j, transform; for(i=0;i<this.transformers.length;i++) { transform = this.transformers[i]({ allowed_elements: this.allowed_elements, config: this.config, node: node, node_name: node.nodeName.toLowerCase(), whitelist_nodes: this.whitelist_nodes, dom: this.dom }); if(transform == null) continue; else if(typeof transform == 'object') { if(transform.whitelist_nodes && transform.whitelist_nodes instanceof Array) { for(j=0;j<transform.whitelist_nodes.length;j++) { if(_array_index(transform.whitelist_nodes[j], this.whitelist_nodes) == -1) { this.whitelist_nodes.push(transform.whitelist_nodes[j]); } } } output.whitelist = transform.whitelist ? true : false; if(transform.attr_whitelist) { output.attr_whitelist = _merge_arrays_uniq(output.attr_whitelist, transform.attr_whitelist); } output.node = transform.node ? transform.node : output.node; } else { throw new Error("transformer output must be an object or null"); } } return output; } for(i=0;i<container.childNodes.length;i++) { _clean.call(this, container.childNodes[i]); } if(fragment.normalize) { fragment.normalize(); } return fragment; } if(!Sanitize.Config) { Sanitize.Config = {}; } Sanitize.Config.BASIC = { elements: [ 'a', 'b', 'blockquote', 'br', 'cite', 'code', 'dd', 'dl', 'dt', 'em', 'i', 'li', 'ol', 'p', 'pre', 'q', 'small', 'strike', 'strong', 'sub', 'sup', 'u', 'ul'], attributes: { 'a' : ['href'], 'blockquote': ['cite'], 'q' : ['cite'] }, add_attributes: { 'a': {'rel': 'nofollow'} }, protocols: { 'a' : {'href': ['ftp', 'http', 'https', 'mailto', Sanitize.RELATIVE]}, 'blockquote': {'cite': ['http', 'https', Sanitize.RELATIVE]}, 'q' : {'cite': ['http', 'https', Sanitize.RELATIVE]} } };
kurbmedia/transit-legacy
app/assets/javascripts/libs/sanitize.js
JavaScript
mit
9,555
const router = require('express').Router() const albumsQueries = require('../../db/albums') const albumsRoutes = require('./albums') const usersQueries = require('../../db/users') const usersRoutes = require('./users') const reviewsQueries = require('../../db/reviews') const {getSimpleDate} = require('../utils') router.use('/albums', albumsRoutes) router.use('/users', usersRoutes) router.get('/', (req, res) => { if (req.session.user) { const userSessionID = req.session.user[0].id const userSession = req.session.user[0] reviewsQueries.getReviews((error, reviews) => { if (error) { res.status(500).render('common/error', { error, }) } albumsQueries.getAlbums((error, albums) => { if (error) { res.status(500).render('common/error', { error, }) } res.render('index/index', { albums, reviews, userSessionID, userSession, }) }) }) } const userSessionID = null const userSession = null reviewsQueries.getReviews((error, reviews) => { if (error) { res.status(500).render('common/error', { error, }) } albumsQueries.getAlbums((error, albums) => { if (error) { res.status(500).render('common/error', { error, }) } res.render('index/index', { albums, reviews, userSessionID, userSession, }) }) }) }) router.get('/signup', (req, res) => { if (req.session.user) { const userSessionID = req.session.user[0].id const userSession = req.session.user[0] res.render('index/signup', { userSessionID, userSession, }) } const userSessionID = null const userSession = null res.render('index/signup', { userSessionID, userSession, }) }) router.post('/signup', (req, res) => { const accountInfo = req.body const dateToday = new Date() const dateJoined = getSimpleDate(dateToday) usersQueries.getUsersByEmail(accountInfo.email, (error, userEmailInfo) => { if (error) { return res.status(500).render('common/error', { error, }) } else if (userEmailInfo.length > 0) { return res.status(401).render('common/error', { error: { message: 'Email address already exists', }, }) } usersQueries.createUser(accountInfo, dateJoined, (error, accountNew) => { if (error) { return res.status(500).render('common/error', { error, }) } return res.redirect(`/users/${accountNew[0].id}`) }) }) }) router.get('/signin', (req, res) => { if (req.session.user) { const userSessionID = req.session.user[0].id const userSession = req.session.user[0] res.render('index/signin', { userSessionID, userSession, }) } const userSessionID = null const userSession = null res.render('index/signin', { userSessionID, userSession, }) }) router.post('/signin', (req, res) => { const loginEmail = req.body.email const loginPassword = req.body.password usersQueries.getUsersByEmail(loginEmail, (error, userEmailInfo) => { if (error) { return res.status(500).render('common/error', { error, }) } else if (userEmailInfo[0] !== undefined) { if (loginPassword !== userEmailInfo[0].password) { return res.status(401).render('common/error', { error: { message: 'Username and password do not match', }, }) } console.log('Logged in') req.session.user = userEmailInfo req.session.save() return res.redirect(`/users/${userEmailInfo[0].id}`) } return res.status(401).render('common/error', { error: { message: 'Username and password do not match', }, }) }) }) router.get('/signout', (req, res) => { req.session.destroy() res.clearCookie('userInformation') res.redirect('/') }) module.exports = router
hhhhhaaaa/phase-4-challenge
src/server/routes/index.js
JavaScript
mit
4,027
// Karma configuration // Generated on Thu Jul 30 2015 17:38:26 GMT-0700 (PDT) // we try our best... let browsers; switch (process.platform) { case 'darwin': // ensured by the npm module ... but may not work on non-consumer // oses. process.env.CHROME_BIN = require('puppeteer').executablePath(); browsers = ['ChromeHeadless']; break; case 'linux': // better have it installed there! browsers = ['ChromiumNoSandbox']; process.env.CHROME_BIN = '/usr/bin/chromium-browser'; break; default: throw new Error(`Unsupported platform: ${process.platform}`); } module.exports = function (config) { config.set({ // base path that will be used to resolve all patterns (eg. files, exclude) basePath: '../..', // frameworks to use // available frameworks: https://npmjs.org/browse/keyword/karma-adapter frameworks: ['jasmine', 'requirejs'], // list of Karma plugins to use // This is someone redundant with what's in package.json, // but I like it to be explicit here. plugins: [ 'karma-jasmine', 'karma-chrome-launcher', 'karma-coverage', 'karma-requirejs' ], // list of files / patterns to load in the browser // NB: paths are relative to the root of the project, which is // set in the basePath property above. files: [ // All of the AMD modules in the hub. { pattern: 'build/dist/client/modules/**/*.js', included: false }, // {pattern: 'build/client/bower_components/**/*.js', included: false}, // Our test specs { pattern: 'test/unit-tests/specs/**/*.js', included: false }, // Spot pickup the config files // { pattern: 'build/build/client/modules/config/*.yml', included: false }, // { pattern: 'build/build/client/modules/config/*.json', included: false }, // { pattern: 'build/build/client/modules/deploy/*.json', included: false }, 'test/unit-tests/setup.js', ], // list of files to exclude exclude: [ '**/*.swp' ], // preprocess matching files before serving them to the browser // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor // Note that we exclude all of the external modules (bower_components). // TODO: We may want to find a way to evaluate dependency test coverage at some point. preprocessors: { 'build/dist/client/modules/!(plugins)/**/*.js': ['coverage'] // 'build/build/client/modules/**/*.js': ['coverage'] }, // TODO: we should put this somewhere else? coverageReporter: { dir: 'build/build-test-coverage/', reporters: [ { type: 'html', subdir: 'html' }, { type: 'lcov', subdir: 'lcov' } ] }, // test results reporter to use // possible values: 'dots', 'progress' // available reporters: https://npmjs.org/browse/keyword/karma-reporter reporters: ['progress', 'coverage'], // web server port port: 9876, // enable / disable colors in the output (reporters and logs) colors: true, // level of logging // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG logLevel: config.LOG_INFO, // enable / disable watching file and executing tests whenever any file changes autoWatch: false, // start these browsers // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher // browsers: ['PhantomJS'], browsers, customLaunchers: { ChromiumNoSandbox: { base: 'ChromiumHeadless', flags: ['--no-sandbox', '--headless', '--disable-gpu', '--disable-translate', '--disable-extensions'] } }, // browsers: ['ChromeHeadless'], // Continuous Integration mode // if true, Karma captures browsers, runs the tests and exits singleRun: true }); };
kbase/kbase-ui
test/unit-tests/karma.conf.js
JavaScript
mit
4,283
let path = require('path'); let glob = require('glob'); let fs = require('fs'); let net = require('net'); let webpack = require('webpack'); let HtmlWebpackPlugin = require('html-webpack-plugin'); let ExtractTextPlugin = require('extract-text-webpack-plugin'); let slash = require('slash'); let autoprefixer = require("autoprefixer"); function getPath(projectPath, ...otherPath) { return path.join(projectPath, ...otherPath); } function fixFileLoaderPath(path) { return process.env.NODE_ENV === 'development' ? path : '/' + path; } function addEntry(directory, ext, entries, chunks, entryName) { let entry = path.join(directory, `index.${ext}`); if (fs.existsSync(entry)) { entryName = slash(entryName).replace(/\//g, '_') entries[entryName] = `${entry}?__webpack__`; chunks.push(entryName) } } function buildEntriesAndPlugins(projectPath, userConfig) { let commonChunks = {}; let vendors = []; let plugins = []; (userConfig.vendors || []).forEach((vendor, key) => { let row = vendor.dependencies; if (row instanceof Array) { row.forEach(function (value, key) { row[key] = value.replace(/\[project\]/gi, projectPath); }); } else if (row instanceof String) { row = row.replace(/\[project\]/gi, projectPath); } commonChunks[vendor.name] = row; vendors.push(vendor.name); }); let entries = Object.assign({}, commonChunks); //html webpack plugin glob.sync(getPath(projectPath, 'src', 'app', '**', '*.html')).forEach(function (file) { let fileParser = path.parse(file); let entryName = path.relative(getPath(projectPath, 'src', 'app'), fileParser.dir); let chunks = [...vendors]; addEntry(fileParser.dir, 'js', entries, chunks, entryName); // addEntry(fileParser.dir, 'less', entries, chunks, entryName); plugins.push(new HtmlWebpackPlugin({ template: file, inject: true, chunks: chunks, filename: getPath(projectPath, 'dist', userConfig.pagePath || '', `${entryName}.html`), favicon: path.join(projectPath, 'src', 'assets', 'images', 'favorite.ico') })) }); //common chunks plugin plugins.push(new webpack.optimize.CommonsChunkPlugin({ names: vendors })); return { entries, plugins } } function getStyleLoaders(ext, options, userConfig) { const cssLoaders = { loader: 'css-loader', options: { importLoaders: 1 } }; const postCssLoader = { loader: 'postcss-loader', options: { plugins: [ autoprefixer({ browsers: userConfig.postCss.browsers, add: true, remove: true }) ] } }; return [{ test: new RegExp(`\.${ext}$`), include: [ path.join(options.projectPath, 'src') ], exclude: [ path.join(options.projectPath, 'node_modules'), path.join(options.cliPath, 'node_modules') ], oneOf: [{ issuer: /\.js$/, use: ExtractTextPlugin.extract({ fallback: 'style-loader', use: [cssLoaders, { loader: 'sprite-loader' }, postCssLoader].concat(ext === 'css' ? [] : [{ loader: `${ext}-loader` }]) }) }, { issuer: /\.(html|tpl)$/, oneOf: [ { resourceQuery: /inline/, use: [{ loader: 'style-loader' }, cssLoaders, { loader: 'sprite-loader' }, postCssLoader].concat(ext === 'css' ? [] : [{ loader: `${ext}-loader` }]) }, { use: [{ loader: 'file-loader', options: { name: fixFileLoaderPath(`styles/[name]_${ext}.[hash:8].css`) } }, { loader: 'extract-loader' }, cssLoaders, { loader: 'sprite-loader' }, postCssLoader].concat(ext === 'css' ? [] : [{ loader: `${ext}-loader` }]) } ] }] }]; } function getScriptLoaders(options) { let babelLoaderConfig = { loader: 'babel-loader', options: { presets: [ require('babel-preset-react') ] } }; return [{ test: /\.js/, include: [path.join(options.projectPath, 'src')], exclude: [path.join(options.projectPath, 'node_modules'), path.join(options.cliPath, 'node_modules')], oneOf: [{ issuer: /\.(html|tpl)$/, oneOf: [{ resourceQuery: /source/, use: [{ loader: 'file-loader', options: { name: fixFileLoaderPath('scripts/[name].[hash:8].js') } }] }, { use: [{ loader: 'entry-loader', options: { name: fixFileLoaderPath('scripts/[name].[hash:8].js'), projectPath: options.projectPath } }, babelLoaderConfig] }] }, { use: [babelLoaderConfig] }] }, { test: /\.jsx$/, use: [babelLoaderConfig] }]; } function throttle(fn, interval = 300) { let canRun = true; return function () { if (!canRun) return; canRun = false; setTimeout(() => { fn.apply(this, arguments); canRun = true; }, interval); }; } module.exports = { getPath, buildEntriesAndPlugins, getStyleLoaders, getScriptLoaders, fixFileLoaderPath, throttle };
IveChen/saber-cli
build/util.js
JavaScript
mit
6,228
export const document = {"viewBox":"0 0 8 8","children":[{"name":"path","attribs":{"d":"M0 0v8h7v-4h-4v-4h-3zm4 0v3h3l-3-3zm-3 2h1v1h-1v-1zm0 2h1v1h-1v-1zm0 2h4v1h-4v-1z"}}]};
wmira/react-icons-kit
src/iconic/document.js
JavaScript
mit
175
import React from 'react'; import { Image, Text, View } from 'react-native'; import Example from '../../shared/example'; const Spacer = () => <View style={{ height: '1rem' }} />; const Heading = ({ children }) => ( <Text accessibilityRole="heading" children={children} style={{ fontSize: '1rem', fontWeight: 'bold', marginBottom: '0.5rem' }} /> ); function Color() { return ( <View> <Heading>color</Heading> <Text style={{ color: 'red' }}>Red color</Text> <Text style={{ color: 'blue' }}>Blue color</Text> </View> ); } function FontFamily() { return ( <View> <Heading>fontFamily</Heading> <Text style={{ fontFamily: 'Cochin' }}>Cochin</Text> <Text style={{ fontFamily: 'Cochin', fontWeight: 'bold' }} > Cochin bold </Text> <Text style={{ fontFamily: 'Helvetica' }}>Helvetica</Text> <Text style={{ fontFamily: 'Helvetica', fontWeight: 'bold' }}>Helvetica bold</Text> <Text style={{ fontFamily: 'Verdana' }}>Verdana</Text> <Text style={{ fontFamily: 'Verdana', fontWeight: 'bold' }} > Verdana bold </Text> </View> ); } function FontSize() { return ( <View> <Heading>fontSize</Heading> <Text style={{ fontSize: 23 }}>Size 23</Text> <Text style={{ fontSize: 8 }}>Size 8</Text> </View> ); } function FontStyle() { return ( <View> <Heading>fontStyle</Heading> <Text style={{ fontStyle: 'normal' }}>Normal text</Text> <Text style={{ fontStyle: 'italic' }}>Italic text</Text> </View> ); } function FontVariant() { return ( <View> <Heading>fontVariant</Heading> <Text style={{ fontVariant: ['small-caps'] }}>Small Caps{'\n'}</Text> <Text style={{ fontVariant: ['oldstyle-nums'] }} > Old Style nums 0123456789{'\n'} </Text> <Text style={{ fontVariant: ['lining-nums'] }} > Lining nums 0123456789{'\n'} </Text> <Text style={{ fontVariant: ['tabular-nums'] }}> Tabular nums{'\n'} 1111{'\n'} 2222{'\n'} </Text> <Text style={{ fontVariant: ['proportional-nums'] }}> Proportional nums{'\n'} 1111{'\n'} 2222{'\n'} </Text> </View> ); } function FontWeight() { return ( <View> <Heading>fontWeight</Heading> <Text style={{ fontSize: 20, fontWeight: '100' }}>Move fast and be ultralight</Text> <Text style={{ fontSize: 20, fontWeight: '200' }}>Move fast and be light</Text> <Text style={{ fontSize: 20, fontWeight: 'normal' }}>Move fast and be normal</Text> <Text style={{ fontSize: 20, fontWeight: 'bold' }}>Move fast and be bold</Text> <Text style={{ fontSize: 20, fontWeight: '900' }}>Move fast and be ultrabold</Text> </View> ); } function LetterSpacing() { return ( <View> <Heading>letterSpacing</Heading> <Text style={{ letterSpacing: 0 }}>letterSpacing = 0</Text> <Text style={{ letterSpacing: 2, marginTop: 5 }}>letterSpacing = 2</Text> <Text style={{ letterSpacing: 9, marginTop: 5 }}>letterSpacing = 9</Text> <View style={{ flexDirection: 'row' }}> <Text style={{ fontSize: 12, letterSpacing: 2, backgroundColor: 'fuchsia', marginTop: 5 }}> With size and background color </Text> </View> <Text style={{ letterSpacing: -1, marginTop: 5 }}>letterSpacing = -1</Text> <Text style={{ letterSpacing: 3, backgroundColor: '#dddddd', marginTop: 5 }}> [letterSpacing = 3] <Text style={{ letterSpacing: 0, backgroundColor: '#bbbbbb' }}> [Nested letterSpacing = 0] </Text> <Text style={{ letterSpacing: 6, backgroundColor: '#eeeeee' }}> [Nested letterSpacing = 6] </Text> </Text> </View> ); } function LineHeight() { return ( <View> <Heading>lineHeight</Heading> <Text style={{ lineHeight: 35 }}> A lot of space should display between the lines of this long passage as they wrap across several lines. A lot of space should display between the lines of this long passage as they wrap across several lines. </Text> </View> ); } function TextAlign() { return ( <View> <Heading>textAlign</Heading> <Text>auto (default) - english LTR</Text> <Text> {'\u0623\u062D\u0628 \u0627\u0644\u0644\u063A\u0629 ' + '\u0627\u0644\u0639\u0631\u0628\u064A\u0629 auto (default) - arabic ' + 'RTL'} </Text> <Text style={{ textAlign: 'left' }}> left left left left left left left left left left left left left left left </Text> <Text style={{ textAlign: 'center' }}> center center center center center center center center center center center </Text> <Text style={{ textAlign: 'right' }}> right right right right right right right right right right right right right </Text> <Text style={{ textAlign: 'justify' }}> justify: this text component{"'"}s contents are laid out with "textAlign: justify" and as you can see all of the lines except the last one span the available width of the parent container. </Text> </View> ); } function TextDecoration() { return ( <View> <Heading>textDecoration</Heading> <Text style={{ textDecorationLine: 'underline', textDecorationStyle: 'solid' }} > Solid underline </Text> <Text style={{ textDecorationLine: 'underline', textDecorationStyle: 'double', textDecorationColor: '#ff0000' }} > Double underline with custom color </Text> <Text style={{ textDecorationLine: 'underline', textDecorationStyle: 'dashed', textDecorationColor: '#9CDC40' }} > Dashed underline with custom color </Text> <Text style={{ textDecorationLine: 'underline', textDecorationStyle: 'dotted', textDecorationColor: 'blue' }} > Dotted underline with custom color </Text> <Text style={{ textDecorationLine: 'none' }}>None textDecoration</Text> <Text style={{ textDecorationLine: 'line-through', textDecorationStyle: 'solid' }} > Solid line-through </Text> <Text style={{ textDecorationLine: 'line-through', textDecorationStyle: 'double', textDecorationColor: '#ff0000' }} > Double line-through with custom color </Text> <Text style={{ textDecorationLine: 'line-through', textDecorationStyle: 'dashed', textDecorationColor: '#9CDC40' }} > Dashed line-through with custom color </Text> <Text style={{ textDecorationLine: 'line-through', textDecorationStyle: 'dotted', textDecorationColor: 'blue' }} > Dotted line-through with custom color </Text> <Text style={{ textDecorationLine: 'underline line-through' }}> Both underline and line-through </Text> </View> ); } function TextShadow() { return ( <View> <Heading>textShadow*</Heading> <Text style={{ fontSize: 20, textShadowOffset: { width: 2, height: 2 }, textShadowRadius: 1, textShadowColor: '#00cccc' }} > Text shadow example </Text> </View> ); } function LineExample({ description, children }) { return ( <View style={{ marginTop: 20 }}> <Text style={{ color: 'gray', marginBottom: 5 }}>{description}</Text> <View style={{ borderWidth: 2, borderColor: 'black', width: 200 }} > {children} </View> </View> ); } export default function TextPage() { return ( <Example title="Text"> <View style={{ maxWidth: 500 }}> <Text> Text wraps across multiple lines by default. Text wraps across multiple lines by default. Text wraps across multiple lines by default. Text wraps across multiple lines by default. </Text> <Spacer /> <Text> (Text inherits styles from parent Text elements, <Text style={{ fontWeight: 'bold' }}> {'\n '} (for example this text is bold <Text style={{ fontSize: 11, color: '#527fe4' }}> {'\n '} (and this text inherits the bold while setting size and color) </Text> {'\n '}) </Text> {'\n'}) </Text> <Spacer /> <Text style={{ opacity: 0.7 }}> (Text opacity <Text> {'\n '} (is inherited <Text style={{ opacity: 0.7 }}> {'\n '} (and accumulated <Text style={{ backgroundColor: '#ffaaaa' }}> {'\n '} (and also applies to the background) </Text> {'\n '}) </Text> {'\n '}) </Text> {'\n'}) </Text> <Spacer /> <Text> This text contains an inline blue view{' '} <View style={{ width: 25, height: 25, backgroundColor: 'steelblue' }} /> and an inline image{' '} <Image source={{ uri: 'http://lorempixel.com/30/11' }} style={{ width: 30, height: 11, resizeMode: 'cover' }} /> . </Text> <Spacer /> <Text> This text contains a view{' '} <View style={{ borderColor: 'red', borderWidth: 1 }}> <Text style={{ borderColor: 'blue', borderWidth: 1 }}>which contains</Text> <Text style={{ borderColor: 'green', borderWidth: 1 }}>another text.</Text> <Text style={{ borderColor: 'yellow', borderWidth: 1 }}> And contains another view <View style={{ borderColor: 'red', borderWidth: 1 }}> <Text style={{ borderColor: 'blue', borderWidth: 1 }}> which contains another text! </Text> </View> </Text> </View>{' '} And then continues as text. </Text> <Text selectable={true}> This text is <Text style={{ fontWeight: 'bold' }}>selectable</Text> if you click-and-hold. </Text> <Text selectable={false}> This text is <Text style={{ fontWeight: 'bold' }}>not selectable</Text> if you click-and-hold. </Text> <View style={{ paddingVertical: 20 }}> <LineExample description="With no line breaks, text is limited to 2 lines."> <Text numberOfLines={2}> { 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.' } </Text> </LineExample> <LineExample description="With line breaks, text is limited to 2 lines."> <Text numberOfLines={2}> { 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.\nUt enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.\nDuis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.\nExcepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.' } </Text> </LineExample> <LineExample description="With no line breaks, text is limited to 1 line."> <Text numberOfLines={1}> { 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.' } </Text> </LineExample> <LineExample description="With line breaks, text is limited to 1 line."> <Text numberOfLines={1}> { 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.\nUt enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.\nDuis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.\nExcepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.' } </Text> </LineExample> <LineExample description="With very long word, text is limited to 1 line and long word is truncated."> <Text numberOfLines={1}>goal aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa</Text> </LineExample> <LineExample description="With space characters within adjacent truncated lines"> <View style={{ display: 'flex', flexDirection: 'row' }}> <Text numberOfLines={1}> <Text>Spaces </Text> <Text>between</Text> <Text> words</Text> </Text> </View> <View style={{ display: 'flex', flexDirection: 'row' }}> <Text>Spaces </Text> <Text>between</Text> <Text> words</Text> </View> </LineExample> </View> <View> <Color /> <Spacer /> <FontFamily /> <Spacer /> <FontSize /> <Spacer /> <FontStyle /> <Spacer /> <FontVariant /> <Spacer /> <FontWeight /> <Spacer /> <LetterSpacing /> <Spacer /> <LineHeight /> <Spacer /> <TextAlign /> <Spacer /> <TextDecoration /> <Spacer /> <TextShadow /> </View> </View> </Example> ); }
necolas/react-native-web
packages/examples/pages/text/index.js
JavaScript
mit
15,012
const ACCOUNTS = [ 'all', 'default', 'kai-tfsa', 'kai-rrsp', 'kai-spouse-rrsp', 'kai-non-registered', 'kai-charles-schwab', 'crystal-non-registered', 'crystal-tfsa', 'crystal-rrsp', 'crystal-spouse-rrsp' ]; export default ACCOUNTS;
kaiguogit/growfolio
client/src/constants/accounts.js
JavaScript
mit
276
import React from 'react'; import PropTypes from 'prop-types'; import serialize from 'serialize-javascript'; import filterWithRules from '../../internal/utils/objects/filterWithRules'; import values from '../values'; // Filter the config down to the properties that are allowed to be included // in the HTML response. const clientConfig = filterWithRules( // These are the rules used to filter the config. values.clientConfigFilter, // The config values to filter. values, ); const serializedClientConfig = serialize(clientConfig); /** * A react component that generates a script tag that binds the allowed * values to the window so that config values can be read within the * browser. * * They get bound to window.__CLIENT_CONFIG__ */ function ClientConfig({ addHash }) { return ( <script type="text/javascript" // eslint-disable-next-line react/no-danger dangerouslySetInnerHTML={{ __html: addHash(`window.__CLIENT_CONFIG__=${serializedClientConfig}`), }} /> ); } ClientConfig.propTypes = { addHash: PropTypes.func.isRequired, }; export default ClientConfig;
ueno-llc/starter-kit-universally
config/components/ClientConfig.js
JavaScript
mit
1,126
import React from 'react'; import ReactDOM from 'react-dom'; import { Router, Route, browserHistory } from 'react-router'; import * as firebase from "firebase"; import './css/index.css'; import PetPage from './pet'; import Welcome from './welcome'; import AddPet from './add-pet'; import MainLayout from './main-layout'; // Initialize Firebase var config = { apiKey: "AIzaSyCy8OwL_E1rrYfutk5vqLygz20RmGW-GBE", authDomain: "petland-4b867.firebaseapp.com", databaseURL: "https://petland-4b867.firebaseio.com", storageBucket: "gs://petland-4b867.appspot.com/", messagingSenderId: "784140166304" }; firebase.initializeApp(config); ReactDOM.render( <Router history={browserHistory}> <Route component={MainLayout}> <Route path="/" component={Welcome} /> <Route path="/pet/:id" component={PetPage} /> <Route path="/add-pet" component={AddPet} /> </Route> </Router>, document.getElementById('root') );
beleidy/Pet-Land
src/index.js
JavaScript
mit
986
const { ArgumentError } = require('rest-facade'); const Auth0RestClient = require('../Auth0RestClient'); const RetryRestClient = require('../RetryRestClient'); /** * Abstracts interaction with the stats endpoint. */ class StatsManager { /** * @param {object} options The client options. * @param {string} options.baseUrl The URL of the API. * @param {object} [options.headers] Headers to be included in all requests. * @param {object} [options.retry] Retry Policy Config */ constructor(options) { if (options === null || typeof options !== 'object') { throw new ArgumentError('Must provide manager options'); } if (options.baseUrl === null || options.baseUrl === undefined) { throw new ArgumentError('Must provide a base URL for the API'); } if ('string' !== typeof options.baseUrl || options.baseUrl.length === 0) { throw new ArgumentError('The provided base URL is invalid'); } const clientOptions = { errorFormatter: { message: 'message', name: 'error' }, headers: options.headers, query: { repeatParams: false }, }; /** * Provides an abstraction layer for consuming the * {@link https://auth0.com/docs/api/v2#!/Stats Stats endpoint}. * * @type {external:RestClient} */ const auth0RestClient = new Auth0RestClient( `${options.baseUrl}/stats/:type`, clientOptions, options.tokenProvider ); this.resource = new RetryRestClient(auth0RestClient, options.retry); } /** * Get the daily stats. * * @example * var params = { * from: '{YYYYMMDD}', // First day included in the stats. * to: '{YYYYMMDD}' // Last day included in the stats. * }; * * management.stats.getDaily(params, function (err, stats) { * if (err) { * // Handle error. * } * * console.log(stats); * }); * @param {object} params Stats parameters. * @param {string} params.from The first day in YYYYMMDD format. * @param {string} params.to The last day in YYYYMMDD format. * @param {Function} [cb] Callback function. * @returns {Promise|undefined} */ getDaily(params, cb) { params = params || {}; params.type = 'daily'; if (cb && cb instanceof Function) { return this.resource.get(params, cb); } return this.resource.get(params); } /** * Get a the active users count. * * @example * management.stats.getActiveUsersCount(function (err, usersCount) { * if (err) { * // Handle error. * } * * console.log(usersCount); * }); * @param {Function} [cb] Callback function. * @returns {Promise|undefined} */ getActiveUsersCount(cb) { const options = { type: 'active-users' }; if (cb && cb instanceof Function) { return this.resource.get(options, cb); } // Return a promise. return this.resource.get(options); } } module.exports = StatsManager;
auth0/node-auth0
src/management/StatsManager.js
JavaScript
mit
3,012
const initialState = { minimoPalpite: 2, valorMaximoAposta: 500, valorMinimoAposta: 5, } function BancaReducer(state= initialState, action) { return state; } export default BancaReducer
sysbet/sysbet-mobile
src/reducers/sistema/banca.js
JavaScript
mit
205
export default { "hljs-comment": { "color": "#776977" }, "hljs-quote": { "color": "#776977" }, "hljs-variable": { "color": "#ca402b" }, "hljs-template-variable": { "color": "#ca402b" }, "hljs-attribute": { "color": "#ca402b" }, "hljs-tag": { "color": "#ca402b" }, "hljs-name": { "color": "#ca402b" }, "hljs-regexp": { "color": "#ca402b" }, "hljs-link": { "color": "#ca402b" }, "hljs-selector-id": { "color": "#ca402b" }, "hljs-selector-class": { "color": "#ca402b" }, "hljs-number": { "color": "#a65926" }, "hljs-meta": { "color": "#a65926" }, "hljs-built_in": { "color": "#a65926" }, "hljs-builtin-name": { "color": "#a65926" }, "hljs-literal": { "color": "#a65926" }, "hljs-type": { "color": "#a65926" }, "hljs-params": { "color": "#a65926" }, "hljs-string": { "color": "#918b3b" }, "hljs-symbol": { "color": "#918b3b" }, "hljs-bullet": { "color": "#918b3b" }, "hljs-title": { "color": "#516aec" }, "hljs-section": { "color": "#516aec" }, "hljs-keyword": { "color": "#7b59c0" }, "hljs-selector-tag": { "color": "#7b59c0" }, "hljs": { "display": "block", "overflowX": "auto", "background": "#f7f3f7", "color": "#695d69", "padding": "0.5em" }, "hljs-emphasis": { "fontStyle": "italic" }, "hljs-strong": { "fontWeight": "bold" } }
conorhastings/react-syntax-highlighter
src/styles/hljs/atelier-heath-light.js
JavaScript
mit
1,709
/** * @license * Based on https://github.com/lodash/lodash/blob/master/perf/perf.js * Available under MIT license <https://lodash.com/license> */ var Benchmark = require('benchmark') var formatNumber = Benchmark.formatNumber var tcParser = require('type-check').parseType var tcChecker = require('type-check').parsedTypeCheck var yatcParser = require('../src/parser') var yatcChecker = require('../src/checker').check var score = {a: [], b: []} var suites = [] function getGeometricMean(array) { return Math.pow(Math.E, array.reduce(function(sum, x) { return sum + Math.log(x) }, 0) / array.length) || 0 } function getHz(bench) { var result = 1 / (bench.stats.mean + bench.stats.moe) return isFinite(result) ? result : 0 } Benchmark.extend(Benchmark.Suite.options, { 'onStart': function () { console.log('\n' + this.name + ':') }, 'onCycle': function (event) { console.log(event.target.toString()) }, 'onComplete': function () { var errored = Object.keys(this).some(function (index) { return !!this[index].error }.bind(this)) if (errored) { console.log('There was a problem, skipping...') } else { var fastest = this.filter('fastest') var fastestHz = getHz(fastest[0]) var slowest = this.filter('slowest') var slowestHz = getHz(slowest[0]) var aHz = getHz(this[0]) var bHz = getHz(this[1]) var percent = ((fastestHz / slowestHz) - 1) * 100 percent = percent < 1 ? percent.toFixed(2) : Math.round(percent) percent = formatNumber(percent) if (fastest.length > 1) { console.log('It\'s too close to call.') aHz = bHz = slowestHz } else { console.log(fastest[0].name + ' is ' + percent + '% faster.') } score.a.push(aHz) score.b.push(bHz) } suites.shift() if (suites.length > 0) { suites[0].run() } else { var aMeanHz = getGeometricMean(score.a) var bMeanHz = getGeometricMean(score.b) var fastestMeanHz = Math.max(aMeanHz, bMeanHz) var slowestMeanHz = Math.min(aMeanHz, bMeanHz) var xFaster = fastestMeanHz / slowestMeanHz var percentFaster = formatNumber(Math.round((xFaster - 1) * 100)) xFaster = xFaster === 1 ? '' : '(' + formatNumber(xFaster.toFixed(2)) + 'x)' var message = 'is ' + percentFaster + '% ' + xFaster + ' faster than' if (aMeanHz > bMeanHz) { console.log('\nyatc ' + message + ' type-check.') } else { console.log('\ntype-check ' + message + ' yatc.') } } } }) function addSuite(benchType, type, input, customTypes) { var tcFn, yatcFn switch (benchType) { case 'parse': tcFn = function () { tcParser(type) } yatcFn = function () { yatcParser(type) } break case 'check': var tcType = tcParser(type) var yatcType = yatcParser(type) tcFn = function () { tcChecker(tcType, customTypes) } yatcFn = function () { yatcChecker(yatcType, customTypes) } break case 'parse&check': tcFn = function () { tcChecker(tcParser(type), input, customTypes) } yatcFn = function () { yatcChecker(yatcParser(type), input, customTypes) } break default: throw new TypeError('Unknow benchType: ' + benchType) } suites.push( Benchmark.Suite(benchType + ' ' + type) .add('yatc', yatcFn) .add('type-check', tcFn) ) } var rawSuites = [ ['Number', 1], ['Number|String', ''], ['Maybe Number', null], ['[Number]', [1, 2]], ['(Int, Float)', [1, 0.1]], ['{a: String}', {a: 'hi'}], ['{a: (Number), ...}', {a: [0], b: 0.1}], ['[{lat: Float, long: Float}]', [{lat: 15.42, long: 42.15}]], ] rawSuites.forEach(function (rawSuite) { var args = ['parse&check'].concat(rawSuite) addSuite.apply(null, args) }) console.log('Make a cup of tea and relax') suites[0].run()
fanatid/yatc
perf/perf.js
JavaScript
mit
3,879
/* jshint unused: false */ /* global describe, before, beforeEach, afterEach, after, it, xdescribe, xit */ 'use strict'; var fs = require('fs'); var restify = require('restify'); var orm = require('orm'); var assert = require('assert'); var restormify = require('../'); var dbProps = {host: 'logger', protocol: 'sqlite'}; var server = restify.createServer(); var client; var db; var baz; server.use(restify.bodyParser()); server.use(restify.queryParser()); describe('node-orm2 validations', function(){ before(function(done){ orm.connect(dbProps, function(err, database){ if(err){ done(err); } db = database; restormify({ db: db, server: server }, function(){ baz = db.define('baz', { name: String, email: {type: 'text', unique: true}, deleted: {type: 'boolean', serverOnly: true}, foo: {type: 'boolean', serverOnly: true} }, {validations: { name: orm.enforce.ranges.length(3, undefined, 'too small') }}); done(); }); }); client = restify.createJsonClient({ url: 'http://localhost:1234/api' }); }); describe('api', function(){ beforeEach(function(done){ server.listen(1234); baz.sync(done); }); it('rejects unique constraints', function(done){ var bazzer = {name: 'foo', email: '[email protected]'}; client.post('/api/baz', bazzer, function(err, req, res){ client.post('/api/baz', bazzer, function(err, req, res){ assert.equal(res.statusCode, 409, '490 Conflict recieved'); assert.equal(err.message, 'baz already exists', 'unique constraint'); done(); }); }); }); it('rejects validation matching', function(done){ var bazzer = {name: 'fo', email:'[email protected]'}; client.post('/api/baz', bazzer, function(err, req, res){ assert.equal(res.statusCode, 400, 'invalid content rejected'); assert.equal(err.message, 'too small', 'validation message matches'); done(); }); }); afterEach(function(done){ server.close(); db.drop(done); }); }); after(function(done){ db.close(); fs.unlink(dbProps.host, function(){ done(); }); }); });
toddself/restormify
test/validation-bubbling.js
JavaScript
mit
2,293
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var Item = function Item() { _classCallCheck(this, Item); this.chords = ''; this.lyrics = ''; }; exports.default = Item;
aggiedefenders/aggiedefenders.github.io
node_modules/chordsheetjs/lib/chord_sheet/item.js
JavaScript
mit
364
//>>excludeStart("jqmBuildExclude", pragmas.jqmBuildExclude); //>>description: A handler for css transition & animation end events to ensure callback is executed //>>label: Animation Complete //>>group: Core define( [ "jquery" ], function( jQuery ) { //>>excludeEnd("jqmBuildExclude"); (function( $, undefined ) { var props = { "animation": {}, "transition": {} }, testElement = document.createElement( "a" ), vendorPrefixes = [ "", "webkit-", "moz-", "o-" ]; $.each( [ "animation", "transition" ], function( i, test ) { // Get correct name for test var testName = ( i === 0 ) ? test + "-" + "name" : test; $.each( vendorPrefixes, function( j, prefix ) { if ( testElement.style[ $.camelCase( prefix + testName ) ] !== undefined ) { props[ test ][ "prefix" ] = prefix; return false; } }); // Set event and duration names for later use props[ test ][ "duration" ] = $.camelCase( props[ test ][ "prefix" ] + test + "-" + "duration" ); props[ test ][ "event" ] = $.camelCase( props[ test ][ "prefix" ] + test + "-" + "end" ); // All lower case if not a vendor prop if ( props[ test ][ "prefix" ] === "" ) { props[ test ][ "duration" ] = props[ test ][ "duration" ].toLowerCase(); props[ test ][ "event" ] = props[ test ][ "event" ].toLowerCase(); } }); // If a valid prefix was found then the it is supported by the browser $.support.cssTransitions = ( props[ "transition" ][ "prefix" ] !== undefined ); $.support.cssAnimations = ( props[ "animation" ][ "prefix" ] !== undefined ); // Remove the testElement $( testElement ).remove(); // Animation complete callback $.fn.animationComplete = function( callback, type, fallbackTime ) { var timer, duration, that = this, animationType = ( !type || type === "animation" ) ? "animation" : "transition"; // Make sure selected type is supported by browser if ( ( $.support.cssTransitions && animationType === "transition" ) || ( $.support.cssAnimations && animationType === "animation" ) ) { // If a fallback time was not passed set one if ( fallbackTime === undefined ) { // Make sure the was not bound to document before checking .css if ( $( this ).context !== document ) { // Parse the durration since its in second multiple by 1000 for milliseconds // Multiply by 3 to make sure we give the animation plenty of time. duration = parseFloat( $( this ).css( props[ animationType ].duration ) ) * 3000; } // If we could not read a duration use the default if ( duration === 0 || duration === undefined ) { duration = $.fn.animationComplete.default; } } // Sets up the fallback if event never comes timer = setTimeout( function() { $( that ).off( props[ animationType ].event ); callback.apply( that ); }, duration ); // Bind the event return $( this ).one( props[ animationType ].event, function() { // Clear the timer so we dont call callback twice clearTimeout( timer ); callback.call( this, arguments ); }); } else { // CSS animation / transitions not supported // Defer execution for consistency between webkit/non webkit setTimeout( $.proxy( callback, this ), 0 ); return $( this ); } }; // Allow default callback to be configured on mobileInit $.fn.animationComplete.default = 1000; })( jQuery ); //>>excludeStart("jqmBuildExclude", pragmas.jqmBuildExclude); }); //>>excludeEnd("jqmBuildExclude");
ericsteele/retrospec.js
test/input/projects/jquery-mobile/rev-1.4.1-3455ada/js/jquery.mobile.animationComplete.js
JavaScript
mit
3,468
/* eslint no-use-before-define: "off" */ import React from 'react'; import { act } from 'react-dom/test-utils'; import { mount } from 'enzyme'; import Transfer from '..'; const listProps = { dataSource: [ { key: 'a', title: 'a', disabled: true, }, { key: 'b', title: 'b', }, { key: 'c', title: 'c', }, { key: 'd', title: 'd', }, { key: 'e', title: 'e', }, ], selectedKeys: ['b'], targetKeys: [], pagination: { pageSize: 4 }, }; describe('Transfer.Dropdown', () => { function clickItem(wrapper, index) { wrapper.find('li.ant-dropdown-menu-item').at(index).simulate('click'); } it('select all', () => { jest.useFakeTimers(); const onSelectChange = jest.fn(); const wrapper = mount(<Transfer {...listProps} onSelectChange={onSelectChange} />); wrapper.find('.ant-transfer-list-header-dropdown').first().simulate('mouseenter'); act(() => { jest.runAllTimers(); }); wrapper.update(); clickItem(wrapper.find('.ant-dropdown-menu').first(), 0); expect(onSelectChange).toHaveBeenCalledWith(['b', 'c', 'd', 'e'], []); jest.useRealTimers(); }); it('select current page', () => { jest.useFakeTimers(); const onSelectChange = jest.fn(); const wrapper = mount(<Transfer {...listProps} onSelectChange={onSelectChange} />); wrapper.find('.ant-transfer-list-header-dropdown').first().simulate('mouseenter'); act(() => { jest.runAllTimers(); }); wrapper.update(); clickItem(wrapper.find('.ant-dropdown-menu').first(), 1); expect(onSelectChange).toHaveBeenCalledWith(['b', 'c', 'd'], []); jest.useRealTimers(); }); it('should hide checkbox and dropdown icon when showSelectAll={false}', () => { const wrapper = mount(<Transfer {...listProps} showSelectAll={false} />); expect(wrapper.find('.ant-transfer-list-header-dropdown').length).toBe(0); expect(wrapper.find('.ant-transfer-list-header .ant-transfer-list-checkbox').length).toBe(0); }); describe('select invert', () => { [ { name: 'with pagination', props: listProps, index: 2, keys: ['c', 'd'] }, { name: 'without pagination', props: { ...listProps, pagination: null }, index: 1, keys: ['c', 'd', 'e'], }, ].forEach(({ name, props, index, keys }) => { it(name, () => { jest.useFakeTimers(); const onSelectChange = jest.fn(); const wrapper = mount(<Transfer {...props} onSelectChange={onSelectChange} />); wrapper.find('.ant-transfer-list-header-dropdown').first().simulate('mouseenter'); act(() => { jest.runAllTimers(); }); wrapper.update(); clickItem(wrapper.find('.ant-dropdown-menu').first(), index); expect(onSelectChange).toHaveBeenCalledWith(keys, []); jest.useRealTimers(); }); }); }); describe('oneWay to remove', () => { [ { name: 'with pagination', props: listProps }, { name: 'without pagination', props: { ...listProps, pagination: null } }, ].forEach(({ name, props }) => { it(name, () => { jest.useFakeTimers(); const onChange = jest.fn(); const wrapper = mount( <Transfer {...props} targetKeys={['b', 'c']} oneWay onChange={onChange} />, ); wrapper.find('.ant-transfer-list-header-dropdown').last().simulate('mouseenter'); act(() => { jest.runAllTimers(); }); wrapper.update(); clickItem(wrapper.find('.ant-dropdown-menu').first(), 0); expect(onChange).toHaveBeenCalledWith([], 'left', ['b', 'c']); jest.useRealTimers(); }); }); }); });
ant-design/ant-design
components/transfer/__tests__/dropdown.test.js
JavaScript
mit
3,765
addJs('http://10.16.28.75:3000/block.js?v=2');
SKing7/charted
pub/resource.js
JavaScript
mit
47
var UserProxy = (function(){ /** * @license almond 0.2.9 Copyright (c) 2011-2014, The Dojo Foundation All Rights Reserved. * Available via the MIT or new BSD license. * see: http://github.com/jrburke/almond for details */ //Going sloppy to avoid 'use strict' string cost, but strict practices should //be followed. /*jslint sloppy: true */ /*global setTimeout: false */ var requirejs, require, define; (function (undef) { var main, req, makeMap, handlers, defined = {}, waiting = {}, config = {}, defining = {}, hasOwn = Object.prototype.hasOwnProperty, aps = [].slice, jsSuffixRegExp = /\.js$/; function hasProp(obj, prop) { return hasOwn.call(obj, prop); } /** * Given a relative module name, like ./something, normalize it to * a real name that can be mapped to a path. * @param {String} name the relative name * @param {String} baseName a real name that the name arg is relative * to. * @returns {String} normalized name */ function normalize(name, baseName) { var nameParts, nameSegment, mapValue, foundMap, lastIndex, foundI, foundStarMap, starI, i, j, part, baseParts = baseName && baseName.split("/"), map = config.map, starMap = (map && map['*']) || {}; //Adjust any relative paths. if (name && name.charAt(0) === ".") { //If have a base name, try to normalize against it, //otherwise, assume it is a top-level require that will //be relative to baseUrl in the end. if (baseName) { //Convert baseName to array, and lop off the last part, //so that . matches that "directory" and not name of the baseName's //module. For instance, baseName of "one/two/three", maps to //"one/two/three.js", but we want the directory, "one/two" for //this normalization. baseParts = baseParts.slice(0, baseParts.length - 1); name = name.split('/'); lastIndex = name.length - 1; // Node .js allowance: if (config.nodeIdCompat && jsSuffixRegExp.test(name[lastIndex])) { name[lastIndex] = name[lastIndex].replace(jsSuffixRegExp, ''); } name = baseParts.concat(name); //start trimDots for (i = 0; i < name.length; i += 1) { part = name[i]; if (part === ".") { name.splice(i, 1); i -= 1; } else if (part === "..") { if (i === 1 && (name[2] === '..' || name[0] === '..')) { //End of the line. Keep at least one non-dot //path segment at the front so it can be mapped //correctly to disk. Otherwise, there is likely //no path mapping for a path starting with '..'. //This can still fail, but catches the most reasonable //uses of .. break; } else if (i > 0) { name.splice(i - 1, 2); i -= 2; } } } //end trimDots name = name.join("/"); } else if (name.indexOf('./') === 0) { // No baseName, so this is ID is resolved relative // to baseUrl, pull off the leading dot. name = name.substring(2); } } //Apply map config if available. if ((baseParts || starMap) && map) { nameParts = name.split('/'); for (i = nameParts.length; i > 0; i -= 1) { nameSegment = nameParts.slice(0, i).join("/"); if (baseParts) { //Find the longest baseName segment match in the config. //So, do joins on the biggest to smallest lengths of baseParts. for (j = baseParts.length; j > 0; j -= 1) { mapValue = map[baseParts.slice(0, j).join('/')]; //baseName segment has config, find if it has one for //this name. if (mapValue) { mapValue = mapValue[nameSegment]; if (mapValue) { //Match, update name to the new value. foundMap = mapValue; foundI = i; break; } } } } if (foundMap) { break; } //Check for a star map match, but just hold on to it, //if there is a shorter segment match later in a matching //config, then favor over this star map. if (!foundStarMap && starMap && starMap[nameSegment]) { foundStarMap = starMap[nameSegment]; starI = i; } } if (!foundMap && foundStarMap) { foundMap = foundStarMap; foundI = starI; } if (foundMap) { nameParts.splice(0, foundI, foundMap); name = nameParts.join('/'); } } return name; } function makeRequire(relName, forceSync) { return function () { //A version of a require function that passes a moduleName //value for items that may need to //look up paths relative to the moduleName return req.apply(undef, aps.call(arguments, 0).concat([relName, forceSync])); }; } function makeNormalize(relName) { return function (name) { return normalize(name, relName); }; } function makeLoad(depName) { return function (value) { defined[depName] = value; }; } function callDep(name) { if (hasProp(waiting, name)) { var args = waiting[name]; delete waiting[name]; defining[name] = true; main.apply(undef, args); } if (!hasProp(defined, name) && !hasProp(defining, name)) { throw new Error('No ' + name); } return defined[name]; } //Turns a plugin!resource to [plugin, resource] //with the plugin being undefined if the name //did not have a plugin prefix. function splitPrefix(name) { var prefix, index = name ? name.indexOf('!') : -1; if (index > -1) { prefix = name.substring(0, index); name = name.substring(index + 1, name.length); } return [prefix, name]; } /** * Makes a name map, normalizing the name, and using a plugin * for normalization if necessary. Grabs a ref to plugin * too, as an optimization. */ makeMap = function (name, relName) { var plugin, parts = splitPrefix(name), prefix = parts[0]; name = parts[1]; if (prefix) { prefix = normalize(prefix, relName); plugin = callDep(prefix); } //Normalize according if (prefix) { if (plugin && plugin.normalize) { name = plugin.normalize(name, makeNormalize(relName)); } else { name = normalize(name, relName); } } else { name = normalize(name, relName); parts = splitPrefix(name); prefix = parts[0]; name = parts[1]; if (prefix) { plugin = callDep(prefix); } } //Using ridiculous property names for space reasons return { f: prefix ? prefix + '!' + name : name, //fullName n: name, pr: prefix, p: plugin }; }; function makeConfig(name) { return function () { return (config && config.config && config.config[name]) || {}; }; } handlers = { require: function (name) { return makeRequire(name); }, exports: function (name) { var e = defined[name]; if (typeof e !== 'undefined') { return e; } else { return (defined[name] = {}); } }, module: function (name) { return { id: name, uri: '', exports: defined[name], config: makeConfig(name) }; } }; main = function (name, deps, callback, relName) { var cjsModule, depName, ret, map, i, args = [], callbackType = typeof callback, usingExports; //Use name if no relName relName = relName || name; //Call the callback to define the module, if necessary. if (callbackType === 'undefined' || callbackType === 'function') { //Pull out the defined dependencies and pass the ordered //values to the callback. //Default to [require, exports, module] if no deps deps = !deps.length && callback.length ? ['require', 'exports', 'module'] : deps; for (i = 0; i < deps.length; i += 1) { map = makeMap(deps[i], relName); depName = map.f; //Fast path CommonJS standard dependencies. if (depName === "require") { args[i] = handlers.require(name); } else if (depName === "exports") { //CommonJS module spec 1.1 args[i] = handlers.exports(name); usingExports = true; } else if (depName === "module") { //CommonJS module spec 1.1 cjsModule = args[i] = handlers.module(name); } else if (hasProp(defined, depName) || hasProp(waiting, depName) || hasProp(defining, depName)) { args[i] = callDep(depName); } else if (map.p) { map.p.load(map.n, makeRequire(relName, true), makeLoad(depName), {}); args[i] = defined[depName]; } else { throw new Error(name + ' missing ' + depName); } } ret = callback ? callback.apply(defined[name], args) : undefined; if (name) { //If setting exports via "module" is in play, //favor that over return value and exports. After that, //favor a non-undefined return value over exports use. if (cjsModule && cjsModule.exports !== undef && cjsModule.exports !== defined[name]) { defined[name] = cjsModule.exports; } else if (ret !== undef || !usingExports) { //Use the return value from the function. defined[name] = ret; } } } else if (name) { //May just be an object definition for the module. Only //worry about defining if have a module name. defined[name] = callback; } }; requirejs = require = req = function (deps, callback, relName, forceSync, alt) { if (typeof deps === "string") { if (handlers[deps]) { //callback in this case is really relName return handlers[deps](callback); } //Just return the module wanted. In this scenario, the //deps arg is the module name, and second arg (if passed) //is just the relName. //Normalize module name, if it contains . or .. return callDep(makeMap(deps, callback).f); } else if (!deps.splice) { //deps is a config object, not an array. config = deps; if (config.deps) { req(config.deps, config.callback); } if (!callback) { return; } if (callback.splice) { //callback is an array, which means it is a dependency list. //Adjust args if there are dependencies deps = callback; callback = relName; relName = null; } else { deps = undef; } } //Support require(['a']) callback = callback || function () {}; //If relName is a function, it is an errback handler, //so remove it. if (typeof relName === 'function') { relName = forceSync; forceSync = alt; } //Simulate async callback; if (forceSync) { main(undef, deps, callback, relName); } else { //Using a non-zero value because of concern for what old browsers //do, and latest browsers "upgrade" to 4 if lower value is used: //http://www.whatwg.org/specs/web-apps/current-work/multipage/timers.html#dom-windowtimers-settimeout: //If want a value immediately, use require('id') instead -- something //that works in almond on the global level, but not guaranteed and //unlikely to work in other AMD implementations. setTimeout(function () { main(undef, deps, callback, relName); }, 4); } return req; }; /** * Just drops the config on the floor, but returns req in case * the config return value is used. */ req.config = function (cfg) { return req(cfg); }; /** * Expose module registry for debugging and tooling */ requirejs._defined = defined; define = function (name, deps, callback) { //This module may not have dependencies if (!deps.splice) { //deps is not an array, so probably means //an object literal or factory function for //the value. Adjust args. callback = deps; deps = []; } if (!hasProp(defined, name) && !hasProp(waiting, name)) { waiting[name] = [name, deps, callback]; } }; define.amd = { jQuery: true }; }()); define("../vendor/almond", function(){}); define('utils',[], function(){ function bind(scope, func) { var args = Array.prototype.slice.call(arguments, 2); return function(){ return func.apply(scope, args.concat(Array.prototype.slice.call(arguments))) }; } // Iterate through obj with the callback function. function each(obj, callback) { if (isArray(obj)) { for (var i = 0; i < obj.length; i++) { if (callback(i, obj[i]) === true) break; } } else { for (var key in obj) { if (obj.hasOwnProperty(key)) { if (callback(key, obj[key]) === true) break; } } } } function getKeys(obj) { var keys = []; each(obj, function(key){ keys.push(key); }); return keys; } // Returns a boolean indicating if object arr is an array. function isArray(arr) { return Object.prototype.toString.call(arr) === "[object Array]"; } // Returns a boolean indicating if the value is in the array. function inArray(value, arr) { for (var i = 0, len = arr.length; i < len; i++) { if (arr[i] === value) { return true; } } return false; } function indexOfArray(value, arr) { for (var i = 0, len = arr.length; i < len; i++) { if (arr[i] === value) { return i; } } return -1; } function indexOf(value, arr) { if (isArray(value, arr)) { return indexOfArray(value, arr); } } // Returns a random number between min and max function getRandomArbitrary(min, max) { return Math.random() * (max - min) + min; } // Returns a random integer between min (included) and max (excluded) function getRandomInt(min, max) { return Math.floor(Math.random() * (max - min)) + min; } // Returns a random string of characters of chars with the length of length function generateToken(chars, length) { if (typeof chars !== "string") chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_"; if (typeof length !== "number") length = 64; var charsLength = chars.length; var token = ""; for (var i = 0; i < length; i++) { token += chars[getRandomInt(0, charsLength)]; } return token; } function escapeECMAVariable(key, defaultKey) { key = key.replace(/[^0-9a-zA-Z_\$]/g, ""); while (/$[0-9]/g.test(key)) { if (key === "") return defaultKey; key = key.substring(1); } return key; } return { bind: bind, each: each, getKeys: getKeys, isArray: isArray, inArray: inArray, indexOf: indexOf, indexOfArray: indexOfArray, getRandomArbitrary: getRandomArbitrary, getRandomInt: getRandomInt, generateToken: generateToken, escapeECMAVariable: escapeECMAVariable }; }); define('support',[], function(){ function customEvent() { try { var e = document.createEvent('CustomEvent'); if (e && typeof e.initCustomEvent === "function") { e.initCustomEvent(mod, true, true, { mod: mod }); return true; } return false; } catch (e) { return false; } } var mod = "support.test"; return { CustomEvent: customEvent }; }); define('CustomEvent',["utils"], function(utils){ function addEventListener(event, listener) { if (!events[event]) { // Creating the array of listeners for event events[event] = []; // Adding the event listener. window.addEventListener(event, utils.bind(null, eventListener, event, events[event]), false); } // Adding listener to array. events[event].push(listener); } function eventListener(event, listeners, e) { e = e || window.event; // Parse the detail to the original object. var data = JSON.parse(e.detail); if (typeof data.detail === "object" && data.token !== token) { var detail = data.detail; for (var i = 0, len = listeners.length; i < len; i++) { // Call the listener with the event name and the parsed detail. listeners[i](detail); } // Prevent propagation if (e && typeof e.stopPropagation === "function") { e.stopPropagation(); } } } /*function eventListener(event, listener, e) { e = e || window.event; // Parse the detail to the original object. var data = JSON.parse(e.detail); if (typeof data.detail === "object" && data.token !== token) { // Prevent propagation if (e && typeof e.stopPropagation === "function") { e.stopPropagation(); } // Call the listener with the parsed detail. listener(data.detail); } }*/ function fireEvent(event, detail) { // Creating the event var e = document.createEvent("CustomEvent"); e.initCustomEvent(event, true, true, JSON.stringify({ detail: detail, token: token })); // Firing the event document.documentElement.dispatchEvent(e); } var token = utils.generateToken(); // The token is used to identify itself and prevent calling its own listeners. var events = {}; return { addEventListener: addEventListener, fireEvent: fireEvent }; }); define('Message',["utils"], function(utils){ function addEventListener(event, listener) { initMessage(); // Init the message event listener if not already initialized. if (!events[event]) events[event] = []; // Bind the event name to the listener as an argument. var boundListener = utils.bind(null, listener, event); // Add the boundListener to the event events[event].push(boundListener); } function fireEvent(event, detail) { window.postMessage(JSON.stringify({ token: token, event: event, detail: detail }), "*"); } function messageListener(e) { e = e || window.event; // Parse the detail to the original object. var data = JSON.parse(e.data); // Verify that the retrieved information is correct and that it didn't call itself. if (typeof data.event === "string" && typeof data.detail === "object" && data.token !== token) { // Iterate through every listener for data.event. if (utils.isArray(events[data.event])) { var listeners = events[data.event]; var detail = data.detail; for (var i = 0, len = listeners.length; i < len; i++) { listeners(detail); } // Prevent propagation only if everything went well. if (e && typeof e.stopPropagation === "function") { e.stopPropagation(); } } } } function initMessage() { if (!messageEventAdded) { // Adding the message event listener. window.addEventListener("message", messageListener, false); } } var messageEventAdded = false; var token = utils.generateToken(); // The token is used to identify itself and prevent calling its own listeners. var events = {}; return { addEventListener: addEventListener, fireEvent: fireEvent }; }); define('memFunction',["utils", "CustomEvent", "Message", "support"], function(utils, customEvent, message, support){ function parseObject(obj, token, type) { if (typeof obj === "object") { utils.each(obj, function(key, value){ if (typeof value === "object") { obj[key] = parseObject(value, token, type); } else if (typeof value === "string") { obj[key] = parseString(value); } else if (typeof value === "function") { var id = cache.push(value) - 1; obj[key] = "${" + token + "/" + type + "/" + id + "}"; } }); } else if (typeof value === "string") { obj = parseString(obj); } else if (typeof obj === "function") { var id = cache.push(obj) - 1; obj = "${" + token + "/" + type + "/" + id + "}"; } return obj; } function parseString(str) { if (/^\$[\\]*\{([0-9a-zA-Z\.\-_\/\\]+)\}$/g.test(str)) { return "$\\" + str.substring(1); } return str; } function restoreString(str, token, type) { if (/^\$\{([0-9a-zA-Z\.\-_]+)\/([0-9a-zA-Z\.\-_]+)\/([0-9]+)\}$/g.test(str)) { var parsed = str.substring(2, str.length - 1).split("/"); // " + token + "/" + type + "/" + id + " var id = parseInt(parsed[2], 10); if (parsed[0] === token && parsed[1] === type) { return cache[id]; } else { return utils.bind(null, functionPlaceholder, parsed[0] + "-" + parsed[1], id); } } else if (/^\$[\\]+\{([0-9a-zA-Z\.\-_\/\\]+)\}$/g.test(str)) { return "$" + str.substring(2); } return str; } function restoreObject(obj, token, type) { if (typeof obj === "object") { utils.each(obj, function(key, value){ if (typeof value === "object") { obj[key] = restoreObject(value, token, type); } else if (typeof value === "string") { obj[key] = restoreString(value, token, type); } else if (typeof value === "function") { throw Error("Function was found!"); } }); } else if (typeof value === "string") { return restoreString(value, token, type); } else if (typeof value === "function") { throw Error("Function was found!"); } return obj; } function functionPlaceholder(event, id) { var args = Array.prototype.slice.call(arguments, 2); if (support.CustomEvent) { return customEvent.fireEvent(event, { callbackId: id, args: args, mem: true }); } else { return message.fireEvent(event, { callbackId: id, args: args, mem: true }); } } function getCacheFunction(id) { return cache[id]; } var cache = []; return { parseObject: parseObject, restoreObject: restoreObject, getCacheFunction: getCacheFunction }; }); define('Connection',["CustomEvent", "Message", "utils", "support", "memFunction"], function(customEvent, message, utils, support, mem){ function initListeners(token, functions) { if (support.CustomEvent) { customEvent.addEventListener(token + "-content", utils.bind(null, listenerProxy, functions, token, "content")); } else { message.addEventListener(token + "-content", utils.bind(null, listenerProxy, functions, token, "content")); } } function listenerProxy(functions, token, type, detail) { setTimeout(utils.bind(null, listener, functions, token, type, detail), 4); } function listener(functions, token, type, detail) { var keys = utils.getKeys(functions); var index = utils.indexOfArray(detail.method, keys); if (index > -1) { var result = functions[keys[index]].apply(null, mem.restoreObject(detail.args, token, type)); if (typeof detail.id === "number") { var memResult = mem.parseObject(result, token, type); var detail = { callbackId: detail.id, args: [ memResult ] }; if (support.CustomEvent) { customEvent.fireEvent(token + "-page", detail); } else { message.addEventListener(token + "-page", detail); } } } else { throw "Method " + detail.method + " has not been set!"; } } function Connection(pageProxy) { this.token = utils.generateToken(); this.functions = {}; this.namespace = "UserProxy"; this.pageProxy = pageProxy; } Connection.prototype.setFunctions = function setFunctions(functions) { this.functions = functions; } Connection.prototype.setNamespace = function setFunctions(namespace) { this.namespace = namespace; } Connection.prototype.inject = function inject(code) { var parent = (document.body || document.head || document.documentElement); if (!parent) throw "Parent was not found!"; var script = document.createElement("script") script.setAttribute("type", "text/javascript"); var wrapper = [";(function(unsafeWindow){var " + utils.escapeECMAVariable(this.namespace) + " = (" + this.pageProxy + ")(\"" + this.token + "\", " + JSON.stringify(utils.getKeys(this.functions)) + ", this);", "})(window);"]; if (typeof code === "string") { code = "function(){" + code + "}" } initListeners(this.token, this.functions); script.appendChild(document.createTextNode(wrapper[0] + "(" + code + ")();" + wrapper[1])); parent.appendChild(script); parent.removeChild(script); } return Connection; }); define('main',["utils", "support", "Connection"], function(utils, support, Connection){ function inject(code) { var conn = new Connection(pageProxy); conn.setFunctions(funcs); conn.setNamespace(namespace); conn.inject(code); } function setFunctions(functions) { funcs = functions; } function setNamespace(n) { namespace = n; } var funcs = {}; var namespace = "UserProxy"; var pageProxy = function(token, functions, scope){ /** * @license almond 0.2.9 Copyright (c) 2011-2014, The Dojo Foundation All Rights Reserved. * Available via the MIT or new BSD license. * see: http://github.com/jrburke/almond for details */ //Going sloppy to avoid 'use strict' string cost, but strict practices should //be followed. /*jslint sloppy: true */ /*global setTimeout: false */ var requirejs, require, define; (function (undef) { var main, req, makeMap, handlers, defined = {}, waiting = {}, config = {}, defining = {}, hasOwn = Object.prototype.hasOwnProperty, aps = [].slice, jsSuffixRegExp = /\.js$/; function hasProp(obj, prop) { return hasOwn.call(obj, prop); } /** * Given a relative module name, like ./something, normalize it to * a real name that can be mapped to a path. * @param {String} name the relative name * @param {String} baseName a real name that the name arg is relative * to. * @returns {String} normalized name */ function normalize(name, baseName) { var nameParts, nameSegment, mapValue, foundMap, lastIndex, foundI, foundStarMap, starI, i, j, part, baseParts = baseName && baseName.split("/"), map = config.map, starMap = (map && map['*']) || {}; //Adjust any relative paths. if (name && name.charAt(0) === ".") { //If have a base name, try to normalize against it, //otherwise, assume it is a top-level require that will //be relative to baseUrl in the end. if (baseName) { //Convert baseName to array, and lop off the last part, //so that . matches that "directory" and not name of the baseName's //module. For instance, baseName of "one/two/three", maps to //"one/two/three.js", but we want the directory, "one/two" for //this normalization. baseParts = baseParts.slice(0, baseParts.length - 1); name = name.split('/'); lastIndex = name.length - 1; // Node .js allowance: if (config.nodeIdCompat && jsSuffixRegExp.test(name[lastIndex])) { name[lastIndex] = name[lastIndex].replace(jsSuffixRegExp, ''); } name = baseParts.concat(name); //start trimDots for (i = 0; i < name.length; i += 1) { part = name[i]; if (part === ".") { name.splice(i, 1); i -= 1; } else if (part === "..") { if (i === 1 && (name[2] === '..' || name[0] === '..')) { //End of the line. Keep at least one non-dot //path segment at the front so it can be mapped //correctly to disk. Otherwise, there is likely //no path mapping for a path starting with '..'. //This can still fail, but catches the most reasonable //uses of .. break; } else if (i > 0) { name.splice(i - 1, 2); i -= 2; } } } //end trimDots name = name.join("/"); } else if (name.indexOf('./') === 0) { // No baseName, so this is ID is resolved relative // to baseUrl, pull off the leading dot. name = name.substring(2); } } //Apply map config if available. if ((baseParts || starMap) && map) { nameParts = name.split('/'); for (i = nameParts.length; i > 0; i -= 1) { nameSegment = nameParts.slice(0, i).join("/"); if (baseParts) { //Find the longest baseName segment match in the config. //So, do joins on the biggest to smallest lengths of baseParts. for (j = baseParts.length; j > 0; j -= 1) { mapValue = map[baseParts.slice(0, j).join('/')]; //baseName segment has config, find if it has one for //this name. if (mapValue) { mapValue = mapValue[nameSegment]; if (mapValue) { //Match, update name to the new value. foundMap = mapValue; foundI = i; break; } } } } if (foundMap) { break; } //Check for a star map match, but just hold on to it, //if there is a shorter segment match later in a matching //config, then favor over this star map. if (!foundStarMap && starMap && starMap[nameSegment]) { foundStarMap = starMap[nameSegment]; starI = i; } } if (!foundMap && foundStarMap) { foundMap = foundStarMap; foundI = starI; } if (foundMap) { nameParts.splice(0, foundI, foundMap); name = nameParts.join('/'); } } return name; } function makeRequire(relName, forceSync) { return function () { //A version of a require function that passes a moduleName //value for items that may need to //look up paths relative to the moduleName return req.apply(undef, aps.call(arguments, 0).concat([relName, forceSync])); }; } function makeNormalize(relName) { return function (name) { return normalize(name, relName); }; } function makeLoad(depName) { return function (value) { defined[depName] = value; }; } function callDep(name) { if (hasProp(waiting, name)) { var args = waiting[name]; delete waiting[name]; defining[name] = true; main.apply(undef, args); } if (!hasProp(defined, name) && !hasProp(defining, name)) { throw new Error('No ' + name); } return defined[name]; } //Turns a plugin!resource to [plugin, resource] //with the plugin being undefined if the name //did not have a plugin prefix. function splitPrefix(name) { var prefix, index = name ? name.indexOf('!') : -1; if (index > -1) { prefix = name.substring(0, index); name = name.substring(index + 1, name.length); } return [prefix, name]; } /** * Makes a name map, normalizing the name, and using a plugin * for normalization if necessary. Grabs a ref to plugin * too, as an optimization. */ makeMap = function (name, relName) { var plugin, parts = splitPrefix(name), prefix = parts[0]; name = parts[1]; if (prefix) { prefix = normalize(prefix, relName); plugin = callDep(prefix); } //Normalize according if (prefix) { if (plugin && plugin.normalize) { name = plugin.normalize(name, makeNormalize(relName)); } else { name = normalize(name, relName); } } else { name = normalize(name, relName); parts = splitPrefix(name); prefix = parts[0]; name = parts[1]; if (prefix) { plugin = callDep(prefix); } } //Using ridiculous property names for space reasons return { f: prefix ? prefix + '!' + name : name, //fullName n: name, pr: prefix, p: plugin }; }; function makeConfig(name) { return function () { return (config && config.config && config.config[name]) || {}; }; } handlers = { require: function (name) { return makeRequire(name); }, exports: function (name) { var e = defined[name]; if (typeof e !== 'undefined') { return e; } else { return (defined[name] = {}); } }, module: function (name) { return { id: name, uri: '', exports: defined[name], config: makeConfig(name) }; } }; main = function (name, deps, callback, relName) { var cjsModule, depName, ret, map, i, args = [], callbackType = typeof callback, usingExports; //Use name if no relName relName = relName || name; //Call the callback to define the module, if necessary. if (callbackType === 'undefined' || callbackType === 'function') { //Pull out the defined dependencies and pass the ordered //values to the callback. //Default to [require, exports, module] if no deps deps = !deps.length && callback.length ? ['require', 'exports', 'module'] : deps; for (i = 0; i < deps.length; i += 1) { map = makeMap(deps[i], relName); depName = map.f; //Fast path CommonJS standard dependencies. if (depName === "require") { args[i] = handlers.require(name); } else if (depName === "exports") { //CommonJS module spec 1.1 args[i] = handlers.exports(name); usingExports = true; } else if (depName === "module") { //CommonJS module spec 1.1 cjsModule = args[i] = handlers.module(name); } else if (hasProp(defined, depName) || hasProp(waiting, depName) || hasProp(defining, depName)) { args[i] = callDep(depName); } else if (map.p) { map.p.load(map.n, makeRequire(relName, true), makeLoad(depName), {}); args[i] = defined[depName]; } else { throw new Error(name + ' missing ' + depName); } } ret = callback ? callback.apply(defined[name], args) : undefined; if (name) { //If setting exports via "module" is in play, //favor that over return value and exports. After that, //favor a non-undefined return value over exports use. if (cjsModule && cjsModule.exports !== undef && cjsModule.exports !== defined[name]) { defined[name] = cjsModule.exports; } else if (ret !== undef || !usingExports) { //Use the return value from the function. defined[name] = ret; } } } else if (name) { //May just be an object definition for the module. Only //worry about defining if have a module name. defined[name] = callback; } }; requirejs = require = req = function (deps, callback, relName, forceSync, alt) { if (typeof deps === "string") { if (handlers[deps]) { //callback in this case is really relName return handlers[deps](callback); } //Just return the module wanted. In this scenario, the //deps arg is the module name, and second arg (if passed) //is just the relName. //Normalize module name, if it contains . or .. return callDep(makeMap(deps, callback).f); } else if (!deps.splice) { //deps is a config object, not an array. config = deps; if (config.deps) { req(config.deps, config.callback); } if (!callback) { return; } if (callback.splice) { //callback is an array, which means it is a dependency list. //Adjust args if there are dependencies deps = callback; callback = relName; relName = null; } else { deps = undef; } } //Support require(['a']) callback = callback || function () {}; //If relName is a function, it is an errback handler, //so remove it. if (typeof relName === 'function') { relName = forceSync; forceSync = alt; } //Simulate async callback; if (forceSync) { main(undef, deps, callback, relName); } else { //Using a non-zero value because of concern for what old browsers //do, and latest browsers "upgrade" to 4 if lower value is used: //http://www.whatwg.org/specs/web-apps/current-work/multipage/timers.html#dom-windowtimers-settimeout: //If want a value immediately, use require('id') instead -- something //that works in almond on the global level, but not guaranteed and //unlikely to work in other AMD implementations. setTimeout(function () { main(undef, deps, callback, relName); }, 4); } return req; }; /** * Just drops the config on the floor, but returns req in case * the config return value is used. */ req.config = function (cfg) { return req(cfg); }; /** * Expose module registry for debugging and tooling */ requirejs._defined = defined; define = function (name, deps, callback) { //This module may not have dependencies if (!deps.splice) { //deps is not an array, so probably means //an object literal or factory function for //the value. Adjust args. callback = deps; deps = []; } if (!hasProp(defined, name) && !hasProp(waiting, name)) { waiting[name] = [name, deps, callback]; } }; define.amd = { jQuery: true }; }()); define("../vendor/almond", function(){}); define('support',[], function(){ function customEvent() { try { var e = document.createEvent('CustomEvent'); if (e && typeof e.initCustomEvent === "function") { e.initCustomEvent(mod, true, true, { mod: mod }); return true; } return false; } catch (e) { return false; } } var mod = "support.test"; return { CustomEvent: customEvent }; }); define('utils',[], function(){ function bind(scope, func) { var args = Array.prototype.slice.call(arguments, 2); return function(){ return func.apply(scope, args.concat(Array.prototype.slice.call(arguments))) }; } // Iterate through obj with the callback function. function each(obj, callback) { if (isArray(obj)) { for (var i = 0; i < obj.length; i++) { if (callback(i, obj[i]) === true) break; } } else { for (var key in obj) { if (obj.hasOwnProperty(key)) { if (callback(key, obj[key]) === true) break; } } } } function getKeys(obj) { var keys = []; each(obj, function(key){ keys.push(key); }); return keys; } // Returns a boolean indicating if object arr is an array. function isArray(arr) { return Object.prototype.toString.call(arr) === "[object Array]"; } // Returns a boolean indicating if the value is in the array. function inArray(value, arr) { for (var i = 0, len = arr.length; i < len; i++) { if (arr[i] === value) { return true; } } return false; } function indexOfArray(value, arr) { for (var i = 0, len = arr.length; i < len; i++) { if (arr[i] === value) { return i; } } return -1; } function indexOf(value, arr) { if (isArray(value, arr)) { return indexOfArray(value, arr); } } // Returns a random number between min and max function getRandomArbitrary(min, max) { return Math.random() * (max - min) + min; } // Returns a random integer between min (included) and max (excluded) function getRandomInt(min, max) { return Math.floor(Math.random() * (max - min)) + min; } // Returns a random string of characters of chars with the length of length function generateToken(chars, length) { if (typeof chars !== "string") chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_"; if (typeof length !== "number") length = 64; var charsLength = chars.length; var token = ""; for (var i = 0; i < length; i++) { token += chars[getRandomInt(0, charsLength)]; } return token; } function escapeECMAVariable(key, defaultKey) { key = key.replace(/[^0-9a-zA-Z_\$]/g, ""); while (/$[0-9]/g.test(key)) { if (key === "") return defaultKey; key = key.substring(1); } return key; } return { bind: bind, each: each, getKeys: getKeys, isArray: isArray, inArray: inArray, indexOf: indexOf, indexOfArray: indexOfArray, getRandomArbitrary: getRandomArbitrary, getRandomInt: getRandomInt, generateToken: generateToken, escapeECMAVariable: escapeECMAVariable }; }); define('CustomEvent',["utils"], function(utils){ function addEventListener(event, listener) { if (!events[event]) { // Creating the array of listeners for event events[event] = []; // Adding the event listener. window.addEventListener(event, utils.bind(null, eventListener, event, events[event]), false); } // Adding listener to array. events[event].push(listener); } function eventListener(event, listeners, e) { e = e || window.event; // Parse the detail to the original object. var data = JSON.parse(e.detail); if (typeof data.detail === "object" && data.token !== token) { var detail = data.detail; for (var i = 0, len = listeners.length; i < len; i++) { // Call the listener with the event name and the parsed detail. listeners[i](detail); } // Prevent propagation if (e && typeof e.stopPropagation === "function") { e.stopPropagation(); } } } /*function eventListener(event, listener, e) { e = e || window.event; // Parse the detail to the original object. var data = JSON.parse(e.detail); if (typeof data.detail === "object" && data.token !== token) { // Prevent propagation if (e && typeof e.stopPropagation === "function") { e.stopPropagation(); } // Call the listener with the parsed detail. listener(data.detail); } }*/ function fireEvent(event, detail) { // Creating the event var e = document.createEvent("CustomEvent"); e.initCustomEvent(event, true, true, JSON.stringify({ detail: detail, token: token })); // Firing the event document.documentElement.dispatchEvent(e); } var token = utils.generateToken(); // The token is used to identify itself and prevent calling its own listeners. var events = {}; return { addEventListener: addEventListener, fireEvent: fireEvent }; }); define('Message',["utils"], function(utils){ function addEventListener(event, listener) { initMessage(); // Init the message event listener if not already initialized. if (!events[event]) events[event] = []; // Bind the event name to the listener as an argument. var boundListener = utils.bind(null, listener, event); // Add the boundListener to the event events[event].push(boundListener); } function fireEvent(event, detail) { window.postMessage(JSON.stringify({ token: token, event: event, detail: detail }), "*"); } function messageListener(e) { e = e || window.event; // Parse the detail to the original object. var data = JSON.parse(e.data); // Verify that the retrieved information is correct and that it didn't call itself. if (typeof data.event === "string" && typeof data.detail === "object" && data.token !== token) { // Iterate through every listener for data.event. if (utils.isArray(events[data.event])) { var listeners = events[data.event]; var detail = data.detail; for (var i = 0, len = listeners.length; i < len; i++) { listeners(detail); } // Prevent propagation only if everything went well. if (e && typeof e.stopPropagation === "function") { e.stopPropagation(); } } } } function initMessage() { if (!messageEventAdded) { // Adding the message event listener. window.addEventListener("message", messageListener, false); } } var messageEventAdded = false; var token = utils.generateToken(); // The token is used to identify itself and prevent calling its own listeners. var events = {}; return { addEventListener: addEventListener, fireEvent: fireEvent }; }); define('memFunction',["utils", "CustomEvent", "Message", "support"], function(utils, customEvent, message, support){ function parseObject(obj, token, type) { if (typeof obj === "object") { utils.each(obj, function(key, value){ if (typeof value === "object") { obj[key] = parseObject(value, token, type); } else if (typeof value === "string") { obj[key] = parseString(value); } else if (typeof value === "function") { var id = cache.push(value) - 1; obj[key] = "${" + token + "/" + type + "/" + id + "}"; } }); } else if (typeof value === "string") { obj = parseString(obj); } else if (typeof obj === "function") { var id = cache.push(obj) - 1; obj = "${" + token + "/" + type + "/" + id + "}"; } return obj; } function parseString(str) { if (/^\$[\\]*\{([0-9a-zA-Z\.\-_\/\\]+)\}$/g.test(str)) { return "$\\" + str.substring(1); } return str; } function restoreString(str, token, type) { if (/^\$\{([0-9a-zA-Z\.\-_]+)\/([0-9a-zA-Z\.\-_]+)\/([0-9]+)\}$/g.test(str)) { var parsed = str.substring(2, str.length - 1).split("/"); // " + token + "/" + type + "/" + id + " var id = parseInt(parsed[2], 10); if (parsed[0] === token && parsed[1] === type) { return cache[id]; } else { return utils.bind(null, functionPlaceholder, parsed[0] + "-" + parsed[1], id); } } else if (/^\$[\\]+\{([0-9a-zA-Z\.\-_\/\\]+)\}$/g.test(str)) { return "$" + str.substring(2); } return str; } function restoreObject(obj, token, type) { if (typeof obj === "object") { utils.each(obj, function(key, value){ if (typeof value === "object") { obj[key] = restoreObject(value, token, type); } else if (typeof value === "string") { obj[key] = restoreString(value, token, type); } else if (typeof value === "function") { throw Error("Function was found!"); } }); } else if (typeof value === "string") { return restoreString(value, token, type); } else if (typeof value === "function") { throw Error("Function was found!"); } return obj; } function functionPlaceholder(event, id) { var args = Array.prototype.slice.call(arguments, 2); if (support.CustomEvent) { return customEvent.fireEvent(event, { callbackId: id, args: args, mem: true }); } else { return message.fireEvent(event, { callbackId: id, args: args, mem: true }); } } function getCacheFunction(id) { return cache[id]; } var cache = []; return { parseObject: parseObject, restoreObject: restoreObject, getCacheFunction: getCacheFunction }; }); define('proxy',["support", "CustomEvent", "Message", "utils", "memFunction"], function(support, customEvent, message, utils, mem){ function listener(detail) { if (typeof detail.callbackId === "number" && utils.isArray(detail.args) && detail.mem) { var args = mem.restoreObject(detail.args, token, "page"); var func = mem.getCacheFunction(detail.callbackId); if (typeof func === "function") { func.apply(null, args); } } else if (typeof detail.callbackId === "number" && utils.isArray(detail.args)) { var args = mem.restoreObject(detail.args, token, "page"); if (typeof callbackCache[detail.callbackId] === "function") { callbackCache[detail.callbackId].apply(null, args); } //callbackCache[detail.callbackId] = null; // Remove reference for GC. } else { throw Error("Malformed detail!", detail); } } function prepareCall(method, callback) { if (!has(method)) { throw Error(method + " is not a defined function!"); } if (typeof callback !== "function") { throw Error("The callback is not a function!"); } var id = callbackCache.push(callback) - 1; var args = Array.prototype.slice.call(arguments, 2); return function() { args = args.concat(Array.prototype.slice.call(arguments, 0)); args = mem.parseObject(args, token, "page"); var detail = { method: method, args: args, id: id }; if (support.CustomEvent) { customEvent.fireEvent(token + "-content", detail); } else { message.fireEvent(token + "-content", detail); } }; } function call(method, args) { function setCallback(callback) { clearTimeout(timer); if (typeof callback === "function") { detail.id = callbackCache.push(callback) - 1; } execute(); } function execute() { if (support.CustomEvent) { customEvent.fireEvent(token + "-content", detail); } else { message.fireEvent(token + "-content", detail); } } args = Array.prototype.slice.call(arguments, 1); if (!has(method)) { throw Error(method + " is not a defined function!"); } args = mem.parseObject(args, token, "page"); var detail = { method: method, args: args }; var timer = setTimeout(execute, 4); return { then: setCallback }; } function has(method) { return utils.indexOfArray(method, functions) > -1; } function getFunction(method) { if (has(method)) { return utils.bind(null, call, method); } else { throw Error(method + " is not defined!"); } } function listFunctions() { return JSON.parse(JSON.stringify(functions)); } var callbackCache = []; if (support.CustomEvent) { customEvent.addEventListener(token + "-page", listener); } else { message.addEventListener(token + "-page", listener); } for (var i = 0, len = functions.length; i < len; i++) { scope[functions[i]] = utils.bind(null, call, functions[i]); } return { call: call, prepareCall: prepareCall, getFunction: getFunction, isDefined: has, listFunctions: listFunctions }; }); return require("proxy"); }; return { connect: inject, setFunctions: setFunctions, setNamespace: setNamespace }; }); return require("main"); })();
YePpHa/UserProxy
UserProxy.js
JavaScript
mit
55,778
export { default as Audience } from './audiences/model' export { default as Client } from './clients/model' export { default as Communication } from './communications/model' export { default as InboundEmail } from './sendgrid/models/inboundEmail' export { default as Lead } from './leads/model' export { default as Market } from './markets/model' export { default as Service } from './services/model' export { default as Subscription } from './subscriptions/model' export { default as TwilioBlacklist } from './twilio/models/blacklist' export { default as User } from './users/model'
LeadGrabr/api
src/components/models.js
JavaScript
mit
584
/** * #describe * Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element. * For example, * Given [3,2,1,5,6,4] and k = 2, return 5. * Note: * You may assume k is always valid, 1 ≤ k ≤ array's length. * Credits: * Special thanks to @mithmatt for adding this problem and creating all test cases. * #describe */ /* answer */ /* answer */ /* test */ /* test */
xiguaxigua/leetcode
answers/kth-largest-element-in-an-array.js
JavaScript
mit
461
var mongoose = require('mongoose'); var Schema = mongoose.Schema; var User = require('./user'); var entitySchema = new Schema({ room: { type: Schema.Types.ObjectId, ref: 'Room' }, x: { type: Number, default: -1 }, y: { type: Number, default: -1 }, body: Schema.Types.Mixed, character: String, color: String, behavior: String, description: String, belongsTo: { type: Schema.Types.ObjectId, ref: 'User' } }); entitySchema.pre('save', function(next) { this.markModified('body'); var now = new Date(); if(this.belongsTo) { this.model('User').update({_id: this.belongsTo}, {lastMessage: now}, function(err, user) { if(err) console.log("While saving entity", err.message); }); } next(); }); entitySchema.static('getColor', function(playerId, callback) { this.findOne({belongsTo: playerId}, function(err, entity) { if(err) console.log(err.message); callback([entity.color, entity.character]); }); }); module.exports = mongoose.model('Entity', entitySchema);
Huntrr/mp.txt
app/schema/entity.js
JavaScript
mit
1,017
angular.module('backAnd.services') .constant('CONSTANTS', { URL: "https://api.backand.com", DEFAULT_APP: null, VERSION : '0.1' });
backand/angularbknd
app/backand/js/services/constants.js
JavaScript
mit
162
const JSUnit = imports.jsUnit; const Cairo = imports.cairo; const Everything = imports.gi.Regress; function _ts(obj) { return obj.toString().slice(8, -1); } function _createSurface() { return new Cairo.ImageSurface(Cairo.Format.ARGB32, 1, 1); } function _createContext() { return new Cairo.Context(_createSurface()); } function testContext() { let cr = _createContext(); JSUnit.assertTrue(cr instanceof Cairo.Context); } function testContextMethods() { let cr = _createContext(); JSUnit.assertTrue(cr instanceof Cairo.Context); cr.save(); cr.restore(); let surface = _createSurface(); JSUnit.assertEquals(_ts(cr.getTarget()), "CairoImageSurface"); let pattern = Cairo.SolidPattern.createRGB(1, 2, 3); cr.setSource(pattern); JSUnit.assertEquals(_ts(cr.getSource()), "CairoSolidPattern"); cr.setSourceSurface(surface, 0, 0); cr.pushGroup(); cr.popGroup(); cr.pushGroupWithContent(Cairo.Content.COLOR); cr.popGroupToSource(); cr.setSourceRGB(1, 2, 3); cr.setSourceRGBA(1, 2, 3, 4); cr.setAntialias(Cairo.Antialias.NONE); JSUnit.assertEquals("antialias", cr.getAntialias(), Cairo.Antialias.NONE); cr.setFillRule(Cairo.FillRule.EVEN_ODD); JSUnit.assertEquals("fillRule", cr.getFillRule(), Cairo.FillRule.EVEN_ODD); cr.setLineCap(Cairo.LineCap.ROUND); JSUnit.assertEquals("lineCap", cr.getLineCap(), Cairo.LineCap.ROUND); cr.setLineJoin(Cairo.LineJoin.ROUND); JSUnit.assertEquals("lineJoin", cr.getLineJoin(), Cairo.LineJoin.ROUND); cr.setLineWidth(1138); JSUnit.assertEquals("lineWidth", cr.getLineWidth(), 1138); cr.setMiterLimit(42); JSUnit.assertEquals("miterLimit", cr.getMiterLimit(), 42); cr.setOperator(Cairo.Operator.IN); JSUnit.assertEquals("operator", cr.getOperator(), Cairo.Operator.IN); cr.setTolerance(144); JSUnit.assertEquals("tolerance", cr.getTolerance(), 144); cr.clip(); cr.clipPreserve(); let rv = cr.clipExtents(); JSUnit.assertEquals("clipExtents", rv.length, 4); cr.fill(); cr.fillPreserve(); let rv = cr.fillExtents(); JSUnit.assertEquals("fillExtents", rv.length, 4); cr.mask(pattern); cr.maskSurface(surface, 0, 0); cr.paint(); cr.paintWithAlpha(1); cr.stroke(); cr.strokePreserve(); let rv = cr.strokeExtents(); JSUnit.assertEquals("strokeExtents", rv.length, 4); cr.inFill(0, 0); cr.inStroke(0, 0); cr.copyPage(); cr.showPage(); let dc = cr.getDashCount(); JSUnit.assertEquals("dashCount", dc, 0); cr.translate(10, 10); cr.scale(10, 10); cr.rotate(180); cr.identityMatrix(); let rv = cr.userToDevice(0, 0); JSUnit.assertEquals("userToDevice", rv.length, 2); let rv = cr.userToDeviceDistance(0, 0); JSUnit.assertEquals("userToDeviceDistance", rv.length, 2); let rv = cr.deviceToUser(0, 0); JSUnit.assertEquals("deviceToUser", rv.length, 2); let rv = cr.deviceToUserDistance(0, 0); JSUnit.assertEquals("deviceToUserDistance", rv.length, 2); cr.showText("foobar"); cr.moveTo(0, 0); cr.setDash([1, 0.5], 1); cr.lineTo(1, 0); cr.lineTo(1, 1); cr.lineTo(0, 1); cr.closePath(); let path = cr.copyPath(); cr.fill(); cr.appendPath(path); cr.stroke(); } function testSolidPattern() { let cr = _createContext(); let p1 = Cairo.SolidPattern.createRGB(1, 2, 3); JSUnit.assertEquals(_ts(p1), "CairoSolidPattern"); cr.setSource(p1); JSUnit.assertEquals(_ts(cr.getSource()), "CairoSolidPattern"); let p2 = Cairo.SolidPattern.createRGBA(1, 2, 3, 4); JSUnit.assertEquals(_ts(p2), "CairoSolidPattern"); cr.setSource(p2); JSUnit.assertEquals(_ts(cr.getSource()), "CairoSolidPattern"); } function testSurfacePattern() { let cr = _createContext(); let surface = _createSurface(); let p1 = new Cairo.SurfacePattern(surface); JSUnit.assertEquals(_ts(p1), "CairoSurfacePattern"); cr.setSource(p1); JSUnit.assertEquals(_ts(cr.getSource()), "CairoSurfacePattern"); } function testLinearGradient() { let cr = _createContext(); let surface = _createSurface(); let p1 = new Cairo.LinearGradient(1, 2, 3, 4); JSUnit.assertEquals(_ts(p1), "CairoLinearGradient"); cr.setSource(p1); JSUnit.assertEquals(_ts(cr.getSource()), "CairoLinearGradient"); } function testRadialGradient() { let cr = _createContext(); let surface = _createSurface(); let p1 = new Cairo.RadialGradient(1, 2, 3, 4, 5, 6); JSUnit.assertEquals(_ts(p1), "CairoRadialGradient"); cr.setSource(p1); JSUnit.assertEquals(_ts(cr.getSource()), "CairoRadialGradient"); } function testCairoSignal() { let o = new Everything.TestObj(); let called = false; o.connect('sig-with-foreign-struct', function(o, cr) { called = true; JSUnit.assertEquals(_ts(cr), "CairoContext"); }); o.emit_sig_with_foreign_struct(); JSUnit.assertTrue(called); } JSUnit.gwkjstestRun(this, JSUnit.setUp, JSUnit.tearDown);
danilocesar/gwkjs
installed-tests/js/testCairo.js
JavaScript
mit
5,061
Ember.Fuel.Grid.View.Toolbar = Ember.Fuel.Grid.View.ContainerBase.extend({ classNames: ['table-toolbar'], classNameBindings: ['childViews.length::hide'], childViewsBinding: 'controller.toolbar' });
redfire1539/ember-fuel
Libraries/Grid/Views/Toolbar.js
JavaScript
mit
203
angular.module('DashboardModule', ['ui.router', 'toastr', 'ngResource', 'angular-js-xlsx', 'angularFileUpload','ngAnimate']) //.config(function ($routeProvider, $locationProvider) { // $routeProvider // // .when('/', { // templateUrl: '/js/private/dashboard/tpl/dashboard.tpl.html', // controller: 'DashboardController' // }) // // .when('/account', { // templateUrl: '/js/private/dashboard/account/tpl/account.tpl.html', // controller: 'AccountController' // }) // ; // $locationProvider.html5Mode({enabled: true, requireBase: false}); //}) .config(['$sceDelegateProvider', function($sceDelegateProvider) { // We must whitelist the JSONP endpoint that we are using to show that we trust it $sceDelegateProvider.resourceUrlWhitelist([ 'self', 'http://localhost:1339/**' ]); }]) .config(function ($stateProvider, $urlRouterProvider, $locationProvider) { $stateProvider .state('home', { url: '/', views: { //'sidebar@': {templateUrl: '/js/private/tpl/sidebar.tpl.html'}, '@': { templateUrl: '/js/public/dashboard/tpl/dashboard.html', controller: 'DashboardController' } } }) .state('home.upload', { url: 'upload', views: { '@': { templateUrl: '/js/public/dashboard/tpl/upload.html', controller: 'DashboardController' } } }) .state('home.file.upload', { url: 'upload', views: { '@': { templateUrl: '/js/public/dashboard/tpl/upload.html', controller: 'DashboardController' } } }) //.state('home.profile.edit', { // url: '/edit', // views: { // '@': { // templateUrl: '/js/private/dashboard/tpl/edit-profile.html', // controller: 'EditProfileController' // } // } //}) // .state('home.profile.restore', { // url: 'restore', // views: { // '@': { // templateUrl: '/js/private/dashboard/tpl/restore-profile.html', // controller: 'RestoreProfileController' // } // } // }) // .state('account', { // url: '/account', // templateUrl: '/js/private/dashboard/account/tpl/account.tpl.html' // }) // .state('contact', { // url: '/contact', // // Будет автоматически вложен в безымянный ui-view // // родительского шаблона. Начиная с состояния верхнего уровня, // // шаблоном этого родительского состояния является index.html. // templateUrl: '/js/private/contacts.html' // }) // // .state('contact.detail', { // views: { // ///////////////////////////////////////////////////// // // Относительное позиционирование // // // позиционируется родительское состояние в ui-view// // ///////////////////////////////////////////////////// // // // Относительное позиционирование вида 'detail' в родительском // // состоянии 'contacts'. // // <div ui-view='detail'/> внутри contacts.html // // "detail": {}, // // // Относительное поциционирование безымянного вида в родительском // // состояния 'contacts'. // // <div ui-view/> внутри contacts.html // // "": {} // // //////////////////////////////////////////////////////////////////////////// // // Абсолютное позиционирование '@' // // // Позиционирование любых видов внутри этого состояния илипредшествующего // // //////////////////////////////////////////////////////////////////////////// // // // Абсолютное позиционирование вида 'info' в состоянии 'contacts.detail'. // // <div ui-view='info'/> внутри contacts.detail.html // //"[email protected]" : { } // // // Абсолютное позиционирование вида 'detail' в состоянии 'contacts'. // // <div ui-view='detail'/> внутри contacts.html // "detail@contact": {templateUrl: '/js/private/contact.detail.tpl.html'} // // // Абсолютное позиционирование безымянного вида в родительском // // состоянии 'contacts'. // // <div ui-view/> внутри contacts.html // // "@contacts" : { } // // // Абсолютное позиционирование вида 'status' в корневом безымянном состоянии. // // <div ui-view='status'/> внутри index.html // // "status@" : { } // // // Абсолютное позиционирование безымянного вида в корневом безымянном состоянии. // // <div ui-view/> внутри index.html // // "@" : { } // } // // .state('route1.viewC', { // // url: "/route1", // // views: { // // "viewC": { template: "route1.viewA" } // // } // // }) // // .state('route2', { // // url: "/route2", // // views: { // // "viewA": { template: "route2.viewA" }, // // "viewB": { template: "route2.viewB" } // // } // // }) // }) ; }) .directive('file', function () { return { scope: { file: '=' }, link: function (scope, el, attrs) { el.bind('change', function (event) { var file = event.target.files[0]; scope.file = file ? file : undefined; scope.$apply(); }); } }; }); //.constant('CONF_MODULE', {baseUrl: '/price/:priceId'}) //.factory('Prices', function ($resource, $state, CONF_MODULE) { // var Prices = $resource( // CONF_MODULE.baseUrl, // {priceId: '@id'}, // // Определяем собственный метод update на обоих уровнях, класса и экземпляра // { // update: { // method: 'PUT' // } // } // ); //}) ;
SETTER2000/price
assets/js/public/dashboard/DashboardModule.js
JavaScript
mit
8,259
(function() { function ce(p, n, id, c, html) { var e = document.createElement(n); p.appendChild(e); if (id) e.id = id; if (c) e.className = c; if (html) e.innerHTML = html; return e; } demoModeGameboard = gameboard.extend ({ init : function(isActive, gameData, generateState, elapsedTime) { arguments.callee.$.init.call(this); this.maxTime = 120.0; var that = this; this.elapsedTime = 0; this.pastMoves = Array(); setTimeout(function() { that.startGame(); }, 100); return this.encodeBoard(); }, uninit : function() { arguments.callee.$.uninit.call(this); _('#demoModeContainer').innerHTML = ''; _('#demoModeContainer').style.display = 'none'; clearInterval(this.startInterval); clearInterval(this.confirmInterval); }, encodeBoard : function() { var boardData = arguments.callee.$.encodeBoard.call(this); return boardData; }, startRound : function() { var that = this; }, endRound : function(success) { this.elapsedTime = 0; clearInterval(this.startInterval); var target = this.captureTile.target; this.captureTile.target = null; var token = this.createToken(target.id, target.color); this.targetTile = null; this.activeTile = null; this.isActive = false; this.activeBidder = null; for (var i = 0; i < this.moveOptions.length; ++i) { this.moveOptions[i] = null; } this.render(); this.init(); }, showPossible : function() { return; }, startGame : function() { var that = this; this.isActive = false; this.captureTileIndex = Math.floor(Math.random()*this.targets.length); this.activeTarget = this.targets[this.captureTileIndex]; this.targets.splice(this.captureTileIndex, 1); var t = this.activeTarget; for (var j = 0; j < this.tiles.length; ++j) { var ti = this.tiles[j]; if (ti.targetId === t.id) { ti.target = t; this.captureTile = ti; break; } } this.render(); this.solution = null; this.simulateMove(); this.speed = 500; }, simulateMove : function() { var that = this; if (!that.solution) { that.solution = that.solve(); } var from = null; var to = null; var mover = null; if (that.solution) { if (that.solution.length == 0) { return; } var move = that.solution.splice(0, 1)[0]; from = that.tiles[move.f]; to = that.tiles[move.t]; mover = move.m; this.activeTile = from; that.showPossible(); this.pastMoves.push(move); this.speed = 500; } else { // Move pieces at random... var pieceIndex = Math.floor(Math.random()*4); var moveOption = null; that.activeTile = that.tiles[that.movers[pieceIndex].tileIndex]; that.showPossible(); do { var moveIndex = Math.floor(Math.random()*4); moveOption = that.moveOptions[moveIndex]; } while (!moveOption); from = that.activeTile; to = moveOption.endTile; mover = that.movers[pieceIndex]; this.speed = 50; } this.render(); if (from.piece != mover) { _alert('wtf'); from.piece = mover; that.render(); that.simulateMove(); return; } this.moveMover(mover, from, to, this.speed, function() { that.simulateMove();} ); } }); window['demoModeGameboard'] = demoModeGameboard; })();
nbclark/bounding-bandits
bb.demomode.js
JavaScript
mit
4,865
/*global describe, beforeEach, it*/ 'use strict'; var path = require('path'); var helpers = require('yeoman-generator').test; describe('statik generator', function () { beforeEach(function (done) { helpers.testDirectory(path.join(__dirname, 'temp'), function (err) { if (err) { return done(err); } this.app = helpers.createGenerator('statik:app', [ '../../app' ]); done(); }.bind(this)); }); it('creates expected files', function (done) { var expected = [ // add files you expect to exist here. '.jshintrc', '.editorconfig' ]; helpers.mockPrompt(this.app, { 'someOption': true }); this.app.options['skip-install'] = true; this.app.run({}, function () { helpers.assertFiles(expected); done(); }); }); });
balintgaspar/generator-statik
test/test-creation.js
JavaScript
mit
965
var gulp = require('gulp'), nodemon = require('gulp-nodemon'), plumber = require('gulp-plumber'), livereload = require('gulp-livereload'), sass = require('gulp-sass'); gulp.task('sass', function () { gulp.src('./public/stylesheets/*.scss') .pipe(plumber()) .pipe(sass()) .pipe(gulp.dest('./public/stylesheets')) .pipe(livereload()); }); gulp.task('watch', function() { gulp.watch('./public/stylesheets/*.scss', ['sass']); }); gulp.task('develop', function () { livereload.listen(); nodemon({ script: 'bin/www', ext: 'js coffee jade', stdout: false }).on('readable', function () { this.stdout.on('data', function (chunk) { if(/^Express server listening on port/.test(chunk)){ livereload.changed(__dirname); } }); this.stdout.pipe(process.stdout); this.stderr.pipe(process.stderr); }); }); gulp.task('default', [ 'sass', 'develop', 'watch' ]);
draptik/rpi-temperature-website
gulpfile.js
JavaScript
mit
936
'use strict'; const loadRule = require('../utils/load-rule'); const ContextBuilder = require('../utils/contextBuilder'); const RequestBuilder = require('../utils/requestBuilder'); const AuthenticationBuilder = require('../utils/authenticationBuilder'); const ruleName = 'require-mfa-once-per-session'; describe(ruleName, () => { let context; let rule; let user; describe('With only a login prompt completed', () => { beforeEach(() => { rule = loadRule(ruleName); const request = new RequestBuilder().build(); const authentication = new AuthenticationBuilder().build(); context = new ContextBuilder() .withRequest(request) .withAuthentication(authentication) .build(); }); it('should set a multifactor provider', (done) => { rule(user, context, (err, u, c) => { expect(c.multifactor.provider).toBe('any'); expect(c.multifactor.allowRememberBrowser).toBe(false); done(); }); }); }); describe('With a login and MFA prompt completed', () => { beforeEach(() => { rule = loadRule(ruleName); const request = new RequestBuilder().build(); const authentication = new AuthenticationBuilder() .withMethods([ { name: 'pwd', timestamp: 1434454643024 }, { name: 'mfa', timestamp: 1534454643881 } ]) .build(); context = new ContextBuilder() .withRequest(request) .withAuthentication(authentication) .build(); }); it('should not set a multifactor provider', (done) => { rule(user, context, (err, u, c) => { expect(c.multifactor).toBe(undefined); done(); }); }); }); });
auth0/rules
test/rules/require-mfa-once-per-session.test.js
JavaScript
mit
1,787
let base_x = {} let dictionaries = {} /// @name Encode /// @description Takes a large number and converts it to a shorter encoded string style string i.e. 1TigYx /// @arg {number} input The number to be encoded to a string /// @arg {number, string} dictionary ['DICTIONARY_52'] - The dictionary to use for the encoding /// @arg {number} padding [0] - The padding (minimum length of the generated string) base_x.encodeNumber = (input, padding, dictionary) => { let result = [] dictionary = base_x.getDictionary(dictionary) let base = dictionary.length let exponent = 1 let remaining = parseInt(input) let a, b, c, d a = b = c = d = 0 padding = padding || 0 // check if padding is being used if (padding) { remaining += Math.pow(base, padding) } // generate the encoded string while (true) { a = Math.pow(base, exponent) // 16^1 = 16 b = remaining % a // 119 % 16 = 7 | 112 % 256 = 112 c = Math.pow(base, exponent - 1) d = b / c result.push(dictionary[parseInt(d)]) remaining -= b // 119 - 7 = 112 | 112 - 112 = 0 if (remaining === 0) { break } exponent++ } return result.reverse().join('') } /// @name Encode /// @description Decodes a shortened encoded string back into a number /// @arg {number} input - The encoded string to be decoded /// @arg {number, string} dictionary ['DICTIONARY_52'] - The dictionary to use for the encoding /// @arg {number} padding [0] - The padding (minimum length of the generated string) to use base_x.decodeNumber = (input, padding, dictionary) => { let chars = input.split('').reverse() dictionary = base_x.getDictionary(dictionary) let base = dictionary.length let result = 0 let map = {} let exponent = 0 padding = padding || 0 // create a map lookup for (let i = 0; i < base; i++) { map[dictionary[i]] = i } // generate the number for (let i = 0; i < input.length; i++) { result += Math.pow(base, exponent) * map[chars[i]] exponent++ } // check if padding is being used if (padding) { result -= Math.pow(base, padding) } return result } /// @name getDictionary /// @description Gets a dictionary or returns the default dictionary of 'DICTIONARY_52' /// @arg {number, string} dictionary ['DICTIONARY_52'] - The dictionary to get /// @returns {array} base_x.getDictionary = (dictionary) => { return dictionaries[dictionary] || dictionaries['DICTIONARY_' + dictionary] || dictionaries.DICTIONARY_52 } /// @name addDictionaries /// @description Adds a new dictionary /// @arg {string} name - The name of the dictionary to add /// @arg {string, array} dictionary - The dictionary to use as an array of characters base_x.addDictionary = (name, dictionary) => { if (typeof dictionary === 'string') { dictionary = dictionary.split('') } dictionaries[name] = dictionary return } let numbers = '0123456789' let lower = 'abcdefghijklmnopqrstuvwxyz' let upper = lower.toUpperCase() // add default dictionarys // numbers and A-F only base_x.addDictionary('DICTIONARY_16', numbers + upper.slice(0, 7) ) // numbers and uppercase letters A-Z base_x.addDictionary('DICTIONARY_32', (numbers + upper).replace(/[0ilo]/gi, '') ) base_x.addDictionary('letters', upper + lower) // numbers, uppercase and lowercase B-Z minus vowels base_x.addDictionary('DICTIONARY_52', (numbers + upper).replace(/[aeiou]/gi, '') ) // numbers, uppercase and lowercase A-Z base_x.addDictionary('DICTIONARY_62', numbers + upper + lower ) // numbers, uppercase and lowercase A-Z and ~!@#$%^& (minus 0,o,O,1,i,I,l,L useful to generate passwords) base_x.addDictionary('DICTIONARY_PASS', (numbers + upper + lower + '~!@#$%^&').replace(/[01oil]/gi, '') ) // numbers, uppercase and lowercase A-Z and ~!@#$%^& (useful to generate passwords) base_x.addDictionary('DICTIONARY_70', numbers + upper + lower + '~!@#$%^&' ) // numbers, uppercase and lowercase A-Z and +"~!@#$%&*/|()=?'[]{}-_:.,; base_x.addDictionary('DICTIONARY_89', numbers + upper + lower + '+"@*#%&/|()=?~[]{}$-_.:,;<>' ) import crypto from 'crypto' base_x.encode = (data, padding = 4, dictionary = 'letters') => { let hash = crypto .createHash('md5') .update(JSON.stringify(data), 'utf8') .digest('hex') .split('') .reduce((prev, next) => prev + next.charCodeAt(), 0) return base_x.encodeNumber(hash, padding, dictionary) } let base = global.base_x = global.base_x || base_x export default base
tjbenton/docs
packages/docs-theme-default/src/base-x.js
JavaScript
mit
4,443
//This file makes it easier to import everything from the common folder export * from './Button'; export * from './Card'; export * from './CardSection'; export * from './Header'; export * from './Input'; export * from './Spinner'; export * from './Confirm';
srserx/react-native-ui-common
index.js
JavaScript
mit
259
import React from 'react'; import Example from './Example'; import Icon from '../../src/Icon'; import Button from '../../src/Button'; import IconButton from '../../src/IconButton'; import FABButton from '../../src/FABButton'; export default ( props ) => ( <section { ...props }> <h3>Buttons</h3> <Example> <FABButton colored> <Icon name="add" /> </FABButton> <FABButton colored ripple> <Icon name="add" /> </FABButton> </Example> <Example> <FABButton> <Icon name="add" /> </FABButton> <FABButton ripple> <Icon name="add" /> </FABButton> <FABButton disabled> <Icon name="add" /> </FABButton> </Example> <Example> <Button raised>Button</Button> <Button raised ripple>Button</Button> <Button raised disabled>Button</Button> </Example> <Example> <Button raised colored>Button</Button> <Button raised accent>Button</Button> <Button raised accent ripple>Button</Button> </Example> <Example> <Button>Button</Button> <Button ripple>Button</Button> <Button disabled>Button</Button> </Example> <Example> <Button primary colored>Button</Button> <Button accent>Button</Button> </Example> <Example> <IconButton name="mood" /> <IconButton colored name="mood" /> </Example> <Example> <FABButton mini> <Icon name="add" /> </FABButton> <FABButton colored mini> <Icon name="add" /> </FABButton> </Example> </section> );
joshq00/react-mdl
demo/sections/Buttons.js
JavaScript
mit
1,885
var async = require('async'); function _hasher() { return "_"; } function accessor(idx) { return (this.memo._ || [])[idx]; }; module.exports = function mymoize(fn) { var memoized = async.memoize(fn, _hasher); memoized.getErr = accessor.bind(memoized, 0); memoized.getRes = accessor.bind(memoized, 1); return memoized; }
adrienjoly/npm-mymoize
index.js
JavaScript
mit
335
// Karma configuration // Generated on Fri Jul 05 2013 01:57:57 GMT-0400 (EDT) /*global basePath:true, exclude:true, reporters:true, files:true*/ /*global coverageReporter:true, junitReporter:true, reporters:true, preprocessors:true, frameworks:true*/ /*global port:true, runnerPort:true, colors:true, logLevel:true*/ /*global autoWatch:true, browsers:true, captureTimeout:true, singleRun:true*/ /*global JASMINE:true, JASMINE_ADAPTER:true, REQUIRE:true, REQUIRE_ADAPTER:true*/ /*global LOG_INFO:true*/ module.exports = function(config) { config.set({ // base path, that will be used to resolve files and exclude // basePath: 'tmp/public', basePath: '', // list of files / patterns to load in the browser files: [ {pattern: 'libs/jquery/jquery.js', included: false}, {pattern: 'libs/requirejs/require.js', included: false}, {pattern: 'src/*.js', included: false}, {pattern: 'test/spec/*-spec.js', included: false}, // helpers & fixtures for jasmine-jquery { pattern: 'test/helpers/*.js', included: true }, 'test/test-main.js', ], frameworks: ['jasmine', 'requirejs'], plugins: [ 'karma-jasmine', 'karma-requirejs', 'karma-coverage', 'karma-phantomjs-launcher', 'karma-chrome-launcher', 'karma-firefox-launcher', 'karma-safari-launcher' ], preprocessors: { '**/src/*.js': 'coverage' }, // list of files to exclude exclude: [], // test results reporter to use // possible values: 'dots', 'progress', 'junit' reporters: 'coverage', coverageReporter: { type : ['text'], dir : '.coverage/' // type: 'cobertura', // dir: 'coverage/', // file: 'coverage.xml' }, // web server port port: 9871, // cli runner port runnerPort: 9130, // enable / disable colors in the output (reporters and logs) colors: true, // level of logging // possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG logLevel: config.LOG_DEBUG, // enable / disable watching file and executing tests whenever any file changes autoWatch: true, // Start these browsers, currently available: // - Chrome // - ChromeCanary // - Firefox // - Opera // - Safari (only Mac) // - PhantomJS // - IE (only Windows) browsers: ['Chrome'], // If browser does not capture in given timeout [ms], kill it captureTimeout: 60000, // Continuous Integration mode // if true, it capture browsers, run tests and exit singleRun: false }); };
goliatone/gmodule
karma.conf.js
JavaScript
mit
2,909
var Promise = require('ia-promise'); var XHRPromise = require('./XHRPromise'); var CommandPromise = require('./CommandPromise'); var ProfilePromise = require('./ProfilePromise'); var ViewPromise = require('./ViewPromise'); var FutureViewPromise = require('./FutureViewPromise'); var RoomPromise = require('./RoomPromise'); function RoomsPromise(app, name) { // Calling parent constructor ViewPromise.call(this, app, name); // Registering UI elements this.tbody = document.querySelector('tbody'), this.trTpl = this.tbody.firstChild; this.tbody.removeChild(this.trTpl); } RoomsPromise.prototype = Object.create(ViewPromise.prototype); RoomsPromise.prototype.reset = function () { while(this.tbody.firstChild) { this.tbody.removeChild(this.tbody.firstChild); } }; RoomsPromise.prototype.hide = function () { this.reset(); this.tbody.appendChild(this.trTpl); }; RoomsPromise.prototype.loop = function (timeout) { var _this = this; // roooms update function getRoomsUpdatePromise() { return new XHRPromise('GET', '/rooms.json', true).then(function(xhr){ _this.reset(); var rooms = JSON.parse(xhr.responseText); rooms.forEach(function(room) { var tr = _this.trTpl.cloneNode(true); tr.firstChild.firstChild.setAttribute('href', _this.trTpl.firstChild.firstChild.getAttribute('href') + room.id); if(room.state) tr.firstChild.firstChild.setAttribute('disabled','disabled'); tr.firstChild.firstChild.firstChild.textContent = room.name; tr.childNodes[1].firstChild.textContent = room.players + '/6'; tr.childNodes[2].firstChild.textContent = room.mode; _this.tbody.appendChild(tr); }); }); } return Promise.all( _this.app.user && _this.app.user.name ? Promise.sure() : new ProfilePromise(_this.app, 'Profile', true), getRoomsUpdatePromise() ).then(function() { _this.display(); return Promise.any( // Handling channel join new CommandPromise(_this.app.cmdMgr, 'join', _this.name).then(function(data) { return new RoomPromise(_this.app, 'Room', data.params.room); }), // Handling channel list refresh new CommandPromise(_this.app.cmdMgr, 'refresh', _this.name), // Handling the back button new CommandPromise(_this.app.cmdMgr, 'back', _this.name).then(function() { _this.end=true; }), // Handling menu new CommandPromise(_this.app.cmdMgr, 'menu', _this.name).then(function(data) { // Loading the selected view return _this.app.loadView(data.params.view); }) ) }); }; module.exports = RoomsPromise;
nfroidure/Liar
src/RoomsPromise.js
JavaScript
mit
2,568
/** * ionNavBar * * ionNavBar and _ionNavBar are created to overcome Meteor's templating limitations. By utilizing Template.dynamic * in blaze, we can force ionNavBar to destroy _ionNavBar, enabling css transitions and none of that javascript * animation. */ let _ionNavBar_Destroyed = new ReactiveVar(false); Template.ionNavBar.onCreated(function() { this.data = this.data || {}; if (Platform.isAndroid()) { this.transition = 'android'; } else { this.transition = 'ios'; } this.ionNavBarTemplate = new ReactiveVar('_ionNavBar'); $(window).on('statechange', e => this.ionNavBarTemplate.set('')); this.autorun(() => { if (_ionNavBar_Destroyed.get()) { this.ionNavBarTemplate.set('_ionNavBar'); } }); }); Template.ionNavBar.onRendered(function() { let container = this.$('.nav-bar-container'); container.attr('nav-bar-direction', 'forward'); let navBarContainer = this.find('.nav-bar-container'); navBarContainer._uihooks = { // Override onDestroyed so that's children won't remove themselves immediately. removeElement: function(node) { // Worst case scenario. Remove if exceeded maximum transition duration. Meteor.setTimeout(() => { node.remove(); }, METEORIC.maximum_transition_duration); } }; }); Template.ionNavBar.helpers({ ionNavBarTemplate: function() { return Template.instance().ionNavBarTemplate.get(); }, transition: function () { return Template.instance().transition; } }); Template._ionNavBar.onCreated(function () { this.entering = false; this.leaving = false; this.activate_view_timeout_id = null; this.deactivate_view_timeout_id = null; _ionNavBar_Destroyed.set(false); }); Template._ionNavBar.onRendered(function () { // Reset nav-bar-direction. let navBarBlock = this.find('.nav-bar-block'); navBarBlock._uihooks = { // Override onDestroyed so that's children won't remove themselves immediately. removeElement: function(node) { // Worst case scenario. Remove if exceeded maximum transition duration. Meteor.setTimeout(() => { node.remove(); }, METEORIC.maximum_transition_duration); } }; let $navBarBlock = this.$('.nav-bar-block').first(); let activate_view = () => { this.entering = false; let activate_timer_active = !!this.activate_view_timeout_id; if (activate_timer_active) { Meteor.clearTimeout(this.activate_view_timeout_id); this.activate_view_timeout_id = null; } $navBarBlock.attr('nav-bar', 'active'); $('[data-navbar-container]').attr('nav-bar-direction', 'forward'); }; $navBarBlock.attr('nav-bar', 'stage'); let $headerBar = this.$('.nav-bar-block *'); Meteor.setTimeout(() => { this.entering = true; $navBarBlock.attr('nav-bar', 'entering'); $headerBar.one(METEORIC.UTILITY.transitionend_events.join(' '), activate_view); }, 0); // Worst case scenario, transitionend did not occur. Just place view in. this.activate_view_timeout_id = Meteor.setTimeout(activate_view, METEORIC.maximum_transition_duration); }); Template._ionNavBar.onDestroyed(function () { _ionNavBar_Destroyed.set(true); let $navBarBlock = this.$('.nav-bar-block'); let deactivate_view = () => { this.leaving = false; // If the user have trigger fingers, in which he/she can click back buttons // really fast, activate view timer might still be going. Kill it. let activate_timer_active = !!this.activate_view_timeout_id; if (activate_timer_active) { Meteor.clearTimeout(this.activate_view_timeout_id); this.activate_view_timeout_id = null; } let deactivate_timer_active = !!this.deactivate_view_timeout_id; if (deactivate_timer_active) { Meteor.clearTimeout(this.deactivate_view_timeout_id); this.deactivate_view_timeout_id = null; } this.deactivate_view_timeout_id = null; $navBarBlock.remove(); }; let $headerBar = this.$('.nav-bar-block *'); Meteor.setTimeout(() => { this.leaving = true; $navBarBlock.attr('nav-bar', 'leaving'); $headerBar.one(METEORIC.UTILITY.transitionend_events.join(' '), deactivate_view); }, 0); // Worst case scenario, transitionend did not occur. Just remove the view. this.deactivate_view_timeout_id = Meteor.setTimeout(deactivate_view, METEORIC.maximum_transition_duration); });
JoeyAndres/meteor-ionic
components/ionNavBar/ionNavBar.js
JavaScript
mit
4,669
/* eslint no-unused-expressions: "off" */ import { expect } from 'chai'; import { Session } from '../utils'; import * as ModelUtils from '../../../src/utils/model-utils'; const session = new Session(); const Vehicle = session.model('Vehicle', {}); const Car = session.model('Car', {}, { 'extends': Vehicle }); const Sedan = session.model('Sedan', { 'numDoors': { 'type': Number } }, { 'extends': Car }); describe('Model Utilities tests', () => { describe('getModel()', () => { it('Fails when no argument given', () => { const result = ModelUtils.getModel(); expect(result).to.be.null; }); it('Fails when given non-model', () => { const result = ModelUtils.getModel({}); expect(result).to.be.null; }); it('Returns model class given', () => { const result = ModelUtils.getModel(Car); expect(result).to.equal(Car); }); it('Returns model class for instance', () => { const car = new Car(); const result = ModelUtils.getModel(car); expect(result).to.not.equal(car); expect(result).to.equal(Car); }); }); describe('getName()', () => { it('Returns name for model class', () => { const result = ModelUtils.getName(Car); expect(result).to.equal('Car'); }); it('Returns name for model instance', () => { const result = ModelUtils.getName(new Car()); expect(result).to.equal('Car'); }); }); describe('getParent()', () => { it('Returns parent for model class', () => { const result = ModelUtils.getParent(Sedan); expect(result).to.equal(Car); }); it('Returns parent for model instance', () => { const result = ModelUtils.getParent(new Sedan()); expect(result).to.equal(Car); }); it('Returns null if given model is root', () => { const result = ModelUtils.getParent(Vehicle); expect(result).to.be.null; }); it('Returns null if argument missing', () => { const result = ModelUtils.getParent(); expect(result).to.be.null; }); }); describe('getAncestors()', () => { it('Returns ancestors for model class', () => { const result = ModelUtils.getAncestors(Sedan, session); expect(result).to.deep.equal([Car, Vehicle]); }); it('Returns ancestors for model instance', () => { const result = ModelUtils.getAncestors(new Sedan(), session); expect(result).to.deep.equal([Car, Vehicle]); }); }); describe('getField()', () => { it('Returns field for model class', () => { const result = ModelUtils.getField(Sedan, 'numDoors'); expect(result).to.deep.equal({ 'column': 'numDoors', 'name': 'numDoors', 'type': Number, 'owningModel': Sedan }); }); it('Returns field for model instance', () => { const result = ModelUtils.getField(new Sedan(), 'numDoors'); expect(result).to.deep.equal({ 'column': 'numDoors', 'name': 'numDoors', 'type': Number, 'owningModel': Sedan }); }); }); describe('getFields()', () => { it('Returns fields for model class', () => { const result = ModelUtils.getFields(Sedan); expect(result).to.deep.equal({ 'numDoors': { 'column': 'numDoors', 'name': 'numDoors', 'owningModel': Sedan, 'type': Number } }); }); it('Returns fields for model instance', () => { const result = ModelUtils.getFields(new Sedan()); expect(result).to.deep.equal({ 'numDoors': { 'column': 'numDoors', 'name': 'numDoors', 'owningModel': Sedan, 'type': Number } }); }); }); describe('getAllFields()', () => { it('Returns fields for model class', () => { const result = ModelUtils.getAllFields(Sedan, session); expect(result).to.deep.equal({ 'numDoors': { 'column': 'numDoors', 'name': 'numDoors', 'owningModel': Sedan, 'type': Number } }); }); it('Returns fields for model instance', () => { const result = ModelUtils.getAllFields(new Sedan(), session); expect(result).to.deep.equal({ 'numDoors': { 'column': 'numDoors', 'name': 'numDoors', 'owningModel': Sedan, 'type': Number } }); }); }); describe('getChangedFields', () => { it('Returns array of field names for model instance', () => { const sedan = new Sedan({ 'numDoors': 4, 'numWheels': 4, 'numWindows': 6 }); const result = ModelUtils.getChangedFields(sedan, session); expect(result).to.deep.equal(['numDoors']); }); }); });
one-orm/core
test/unit/utils/model-utils-test.js
JavaScript
mit
5,551
var express = require('express'); var router = express.Router(); /* GET home page. */ router.get('/', function(req, res) { res.render('index', { title: 'Express',reqCsrf:req.csrfToken()}); }); router.post('/regist',function(req,res){ res.send('OK') }); router.post('/registXhr',function(req,res){ if(req.xhr){ res.send('xhr Access'); }else{ res.send('not xhr Access'); } }); module.exports = router
CM-Kajiwara/csurfSample
routes/index.js
JavaScript
mit
439
var React = require('react'); var AWSMixin = require('../mixins/aws.mixin'); var AWSActions = require('../actions/AWSActions'); var EC2Item = React.createClass({ render: function() { return ( <a href="#" onClick={this._onSSHClick} className="col one-fourth ec2-instance">{this.props.instance.Name}</a> ); }, _onSSHClick: function() { AWSActions.sshInto(this.props.instance); } }); var EC2Section = React.createClass({ mixins:[AWSMixin], render: function() { instances = this.state['ec2-instances']; var ec2items = []; instances.forEach(function(i) { ec2items.push(<EC2Item instance={i} />); }); return ( <div> <h4 class="section-title" id="grid">EC2 Instances</h4> <div className="container" id="ec2-instances">{ec2items}</div> </div> ); } }); module.exports = EC2Section;
sunils34/visualize-aws
www/js/components/EC2.react.js
JavaScript
mit
865
describe('jQuery Plugin', function () { it('jQuery.fn.plugin should exist', function () { expect(jQuery.fn.plugin).toBeDefined(); }); });
angryobject/jquery-plugin-starter
app/jquery.plugin.spec.js
JavaScript
mit
149
/** * @license * Copyright (c) 2011 NVIDIA Corporation. All rights reserved. * * TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, THIS SOFTWARE IS PROVIDED * *AS IS* AND NVIDIA AND ITS SUPPLIERS DISCLAIM ALL WARRANTIES, EITHER EXPRESS * OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, NONINFRINGEMENT,IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL NVIDIA * OR ITS SUPPLIERS BE LIABLE FOR ANY DIRECT, SPECIAL, INCIDENTAL, INDIRECT, OR * CONSEQUENTIAL DAMAGES WHATSOEVER (INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS * OF BUSINESS PROFITS, BUSINESS INTERRUPTION, LOSS OF BUSINESS INFORMATION, OR ANY * OTHER PECUNIARY LOSS) ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, * EVEN IF NVIDIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. */ //This file is automatically rebuilt by the Cesium build process. /*global define*/ define(function() { 'use strict'; return "#ifndef FXAA_PRESET\n\ #define FXAA_PRESET 3\n\ #endif\n\ #if (FXAA_PRESET == 3)\n\ #define FXAA_EDGE_THRESHOLD (1.0/8.0)\n\ #define FXAA_EDGE_THRESHOLD_MIN (1.0/24.0)\n\ #define FXAA_SEARCH_STEPS 16\n\ #define FXAA_SEARCH_THRESHOLD (1.0/4.0)\n\ #define FXAA_SUBPIX_CAP (3.0/4.0)\n\ #define FXAA_SUBPIX_TRIM (1.0/4.0)\n\ #endif\n\ #if (FXAA_PRESET == 4)\n\ #define FXAA_EDGE_THRESHOLD (1.0/8.0)\n\ #define FXAA_EDGE_THRESHOLD_MIN (1.0/24.0)\n\ #define FXAA_SEARCH_STEPS 24\n\ #define FXAA_SEARCH_THRESHOLD (1.0/4.0)\n\ #define FXAA_SUBPIX_CAP (3.0/4.0)\n\ #define FXAA_SUBPIX_TRIM (1.0/4.0)\n\ #endif\n\ #if (FXAA_PRESET == 5)\n\ #define FXAA_EDGE_THRESHOLD (1.0/8.0)\n\ #define FXAA_EDGE_THRESHOLD_MIN (1.0/24.0)\n\ #define FXAA_SEARCH_STEPS 32\n\ #define FXAA_SEARCH_THRESHOLD (1.0/4.0)\n\ #define FXAA_SUBPIX_CAP (3.0/4.0)\n\ #define FXAA_SUBPIX_TRIM (1.0/4.0)\n\ #endif\n\ #define FXAA_SUBPIX_TRIM_SCALE (1.0/(1.0 - FXAA_SUBPIX_TRIM))\n\ float FxaaLuma(vec3 rgb) {\n\ return rgb.y * (0.587/0.299) + rgb.x;\n\ }\n\ vec3 FxaaLerp3(vec3 a, vec3 b, float amountOfA) {\n\ return (vec3(-amountOfA) * b) + ((a * vec3(amountOfA)) + b);\n\ }\n\ vec4 FxaaTexOff(sampler2D tex, vec2 pos, ivec2 off, vec2 rcpFrame) {\n\ float x = pos.x + float(off.x) * rcpFrame.x;\n\ float y = pos.y + float(off.y) * rcpFrame.y;\n\ return texture2D(tex, vec2(x, y));\n\ }\n\ vec3 FxaaPixelShader(vec2 pos, sampler2D tex, vec2 rcpFrame)\n\ {\n\ vec3 rgbN = FxaaTexOff(tex, pos.xy, ivec2( 0,-1), rcpFrame).xyz;\n\ vec3 rgbW = FxaaTexOff(tex, pos.xy, ivec2(-1, 0), rcpFrame).xyz;\n\ vec3 rgbM = FxaaTexOff(tex, pos.xy, ivec2( 0, 0), rcpFrame).xyz;\n\ vec3 rgbE = FxaaTexOff(tex, pos.xy, ivec2( 1, 0), rcpFrame).xyz;\n\ vec3 rgbS = FxaaTexOff(tex, pos.xy, ivec2( 0, 1), rcpFrame).xyz;\n\ float lumaN = FxaaLuma(rgbN);\n\ float lumaW = FxaaLuma(rgbW);\n\ float lumaM = FxaaLuma(rgbM);\n\ float lumaE = FxaaLuma(rgbE);\n\ float lumaS = FxaaLuma(rgbS);\n\ float rangeMin = min(lumaM, min(min(lumaN, lumaW), min(lumaS, lumaE)));\n\ float rangeMax = max(lumaM, max(max(lumaN, lumaW), max(lumaS, lumaE)));\n\ float range = rangeMax - rangeMin;\n\ if(range < max(FXAA_EDGE_THRESHOLD_MIN, rangeMax * FXAA_EDGE_THRESHOLD))\n\ {\n\ return rgbM;\n\ }\n\ vec3 rgbL = rgbN + rgbW + rgbM + rgbE + rgbS;\n\ float lumaL = (lumaN + lumaW + lumaE + lumaS) * 0.25;\n\ float rangeL = abs(lumaL - lumaM);\n\ float blendL = max(0.0, (rangeL / range) - FXAA_SUBPIX_TRIM) * FXAA_SUBPIX_TRIM_SCALE;\n\ blendL = min(FXAA_SUBPIX_CAP, blendL);\n\ vec3 rgbNW = FxaaTexOff(tex, pos.xy, ivec2(-1,-1), rcpFrame).xyz;\n\ vec3 rgbNE = FxaaTexOff(tex, pos.xy, ivec2( 1,-1), rcpFrame).xyz;\n\ vec3 rgbSW = FxaaTexOff(tex, pos.xy, ivec2(-1, 1), rcpFrame).xyz;\n\ vec3 rgbSE = FxaaTexOff(tex, pos.xy, ivec2( 1, 1), rcpFrame).xyz;\n\ rgbL += (rgbNW + rgbNE + rgbSW + rgbSE);\n\ rgbL *= vec3(1.0/9.0);\n\ float lumaNW = FxaaLuma(rgbNW);\n\ float lumaNE = FxaaLuma(rgbNE);\n\ float lumaSW = FxaaLuma(rgbSW);\n\ float lumaSE = FxaaLuma(rgbSE);\n\ float edgeVert =\n\ abs((0.25 * lumaNW) + (-0.5 * lumaN) + (0.25 * lumaNE)) +\n\ abs((0.50 * lumaW ) + (-1.0 * lumaM) + (0.50 * lumaE )) +\n\ abs((0.25 * lumaSW) + (-0.5 * lumaS) + (0.25 * lumaSE));\n\ float edgeHorz =\n\ abs((0.25 * lumaNW) + (-0.5 * lumaW) + (0.25 * lumaSW)) +\n\ abs((0.50 * lumaN ) + (-1.0 * lumaM) + (0.50 * lumaS )) +\n\ abs((0.25 * lumaNE) + (-0.5 * lumaE) + (0.25 * lumaSE));\n\ bool horzSpan = edgeHorz >= edgeVert;\n\ float lengthSign = horzSpan ? -rcpFrame.y : -rcpFrame.x;\n\ if(!horzSpan)\n\ {\n\ lumaN = lumaW;\n\ lumaS = lumaE;\n\ }\n\ float gradientN = abs(lumaN - lumaM);\n\ float gradientS = abs(lumaS - lumaM);\n\ lumaN = (lumaN + lumaM) * 0.5;\n\ lumaS = (lumaS + lumaM) * 0.5;\n\ if (gradientN < gradientS)\n\ {\n\ lumaN = lumaS;\n\ lumaN = lumaS;\n\ gradientN = gradientS;\n\ lengthSign *= -1.0;\n\ }\n\ vec2 posN;\n\ posN.x = pos.x + (horzSpan ? 0.0 : lengthSign * 0.5);\n\ posN.y = pos.y + (horzSpan ? lengthSign * 0.5 : 0.0);\n\ gradientN *= FXAA_SEARCH_THRESHOLD;\n\ vec2 posP = posN;\n\ vec2 offNP = horzSpan ? vec2(rcpFrame.x, 0.0) : vec2(0.0, rcpFrame.y);\n\ float lumaEndN = lumaN;\n\ float lumaEndP = lumaN;\n\ bool doneN = false;\n\ bool doneP = false;\n\ posN += offNP * vec2(-1.0, -1.0);\n\ posP += offNP * vec2( 1.0, 1.0);\n\ for(int i = 0; i < FXAA_SEARCH_STEPS; i++) {\n\ if(!doneN)\n\ {\n\ lumaEndN = FxaaLuma(texture2D(tex, posN.xy).xyz);\n\ }\n\ if(!doneP)\n\ {\n\ lumaEndP = FxaaLuma(texture2D(tex, posP.xy).xyz);\n\ }\n\ doneN = doneN || (abs(lumaEndN - lumaN) >= gradientN);\n\ doneP = doneP || (abs(lumaEndP - lumaN) >= gradientN);\n\ if(doneN && doneP)\n\ {\n\ break;\n\ }\n\ if(!doneN)\n\ {\n\ posN -= offNP;\n\ }\n\ if(!doneP)\n\ {\n\ posP += offNP;\n\ }\n\ }\n\ float dstN = horzSpan ? pos.x - posN.x : pos.y - posN.y;\n\ float dstP = horzSpan ? posP.x - pos.x : posP.y - pos.y;\n\ bool directionN = dstN < dstP;\n\ lumaEndN = directionN ? lumaEndN : lumaEndP;\n\ if(((lumaM - lumaN) < 0.0) == ((lumaEndN - lumaN) < 0.0))\n\ {\n\ lengthSign = 0.0;\n\ }\n\ float spanLength = (dstP + dstN);\n\ dstN = directionN ? dstN : dstP;\n\ float subPixelOffset = (0.5 + (dstN * (-1.0/spanLength))) * lengthSign;\n\ vec3 rgbF = texture2D(tex, vec2(\n\ pos.x + (horzSpan ? 0.0 : subPixelOffset),\n\ pos.y + (horzSpan ? subPixelOffset : 0.0))).xyz;\n\ return FxaaLerp3(rgbL, rgbF, blendL);\n\ }\n\ uniform sampler2D u_texture;\n\ uniform vec2 u_step;\n\ varying vec2 v_textureCoordinates;\n\ void main()\n\ {\n\ gl_FragColor = vec4(FxaaPixelShader(v_textureCoordinates, u_texture, u_step), 1.0);\n\ }\n\ "; });
denverpierce/denverpierce.github.io
Cesium/Source/Shaders/PostProcessFilters/FXAA.js
JavaScript
mit
6,619
import React from 'react'; import Example from './Example'; import Tooltip from '../../src/Tooltip'; import Icon from '../../src/Icon'; export default ( props ) => ( <section { ...props }> <h3>Tooltips</h3> <Example> <Tooltip label="Follow"> <Icon name="add" /> </Tooltip> <Tooltip large label="Print"> <Icon name="print" /> </Tooltip> </Example> <Example> <Tooltip label={ <span> Upload <strong>file.zip</strong> </span> } > <Icon name="cloud_upload" /> </Tooltip> <Tooltip label={ <span> Share your content<br /> via social media </span> }> <Icon name="share" /> </Tooltip> </Example> </section> );
joshq00/react-mdl
demo/sections/Tooltips.js
JavaScript
mit
1,004
// Generated by CoffeeScript 1.6.3 (function() { this.Position = (function() { function Position(id, top, left) { this.id = id; this.top = top; this.left = left; } return Position; })(); this.Postit = (function() { function Postit() { this.id = new Date().getTime(); this.position = new Position(this.id, 0, 0); this.identify = {}; this.contents = []; this.isDelete = false; } Postit.getIndexById = function(postits, id) { var findout, index, p, _i, _len; index = 0; findout = false; for (_i = 0, _len = postits.length; _i < _len; _i++) { p = postits[_i]; if (id.toString() === p.id.toString()) { findout = true; break; } index++; } if (findout) { return index; } else { return -1; } }; Postit.prototype.getIndex = function(postits) { return Postit.getIndexById(postits, this.id); }; Postit.prototype.toSend = function(method, sender) { var p; p = new Postit(sender.id); switch (method) { case MethodType.Move: p.position = sender.position; break; case MethodType.Save: p.position = sender.position; p.contents = sender.contents; break; case MethodType.Delete: p.isDelete = true; } return p; }; return Postit; })(); this.MethodType = (function() { function MethodType(index) { this.index = index; } MethodType.Move = 0; MethodType.Save = 1; MethodType.Delete = 2; MethodType.prototype.valueOf = function() { return this.index; }; return MethodType; })(); this.ContentType = (function() { function ContentType(index) { this.index = index; } ContentType.Document = 0; ContentType.Link = 1; ContentType.Image = 2; ContentType.prototype.valueOf = function() { return this.index; }; return ContentType; })(); this.Content = (function() { function Content(type, value) { this.type = type; this.value = value; } return Content; })(); }).call(this);
icoxfog417/whitewall
public/javascripts/postit.js
JavaScript
mit
2,232
var utils = require('./utils'); exports.setItemDetails = function(item, description) { return { "author": { "name": "Santiago", "lastname": "Alurralde" }, "item": { "id": item.id, "title": item.title, "price": { "currency": item.currency_id, "amount": utils.getPriceAmount(item), "decimals": utils.getPriceDecimals(item) }, "picture": item.pictures[0].url, "condition": utils.getItemCondition(item), "free_shipping": item.shipping.free_shipping, "sold_quantity": item.sold_quantity, "description": description.text, "category": item.category_id } }; };
santalurr/mercadolibre
api/item.js
JavaScript
mit
611
'use strict'; var isString = require('lodash/isString'); var each = require('lodash/each'); var last = require('lodash/last'); var uuid = require('../util/uuid'); var EditingBehavior = require('../model/EditingBehavior'); var insertText = require('../model/transform/insertText'); var copySelection = require('../model/transform/copySelection'); var deleteSelection = require('../model/transform/deleteSelection'); var breakNode = require('../model/transform/breakNode'); var insertNode = require('../model/transform/insertNode'); var switchTextType = require('../model/transform/switchTextType'); var paste = require('../model/transform/paste'); var Surface = require('./Surface'); var RenderingEngine = require('./RenderingEngine'); /** Represents a flow editor that manages a sequence of nodes in a container. Needs to be instantiated inside a {@link ui/Controller} context. @class ContainerEditor @component @extends ui/Surface @prop {String} name unique editor name @prop {String} containerId container id @prop {Object[]} textTypes array of textType definition objects @prop {ui/SurfaceCommand[]} commands array of command classes to be available @example Create a full-fledged `ContainerEditor` for the `body` container of a document. Allow Strong and Emphasis annotations and to switch text types between paragraph and heading at level 1. ```js $$(ContainerEditor, { name: 'bodyEditor', containerId: 'body', textTypes: [ {name: 'paragraph', data: {type: 'paragraph'}}, {name: 'heading1', data: {type: 'heading', level: 1}} ], commands: [StrongCommand, EmphasisCommand, SwitchTextTypeCommand], }) ``` */ function ContainerEditor() { Surface.apply(this, arguments); this.containerId = this.props.containerId; if (!isString(this.props.containerId)) { throw new Error("Illegal argument: Expecting containerId."); } var doc = this.getDocument(); this.container = doc.get(this.containerId); if (!this.container) { throw new Error('Container with id ' + this.containerId + ' does not exist.'); } this.editingBehavior = new EditingBehavior(); } ContainerEditor.Prototype = function() { var _super = Object.getPrototypeOf(this); // Note: this component is self managed this.shouldRerender = function() { // TODO: we should still detect when the document has changed, // see https://github.com/substance/substance/issues/543 return false; }; this.render = function($$) { var el = _super.render.apply(this, arguments); var doc = this.getDocument(); var containerId = this.props.containerId; var containerNode = doc.get(this.props.containerId); if (!containerNode) { console.warn('No container node found for ', this.props.containerId); } var isEditable = this.isEditable(); el.addClass('sc-container-editor container-node ' + containerId) .attr({ spellCheck: false, "data-id": containerId, "contenteditable": isEditable }); if (this.isEmpty()) { el.append( $$('a').attr('href', '#').append('Start writing').on('click', this.onCreateText) ); } else { // node components each(containerNode.nodes, function(nodeId) { el.append(this._renderNode($$, nodeId)); }.bind(this)); } return el; }; // Used by Clipboard this.isContainerEditor = function() { return true; }; /** Returns the containerId the editor is bound to */ this.getContainerId = function() { return this.props.containerId; }; // TODO: do we really need this in addition to getContainerId? this.getContainer = function() { return this.getDocument().get(this.getContainerId()); }; this.isEmpty = function() { var doc = this.getDocument(); var containerNode = doc.get(this.props.containerId); return (containerNode && containerNode.nodes.length === 0); }; this.isEditable = function() { return _super.isEditable.call(this) && !this.isEmpty(); }; /* TODO: Select first content to be found */ this.selectFirst = function() { console.warn('TODO: Implement selection of first content to be found.'); }; /* Register custom editor behavior using this method */ this.extendBehavior = function(extension) { extension.register(this.editingBehavior); }; this.getTextTypes = function() { return this.textTypes || []; }; // Used by TextTool // TODO: Filter by enabled commands for this Surface this.getTextCommands = function() { var textCommands = {}; this.commandRegistry.each(function(cmd) { if (cmd.constructor.static.textTypeName) { textCommands[cmd.getName()] = cmd; } }); return textCommands; }; this.enable = function() { // As opposed to a ContainerEditor, a regular Surface // is not a ContentEditable -- but every contained TextProperty this.attr('contentEditable', true); this.enabled = true; }; this.disable = function() { this.removeAttr('contentEditable'); this.enabled = false; }; /* Editing behavior */ /** Performs a {@link model/transform/deleteSelection} transformation */ this.delete = function(tx, args) { this._prepareArgs(args); return deleteSelection(tx, args); }; /** Performs a {@link model/transform/breakNode} transformation */ this.break = function(tx, args) { this._prepareArgs(args); if (args.selection.isPropertySelection() || args.selection.isContainerSelection()) { return breakNode(tx, args); } }; /** Performs an {@link model/transform/insertNode} transformation */ this.insertNode = function(tx, args) { this._prepareArgs(args); if (args.selection.isPropertySelection() || args.selection.isContainerSelection()) { return insertNode(tx, args); } }; /** * Performs a {@link model/transform/switchTextType} transformation */ this.switchType = function(tx, args) { this._prepareArgs(args); if (args.selection.isPropertySelection()) { return switchTextType(tx, args); } }; /** Selects all content in the container */ this.selectAll = function() { var doc = this.getDocument(); var container = doc.get(this.getContainerId()); if (container.nodes.length === 0) { return; } var firstNodeId = container.nodes[0]; var lastNodeId = last(container.nodes); var sel = doc.createSelection({ type: 'container', containerId: container.id, startPath: [firstNodeId], startOffset: 0, endPath: [lastNodeId], endOffset: 1 }); this.setSelection(sel); }; this.selectFirst = function() { var doc = this.getDocument(); var nodes = this.getContainer().nodes; if (nodes.length === 0) { console.info('ContainerEditor.selectFirst(): Container is empty.'); return; } var node = doc.get(nodes[0]); var sel; if (node.isText()) { sel = doc.createSelection(node.getTextPath(), 0); } else { sel = doc.createSelection(this.getContainerId(), [node.id], 0, [node.id], 1); } this.setSelection(sel); }; /** Performs a {@link model/transform/paste} transformation */ this.paste = function(tx, args) { this._prepareArgs(args); if (args.selection.isPropertySelection() || args.selection.isContainerSelection()) { return paste(tx, args); } }; /** Performs an {@link model/transform/insertText} transformation */ this.insertText = function(tx, args) { if (args.selection.isPropertySelection() || args.selection.isContainerSelection()) { return insertText(tx, args); } }; /** Inserts a soft break */ this.softBreak = function(tx, args) { args.text = "\n"; return this.insertText(tx, args); }; /** Copy the current selection. Performs a {@link model/transform/copySelection} transformation. */ this.copy = function(doc, selection) { var result = copySelection(doc, { selection: selection }); return result.doc; }; this.onDocumentChange = function(change) { // first update the container var renderContext = RenderingEngine.createContext(this); if (change.isAffected([this.props.containerId, 'nodes'])) { for (var i = 0; i < change.ops.length; i++) { var op = change.ops[i]; if (op.type === "update" && op.path[0] === this.props.containerId) { var diff = op.diff; if (diff.type === "insert") { var nodeEl = this._renderNode(renderContext.$$, diff.getValue()); this.insertAt(diff.getOffset(), nodeEl); } else if (diff.type === "delete") { this.removeAt(diff.getOffset()); } } } } // do other stuff such as rerendering text properties _super.onDocumentChange.apply(this, arguments); }; // Create a first text element this.onCreateText = function(e) { e.preventDefault(); var newSel; this.transaction(function(tx) { var container = tx.get(this.props.containerId); var textType = tx.getSchema().getDefaultTextType(); var node = tx.create({ id: uuid(textType), type: textType, content: '' }); container.show(node.id); newSel = tx.createSelection({ type: 'property', path: [ node.id, 'content'], startOffset: 0, endOffset: 0 }); }.bind(this)); this.rerender(); this.setSelection(newSel); }; this._prepareArgs = function(args) { args.containerId = this.getContainerId(); args.editingBehavior = this.editingBehavior; }; }; Surface.extend(ContainerEditor); module.exports = ContainerEditor;
TypesetIO/substance
ui/ContainerEditor.js
JavaScript
mit
9,737