code
stringlengths
2
1.05M
export default { "ajs.datepicker.localisations.day-names.sunday": "Dimanĉo", "ajs.datepicker.localisations.day-names.monday": "Lundo", "ajs.datepicker.localisations.day-names.tuesday": "Mardo", "ajs.datepicker.localisations.day-names.wednesday": "Merkredo", "ajs.datepicker.localisations.day-names.thursday": "Ĵaŭdo", "ajs.datepicker.localisations.day-names.friday": "Vendredo", "ajs.datepicker.localisations.day-names.saturday": "Sabato", "ajs.datepicker.localisations.day-names-min.sunday": "Dim", "ajs.datepicker.localisations.day-names-min.monday": "Lun", "ajs.datepicker.localisations.day-names-min.tuesday": "Mar", "ajs.datepicker.localisations.day-names-min.wednesday": "Mer", "ajs.datepicker.localisations.day-names-min.thursday": "Ĵaŭ", "ajs.datepicker.localisations.day-names-min.friday": "Ven", "ajs.datepicker.localisations.day-names-min.saturday": "Sab", "ajs.datepicker.localisations.first-day": 0, "ajs.datepicker.localisations.is-RTL": false, "ajs.datepicker.localisations.month-names.january": "Januaro", "ajs.datepicker.localisations.month-names.february": "Februaro", "ajs.datepicker.localisations.month-names.march": "Marto", "ajs.datepicker.localisations.month-names.april": "Aprilo", "ajs.datepicker.localisations.month-names.may": "Majo", "ajs.datepicker.localisations.month-names.june": "Junio", "ajs.datepicker.localisations.month-names.july": "Julio", "ajs.datepicker.localisations.month-names.august": "Aŭgusto", "ajs.datepicker.localisations.month-names.september": "Septembro", "ajs.datepicker.localisations.month-names.october": "Oktobro", "ajs.datepicker.localisations.month-names.november": "Novembro", "ajs.datepicker.localisations.month-names.december": "Decembro", "ajs.datepicker.localisations.show-month-after-year": false, "ajs.datepicker.localisations.year-suffix": null }
// FIXME large resolutions lead to too large framebuffers :-( // FIXME animated shaders! check in redraw goog.provide('ol.renderer.webgl.TileLayer'); goog.require('ol'); goog.require('ol.Tile'); goog.require('ol.TileRange'); goog.require('ol.array'); goog.require('ol.extent'); goog.require('ol.math'); goog.require('ol.renderer.webgl.Layer'); goog.require('ol.renderer.webgl.tilelayershader'); goog.require('ol.size'); goog.require('ol.transform'); goog.require('ol.webgl'); goog.require('ol.webgl.Buffer'); /** * @constructor * @extends {ol.renderer.webgl.Layer} * @param {ol.renderer.webgl.Map} mapRenderer Map renderer. * @param {ol.layer.Tile} tileLayer Tile layer. */ ol.renderer.webgl.TileLayer = function(mapRenderer, tileLayer) { ol.renderer.webgl.Layer.call(this, mapRenderer, tileLayer); /** * @private * @type {ol.webgl.Fragment} */ this.fragmentShader_ = ol.renderer.webgl.tilelayershader.fragment; /** * @private * @type {ol.webgl.Vertex} */ this.vertexShader_ = ol.renderer.webgl.tilelayershader.vertex; /** * @private * @type {ol.renderer.webgl.tilelayershader.Locations} */ this.locations_ = null; /** * @private * @type {ol.webgl.Buffer} */ this.renderArrayBuffer_ = new ol.webgl.Buffer([ 0, 0, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 1, 0 ]); /** * @private * @type {ol.TileRange} */ this.renderedTileRange_ = null; /** * @private * @type {ol.Extent} */ this.renderedFramebufferExtent_ = null; /** * @private * @type {number} */ this.renderedRevision_ = -1; /** * @private * @type {ol.Size} */ this.tmpSize_ = [0, 0]; }; ol.inherits(ol.renderer.webgl.TileLayer, ol.renderer.webgl.Layer); /** * @inheritDoc */ ol.renderer.webgl.TileLayer.prototype.disposeInternal = function() { var context = this.mapRenderer.getContext(); context.deleteBuffer(this.renderArrayBuffer_); ol.renderer.webgl.Layer.prototype.disposeInternal.call(this); }; /** * Create a function that adds loaded tiles to the tile lookup. * @param {ol.source.Tile} source Tile source. * @param {ol.proj.Projection} projection Projection of the tiles. * @param {Object.<number, Object.<string, ol.Tile>>} tiles Lookup of loaded * tiles by zoom level. * @return {function(number, ol.TileRange):boolean} A function that can be * called with a zoom level and a tile range to add loaded tiles to the * lookup. * @protected */ ol.renderer.webgl.TileLayer.prototype.createLoadedTileFinder = function(source, projection, tiles) { var mapRenderer = this.mapRenderer; return ( /** * @param {number} zoom Zoom level. * @param {ol.TileRange} tileRange Tile range. * @return {boolean} The tile range is fully loaded. */ function(zoom, tileRange) { function callback(tile) { var loaded = mapRenderer.isTileTextureLoaded(tile); if (loaded) { if (!tiles[zoom]) { tiles[zoom] = {}; } tiles[zoom][tile.tileCoord.toString()] = tile; } return loaded; } return source.forEachLoadedTile(projection, zoom, tileRange, callback); }); }; /** * @inheritDoc */ ol.renderer.webgl.TileLayer.prototype.handleWebGLContextLost = function() { ol.renderer.webgl.Layer.prototype.handleWebGLContextLost.call(this); this.locations_ = null; }; /** * @inheritDoc */ ol.renderer.webgl.TileLayer.prototype.prepareFrame = function(frameState, layerState, context) { var mapRenderer = this.mapRenderer; var gl = context.getGL(); var viewState = frameState.viewState; var projection = viewState.projection; var tileLayer = /** @type {ol.layer.Tile} */ (this.getLayer()); var tileSource = tileLayer.getSource(); var tileGrid = tileSource.getTileGridForProjection(projection); var z = tileGrid.getZForResolution(viewState.resolution); var tileResolution = tileGrid.getResolution(z); var tilePixelSize = tileSource.getTilePixelSize(z, frameState.pixelRatio, projection); var pixelRatio = tilePixelSize[0] / ol.size.toSize(tileGrid.getTileSize(z), this.tmpSize_)[0]; var tilePixelResolution = tileResolution / pixelRatio; var tileGutter = frameState.pixelRatio * tileSource.getGutter(projection); var center = viewState.center; var extent; if (tileResolution == viewState.resolution) { center = this.snapCenterToPixel(center, tileResolution, frameState.size); extent = ol.extent.getForViewAndSize( center, tileResolution, viewState.rotation, frameState.size); } else { extent = frameState.extent; } var tileRange = tileGrid.getTileRangeForExtentAndResolution( extent, tileResolution); var framebufferExtent; if (this.renderedTileRange_ && this.renderedTileRange_.equals(tileRange) && this.renderedRevision_ == tileSource.getRevision()) { framebufferExtent = this.renderedFramebufferExtent_; } else { var tileRangeSize = tileRange.getSize(); var maxDimension = Math.max( tileRangeSize[0] * tilePixelSize[0], tileRangeSize[1] * tilePixelSize[1]); var framebufferDimension = ol.math.roundUpToPowerOfTwo(maxDimension); var framebufferExtentDimension = tilePixelResolution * framebufferDimension; var origin = tileGrid.getOrigin(z); var minX = origin[0] + tileRange.minX * tilePixelSize[0] * tilePixelResolution; var minY = origin[1] + tileRange.minY * tilePixelSize[1] * tilePixelResolution; framebufferExtent = [ minX, minY, minX + framebufferExtentDimension, minY + framebufferExtentDimension ]; this.bindFramebuffer(frameState, framebufferDimension); gl.viewport(0, 0, framebufferDimension, framebufferDimension); gl.clearColor(0, 0, 0, 0); gl.clear(ol.webgl.COLOR_BUFFER_BIT); gl.disable(ol.webgl.BLEND); var program = context.getProgram(this.fragmentShader_, this.vertexShader_); context.useProgram(program); if (!this.locations_) { this.locations_ = new ol.renderer.webgl.tilelayershader.Locations(gl, program); } context.bindBuffer(ol.webgl.ARRAY_BUFFER, this.renderArrayBuffer_); gl.enableVertexAttribArray(this.locations_.a_position); gl.vertexAttribPointer( this.locations_.a_position, 2, ol.webgl.FLOAT, false, 16, 0); gl.enableVertexAttribArray(this.locations_.a_texCoord); gl.vertexAttribPointer( this.locations_.a_texCoord, 2, ol.webgl.FLOAT, false, 16, 8); gl.uniform1i(this.locations_.u_texture, 0); /** * @type {Object.<number, Object.<string, ol.Tile>>} */ var tilesToDrawByZ = {}; tilesToDrawByZ[z] = {}; var findLoadedTiles = this.createLoadedTileFinder( tileSource, projection, tilesToDrawByZ); var useInterimTilesOnError = tileLayer.getUseInterimTilesOnError(); var allTilesLoaded = true; var tmpExtent = ol.extent.createEmpty(); var tmpTileRange = new ol.TileRange(0, 0, 0, 0); var childTileRange, drawable, fullyLoaded, tile, tileState; var x, y, tileExtent; for (x = tileRange.minX; x <= tileRange.maxX; ++x) { for (y = tileRange.minY; y <= tileRange.maxY; ++y) { tile = tileSource.getTile(z, x, y, pixelRatio, projection); if (layerState.extent !== undefined) { // ignore tiles outside layer extent tileExtent = tileGrid.getTileCoordExtent(tile.tileCoord, tmpExtent); if (!ol.extent.intersects(tileExtent, layerState.extent)) { continue; } } tileState = tile.getState(); drawable = tileState == ol.Tile.State.LOADED || tileState == ol.Tile.State.EMPTY || tileState == ol.Tile.State.ERROR && !useInterimTilesOnError; if (!drawable && tile.interimTile) { tile = tile.interimTile; } tileState = tile.getState(); if (tileState == ol.Tile.State.LOADED) { if (mapRenderer.isTileTextureLoaded(tile)) { tilesToDrawByZ[z][tile.tileCoord.toString()] = tile; continue; } } else if (tileState == ol.Tile.State.EMPTY || (tileState == ol.Tile.State.ERROR && !useInterimTilesOnError)) { continue; } allTilesLoaded = false; fullyLoaded = tileGrid.forEachTileCoordParentTileRange( tile.tileCoord, findLoadedTiles, null, tmpTileRange, tmpExtent); if (!fullyLoaded) { childTileRange = tileGrid.getTileCoordChildTileRange( tile.tileCoord, tmpTileRange, tmpExtent); if (childTileRange) { findLoadedTiles(z + 1, childTileRange); } } } } /** @type {Array.<number>} */ var zs = Object.keys(tilesToDrawByZ).map(Number); zs.sort(ol.array.numberSafeCompareFunction); var u_tileOffset = new Float32Array(4); var i, ii, tileKey, tilesToDraw; for (i = 0, ii = zs.length; i < ii; ++i) { tilesToDraw = tilesToDrawByZ[zs[i]]; for (tileKey in tilesToDraw) { tile = tilesToDraw[tileKey]; tileExtent = tileGrid.getTileCoordExtent(tile.tileCoord, tmpExtent); u_tileOffset[0] = 2 * (tileExtent[2] - tileExtent[0]) / framebufferExtentDimension; u_tileOffset[1] = 2 * (tileExtent[3] - tileExtent[1]) / framebufferExtentDimension; u_tileOffset[2] = 2 * (tileExtent[0] - framebufferExtent[0]) / framebufferExtentDimension - 1; u_tileOffset[3] = 2 * (tileExtent[1] - framebufferExtent[1]) / framebufferExtentDimension - 1; gl.uniform4fv(this.locations_.u_tileOffset, u_tileOffset); mapRenderer.bindTileTexture(tile, tilePixelSize, tileGutter * pixelRatio, ol.webgl.LINEAR, ol.webgl.LINEAR); gl.drawArrays(ol.webgl.TRIANGLE_STRIP, 0, 4); } } if (allTilesLoaded) { this.renderedTileRange_ = tileRange; this.renderedFramebufferExtent_ = framebufferExtent; this.renderedRevision_ = tileSource.getRevision(); } else { this.renderedTileRange_ = null; this.renderedFramebufferExtent_ = null; this.renderedRevision_ = -1; frameState.animate = true; } } this.updateUsedTiles(frameState.usedTiles, tileSource, z, tileRange); var tileTextureQueue = mapRenderer.getTileTextureQueue(); this.manageTilePyramid( frameState, tileSource, tileGrid, pixelRatio, projection, extent, z, tileLayer.getPreload(), /** * @param {ol.Tile} tile Tile. */ function(tile) { if (tile.getState() == ol.Tile.State.LOADED && !mapRenderer.isTileTextureLoaded(tile) && !tileTextureQueue.isKeyQueued(tile.getKey())) { tileTextureQueue.enqueue([ tile, tileGrid.getTileCoordCenter(tile.tileCoord), tileGrid.getResolution(tile.tileCoord[0]), tilePixelSize, tileGutter * pixelRatio ]); } }, this); this.scheduleExpireCache(frameState, tileSource); this.updateLogos(frameState, tileSource); var texCoordMatrix = this.texCoordMatrix; ol.transform.reset(texCoordMatrix); ol.transform.translate(texCoordMatrix, (center[0] - framebufferExtent[0]) / (framebufferExtent[2] - framebufferExtent[0]), (center[1] - framebufferExtent[1]) / (framebufferExtent[3] - framebufferExtent[1])); if (viewState.rotation !== 0) { ol.transform.rotate(texCoordMatrix, viewState.rotation); } ol.transform.scale(texCoordMatrix, frameState.size[0] * viewState.resolution / (framebufferExtent[2] - framebufferExtent[0]), frameState.size[1] * viewState.resolution / (framebufferExtent[3] - framebufferExtent[1])); ol.transform.translate(texCoordMatrix, -0.5, -0.5); return true; }; /** * @param {ol.Pixel} pixel Pixel. * @param {olx.FrameState} frameState FrameState. * @param {function(this: S, ol.layer.Layer, ol.Color): T} callback Layer * callback. * @param {S} thisArg Value to use as `this` when executing `callback`. * @return {T|undefined} Callback result. * @template S,T,U */ ol.renderer.webgl.TileLayer.prototype.forEachLayerAtPixel = function(pixel, frameState, callback, thisArg) { if (!this.framebuffer) { return undefined; } var pixelOnMapScaled = [ pixel[0] / frameState.size[0], (frameState.size[1] - pixel[1]) / frameState.size[1]]; var pixelOnFrameBufferScaled = ol.transform.apply( this.texCoordMatrix, pixelOnMapScaled.slice()); var pixelOnFrameBuffer = [ pixelOnFrameBufferScaled[0] * this.framebufferDimension, pixelOnFrameBufferScaled[1] * this.framebufferDimension]; var gl = this.mapRenderer.getContext().getGL(); gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer); var imageData = new Uint8Array(4); gl.readPixels(pixelOnFrameBuffer[0], pixelOnFrameBuffer[1], 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, imageData); if (imageData[3] > 0) { return callback.call(thisArg, this.getLayer(), imageData); } else { return undefined; } };
angular.module('app') .factory('urlService', ['BACKEND_SERVER_DOMAIN', 'BACKEND_SERVER_PORT', 'BACKEND_SERVER_PROTOCOL', urlService]); function urlService(BSD, BSPORT, BSPROT){ // if port is a non-empty string then set requestURL as such if(BSPORT){ var requestURL = BSPROT + '://' + BSD + ':' + BSPORT; // console.log(requestURL) } // if port is an empty string then set requestURL as such else{ var requestURL = BSPROT + '://' + BSD; // console.log(requestURL) } // returns url of backend with path appended function backendUrl(path){ return (requestURL + path); } return { 'backendUrl': backendUrl }; }
import React from 'react' import Helmet from 'react-helmet' import { prefixLink } from 'gatsby-helpers' const BUILD_TIME = new Date().getTime() module.exports = React.createClass({ displayName: 'HTML', propTypes: { body: React.PropTypes.string, }, render() { const {body, route} = this.props const head = Helmet.rewind() let css if (process.env.NODE_ENV === 'production') { css = <style dangerouslySetInnerHTML={ { __html: require('!raw!./public/styles.css')} } /> } return ( <html lang="en"> <head> <meta charSet="utf-8" /> <meta httpEquiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0 maximum-scale=5.0" /> { head.title.toComponent() } { head.meta.toComponent() } { css } </head> <body className="avenir black"> <div id="react-mount" dangerouslySetInnerHTML={ { __html: this.props.body} } /> <script src={ prefixLink(`/bundle.js?t=${BUILD_TIME}`) } /> </body> </html> ) }, })
define(['angular', 'angular-couch-potato', 'angular-ui-router' ], function (ng, couchPotato) { "use strict"; var module = ng.module('app.system', ['ui.router']); couchPotato.configureApp(module) module.config(function ($stateProvider, $couchPotatoProvider) { $stateProvider .state('app.system', { abstract: true, data: { title: 'Sistem Yönetimi' } }) .state('app.system.userList', { url: '/system/userList', data: { title: 'Kullanıcı Listesi' }, views: { "content@app": { templateUrl: "app/modules/system/views/UserList.html", controller: 'UserCtrl', resolve: { deps: $couchPotatoProvider.resolveDependencies([ 'modules/system/controllers/UserCtrl', 'modules/system/controllers/UserDetailCtrl', 'modules/system/controllers/UserRoleCtrl', 'layout/controllers/GeneralModalDetailCtrl', 'auth/models/UserService', 'layout/directives/convertValueToImage' ]) } } } }) }); module.run(function ($couchPotato) { module.lazy = $couchPotato; }); return module; });
(function() { 'use strict'; module.exports = function(require) { require.gulp.task('clean-code', function(done) { var files = [].concat( require.config.temp + '**/*.js', require.config.build + 'js/**/*.js', require.config.build + '**/*.html' ); clean(files, done); }); /** * Delete all files in a given path * @param {Array} path - array of paths to delete * @param {Function} done - callback when complete */ function clean(path, done) { require.logger(require.$.util, 'Cleaning: ' + require.$.util.colors.blue(path)); require.del(path, done); } }; }());
'use strict'; import React, { Component } from 'react'; import { AlertIOS, AppRegistry, StyleSheet, Text, TouchableOpacity, View, } from 'react-native'; import Video from '@drivetribe/react-native-video'; class VideoPlayer extends Component { constructor(props) { super(props); this.onLoad = this.onLoad.bind(this); this.onProgress = this.onProgress.bind(this); this.onBuffer = this.onBuffer.bind(this); } state = { rate: 1, volume: 1, muted: false, resizeMode: 'contain', duration: 0.0, currentTime: 0.0, controls: false, paused: true, skin: 'custom', isBuffering: false, }; onLoad(data) { console.log('On load fired!'); this.setState({duration: data.duration}); } onProgress(data) { this.setState({currentTime: data.currentTime}); } onBuffer({ isBuffering }: { isBuffering: boolean }) { this.setState({ isBuffering }); } getCurrentTimePercentage() { if (this.state.currentTime > 0) { return parseFloat(this.state.currentTime) / parseFloat(this.state.duration); } else { return 0; } } renderSkinControl(skin) { const isSelected = this.state.skin == skin; const selectControls = skin == 'native' || skin == 'embed'; return ( <TouchableOpacity onPress={() => { this.setState({ controls: selectControls, skin: skin }) }}> <Text style={[styles.controlOption, {fontWeight: isSelected ? "bold" : "normal"}]}> {skin} </Text> </TouchableOpacity> ); } renderRateControl(rate) { const isSelected = (this.state.rate == rate); return ( <TouchableOpacity onPress={() => { this.setState({rate: rate}) }}> <Text style={[styles.controlOption, {fontWeight: isSelected ? "bold" : "normal"}]}> {rate}x </Text> </TouchableOpacity> ) } renderResizeModeControl(resizeMode) { const isSelected = (this.state.resizeMode == resizeMode); return ( <TouchableOpacity onPress={() => { this.setState({resizeMode: resizeMode}) }}> <Text style={[styles.controlOption, {fontWeight: isSelected ? "bold" : "normal"}]}> {resizeMode} </Text> </TouchableOpacity> ) } renderVolumeControl(volume) { const isSelected = (this.state.volume == volume); return ( <TouchableOpacity onPress={() => { this.setState({volume: volume}) }}> <Text style={[styles.controlOption, {fontWeight: isSelected ? "bold" : "normal"}]}> {volume * 100}% </Text> </TouchableOpacity> ) } renderCustomSkin() { const flexCompleted = this.getCurrentTimePercentage() * 100; const flexRemaining = (1 - this.getCurrentTimePercentage()) * 100; return ( <View style={styles.container}> <TouchableOpacity style={styles.fullScreen} onPress={() => {this.setState({paused: !this.state.paused})}}> <Video source={require('./broadchurch.mp4')} style={styles.fullScreen} rate={this.state.rate} paused={this.state.paused} volume={this.state.volume} muted={this.state.muted} resizeMode={this.state.resizeMode} onLoad={this.onLoad} onBuffer={this.onBuffer} onProgress={this.onProgress} onEnd={() => { AlertIOS.alert('Done!') }} repeat={true} /> </TouchableOpacity> <View style={styles.controls}> <View style={styles.generalControls}> <View style={styles.skinControl}> {this.renderSkinControl('custom')} {this.renderSkinControl('native')} {this.renderSkinControl('embed')} </View> </View> <View style={styles.generalControls}> <View style={styles.rateControl}> {this.renderRateControl(0.5)} {this.renderRateControl(1.0)} {this.renderRateControl(2.0)} </View> <View style={styles.volumeControl}> {this.renderVolumeControl(0.5)} {this.renderVolumeControl(1)} {this.renderVolumeControl(1.5)} </View> <View style={styles.resizeModeControl}> {this.renderResizeModeControl('cover')} {this.renderResizeModeControl('contain')} {this.renderResizeModeControl('stretch')} </View> </View> <View style={styles.trackingControls}> <View style={styles.progress}> <View style={[styles.innerProgressCompleted, {flex: flexCompleted}]} /> <View style={[styles.innerProgressRemaining, {flex: flexRemaining}]} /> </View> </View> </View> </View> ); } renderNativeSkin() { const videoStyle = this.state.skin == 'embed' ? styles.nativeVideoControls : styles.fullScreen; return ( <View style={styles.container}> <View style={styles.fullScreen}> <Video source={require('./broadchurch.mp4')} style={videoStyle} rate={this.state.rate} paused={this.state.paused} volume={this.state.volume} muted={this.state.muted} resizeMode={this.state.resizeMode} onLoad={this.onLoad} onBuffer={this.onBuffer} onProgress={this.onProgress} onEnd={() => { AlertIOS.alert('Done!') }} repeat={true} controls={this.state.controls} /> </View> <View style={styles.controls}> <View style={styles.generalControls}> <View style={styles.skinControl}> {this.renderSkinControl('custom')} {this.renderSkinControl('native')} {this.renderSkinControl('embed')} </View> </View> <View style={styles.generalControls}> <View style={styles.rateControl}> {this.renderRateControl(0.5)} {this.renderRateControl(1.0)} {this.renderRateControl(2.0)} </View> <View style={styles.volumeControl}> {this.renderVolumeControl(0.5)} {this.renderVolumeControl(1)} {this.renderVolumeControl(1.5)} </View> <View style={styles.resizeModeControl}> {this.renderResizeModeControl('cover')} {this.renderResizeModeControl('contain')} {this.renderResizeModeControl('stretch')} </View> </View> </View> </View> ); } render() { return this.state.controls ? this.renderNativeSkin() : this.renderCustomSkin(); } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: 'black', }, fullScreen: { position: 'absolute', top: 0, left: 0, bottom: 0, right: 0, }, controls: { backgroundColor: "transparent", borderRadius: 5, position: 'absolute', bottom: 44, left: 4, right: 4, }, progress: { flex: 1, flexDirection: 'row', borderRadius: 3, overflow: 'hidden', }, innerProgressCompleted: { height: 20, backgroundColor: '#cccccc', }, innerProgressRemaining: { height: 20, backgroundColor: '#2C2C2C', }, generalControls: { flex: 1, flexDirection: 'row', overflow: 'hidden', paddingBottom: 10, }, skinControl: { flex: 1, flexDirection: 'row', justifyContent: 'center', }, rateControl: { flex: 1, flexDirection: 'row', justifyContent: 'center', }, volumeControl: { flex: 1, flexDirection: 'row', justifyContent: 'center', }, resizeModeControl: { flex: 1, flexDirection: 'row', alignItems: 'center', justifyContent: 'center' }, controlOption: { alignSelf: 'center', fontSize: 11, color: "white", paddingLeft: 2, paddingRight: 2, lineHeight: 12, }, nativeVideoControls: { top: 184, height: 300 } }); AppRegistry.registerComponent('VideoPlayer', () => VideoPlayer);
// Require modules const check = require('./check') /** * The exported checking function. * * @param {CheckOptions} options The options for the version check. * @param {CallbackFunction|undefined} callback An optional callback to pass the result to. * Can be omitted to return a Promise. * @return null or a Promise. */ module.exports = (options, callback) => { if (callback) { check(options, callback) return null } else { return new Promise((resolve, reject) => { check(options, (error, update) => { if (error) reject(error) else if (update) resolve(update) else resolve(null) }) }) } }
var Ball = function (r, px, py, vx, vy, color) { this.radius = r; this.mass = r; this.position = new Point(px, py); this.velocity = new Vector(vx, vy); this.color = color || "black"; this.wireframe = false; }; Ball.prototype.updateBoundingBox = function () { this.boundingBox = { left : this.position.x - this.radius, right : this.position.x + this.radius, top : this.position.y - this.radius, bottom : this.position.y + this.radius, }; }; Ball.prototype.snap2wall = function () { if (this.boundingBox.left < container.left) { this.position.x = container.left + this.radius; } if (this.boundingBox.right > container.right) { this.position.x = container.right - this.radius; } this.updateBoundingBox(); }; Ball.prototype.snap2ball = function (ball) { var b1_mag = this.velocity.magnitude(); var b2_mag = ball.velocity.magnitude(); var intersection = (this.radius + ball.radius) - Math.abs(this.position.x - ball.position.x); if (b1_mag != 0 && b2_mag != 0) { var min_mag = Math.min(b1_mag, b2_mag); var max_mag = Math.max(b1_mag, b2_mag); var mag_rat = min_mag / max_mag; var min_offset = 0; var max_offset = 0; if (b1_mag < b2_mag) { min_offset = Math.round(intersection / (1 + mag_rat)); max_offset = intersection - min_offset; } else { max_offset = Math.round(intersection / (1 + mag_rat)); min_offset = intersection - max_offset; } if (min_mag == b1_mag) { this.position.x -= min_offset; ball.position.x += max_offset; } else if (min_mag == b2_mag) { ball.position.x += min_offset; this.position.x -= max_offset; } } else if (b1_mag == 0 || b2_mag == 0) { if (b1_mag == 0) { ball.position.x += intersection; } else if (b2_mag == 0) { this.position.x -= intersection; } } this.updateBoundingBox(); ball.updateBoundingBox(); }; Ball.prototype.move = function () { this.position.add(this.velocity); this.updateBoundingBox(); this.snap2wall(); }; Ball.prototype.detectWallCollision = function () { if (this.boundingBox.left <= container.left || this.boundingBox.right >= container.right) { this.velocity.reverse("x"); } }; Ball.prototype.collidingWith = function (ball) { // checking if balls are colliding isn't enough // before the collision, we need to make sure the balls are touching, not intersecting // we need to handle this the same way we handled wall intersection if (this.boundingBox.right >= ball.boundingBox.left && this.boundingBox.left <= ball.boundingBox.right) { return true; } return false; }; Ball.prototype.draw = function () { context.beginPath(); context.arc(this.position.x, this.position.y, this.radius, 0, 2 * Math. PI); if (this.wireframe) { context.strokeStyle = this.color; context.stroke(); } else { context.fillStyle = this.color; context.fill(); } }; Ball.prototype.resoveCollision = function (ball) { var vx1 = (this.velocity.x * (this.mass - ball.mass) + 2 * ball.mass * ball.velocity.x) / (this.mass + ball.mass); var vx2 = (ball.velocity.x * (ball.mass - this.mass) + 2 * this.mass * this.velocity.x) / (this.mass + ball.mass); this.velocity = new Vector(vx1, 0); ball.velocity = new Vector(vx2, 0); }; function trackBallCollisions() { for (var i = 0; i < balls.length; i++) { for (var j = i + 1; j < balls.length; j++) { if (balls[i].collidingWith(balls[j])) { balls[i].resoveCollision(balls[j]); balls[i].snap2ball(balls[j]); } } } }
"use strict"; const EventEmitter = require('events'); const http = require('http'); const https = require('https'); const urlLib = require('url'); const toughCookie = require('tough-cookie'); // http://stackoverflow.com/a/19709846/1725509 const absoluteUrlCheck = new RegExp('^(?:[a-z]+:)?//', 'i'); class Request extends EventEmitter { constructor(url, options, agent) { super(); if (!url) throw new Error("URL required for Giles Request"); if (!agent) throw new Error("Agent required for Giles Request"); this.url = url; this.options = options || {}; this.agent = agent; this.redirectChain = []; this.data = ""; this.dataSize = 0; this.promise = new Promise((resolve, reject) => { this.on('error', reject); this.on('complete', resolve); }); this.on('redirect', (url) => this._onRedirect(url)); } get cookies() { if (this.cookieJar) { return this.cookieJar.getCookiesSync(this.url).join("; "); } else { return undefined; } } get _httpOptions() { var obj = { protocol: this.url.protocol, hostname: this.url.hostname, port: this.url.port, path: this.url.path, headers: { // https://developer.mozilla.org/en-US/docs/Web/HTTP/Content_negotiation#The_Accept.3a_header "Accept": "text/html;q=0.9,*/*;q=0.8", // "Accept-Encoding": "gzip", maybe some day "User-Agent": this.agent.userAgent } }; var cookies = this.cookies; if (cookies) obj.headers["Cookie"] = cookies; return obj; } get responseObject() { return { data: this.data, redirectChain: this.redirectChain }; } _send() { // TODO: request timeout: http://stackoverflow.com/questions/6214902/how-to-set-a-timeout-on-a-http-request-in-node var options = this._httpOptions; if (options.protocol === 'http:') { options.agent = this.agent.httpAgent; this.request = http.get(options); } else if (options.protocol === 'https:') { options.agent = this.agent.secureAgent; this.request = https.get(options); } else { return this.emit('error', new Error("Request does not fit HTTP or HTTPS protocols")); } // Set timeout if (this.options.timeout) { this.request.socket.setTimeout(this.options.timeout); this.request.socket.on('timeout', () => { var err = new Error("Connection timed out"); err.type = "giles.timeout"; this._kill(err); }); } this.request.on('abort', () => this._onClientAbort()); this.request.on('response', (res) => this._onResponse(res)); this.request.on('end', () => this._onEnd()); } _onData(d) { this.data += d; this.dataSize += d.length; if (this.options.maxSize && this.options.maxSize < this.dataSize) { var err = new Error("Content exceeds maximum length"); err.type = "giles.maxlength"; this._kill(err); } } _onClientAbort() { var err = new Error("The connection was aborted."); err.type = "giles.aborted"; this.emit('error', err); } _onResponse(res) { // res is a http(s).IncomingMessage var headers = res.headers; if (headers['set-cookie']) { if (!this.cookieJar) this.cookieJar = new toughCookie.CookieJar(); headers['set-cookie'].forEach((c) => { this.cookieJar.setCookieSync(c, this.url); }); } // Check status code/if redirect switch (res.statusCode) { case 200: break; case 301: case 302: case 303: case 307: var url; var location = headers['location']; if (absoluteUrlCheck.test()) { url = location; } else { url = urlLib.resolve(this.url, location); } return this.emit('redirect', url); case 404: var err = new Error("Page not found"); err.type = "giles.notfound"; return this._kill(err); default: var err = new Error(res.statusMessage); err.type = "giles.fetcherror"; return this._kill(err); } // Check if return type is text/html if (!headers['content-type'].startsWith('text/html')) { var err = new Error("Content type is "+headers['content-type']); err.type = "giles.badtype"; return this._kill(err); } // Check if content-length is greater than max // Set max size to content-length if (headers['content-length']) { if (headers['content-length'] > this.options.maxSize) { var err = new Error("Content size is too large"); err.type = "giles.maxlength"; return this._kill(err); } this.options.maxSize = headers['content-length']; } // Check that encoding is acceptable if (headers['content-encoding'] && headers['content-encoding'] !== "identity") { var err = new Error("Unacceptable encoding type: "+headers['content-encoding']); err.type = "giles.unsupported-encoding"; return this._kill(err); } // Add all of the appropriate listeners to res res.on('data', (d) => this._onData(d)); res.on('end', () => this._onEnd()); // Set this.response to res this.response = res; } _onRedirect(url) { this.request.removeAllListeners(); this.request.abort(); this.redirectChain.push(this.url); var oldUrl = this.url; this.url = urlLib.parse(url); // If the host and protocol don't change, we don't need to recheck if (oldUrl.hostname === this.url.hostname && oldUrl.protocol === this.url.protocol) { this._send(); return; } // Check blacklist if (this.agent.blacklist.has(this.url.hostname)) { var err = new Error("Redirected URL is in blacklist"); err.type = "giles.blacklist"; this._kill(err); return; } // Check robots.txt this.agent.checkRobots(this.url.protocol, this.url.host, this.url.path) .then((allowed) => { if (allowed) this._send(); else { var err = new Error(url + " is not permitted by robots.txt"); err.type = "giles:robots"; this._kill(err); } }).catch((err) => { this._kill(err); }); } _onEnd() { this.redirectChain.push(this.url); this.emit('complete', this.responseObject); } _kill(err) { this.request.abort(); this.emit('error', err); } exec() { // User-facing method to start request and return a Promise this._send(); return this.promise; } } module.exports = Request;
// Used to read secrets from the .env file require('dotenv').config() module.exports = { siteMetadata: { title: `Gatsby Default Starter`, description: `Kick off your next, great Gatsby project with this default starter. This barebones starter ships with the main Gatsby configuration files you might need.`, author: `@gatsbyjs`, }, plugins: [ `gatsby-plugin-react-helmet`, { resolve: `gatsby-source-filesystem`, options: { name: `images`, path: `${__dirname}/src/images`, }, }, `gatsby-transformer-sharp`, `gatsby-plugin-sharp`, { resolve: `gatsby-plugin-manifest`, options: { name: `gatsby-starter-default`, short_name: `starter`, start_url: `/`, background_color: `#663399`, theme_color: `#663399`, display: `minimal-ui`, icon: `src/images/gatsby-icon.png`, // This path is relative to the root of the site. } }, `gatsby-plugin-sass`, { resolve: `gatsby-source-contentful`, options: { spaceId: process.env.CONTENTFUL_SPACE_ID, accessToken: process.env.CONTENTFUL_DELIVERY_ACCESS_TOKEN } } // this (optional) plugin enables Progressive Web App + Offline functionality // To learn more, visit: https://gatsby.dev/offline // `gatsby-plugin-offline`, ], }
var config = { tokenSeparatorHTML: '&raquo;', initialList: 'foods', lists: { foods: [ { value: 'Fruits', children: 'fruits' }, { value: 'Meats', children: 'meats' }, { value: 'Vegetables', children: 'vegetables' } ], fruits: ['Apple', 'Banana', 'Orange'], meats: ['Beef', 'Chicken', 'Pork'], vegetables: ['Carrot', 'Lettuce', 'Onion'] } }; var widget = new AutoComplete('search_bar', config);
var pipeworks = require('pipeworks'); var AppImage = require('./app_image'); var BuildImage = require('./build_image'); var Container = require('../container'); var StepRunner = require('./step_runner'); var config = require('../config/build_container'); var server = require('../config/server'); function Context() { this.buildImage = null; this.appImage = null; } var BuildProcess = module.exports = function(app, input) { this.app = app; this.input = input; }; BuildProcess.prototype.execute = function(cb) { var pipeline = pipeworks(); var container = Container.create(server); var self = this; pipeline.fit(function(context, next) { context.buildImage = new BuildImage(container, config, self.input, self.app); var buildImageRunner = new StepRunner(context.buildImage); buildImageRunner.run(function(err) { if (err) return cb(err); next(context); }); }); pipeline.fit(function(context, next) { context.appImage = new AppImage(container, context.buildImage.name, self.app); var appImageRunner = new StepRunner(context.appImage); appImageRunner.run(function(err) { if (err) return cb(err); next(context); }) }); pipeline.fit(function(context, next) { cb(null, context.appImage.name); }); var context = new Context(); pipeline.flow(context); };
import { LinearFilter, LinearMipmapLinearFilter, LinearMipmapNearestFilter, NearestFilter, NearestMipmapLinearFilter, NearestMipmapNearestFilter, RGBFormat, RGBAFormat, DepthFormat, DepthStencilFormat, UnsignedShortType, UnsignedIntType, UnsignedInt248Type, FloatType, HalfFloatType, MirroredRepeatWrapping, ClampToEdgeWrapping, RepeatWrapping } from '../../constants.js'; import { MathUtils } from '../../math/MathUtils.js'; function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info ) { const isWebGL2 = capabilities.isWebGL2; const maxTextures = capabilities.maxTextures; const maxCubemapSize = capabilities.maxCubemapSize; const maxTextureSize = capabilities.maxTextureSize; const maxSamples = capabilities.maxSamples; const _videoTextures = new WeakMap(); let _canvas; // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas, // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")! // Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d). let useOffscreenCanvas = false; try { useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined' && ( new OffscreenCanvas( 1, 1 ).getContext( "2d" ) ) !== null; } catch ( err ) { // Ignore any errors } function createCanvas( width, height ) { // Use OffscreenCanvas when available. Specially needed in web workers return useOffscreenCanvas ? new OffscreenCanvas( width, height ) : document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ); } function resizeImage( image, needsPowerOfTwo, needsNewCanvas, maxSize ) { let scale = 1; // handle case if texture exceeds max size if ( image.width > maxSize || image.height > maxSize ) { scale = maxSize / Math.max( image.width, image.height ); } // only perform resize if necessary if ( scale < 1 || needsPowerOfTwo === true ) { // only perform resize for certain image types if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) || ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) || ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) { const floor = needsPowerOfTwo ? MathUtils.floorPowerOfTwo : Math.floor; const width = floor( scale * image.width ); const height = floor( scale * image.height ); if ( _canvas === undefined ) _canvas = createCanvas( width, height ); // cube textures can't reuse the same canvas const canvas = needsNewCanvas ? createCanvas( width, height ) : _canvas; canvas.width = width; canvas.height = height; const context = canvas.getContext( '2d' ); context.drawImage( image, 0, 0, width, height ); console.warn( 'THREE.WebGLRenderer: Texture has been resized from (' + image.width + 'x' + image.height + ') to (' + width + 'x' + height + ').' ); return canvas; } else { if ( 'data' in image ) { console.warn( 'THREE.WebGLRenderer: Image in DataTexture is too big (' + image.width + 'x' + image.height + ').' ); } return image; } } return image; } function isPowerOfTwo( image ) { return MathUtils.isPowerOfTwo( image.width ) && MathUtils.isPowerOfTwo( image.height ); } function textureNeedsPowerOfTwo( texture ) { if ( isWebGL2 ) return false; return ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) || ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ); } function textureNeedsGenerateMipmaps( texture, supportsMips ) { return texture.generateMipmaps && supportsMips && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter; } function generateMipmap( target, texture, width, height ) { _gl.generateMipmap( target ); const textureProperties = properties.get( texture ); // Note: Math.log( x ) * Math.LOG2E used instead of Math.log2( x ) which is not supported by IE11 textureProperties.__maxMipLevel = Math.log( Math.max( width, height ) ) * Math.LOG2E; } function getInternalFormat( internalFormatName, glFormat, glType ) { if ( isWebGL2 === false ) return glFormat; if ( internalFormatName !== null ) { if ( _gl[ internalFormatName ] !== undefined ) return _gl[ internalFormatName ]; console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' ); } let internalFormat = glFormat; if ( glFormat === _gl.RED ) { if ( glType === _gl.FLOAT ) internalFormat = _gl.R32F; if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.R16F; if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.R8; } if ( glFormat === _gl.RGB ) { if ( glType === _gl.FLOAT ) internalFormat = _gl.RGB32F; if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.RGB16F; if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RGB8; } if ( glFormat === _gl.RGBA ) { if ( glType === _gl.FLOAT ) internalFormat = _gl.RGBA32F; if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.RGBA16F; if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RGBA8; } if ( internalFormat === _gl.R16F || internalFormat === _gl.R32F || internalFormat === _gl.RGBA16F || internalFormat === _gl.RGBA32F ) { extensions.get( 'EXT_color_buffer_float' ); } return internalFormat; } // Fallback filters for non-power-of-2 textures function filterFallback( f ) { if ( f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter ) { return _gl.NEAREST; } return _gl.LINEAR; } // function onTextureDispose( event ) { const texture = event.target; texture.removeEventListener( 'dispose', onTextureDispose ); deallocateTexture( texture ); if ( texture.isVideoTexture ) { _videoTextures.delete( texture ); } info.memory.textures --; } function onRenderTargetDispose( event ) { const renderTarget = event.target; renderTarget.removeEventListener( 'dispose', onRenderTargetDispose ); deallocateRenderTarget( renderTarget ); info.memory.textures --; } // function deallocateTexture( texture ) { const textureProperties = properties.get( texture ); if ( textureProperties.__webglInit === undefined ) return; _gl.deleteTexture( textureProperties.__webglTexture ); properties.remove( texture ); } function deallocateRenderTarget( renderTarget ) { const renderTargetProperties = properties.get( renderTarget ); const textureProperties = properties.get( renderTarget.texture ); if ( ! renderTarget ) return; if ( textureProperties.__webglTexture !== undefined ) { _gl.deleteTexture( textureProperties.__webglTexture ); } if ( renderTarget.depthTexture ) { renderTarget.depthTexture.dispose(); } if ( renderTarget.isWebGLCubeRenderTarget ) { for ( let i = 0; i < 6; i ++ ) { _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] ); if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] ); } } else { _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer ); if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer ); if ( renderTargetProperties.__webglMultisampledFramebuffer ) _gl.deleteFramebuffer( renderTargetProperties.__webglMultisampledFramebuffer ); if ( renderTargetProperties.__webglColorRenderbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglColorRenderbuffer ); if ( renderTargetProperties.__webglDepthRenderbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthRenderbuffer ); } properties.remove( renderTarget.texture ); properties.remove( renderTarget ); } // let textureUnits = 0; function resetTextureUnits() { textureUnits = 0; } function allocateTextureUnit() { const textureUnit = textureUnits; if ( textureUnit >= maxTextures ) { console.warn( 'THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + maxTextures ); } textureUnits += 1; return textureUnit; } // function setTexture2D( texture, slot ) { const textureProperties = properties.get( texture ); if ( texture.isVideoTexture ) updateVideoTexture( texture ); if ( texture.version > 0 && textureProperties.__version !== texture.version ) { const image = texture.image; if ( image === undefined ) { console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is undefined' ); } else if ( image.complete === false ) { console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete' ); } else { uploadTexture( textureProperties, texture, slot ); return; } } state.activeTexture( _gl.TEXTURE0 + slot ); state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture ); } function setTexture2DArray( texture, slot ) { const textureProperties = properties.get( texture ); if ( texture.version > 0 && textureProperties.__version !== texture.version ) { uploadTexture( textureProperties, texture, slot ); return; } state.activeTexture( _gl.TEXTURE0 + slot ); state.bindTexture( _gl.TEXTURE_2D_ARRAY, textureProperties.__webglTexture ); } function setTexture3D( texture, slot ) { const textureProperties = properties.get( texture ); if ( texture.version > 0 && textureProperties.__version !== texture.version ) { uploadTexture( textureProperties, texture, slot ); return; } state.activeTexture( _gl.TEXTURE0 + slot ); state.bindTexture( _gl.TEXTURE_3D, textureProperties.__webglTexture ); } function setTextureCube( texture, slot ) { if ( texture.image.length !== 6 ) return; const textureProperties = properties.get( texture ); if ( texture.version > 0 && textureProperties.__version !== texture.version ) { initTexture( textureProperties, texture ); state.activeTexture( _gl.TEXTURE0 + slot ); state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture ); _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY ); const isCompressed = ( texture && ( texture.isCompressedTexture || texture.image[ 0 ].isCompressedTexture ) ); const isDataTexture = ( texture.image[ 0 ] && texture.image[ 0 ].isDataTexture ); const cubeImage = []; for ( let i = 0; i < 6; i ++ ) { if ( ! isCompressed && ! isDataTexture ) { cubeImage[ i ] = resizeImage( texture.image[ i ], false, true, maxCubemapSize ); } else { cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ]; } } const image = cubeImage[ 0 ], supportsMips = isPowerOfTwo( image ) || isWebGL2, glFormat = utils.convert( texture.format ), glType = utils.convert( texture.type ), glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType ); setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, supportsMips ); let mipmaps; if ( isCompressed ) { for ( let i = 0; i < 6; i ++ ) { mipmaps = cubeImage[ i ].mipmaps; for ( let j = 0; j < mipmaps.length; j ++ ) { const mipmap = mipmaps[ j ]; if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) { if ( glFormat !== null ) { state.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data ); } else { console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()' ); } } else { state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data ); } } } textureProperties.__maxMipLevel = mipmaps.length - 1; } else { mipmaps = texture.mipmaps; for ( let i = 0; i < 6; i ++ ) { if ( isDataTexture ) { state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data ); for ( let j = 0; j < mipmaps.length; j ++ ) { const mipmap = mipmaps[ j ]; const mipmapImage = mipmap.image[ i ].image; state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data ); } } else { state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, glFormat, glType, cubeImage[ i ] ); for ( let j = 0; j < mipmaps.length; j ++ ) { const mipmap = mipmaps[ j ]; state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[ i ] ); } } } textureProperties.__maxMipLevel = mipmaps.length; } if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) { // We assume images for cube map have the same size. generateMipmap( _gl.TEXTURE_CUBE_MAP, texture, image.width, image.height ); } textureProperties.__version = texture.version; if ( texture.onUpdate ) texture.onUpdate( texture ); } else { state.activeTexture( _gl.TEXTURE0 + slot ); state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture ); } } function setTextureCubeDynamic( texture, slot ) { state.activeTexture( _gl.TEXTURE0 + slot ); state.bindTexture( _gl.TEXTURE_CUBE_MAP, properties.get( texture ).__webglTexture ); } const wrappingToGL = { [ RepeatWrapping ]: _gl.REPEAT, [ ClampToEdgeWrapping ]: _gl.CLAMP_TO_EDGE, [ MirroredRepeatWrapping ]: _gl.MIRRORED_REPEAT }; const filterToGL = { [ NearestFilter ]: _gl.NEAREST, [ NearestMipmapNearestFilter ]: _gl.NEAREST_MIPMAP_NEAREST, [ NearestMipmapLinearFilter ]: _gl.NEAREST_MIPMAP_LINEAR, [ LinearFilter ]: _gl.LINEAR, [ LinearMipmapNearestFilter ]: _gl.LINEAR_MIPMAP_NEAREST, [ LinearMipmapLinearFilter ]: _gl.LINEAR_MIPMAP_LINEAR }; function setTextureParameters( textureType, texture, supportsMips ) { if ( supportsMips ) { _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] ); _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] ); if ( textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY ) { _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] ); } _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] ); _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterToGL[ texture.minFilter ] ); } else { _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE ); _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE ); if ( textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY ) { _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_R, _gl.CLAMP_TO_EDGE ); } if ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) { console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.' ); } _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) ); _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) ); if ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) { console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.' ); } } const extension = extensions.get( 'EXT_texture_filter_anisotropic' ); if ( extension ) { if ( texture.type === FloatType && extensions.get( 'OES_texture_float_linear' ) === null ) return; if ( texture.type === HalfFloatType && ( isWebGL2 || extensions.get( 'OES_texture_half_float_linear' ) ) === null ) return; if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) { _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) ); properties.get( texture ).__currentAnisotropy = texture.anisotropy; } } } function initTexture( textureProperties, texture ) { if ( textureProperties.__webglInit === undefined ) { textureProperties.__webglInit = true; texture.addEventListener( 'dispose', onTextureDispose ); textureProperties.__webglTexture = _gl.createTexture(); info.memory.textures ++; } } function uploadTexture( textureProperties, texture, slot ) { let textureType = _gl.TEXTURE_2D; if ( texture.isDataTexture2DArray ) textureType = _gl.TEXTURE_2D_ARRAY; if ( texture.isDataTexture3D ) textureType = _gl.TEXTURE_3D; initTexture( textureProperties, texture ); state.activeTexture( _gl.TEXTURE0 + slot ); state.bindTexture( textureType, textureProperties.__webglTexture ); _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY ); _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha ); _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment ); const needsPowerOfTwo = textureNeedsPowerOfTwo( texture ) && isPowerOfTwo( texture.image ) === false; const image = resizeImage( texture.image, needsPowerOfTwo, false, maxTextureSize ); const supportsMips = isPowerOfTwo( image ) || isWebGL2, glFormat = utils.convert( texture.format ); let glType = utils.convert( texture.type ), glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType ); setTextureParameters( textureType, texture, supportsMips ); let mipmap; const mipmaps = texture.mipmaps; if ( texture.isDepthTexture ) { // populate depth texture with dummy data glInternalFormat = _gl.DEPTH_COMPONENT; if ( isWebGL2 ) { if ( texture.type === FloatType ) { glInternalFormat = _gl.DEPTH_COMPONENT32F; } else if ( texture.type === UnsignedIntType ) { glInternalFormat = _gl.DEPTH_COMPONENT24; } else if ( texture.type === UnsignedInt248Type ) { glInternalFormat = _gl.DEPTH24_STENCIL8; } else { glInternalFormat = _gl.DEPTH_COMPONENT16; // WebGL2 requires sized internalformat for glTexImage2D } } else { if ( texture.type === FloatType ) { console.error( 'WebGLRenderer: Floating point depth texture requires WebGL2.' ); } } // validation checks for WebGL 1 if ( texture.format === DepthFormat && glInternalFormat === _gl.DEPTH_COMPONENT ) { // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/) if ( texture.type !== UnsignedShortType && texture.type !== UnsignedIntType ) { console.warn( 'THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.' ); texture.type = UnsignedShortType; glType = utils.convert( texture.type ); } } if ( texture.format === DepthStencilFormat && glInternalFormat === _gl.DEPTH_COMPONENT ) { // Depth stencil textures need the DEPTH_STENCIL internal format // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/) glInternalFormat = _gl.DEPTH_STENCIL; // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/) if ( texture.type !== UnsignedInt248Type ) { console.warn( 'THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.' ); texture.type = UnsignedInt248Type; glType = utils.convert( texture.type ); } } // state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null ); } else if ( texture.isDataTexture ) { // use manually created mipmaps if available // if there are no manual mipmaps // set 0 level mipmap and then use GL to generate other mipmap levels if ( mipmaps.length > 0 && supportsMips ) { for ( let i = 0, il = mipmaps.length; i < il; i ++ ) { mipmap = mipmaps[ i ]; state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data ); } texture.generateMipmaps = false; textureProperties.__maxMipLevel = mipmaps.length - 1; } else { state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data ); textureProperties.__maxMipLevel = 0; } } else if ( texture.isCompressedTexture ) { for ( let i = 0, il = mipmaps.length; i < il; i ++ ) { mipmap = mipmaps[ i ]; if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) { if ( glFormat !== null ) { state.compressedTexImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data ); } else { console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' ); } } else { state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data ); } } textureProperties.__maxMipLevel = mipmaps.length - 1; } else if ( texture.isDataTexture2DArray ) { state.texImage3D( _gl.TEXTURE_2D_ARRAY, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data ); textureProperties.__maxMipLevel = 0; } else if ( texture.isDataTexture3D ) { state.texImage3D( _gl.TEXTURE_3D, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data ); textureProperties.__maxMipLevel = 0; } else { // regular Texture (image, video, canvas) // use manually created mipmaps if available // if there are no manual mipmaps // set 0 level mipmap and then use GL to generate other mipmap levels if ( mipmaps.length > 0 && supportsMips ) { for ( let i = 0, il = mipmaps.length; i < il; i ++ ) { mipmap = mipmaps[ i ]; state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, glFormat, glType, mipmap ); } texture.generateMipmaps = false; textureProperties.__maxMipLevel = mipmaps.length - 1; } else { state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, glFormat, glType, image ); textureProperties.__maxMipLevel = 0; } } if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) { generateMipmap( textureType, texture, image.width, image.height ); } textureProperties.__version = texture.version; if ( texture.onUpdate ) texture.onUpdate( texture ); } // Render targets // Setup storage for target texture and bind it to correct framebuffer function setupFrameBufferTexture( framebuffer, renderTarget, attachment, textureTarget ) { const glFormat = utils.convert( renderTarget.texture.format ); const glType = utils.convert( renderTarget.texture.type ); const glInternalFormat = getInternalFormat( renderTarget.texture.internalFormat, glFormat, glType ); state.texImage2D( textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null ); _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer ); _gl.framebufferTexture2D( _gl.FRAMEBUFFER, attachment, textureTarget, properties.get( renderTarget.texture ).__webglTexture, 0 ); _gl.bindFramebuffer( _gl.FRAMEBUFFER, null ); } // Setup storage for internal depth/stencil buffers and bind to correct framebuffer function setupRenderBufferStorage( renderbuffer, renderTarget, isMultisample ) { _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer ); if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) { let glInternalFormat = _gl.DEPTH_COMPONENT16; if ( isMultisample ) { const depthTexture = renderTarget.depthTexture; if ( depthTexture && depthTexture.isDepthTexture ) { if ( depthTexture.type === FloatType ) { glInternalFormat = _gl.DEPTH_COMPONENT32F; } else if ( depthTexture.type === UnsignedIntType ) { glInternalFormat = _gl.DEPTH_COMPONENT24; } } const samples = getRenderTargetSamples( renderTarget ); _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height ); } else { _gl.renderbufferStorage( _gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height ); } _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer ); } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) { if ( isMultisample ) { const samples = getRenderTargetSamples( renderTarget ); _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, _gl.DEPTH24_STENCIL8, renderTarget.width, renderTarget.height ); } else { _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height ); } _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer ); } else { const glFormat = utils.convert( renderTarget.texture.format ); const glType = utils.convert( renderTarget.texture.type ); const glInternalFormat = getInternalFormat( renderTarget.texture.internalFormat, glFormat, glType ); if ( isMultisample ) { const samples = getRenderTargetSamples( renderTarget ); _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height ); } else { _gl.renderbufferStorage( _gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height ); } } _gl.bindRenderbuffer( _gl.RENDERBUFFER, null ); } // Setup resources for a Depth Texture for a FBO (needs an extension) function setupDepthTexture( framebuffer, renderTarget ) { const isCube = ( renderTarget && renderTarget.isWebGLCubeRenderTarget ); if ( isCube ) throw new Error( 'Depth Texture with cube render targets is not supported' ); _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer ); if ( ! ( renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture ) ) { throw new Error( 'renderTarget.depthTexture must be an instance of THREE.DepthTexture' ); } // upload an empty depth texture with framebuffer size if ( ! properties.get( renderTarget.depthTexture ).__webglTexture || renderTarget.depthTexture.image.width !== renderTarget.width || renderTarget.depthTexture.image.height !== renderTarget.height ) { renderTarget.depthTexture.image.width = renderTarget.width; renderTarget.depthTexture.image.height = renderTarget.height; renderTarget.depthTexture.needsUpdate = true; } setTexture2D( renderTarget.depthTexture, 0 ); const webglDepthTexture = properties.get( renderTarget.depthTexture ).__webglTexture; if ( renderTarget.depthTexture.format === DepthFormat ) { _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 ); } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) { _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 ); } else { throw new Error( 'Unknown depthTexture format' ); } } // Setup GL resources for a non-texture depth buffer function setupDepthRenderbuffer( renderTarget ) { const renderTargetProperties = properties.get( renderTarget ); const isCube = ( renderTarget.isWebGLCubeRenderTarget === true ); if ( renderTarget.depthTexture ) { if ( isCube ) throw new Error( 'target.depthTexture not supported in Cube render targets' ); setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget ); } else { if ( isCube ) { renderTargetProperties.__webglDepthbuffer = []; for ( let i = 0; i < 6; i ++ ) { _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ i ] ); renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer(); setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget, false ); } } else { _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer ); renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer(); setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget, false ); } } _gl.bindFramebuffer( _gl.FRAMEBUFFER, null ); } // Set up GL resources for the render target function setupRenderTarget( renderTarget ) { const renderTargetProperties = properties.get( renderTarget ); const textureProperties = properties.get( renderTarget.texture ); renderTarget.addEventListener( 'dispose', onRenderTargetDispose ); textureProperties.__webglTexture = _gl.createTexture(); info.memory.textures ++; const isCube = ( renderTarget.isWebGLCubeRenderTarget === true ); const isMultisample = ( renderTarget.isWebGLMultisampleRenderTarget === true ); const supportsMips = isPowerOfTwo( renderTarget ) || isWebGL2; // Handles WebGL2 RGBFormat fallback - #18858 if ( isWebGL2 && renderTarget.texture.format === RGBFormat && ( renderTarget.texture.type === FloatType || renderTarget.texture.type === HalfFloatType ) ) { renderTarget.texture.format = RGBAFormat; console.warn( 'THREE.WebGLRenderer: Rendering to textures with RGB format is not supported. Using RGBA format instead.' ); } // Setup framebuffer if ( isCube ) { renderTargetProperties.__webglFramebuffer = []; for ( let i = 0; i < 6; i ++ ) { renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer(); } } else { renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer(); if ( isMultisample ) { if ( isWebGL2 ) { renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer(); renderTargetProperties.__webglColorRenderbuffer = _gl.createRenderbuffer(); _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer ); const glFormat = utils.convert( renderTarget.texture.format ); const glType = utils.convert( renderTarget.texture.type ); const glInternalFormat = getInternalFormat( renderTarget.texture.internalFormat, glFormat, glType ); const samples = getRenderTargetSamples( renderTarget ); _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height ); _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer ); _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer ); _gl.bindRenderbuffer( _gl.RENDERBUFFER, null ); if ( renderTarget.depthBuffer ) { renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer(); setupRenderBufferStorage( renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true ); } _gl.bindFramebuffer( _gl.FRAMEBUFFER, null ); } else { console.warn( 'THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.' ); } } } // Setup color buffer if ( isCube ) { state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture ); setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget.texture, supportsMips ); for ( let i = 0; i < 6; i ++ ) { setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i ); } if ( textureNeedsGenerateMipmaps( renderTarget.texture, supportsMips ) ) { generateMipmap( _gl.TEXTURE_CUBE_MAP, renderTarget.texture, renderTarget.width, renderTarget.height ); } state.bindTexture( _gl.TEXTURE_CUBE_MAP, null ); } else { state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture ); setTextureParameters( _gl.TEXTURE_2D, renderTarget.texture, supportsMips ); setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D ); if ( textureNeedsGenerateMipmaps( renderTarget.texture, supportsMips ) ) { generateMipmap( _gl.TEXTURE_2D, renderTarget.texture, renderTarget.width, renderTarget.height ); } state.bindTexture( _gl.TEXTURE_2D, null ); } // Setup depth and stencil buffers if ( renderTarget.depthBuffer ) { setupDepthRenderbuffer( renderTarget ); } } function updateRenderTargetMipmap( renderTarget ) { const texture = renderTarget.texture; const supportsMips = isPowerOfTwo( renderTarget ) || isWebGL2; if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) { const target = renderTarget.isWebGLCubeRenderTarget ? _gl.TEXTURE_CUBE_MAP : _gl.TEXTURE_2D; const webglTexture = properties.get( texture ).__webglTexture; state.bindTexture( target, webglTexture ); generateMipmap( target, texture, renderTarget.width, renderTarget.height ); state.bindTexture( target, null ); } } function updateMultisampleRenderTarget( renderTarget ) { if ( renderTarget.isWebGLMultisampleRenderTarget ) { if ( isWebGL2 ) { const renderTargetProperties = properties.get( renderTarget ); _gl.bindFramebuffer( _gl.READ_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer ); _gl.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglFramebuffer ); const width = renderTarget.width; const height = renderTarget.height; let mask = _gl.COLOR_BUFFER_BIT; if ( renderTarget.depthBuffer ) mask |= _gl.DEPTH_BUFFER_BIT; if ( renderTarget.stencilBuffer ) mask |= _gl.STENCIL_BUFFER_BIT; _gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, _gl.NEAREST ); _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer ); // see #18905 } else { console.warn( 'THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.' ); } } } function getRenderTargetSamples( renderTarget ) { return ( isWebGL2 && renderTarget.isWebGLMultisampleRenderTarget ) ? Math.min( maxSamples, renderTarget.samples ) : 0; } function updateVideoTexture( texture ) { const frame = info.render.frame; // Check the last frame we updated the VideoTexture if ( _videoTextures.get( texture ) !== frame ) { _videoTextures.set( texture, frame ); texture.update(); } } // backwards compatibility let warnedTexture2D = false; let warnedTextureCube = false; function safeSetTexture2D( texture, slot ) { if ( texture && texture.isWebGLRenderTarget ) { if ( warnedTexture2D === false ) { console.warn( "THREE.WebGLTextures.safeSetTexture2D: don't use render targets as textures. Use their .texture property instead." ); warnedTexture2D = true; } texture = texture.texture; } setTexture2D( texture, slot ); } function safeSetTextureCube( texture, slot ) { if ( texture && texture.isWebGLCubeRenderTarget ) { if ( warnedTextureCube === false ) { console.warn( "THREE.WebGLTextures.safeSetTextureCube: don't use cube render targets as textures. Use their .texture property instead." ); warnedTextureCube = true; } texture = texture.texture; } // currently relying on the fact that WebGLCubeRenderTarget.texture is a Texture and NOT a CubeTexture // TODO: unify these code paths if ( ( texture && texture.isCubeTexture ) || ( Array.isArray( texture.image ) && texture.image.length === 6 ) ) { // CompressedTexture can have Array in image :/ // this function alone should take care of cube textures setTextureCube( texture, slot ); } else { // assumed: texture property of THREE.WebGLCubeRenderTarget setTextureCubeDynamic( texture, slot ); } } // this.allocateTextureUnit = allocateTextureUnit; this.resetTextureUnits = resetTextureUnits; this.setTexture2D = setTexture2D; this.setTexture2DArray = setTexture2DArray; this.setTexture3D = setTexture3D; this.setTextureCube = setTextureCube; this.setTextureCubeDynamic = setTextureCubeDynamic; this.setupRenderTarget = setupRenderTarget; this.updateRenderTargetMipmap = updateRenderTargetMipmap; this.updateMultisampleRenderTarget = updateMultisampleRenderTarget; this.safeSetTexture2D = safeSetTexture2D; this.safeSetTextureCube = safeSetTextureCube; } export { WebGLTextures };
module.exports = { name: "createInterface", ns: "readline", title: "Create Interface", description: "Creates a readline Interface instance", phrases: { active: "Creating interface" }, ports: { input: { input: { title: "Input Stream", type: "Stream" }, output: { title: "Output Stream", type: "Stream" }, terminal: { title: "Terminal", type: "boolean", "default": null } }, output: { readline: { title: "Readline", type: "Interface" }, line: { title: "Line", type: "any" }, pause: { title: "Pause", type: "any" }, resume: { title: "Resume", type: "any" }, close: { title: "Close", type: "any" }, SIGINT: { title: "SIGINT", type: "any" }, SIGTSTP: { title: "SIGTSTP", type: "any" }, SIGCONT: { title: "SIGCONT", type: "any" } } }, dependencies: { npm: { readline: require('readline') } }, fn: function createInterface(input, $, output, state, done, cb, on, readline) { var r = function() { var iface = readline.createInterface({ input: $.input, output: $.output, terminal: $.terminal || undefined }); iface.on('line', function(line) { output({ line: $.create(line) }); }); iface.on('pause', function() { output({ pause: '' }); }); iface.on('resume', function() { output({ resume: '' }); }); iface.on('close', function() { output({ close: '' }); }); iface.on('SIGINT', function() { output({ SIGINT: '' }); }); iface.on('SIGTSTP', function() { output({ SIGTSTP: '' }); }); iface.on('SIGCONT', function() { output({ SIGCONT: '' }); }); output({ readline: $.create(iface) }); }.call(this); return { output: output, state: state, on: on, return: r }; } }
class httpService { constructor($http, $httpParamSerializerJQLike, stripeConfig) { this.$http = $http; this.stripeConfig = stripeConfig; this.$httpParamSerializerJQLike = $httpParamSerializerJQLike; } doRequest(options, callback) { const configs = this.stripeConfig; if (options.data) options.data.key = configs.key; options.auth = false; options.url = (options.url.indexOf(configs.base_url) === -1) ? `${configs.base_url}${options.url}` : options.url; options.data = this.$httpParamSerializerJQLike(options.data); options.headers = angular.extend({ 'Content-Type': 'application/x-www-form-urlencoded' }, options.headers, { auth: false }); return (typeof callback !== 'function') ? this.$http(options) : this.$http(options) .then(R => callback(R.status, R.data)) .catch(ERR => callback(ERR.status, (ERR.error || ERR.data || ERR))) } } httpService.$inject = ['$http', '$httpParamSerializerJQLike', 'stripeConfig']; export default httpService;
app.factory('notificationService', function () { var notifChangedCB = function (notif) { }; return { setNotifChangedCB: function (cb) { notifChangedCB = cb; }, setNotif: function(notif) { notifChangedCB(notif); } }; });
class Ground { constructor(y){ this.y = y; } show() { rect(0, this.y, width, height - this.y); } }
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } var INITIAL_VALUE = { rows: [], values: {} }; exports.default = function () { var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : INITIAL_VALUE; var action = arguments[1]; switch (action.type) { case 'SET': return _extends({}, state, { rows: action.rows }); case 'ADD': return _extends({}, state, { rows: [].concat(_toConsumableArray(state.rows), [action.row]), values: {} }); case 'UPDATE': return _extends({}, state, { values: _extends({}, state.values, _defineProperty({}, action.key, action.value)) }); case 'REMOVE': return _extends({}, state, { rows: [].concat(_toConsumableArray(state.rows.filter(function (row, index) { return index !== action.index; }))) }); case 'REORDER': return _extends({}, state, { rows: action.from < action.to ? [].concat(_toConsumableArray(state.rows.slice(0, action.from)), _toConsumableArray(state.rows.slice(action.from + 1, action.to + 1)), [state.rows[action.from]], _toConsumableArray(state.rows.slice(action.to + 1))) : [].concat(_toConsumableArray(state.rows.slice(0, action.to)), [state.rows[action.from]], _toConsumableArray(state.rows.slice(action.to, action.from)), _toConsumableArray(state.rows.slice(action.from + 1))) }); default: return state; } };
const electron = require('electron') const ipc = electron.ipcRenderer const $ = require('jquery') const gbfs = require('gbfs-client') const gbfsClient = new gbfs('https://gbfs.citibikenyc.com/gbfs/en/') const $stationsList = $('.station-list') const createStationElement = require('./support/create-station-element') const GOOGLE_API_KEY = process.env.GOOGLE_API_KEY const GEOLOCATION_URI = "https://www.googleapis.com/geolocation/v1/geolocate?key=" + GOOGLE_API_KEY showStationsForCurrentLocation = () => { $.post(GEOLOCATION_URI) .done((data) => { const position = { lat: data.location.lat, lon: data.location.lng } addStationtoList(position) }) } addStationtoList = (position) => { // get gbfs format citibike information gbfsClient.stationInfo() .then(stations => { return getNearestNStations(position, stations, 5) }) .then((nearestStations) => { showNearestNStations(nearestStations) }) } notifyAvailabilty = () => { new Notification('Citibike Status', { body: "Lots of bikes currently available" }) } showNearestNStations = (nearestStations) => { nearestStationsWithAvailability = [] nearestStations.forEach((station) => { gbfsClient.stationStatus(station.station_id) .then((status) => { station.num_bikes_available = status.num_bikes_available station.num_docks_available = status.num_docks_available nearestStationsWithAvailability.push(station) const $station = createStationElement(station.name, status.num_bikes_available, status.num_docks_available, station.distance) $stationsList.append($station) }) }) return nearestStationsWithAvailability } getNearestNStations = (position, stations, n) => { const stationCount = stations.length var closest_loc var closest_dist = 23423432 var stationWithDist = [] stations.forEach((station) => { station_distance = distance(station, position) stationWithDist.push({ name: station.name, distance: station_distance, lat: station.lat, lon: station.lon, station_id: station.station_id }) }) stationCompare = (a, b) => { return a.distance - b.distance } stationsWithDistSort = stationWithDist.sort(stationCompare) const nearestN = stationsWithDistSort.slice(0, n) return nearestN } function distance(position1, position2) { var lat1 = position1.lat; var lat2 = position2.lat; var lon1 = position1.lon; var lon2 = position2.lon; var R = 6371000; // metres var φ1 = toRadians(lat1); var φ2 = toRadians(lat2); var Δφ = toRadians((lat2 - lat1)); var Δλ = toRadians((lon2 - lon1)); var a = Math.sin(Δφ / 2) * Math.sin(Δφ / 2) + Math.cos(φ1) * Math.cos(φ2) * Math.sin(Δλ / 2) * Math.sin(Δλ / 2); var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); var d = R * c; return d; } function toRadians(x) { return x * Math.PI / 180; } showStationsForCurrentLocation()
// Create an instance of Meny var meny = Meny.create({ // The element that will be animated in from off screen menuElement: document.querySelector( '.meny' ), // The contents that gets pushed aside while Meny is active contentsElement: document.querySelector( '.contents' ), // [optional] The alignment of the menu (top/right/bottom/left) position: Meny.getQuery().p || 'left', // [optional] The height of the menu (when using top/bottom position) height: 200, // [optional] The width of the menu (when using left/right position) width: 260, // [optional] Distance from mouse (in pixels) when menu should open threshold: 40, // [optional] Use mouse movement to automatically open/close mouse: true, // [optional] Use touch swipe events to open/close touch: true }); // API Methods: // meny.open(); // meny.close(); // meny.isOpen(); // Events: // meny.addEventListener( 'open', function(){ console.log( 'open' ); } ); // meny.addEventListener( 'close', function(){ console.log( 'close' ); } ); // Embed an iframe if a URL is passed in if( Meny.getQuery().u && Meny.getQuery().u.match( /^http/gi ) ) { var contents = document.querySelector( '.contents' ); contents.style.padding = '0px'; contents.innerHTML = '<div class="cover"></div><iframe src="'+ Meny.getQuery().u +'" style="width: 100%; height: 100%; border: 0; position: absolute;"></iframe>'; }
/** * ============================== * Your Javascript Code Goes Here * ============================== **/
const path = require('path') const should = require('should/as-function') const fixtures = require('../../fixtures') const exiftool = require('../../../src/components/exiftool/parallel') describe('exiftool', function () { this.slow(1000) this.timeout(1000) it('processes all files', (done) => { // generate some photos in a temp folder const image = fixtures.fromDisk('photo.jpg') const structure = {} for (let i = 0; i < 10; ++i) { structure[`IMG_00${i}.jpg`] = image } const tmpdir = fixtures.createTempStructure(structure) // process them in batch const processed = [] const stream = exiftool.parse(tmpdir, Object.keys(structure)) stream.on('data', entry => { // <entry> should be the deserialized JSON output from exiftool processed.push(entry.SourceFile) }).on('end', () => { const expected = Object.keys(structure).sort() should(processed.sort()).eql(expected) done() }) }) it('can process badly encoded fields', (done) => { // here we test with an XMP file because it's easier to see what's wrong // but the problem will more likely be with a badly encoded XMP section inside a JPG file // note: use <vi> to edit <bad-encoding.xmp> if required, to avoid converting it to UTF const testFixtures = path.join(__dirname, '..', '..', '..', 'test-fixtures') const stream = exiftool.parse(testFixtures, ['bad-encoding.xmp']) const processed = [] stream.on('data', entry => { processed.push(entry.SourceFile) }).on('end', () => { should(processed).eql(['bad-encoding.xmp']) done() }) }) })
/* 作者: dailc * 时间: 2017-06-06 * 描述: Dungeon-Game * * 来自: https://leetcode.com/problems/dungeon-game */ (function(exports) { /** * @description * @param {number[][]} dungeon * @return {number} */ LeetCode.calculateMinimumHP = function(dungeon) { var m = dungeon.length, n = dungeon[0].length; var dp = []; for( var i = 0; i < m; i ++ ) { dp[i] = []; } dp[0][0] = { min: dungeon[0][0] < 0 ? dungeon[0][0] : 0, opt: dungeon[0][0] > 0 ? dungeon[0][0] : 0 }; // 初始化第一列 for( var i = 1; i < m; i ++ ) { dp[i][0] = {}; // 判断护罩 var diff = dp[i - 1][0].opt + dungeon[i][0]; if( diff < 0) { // 最小值需要再次变小 dp[i][0].min = dp[i - 1][0].min + diff; // 护罩已经消耗光 dp[i][0].opt = 0; } else { // 最小值不变 dp[i][0].min = dp[i - 1][0].min; // 护罩累积 dp[i][0].opt = dp[i - 1][0].opt + diff; } } // 初始化第一行 for( var j = 1; j < n; j ++ ) { dp[0][j] = {}; // 判断护罩 var diff = dp[0][j-1].opt + dungeon[0][j]; if( diff < 0) { // 最小值需要再次变小 dp[0][j].min = dp[0][j-1].min + diff; // 护罩已经消耗光 dp[0][j].opt = 0; } else { // 最小值不变 dp[0][j].min = dp[0][j-1].min; // 护罩累积 dp[0][j].opt = dp[0][j-1].opt + diff; } } // 初始化i,j for( var i = 1; i < m; i ++ ) { for( var j = 1; j < n; j ++ ) { // 依次判断i和j var leftDiff = dp[i - 1][j].opt + dungeon[i][j]; var upDiff = dp[i][j - 1].opt + dungeon[i][j]; } } console.log(dp); }; LeetCode.calculateMinimumHP2 = function(dungeon) { var m = dungeon.length, n = dungeon[0].length; var dp = []; for( var i = 0; i < m; i ++ ) { dp[i] = []; } // 初始化最后一行和最后一列 dp[m - 1][n - 1] = dungeon[m - 1][n - 1] > 0 ? 0 : - dungeon[m - 1][n - 1]; for( var i = m - 2; i >= 0; i --) { dp[i][n - 1] = dungeon[i][n - 1] >= dp[i + 1][n - 1] ? 0 : (dp[i + 1][n - 1] - dungeon[i][n - 1]); } for( var j = n - 2; j >= 0; j --) { dp[m - 1][j] = dungeon[m - 1][j] >= dp[m - 1][j + 1] ? 0 : (dp[m - 1][j + 1] - dungeon[m - 1][j]); } // 从右下角往左上角遍历 for( var i = m - 2; i >= 0; i -- ) { for( var j = n - 2; j >= 0; j -- ) { var down = dungeon[i][j] >= dp[i + 1][j] ? 0 : dp[i + 1][j] - dungeon[i][j]; var right = dungeon[i][j] >= dp[i][j + 1] ? 0 : dp[i][j + 1] - dungeon[i][j]; dp[i][j] = Math.min(down, right); } } // 要保证勇士活着,至少需要1魔力 return dp[0][0] + 1; }; })(window.LeetCode = window.LeetCode || {});
"use strict"; angular.module('utility').directive('pageFormatCreation', [ function() { return { templateUrl: 'modules/utility/directives/template/default-format.html', restrict: 'E', link: function postLink(scope, element, attrs) { } }; } ]);
(function() { (function (app, $) { var d = 1; function f() { return d; } app.a = 1; app.h = function () { return f() * 2; }; $(function () { console.log(d); }); }(this, jQuery)); (function (elo) { elo.a = 2; elo.b = 2; }(this)); console.log(this); }.call({}));
var debug = require('debug')('hoardr:socketio:session-global'); var util = require('util'); exports = module.exports = function(socket, ipc) { var session = socket.handshake.session; var updateEvent = 'update:' + session.passport.user; function publishUpdate(data) { socket.emit('update', data); } debug('session socket connected with'); debug(util.inspect(session)); ipc.on(updateEvent, publishUpdate); socket.on('message', function(data) { debug('got message via session socket: ' + data); }); socket.on('disconnect', function() { ipc.removeListener(updateEvent, publishUpdate); debug('session socket disconnected'); }); };
/** * jquery.stylized-selector.js * ----------------------------- * @author aganglada * @since 06/01/2014 * @link https://github.com/aganglada/stylized-selector * @version 1.0 * */ (function ($) { $.fn.stylizedSelector = function(options) { // select data-id var selectCount = 0, // keyboard utilities UP = 38, DOWN = 40, SPACE = 32, RETURN = 13, TAB = 9, ESC = 27, DELETE = 8, // to be used on search timer = undefined, defaults = { hiddenClass : 'hidden', wrapperClass : 'select', styledSelectorClass : 'styled-select', optionsClass : 'options', openSelectorClass : 'open', activeOptionClass : 'selected', currentTextClass : 'current', isMultipleClass : 'multiple', arrowIconClass : false, onKeyDownTimeout : 2000, onOpen : function(){}, onChange : function(){} }, settings = $.extend( {}, defaults, options ), /** * saving data on selector. * to be used later :) * @param $selector */ updateDataSelector = function($selector) { $selector.data({ 'isMultiple': $selector.attr('multiple') !== undefined, 'styledSelect': $selector.next('div.' + settings.styledSelectorClass), 'optionList': $selector.children(), 'optionSelected': $selector.children().filter(':selected') }); }, /** * general method to get a data(index). * @param $selector * @param index * @returns {*} */ dataSelector = function($selector, index) { return $selector.data(index); }, /** * initializing selector, * building structure to wrap it. * @param $selector */ buildSelector = function($selector) { var isMultipleClass = dataSelector($selector, 'isMultiple') ? ' ' + settings.isMultipleClass : ''; $selector .addClass(settings.hiddenClass) .wrap('<div data-id="' + selectCount + '" class="' + settings.wrapperClass + isMultipleClass + '"></div>'); // if is not a multiple select if (!dataSelector($selector, 'isMultiple')) { $selector.after('<div class="' + settings.styledSelectorClass + '">' + '<span class="' + settings.currentTextClass + '"></span>' + '</div>'); setSelectedOption($selector); if (settings.arrowIconClass !== false) { var $styledSelect = $selector.next('div.' + settings.styledSelectorClass); $styledSelect.append('<i class="' + settings.arrowIconClass + '"></i>'); } } // TODO feature: multiple select support }, /** * set initial value. * @param $selector */ setSelectedOption = function($selector) { updateDataSelector($selector); var $selectedOption = dataSelector($selector, 'optionSelected'), $styledSelect = dataSelector($selector, 'styledSelect'), $currentOption = $styledSelect.children(); $currentOption.html($selectedOption.text()); }, /** * building options in selector list. * @param $selector */ updateSelect = function($selector) { updateDataSelector($selector); var $selectedOption = dataSelector($selector, 'optionSelected'), $styledSelect = dataSelector($selector, 'styledSelect'); var $list = $('<ul />', { 'class': settings.optionsClass }).insertAfter($styledSelect ? $styledSelect : $selector); for (var i = 0; i < dataSelector($selector, 'optionList').length; i++) { $('<li />', { text : $selector.children('option').eq(i).text(), rel : $selector.children('option').eq(i).val(), 'class' : $selectedOption[0] && $selectedOption[0].index == i ? settings.activeOptionClass : '' }).appendTo($list); } }, /** * onClick selector. * @param event */ toggleOpen = function(event) { event.stopPropagation(); var $styledSelect = $(event.target).closest('.' + settings.styledSelectorClass), $selectorWrapper = $styledSelect.parent(), selectorIsOpen = $styledSelect.is('.' + settings.openSelectorClass); closeAll(); if (!selectorIsOpen) { $styledSelect.toggleClass(settings.openSelectorClass).next('ul.' + settings.optionsClass).toggle(); $('select', $selectorWrapper).trigger('onOpen'); } }, /** * triggered on toggleOpen method. */ closeAll = function() { var $styledSelectors = $('.' + settings.styledSelectorClass), $selectorWrapper = $styledSelectors.parent(); $styledSelectors.removeClass(settings.openSelectorClass); $('ul', $selectorWrapper).hide(); }, /** * on optionList click. * @param event */ selectListItem = function(event) { selectItem(event, $(event.target).closest('li')); }, /** * * @param event * @param $_optionClicked */ selectItem = function(event, $_optionClicked) { event.stopPropagation(); var $selectorWrapper = $_optionClicked.closest('.' + settings.wrapperClass), $currentOption = $selectorWrapper.find('.' + settings.currentTextClass), $list = $selectorWrapper.find('ul'), $selector = $selectorWrapper.find('select'); $currentOption.text($_optionClicked.text()); $list.children('li').removeClass(settings.activeOptionClass); $_optionClicked.addClass(settings.activeOptionClass); $selector.val($_optionClicked.attr('rel')); if (event.type == 'click') { $selectorWrapper.find('.' + settings.styledSelectorClass).removeClass(settings.openSelectorClass); $list.hide(); $selector.trigger('onChange', [{ 'selectedValue': $_optionClicked.attr('rel') }]); } }, /** * this is what's happen always when a selector is clicked (open). * @param event */ onDefaultOpen = function(event) { var target = event.target, $selectorWrapper = $(target).parent(), $list = $selectorWrapper.find('ul'), $selectedOption = $list.children('li').filter('.' + settings.activeOptionClass); reloadSelectedPosition($list, $selectedOption); settings.onOpen.call(this); }, onDefaultFocus = function() { console.log($(this)); }, /** * on open we go to the centered position of the selected value. * @param $list * @param $current */ reloadSelectedPosition = function($list, $current) { $list.scrollTop($list.scrollTop() + $current.position().top - $list.height()/2 + $current.height()/2); }, /** * onKeyPress (if select is open) * @param event */ selectKeyPress = function(event) { var $currentOpenSelector = $('.' + settings.styledSelectorClass + '.' + settings.openSelectorClass), $currentWrapperSelector = $currentOpenSelector.parent(), $selector = $('select', $currentWrapperSelector), $list = $('ul', $currentWrapperSelector), $current = $('li.' + settings.activeOptionClass, $list), $currentPrev = $current.prev(), $currentNext = $current.next(), matchString = '', count = $selector.data('count') || 0; // keyboard conditions var currentKeyCode = event.keyCode, keyboard = event.keyCode >= 48 && event.keyCode <= 90, numeric = event.keyCode >= 96 && event.keyCode <= 105; if ($currentOpenSelector.length > 0) { event.preventDefault(); } matchString = $selector.data('matchString') !== undefined ? $selector.data('matchString') : ''; if ( currentKeyCode == RETURN || currentKeyCode == TAB || currentKeyCode == ESC ) { $current.trigger('click'); return; } else if (currentKeyCode == UP && $currentPrev.length && $currentPrev.is('li')) { selectItem(event, $currentPrev); reloadSelectedPosition($list, $current); } else if (currentKeyCode == DOWN && $currentNext.length && $currentNext.is('li')) { selectItem(event, $currentNext); reloadSelectedPosition($list, $current); } else if (currentKeyCode == SPACE) { $currentOpenSelector.trigger('click'); } else if (currentKeyCode == DELETE) { matchString = matchString.slice(0, -1); $selector.data( 'matchString', matchString ); } else if (keyboard || numeric) { currentKeyCode = numeric ? currentKeyCode -48 : currentKeyCode; var string = String.fromCharCode(currentKeyCode).toLowerCase(); // #1 if (string != matchString) { matchString = matchString + String.fromCharCode(currentKeyCode).toLowerCase(); $selector.data('count', 0); } else { matchString = string; $selector.data('count', count+1); } $selector.data( 'matchString', matchString ); checkForMatch(event, $currentOpenSelector); } timer = $selector.data('timer'); if (timer !== undefined) { clearTimeout(timer); } timer = setTimeout( callClearTimeout, settings.onKeyDownTimeout ); $selector.data('timer', timer); }, /** * 3 sec. to clear out the search data. */ callClearTimeout = function() { var $currentOpenSelector = $('.' + settings.styledSelectorClass + '.' + settings.openSelectorClass), $selector = $('select', $currentOpenSelector.parent()); clearKeyStrokes($selector); }, /** * looking for a match in the options, * if the select is open. * @param event * @param $currentOpenSelector */ checkForMatch = function(event, $currentOpenSelector) { var $openSelectorWrapper = $currentOpenSelector.parent(), $selector = $('select', $openSelectorWrapper), $list = $('ul', $openSelectorWrapper), matchString = $('select', $openSelectorWrapper).data('matchString'), matchesElements = [], $selectedOption = undefined, count = $selector.data('count'); $('li', $list).each(function(key, element) { var text = $(element).text().toLowerCase().trim(); if (text.indexOf(matchString) == 0) { $selectedOption = $(this); matchesElements.push($selectedOption); } }); if (count >= matchesElements.length) { $selector.data('count', 0); count = 0; } $selectedOption = matchesElements[count]; if ($selectedOption !== undefined) { selectItem(event, $selectedOption); reloadSelectedPosition($list, $selectedOption); } }, /** * reset search * @param $selector */ clearKeyStrokes = function($selector) { $selector.removeData(); timer = undefined; }; /** * jQuery plugin Loop * * Add a handler to manage the original select * */ this.each(function() { var $selector = $(this); updateDataSelector($selector); buildSelector($selector); updateSelect($selector); selectCount++; }); var $_document = $(document); $_document.on('click', '.' + settings.styledSelectorClass, toggleOpen); $_document.on('click', closeAll); $_document.on('click', '.' + settings.optionsClass, selectListItem); $_document.on('keydown', selectKeyPress); $_document.on('onOpen', 'select', onDefaultOpen); $_document.on('onChange', 'select', function(event, data) { settings.onChange.call(this, data.selectedValue); }); $_document.on('focus', 'select', onDefaultFocus); return this; }; }( jQuery ));
import React, { Component } from "react"; import { PropTypes } from "prop-types"; import SpeechRecognition from "react-speech-recognition"; const propTypes = { transcript: PropTypes.string, resetTranscript: PropTypes.func, browserSupportsSpeechRecognition: PropTypes.bool }; const options = { autoStart: false }; class VoiceRecognition extends Component { state = { listening: false }; render() { const { transcript, resetTranscript, browserSupportsSpeechRecognition, startListening, stopListening, setVoice } = this.props; if (!browserSupportsSpeechRecognition) { return <div />; } return ( <div className="isoVoiceSearch"> {!this.state.listening ? <div className="isoVoiceSearchStart"> <button onClick={() => { startListening(); this.setState({ listening: true }); }} /> <span>Start Speaking</span> </div> : <div className="isoVoiceSearchRunning"> <button onClick={() => { setVoice(transcript); resetTranscript(); stopListening(); this.setState({ listening: false }); }} /> {/* <span>Search</span> */} <span> {transcript} </span> </div>} </div> ); } } VoiceRecognition.propTypes = propTypes; export default SpeechRecognition(options)(VoiceRecognition);
var api = require("../../gettyimages-api"); var nock = require("nock"); module.exports = function () { this.Given(/^a video id$/, function (callback) { this.ids = ["valid_id"]; callback(); }); this.Given(/^caption field is specified$/, function (callback) { if (!this.fields) { this.fields = []; } this.fields.push("caption"); callback(); }); this.Given(/^a non\-existent video id$/, function (callback) { this.ids = ["invalid_id"]; callback(); }); this.Given(/^a list of video ids$/, function (callback) { this.ids = ["1", "2", "3", "4"]; callback(); }); this.When(/^the video metadata request is executed$/, function (callback) { var context = this; nock("https://api.gettyimages.com") .post("/oauth2/token", "client_id=apikey&client_secret=apisecret&grant_type=client_credentials") .reply(200, { access_token: "client_credentials_access_token", token_type: "Bearer", expires_in: "1800" }) .post("/oauth2/token", "client_id=apikey&client_secret=apisecret&grant_type=password&username=username&password=password") .reply(200, { access_token: "resource_owner_access_token", token_type: "Bearer", expires_in: "1800", refresh_token: "refreshtoken" }) .get(getPath(context)) .query(getQuery(context)) .reply(getReplyCode(context), {}); var client = new api({ apiKey: this.apikey, apiSecret: this.apisecret, username: this.username, password: this.password }).videos(); if (this.ids && this.ids.length == 1) { client.withId(this.ids[0]); } if (this.ids && this.ids.length > 1) { client.withIds(this.ids); } if (this.fields && this.fields.length > 0) { this.fields.forEach(function (element) { client.withResponseField(element); }, this); } client.execute(function (err, response) { if (err) { context.error = err; callback(); } else { context.response = response; callback(); } }); }); this.Then(/^a list of video metadata is returned$/, function (callback) { // noop callback(); }); this.Then(/^an error is returned$/, function (callback) { if (this.error) { callback(); } callback("Expected an error"); }); this.Then(/^the error explains that the video was not found$/, function (callback) { if (this.error.statusCode === 404) { callback(); } callback("Expected error to be 404"); }); this.Then(/^the status is success$/, function (callback) { // noop callback(); }); this.Then(/^the video metadata is returned$/, function (callback) { // noop callback(); }); this.Then(/^the caption field is returned$/, function (callback) { // noop callback(); }); function getPath(context) { var path = "/v3/videos"; if (context.ids.length === 1) { path += "/" + context.ids[0]; } return path; } function getQuery(context) { var params = {}; if (context.ids && context.ids.length > 1) { params.ids = encodeURI(context.ids.join(",")); } if (context.fields && context.fields.length > 0) { params.fields = encodeURI(context.fields.join(",")); } return params; } function getReplyCode(context) { if (context.ids && context.ids[0] == "invalid_id") { return 404; } else { return 200; } } };
import fs from "fs"; import path from "path"; import yaml from "js-yaml"; import { generator } from "../src/index"; jest.mock("commander", () => ({ checkRequired: true, arguments: jest.fn().mockReturnThis(), option: jest.fn().mockReturnThis(), action: jest.fn().mockReturnThis(), parse: jest.fn().mockReturnThis() })); describe("generate flow types", () => { describe("parse objct in array", () => { it("should generate expected flow types", () => { const file = path.join(__dirname, "__mocks__/nestedObject.swagger.yaml"); const content = yaml.safeLoad(fs.readFileSync(file, "utf8")); const expected = path.join(__dirname, "__mocks__/nestedObject.flow.js"); const expectedString = fs.readFileSync(expected, "utf8"); expect(generator(content)).toEqual(expectedString); }); }); });
function fundCtrl($scope, $http, $firebaseObject, $firebaseArray, $firebase, $state, $ionicModal, $ionicSlideBoxDelegate, $ionicScrollDelegate){ $scope.currentPage1 = 0; $scope.itemPerPage = 5; //Firebase method var rootRef = firebase.database().ref(); var arrRef = rootRef.child('agencies'); $scope.agencies = $firebaseArray(arrRef); var caseRef = rootRef.child('case_manager'); $scope.casemanagers = $firebaseArray(caseRef); var clntRef= rootRef.child('St_Patrick'); $scope.clients = $firebaseArray(clntRef); $scope.agencies.$loaded().then(function(pages) { for(i=0; i<$scope.agencies.length; i++) { if($scope.agencies.$getRecord(i).Agency == "St. Patrick"){ $scope.agency = $scope.agencies.$getRecord(i); } } }); $scope.casemanagers.$loaded().then(function(pages) { $scope.pages = toPages($scope.casemanagers, $scope.itemPerPage); }); $scope.clients.$loaded().then(function(pages) { $scope.clients = getAge($scope.clients); $scope.children = 0; $scope.male = 0; $scope.female = 0; $scope.Asian = 0; $scope.Black = 0; $scope.NativeHIOtherPacific = 0; $scope.White = 0; $scope.Veteran = 0; for(i=0; i<$scope.clients.length; i++){ if($scope.clients.$getRecord(i).age < 18){ $scope.children++ } if($scope.clients.$getRecord(i).gender == 1){ $scope.male++ } if($scope.clients.$getRecord(i).gender == 0){ $scope.female++ } if($scope.clients.$getRecord(i).Asian == 1){ $scope.Asian++ } if($scope.clients.$getRecord(i).Black == 1){ $scope.Black++ } if($scope.clients.$getRecord(i).NativeHIOtherPacific == 1){ $scope.NativeHIOtherPacific++ } if($scope.clients.$getRecord(i).White == 1){ $scope.White++ } if($scope.clients.$getRecord(i).VeteranStatus == 1){ $scope.Veteran++ } } }); $scope.decreasePage = function(page) { return decrease(page); } $scope.increasePage = function(page, max) { return increase(page, max-1); } } angular.module("SHARKZ").controller("fundCtrl", ["$scope", "$http", "$firebaseObject", "$firebaseArray", "firebase", "$state", "$ionicModal", "$ionicSlideBoxDelegate", "$ionicScrollDelegate", fundCtrl]);
'use strict'; const {onEndModify} = require('./../../common/flux/reducers'); const createUIStateStore = require('./../../common/flux/ui-state-store'); const signupStore = { initialState: { email: '', password: '' } }; module.exports = createUIStateStore( 'SignupUIStateStore', ['signup'], signupStore ).updateStoreOn({ 'signup.end': [onEndModify] });
var util = require ("util"); var net = require ("net"); var tls = require ("tls"); var User = require ("./User.js"); /* * A special connection for handling the IRC protocol. * It is responsible for: * -- Identifying with the server * -- Handling pings * -- Message throttling * * For information about the `profile` object, * consult the README. */ var Connection = function (profile) { this.profile = profile; /* profile.host: The hostname of the IRC server to connect to */ this.host = profile.host || "localhost"; /* profile.port: The port in which the server is listening to */ this.port = profile.port || 6667; /* profile.name: The special name used to identify the connection */ this.name = profile.name || this.host; /* profile.nick: The IRC nickname */ if (typeof profile.nick === "string") { this.nickname = profile.nick; this.nickname_alts = [profile.nick]; } else { this.nickname = profile.nick[0]; this.nickname_alts = profile.nick; } /* profile.user: The IRC username */ this.username = profile.username || "guest"; /* profile.realname: The real name used to identify the user */ this.realname = profile.realname || "Guest"; /* profile.password: The IRC password, if any */ this.password = profile.password || null; /* profile.encoding: The encoding of the stream */ this.encoding = profile.encoding || "utf8"; this.welcomed = false; this.connected = false; this.connection = null; this.timeout = 0; /* Flood protection */ this.message_queue = []; this.message_speed = profile.message_speed || 2200; // Time between messages in milliseconds this.message_time = 0; // Time the last message was sent this.on ("connect", function () { this.identify (); }); this.on ("secureConnect", function () { if (this.connection.authorized) { this.emit ("connect"); } else { console.log ("%s: Peer certificate was not signed by specified CA: %s", this.name, this.connection.authorizationError); this.connection.end (); } }); var buffer = ""; this.on ("data", function (chunk) { var offset, message; buffer += chunk; while (buffer) { offset = buffer.indexOf ("\r\n"); if (offset < 0) { return; } message = buffer.substr (0, offset); buffer = buffer.substr (offset + 2); this.emit ("raw", message); } }); this.on ("raw", function (message) { var data; data = this.parse_message (message); if (data) { this.emit ("message", data); this.emit (data.command, data); } }); this.on ("PING", function (data) { this.raw ("PONG :" + data.params[0]); }); this.on ("001", function () { this.welcomed = true; }); // Welcome this.on ("NICK", function (data) { var parse; parse = User.parse (data.prefix); if (parse.nick === this.nickname) { this.nickname = data.params[0]; } }); }; util.inherits (Connection, process.EventEmitter); Connection.prototype.get_item_name = function(data) { // TODO: Make this specific to the items representing the channels. // For now, we will just return irc/<name> var item = ["irc", this.name]; if (data.params[0] && data.params[0] !== "*") { item.push (data.params[0]); } return item; }; Connection.prototype.connect = function() { var connection, self = this; function setup (connection) { connection.setEncoding (this.encoding); connection.setTimeout (this.timeout); // Node.js version 0.6.12 doesn't have the setKeepAlive function inherited for TLS connections. if (connection.setKeepAlive) { connection.setKeepAlive (true); } /* We need to tunnel the events to this Connection object */ connection.on ("secureConnect", function() { self.emit ("secureConnect"); }); connection.on ("connect", function() { self.emit ("connect"); }); connection.on ("data", function(data) { self.emit ("data", data); }); connection.on ("close", function(err) { self.emit ("close", err); }); connection.on ("error", function() { self.emit ("error"); }); connection.on ("timeout", function() { self.emit ("timeout"); }); self.connection = connection; } if (this.profile.ssl) { this.ssl_load (function (options) { connection = tls.connect (this.port, this.host, options); setup (connection); }); } else { connection = net.createConnection (this.port, this.host); setup (connection); } }; Connection.prototype.ssl_load = function (callback) { var options = {}; /* TODO: Use asyncronous calls, allow keys/certs if (this.profile.ssl_key) { options.key = fs.readFileSync (this.profile.ssl_key); } if (this.profile.ssl_cert) { options.cert = fs.readFileSync (this.profile.ssl_cert); } */ callback.call (this, options); }; /* Connection#quit(message): * * Ends the connection to the server after sending the quit command, * with the specified quit message from the config. * * We need to wait for the server to close the connection instead * of closing it manually or the quit message will not be displayed. * We will send the quit message and then set a timeout to end the * connection manually. */ Connection.prototype.quit = function (quit_message, callback) { var self = this; if (!quit_message) { quit_message = this.profile.quit_message; } if (!this.connection || this.connection.readyState !== "open") { if (callback) { callback.call (this); } return; } // If we didn't receive a 001 command, // then we should just end the connection if (!this.welcomed) { this.connection.end (); if (callback) { callback.call (this); } return; } this.send ("QUIT" + (quit_message ? " :" + quit_message : " :Client Quit")); this.connection.once ("end", function () { if (callback) { callback.call (self); } }); setTimeout (function () { self.connection.end (); if (callback) { callback.call (self); } }, 10000); }; Connection.prototype.parse_message = function(incoming) { var parse, match; parse = {}; match = incoming.match(/^(?::(\S+)\s+)?(\S+)((?:\s+[^:]\S*)*)(?:\s+:(.*))?$/); if (match) { parse.command = match[2]; parse.params = match[3].match(/\S+/g) || []; if (match[1] != null) { parse.prefix = match[1]; } if (match[4] != null) { parse.params.push(match[4]); } } return parse; }; /* Connection#send: Sends a message with flood control */ Connection.prototype.send = function(message) { var queue, now; now = Date.now (); queue = this.message_queue; /* If the last message was sent early enough... */ if (this.message_time < (now - this.message_speed)) { /* Send it through without queueing it. */ this.raw (message); return; } this.message_queue.push (message); if (this.message_queue.length === 1) { this.run_queue (); } }; Connection.prototype.run_queue = function () { var now, last, delay, self = this; if (!this.message_queue.length) { return; } now = Date.now (); last = this.message_time; delay = this.message_speed; setTimeout (function () { var queue; queue = self.message_queue; self.raw (queue.shift ()); self.run_queue (); }, delay - now + last); }; /* Connection#raw: Sends a message directly to the server */ Connection.prototype.raw = function (message) { if (this.connection.readyState !== "open") { return false; } this.connection.write (message + "\r\n", this.encoding); console.log("\x1b[32m" + message + "\x1b[m"); this.message_time = Date.now (); return true; }; Connection.prototype.identify = function () { /** * Picks another nickname from the list of alternates * or generates a guest nick **/ var alts = this.nickname_alts, nickindex = 0; function nick_alt (data) { var nick; if (this.welcomed) { return; } // We have specified alternate nicknames nickindex++; if (alts[nickindex]) { nick = alts[nickindex]; } else { // Generate guest nick randomly nick = "Guest" + Math.floor(Math.random() * 9999); } this.nick (nick); this.nickname = nick; } if (this.password) { this.pass (this.password); } this.nick (this.nickname); this.user (this.username, this.realname); this.on ("432", nick_alt); // Erroneous nickname this.on ("433", nick_alt); // Nickname in use this.on ("436", nick_alt); // Nickname collision }; Connection.prototype.nick = function (nick) { this.send ("NICK " + nick); }; Connection.prototype.pass = function (pass) { this.send ("PASS " + pass); }; Connection.prototype.user = function (username, realname) { this.send ("USER " + username + " 0 * :" + realname); }; module.exports = Connection; /*var c = new Connection ({host: "irc.freenode.net", nick: "oftn-bot2"}); c.on ("raw", function (m) { console.log (m); }); require ('repl').start ().context.c = c;*/
var events = require("events"), _ = require("underscore"), logger = require("./logging").getLogger(); function VideoSync() { this.playing = false; }; _.extend(VideoSync.prototype, events.EventEmitter.prototype, { start: function(seekSeconds) { seekSeconds = seekSeconds || 0; this.startTime = new Date().getTime(); this.offset = this.startTime - (seekSeconds * 1000); this.playing = true; this.emit("control-video", this.getState()); logger.debug("Starting Video"); }, pause: function(options) { this.playing = false; clearInterval(this.interval); if (!options || !options.silent) { this.emit("control-video", this.getState()); } logger.debug("Pausing video"); }, control: function(args) { switch (args.action) { case "play": this.start(args.time); break; case "pause": this.pause(); break; } }, getState: function() { var now = Date.now(); return { state: this.playing ? "playing" : "paused", time: (now - this.offset) / 1000 }; }, }); module.exports = VideoSync;
/** * Maps the spreadsheet cells into a dataframe, consisting of an array of rows (i.e. a 2d array) * In many cases we have empty rows or incomplete rows, so you can skip those by including * the realrowlength parameter - it will skip any rows that don't have this length. * Alternatively, you can just choose to skip the first 'n' rows by setting the skip parameter. */ function mapEntries(json, realrowlength, skip){ if (!skip) skip = 0; var dataframe = new Array(); var row = new Array(); for (var i=0; i < json.feed.entry.length; i++) { var entry = json.feed.entry[i]; if (entry.gs$cell.col == '1') { if (row != null) { if ((!realrowlength || row.length === realrowlength) && (skip === 0)){ dataframe.push(row); } else { if (skip > 0) skip--; } } var row = new Array(); } row.push(entry.content.$t); } dataframe.push(row); return dataframe; }
// TEST 1 @Component({ selector: 'standard-module-id', moduleId: module.id, templateUrl: 'app.html' }) export class StandardModuleId {} // TEST 2 @Component({ selector: 'multiline-module-id', moduleId: module.id , templateUrl: 'app.html' }) export class MultilineModuleId {} // TEST 3 @Component({ selector: 'module-id-no-trailing-comma', moduleId: module.id }) export class LastPropertyModuleId {} // TEST 4 @Component({ selector: 'string module id', moduleId: 'path/to/module.ts' }) export class StringModuleId {}
// path-utils.js - version 0.1 // Copyright (c) 2011, Kin Blas // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of the <organization> nor the // names of its contributors may be used to endorse or promote products // derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY // DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. (function(l){function m(a){return function(e){return b.parseUrl(e)[a]}}var b={urlParseRE:/^(((([^:\/#\?]+:)?(?:(\/\/)((?:(([^:@\/#\?]+)(?:\:([^:@\/#\?]+))?)@)?(([^:\/#\?\]\[]+|\[[^\/\]@#?]+\])(?:\:([0-9]+))?))?)?)?((\/?(?:[^\/\?#]+\/+)*)([^\?#\.]*(?:\.[^\?#\.]+)*(\.[^\?#\.]+)|[^\?#]*)))?(\?[^#]+)?)(#.*)?/,parsedUrlPropNames:"href,hrefNoHash,hrefNoSearch,domain,protocol,doubleSlash,authority,userinfo,username,password,host,hostname,port,pathname,directory,filename,filenameExtension,search,hash".split(","), defaultPorts:{http:"80",https:"443",ftp:"20",ftps:"990"},parseUrl:function(a){if(a&&typeof a==="object")return a;var a=b.urlParseRE.exec(a||"")||[],e=b.parsedUrlPropNames,c=e.length,f={},d;for(d=0;d<c;d++)f[e[d]]=a[d]||"";return f},port:function(a){a=b.parseUrl(a);return a.port||b.defaultPorts[a.protocol]},isSameDomain:function(a,e){return b.parseUrl(a).domain===b.parseUrl(e).domain},isRelativeUrl:function(a){return b.parseUrl(a).protocol===""},isAbsoluteUrl:function(a){return b.parseUrl(a).protocol!== ""},makePathAbsolute:function(a,e){if(a&&a.charAt(0)==="/")return a;for(var a=a||"",c=(e=e?e.replace(/^\/|(\/[^\/]*|[^\/]+)$/g,""):"")?e.split("/"):[],b=a.split("/"),d=0;d<b.length;d++){var j=b[d];switch(j){case ".":break;case "..":c.length&&c.pop();break;default:c.push(j)}}return"/"+c.join("/")},makePathRelative:function(a,b){for(var b=b?b.replace(/^\/|\/?[^\/]*$/g,""):"",a=a?a.replace(/^\//,""):"",c=b?b.split("/"):[],f=a.split("/"),d=[],j=c.length,g=false,i=0;i<j;i++)(g=g||f[0]!==c[i])?d.push(".."): f.shift();return d.concat(f).join("/")},makeUrlAbsolute:function(a,e){if(!b.isRelativeUrl(a))return a;var c=b.parseUrl(a),f=b.parseUrl(e),d=c.protocol||f.protocol,g=c.protocol?c.doubleSlash:c.doubleSlash||f.doubleSlash,h=c.authority||f.authority,i=c.pathname!=="",k=b.makePathAbsolute(c.pathname||f.filename,f.pathname);return d+g+h+k+(c.search||!i&&f.search||"")+c.hash}},g,h,k=b.parsedUrlPropNames,n=k.length;for(g=0;g<n;g++)h=k[g],b[h]||(b[h]=m(h));l.PathUtils=b})(window);
import { combineReducers } from 'redux' import { reducer as responsive } from 'redux-mediaquery' import { reducer as form } from 'redux-form' import sidenav from 'reducers/sidenav.reducer' import auth from 'reducers/auth.reducer' import users from 'reducers/users.reducer' import profile from 'reducers/profile.reducer' import clients from 'reducers/clients.reducer' import projects from 'reducers/projects.reducer' import tasks from 'reducers/tasks.reducer' import times from 'reducers/time.reducer' export default combineReducers({ responsive, sidenav, auth, profile, projects, clients, users, form, tasks, times })
// Global rotation variables. var ROTATION_OBJ = ""; var ROTATION_CURRENT = -1; var ROTATION_TOTAL = 0; var ROTATION_PAUSED = false; $(document).ready(function() { var opt; chrome.storage.sync.get('chromeboardPrefs', function (obj) { ROTATION_OBJ = obj.chromeboardPrefs; ROTATION_TOTAL = obj.chromeboardPrefs.urlCol.length; if (ROTATION_OBJ.password === false) { document.getElementById("pswdUnlock").remove(); } if (ROTATION_OBJ.urlCol.length > 0 && ROTATION_OBJ.urlCol != "") { for (var i = 0; i < ROTATION_OBJ.urlCol.length; i++) { if(typeof ROTATION_OBJ.urlCol === 'object') { // New format save. createFrame((i + 1), ROTATION_OBJ.urlCol[i].url); } else { // Old format save. createFrame((i + 1), ROTATION_OBJ.urlCol[i]); } } } else { createFrame(); } dockPosition(obj.chromeboardPrefs.dockPlacement); slide(10, obj.chromeboardPrefs.transitionTime); }); }); // -- Settings button and background handlers -- $("#settclick").click(function(event) { toggleSettingsFrame(event); }); $(".settings-modal-close-shadow").click(function(event) { toggleSettingsFrame(event); }); // -- End of settings button and background handlers -- // -- Lockstate handlers -- $("#setlockstate").click(function(event) { toggleLockstate(event); }); $("#setunlockstate").click(function(event) { toggleLockstate(event); }); $(document).on({ "contextmenu": function(e) { if($('#sb-unlocked').hasClass('hidden')) { e.preventDefault(); } } }); // -- End of lockstate handlers -- // -- Other buttons -- $("#pauserotation").click(function(event) { pause(); }); $("#resumerotation").click(function(event) { pause(); }); $("#nextrotation").click(function(event) { rotation(); }); // -- End of Other buttons -- /** * Opens and closes the modal settings IFrame. * @param {event} event */ function toggleSettingsFrame(event) { event.preventDefault(); if( $('.settings-modal').hasClass('active') ) { $('.settings-modal-close-shadow').removeClass('active'); $('.settings-modal').removeClass('active'); window.location.reload(); } else { $('.settings-modal-close-shadow').addClass('active'); $('.settings-modal').addClass('active'); } } /** * Enables and disables the locked rotation state. * @param {event} event */ function toggleLockstate(event) { event.preventDefault(); if( $('#sb-unlocked').hasClass('hidden') ) { if (ROTATION_OBJ.password !== false) { if (ROTATION_OBJ.password === document.getElementById("pswdUnlock").value) { $('#sb-unlocked').removeClass('hidden'); $('#sb-locked').addClass('hidden'); $('.noclick-zone').remove(); document.getElementById("pswdUnlock").value = ""; } } else { $('#sb-unlocked').removeClass('hidden'); $('#sb-locked').addClass('hidden'); $('.noclick-zone').remove(); } } else { $('#sb-unlocked').addClass('hidden'); $('#sb-locked').removeClass('hidden'); $('body').append( $('<div/>').addClass("noclick-zone") ); } } /** * Infinite loop handling the tab switching process. * @param {integer} repeats Defunct, amount of times to repeat. Input less than 0 to stop entirely. * @param {integer} duration Length of time on the tab. */ function slide(repeats, duration) { if (duration < 1) { duration = 1; } if (!ROTATION_PAUSED) { rotation(); } window.setTimeout( function(){ slide(repeats, duration) }, (duration * 1000) ); } /** * Switches the current tab. Allows specifying of the desired page number (listing order). * * @param {integer} newtab If unchanged, goes to next in line. */ function rotation(newtab = false) { originalTab = ROTATION_CURRENT; // Current identifier, for refreshing later. nextActive = ROTATION_CURRENT + 1; // The new tab that's being shown. if (nextActive > (ROTATION_TOTAL - 1)) { nextActive = 0; } // New tab wasn't specified. if (newtab === false) { for (var i = 0; i < ROTATION_TOTAL; i++) { // Each site to the count of the rotation, remove (if any) the 'active' class, // and add it to the selected one. $('#site-'+(i + 1)).removeClass('active'); if (nextActive == i) { $('#site-'+(i + 1)).addClass('active'); ROTATION_CURRENT = nextActive; } } } else { for (var i = 0; i < ROTATION_TOTAL; i++) { // TODO - Remove code duplication. $('#site-'+(i + 1)).removeClass('active'); if (i == newtab) { $('#site-'+(i + 1)).addClass('active'); ROTATION_CURRENT = newtab; } } } if (ROTATION_OBJ.urlCol[originalTab] != null && ROTATION_OBJ.urlCol[originalTab].bgRef) { refresh((originalTab + 1)); } } /** * Pauses the rotation. */ function pause() { ROTATION_PAUSED = (ROTATION_PAUSED) ? false : true; if (ROTATION_PAUSED) { $('#floater').removeClass('hidden'); $('#pauserotation').addClass('hidden'); $('#resumerotation').removeClass('hidden'); } else { $('#floater').addClass('hidden'); $('#pauserotation').removeClass('hidden'); $('#resumerotation').addClass('hidden'); } } /** * Change the dock position. * @param {integer} posId Numeric corners, clockwise around screen. */ function dockPosition(posId = 2) { $('#settings-tray').removeClass('topright topleft bottomleft bottomright'); switch (parseInt(posId)) { case 1: $('#settings-tray').addClass('topleft'); return true; case 2: $('#settings-tray').addClass('topright'); return true; case 3: $('#settings-tray').addClass('bottomleft'); return true; case 4: $('#settings-tray').addClass('bottomright'); return true; default: console.log('Invalid position ID of ' + posId + ' supplied. Default position used.'); $('#settings-tray').addClass('topright'); return true; } } /** * Creates an IFrame in the site-collection ID. No arguments creates an example tab. * @param {integer} $id * @param {string} $url */ function createFrame(id = -1, url = null) { var newFrame = document.createElement('iframe'); newFrame.id = "site-" + id; newFrame.setAttribute("src", url); newFrame.setAttribute("sandbox", "allow-forms allow-same-origin allow-scripts"); if (id !== -1) { newFrame.id = "site-" + id; newFrame.setAttribute("src", url); } else { newFrame.id = "site-1"; newFrame.setAttribute("src", "blankingpage.html"); newFrame.setAttribute("class", "active"); } document.getElementById("site-collection").appendChild(newFrame); } /** * Reloads the specific rotation page. * @param {integer} siteId The on-screen ID of the frame in question. */ function refresh(siteId) { var iframe = document.getElementById('site-' + siteId); iframe.src = iframe.src; } /** * Finds a specific URL object from an array collection. * @param {string} url * @param {array} objectCollection */ function findURLObjectInArray(url, objectCollection) { for (var i = 0; i < objectCollection.length; i++) { if (objectCollection[i].url === url) { return objectCollection[i]; } } return false; }
var options = {name: 'John', age: 33, gender: 'male'}, testString = 'My name is #{name} and I am #{age}-years-old. I am a #{gender}'; // 'My name is #{name} and I am #{age}-years-old'.format(options); String.prototype.format = function(options) { var match, pattern = /#{(\w+)}/g, resultString = this; while (match = pattern.exec(resultString)) { resultString = resultString.split(match[0]).join(options[match[1]]); } return resultString; }; console.log('Problem 1'); console.log(testString.format(options)); console.log('\n');
/* * @require router.js */ /************************* Filter *****************************/
'use strict'; let passport = require('passport'); let express = require('express'); let router = express.Router(); router.get('/facebook', passport.authenticate('facebook')); router.get('/facebook/callback', passport.authenticate('facebook', { failureRedirect: '/' }), function(req, res) { // Successful authentication, redirect home. res.redirect('/'); }); router.get('/google', passport.authenticate('google', { scope: ['https://www.googleapis.com/auth/plus.login', 'https://www.googleapis.com/auth/plus.profile.emails.read' ] })); router.get('/google/callback', passport.authenticate('google', { successRedirect: '/', failureRedirect: '/' })); router.get('/twitter', passport.authenticate('twitter')); router.get('/twitter/callback', passport.authenticate('twitter', { failureRedirect: '/' }), function(req, res) { // Successful authentication, redirect home. res.redirect('/'); }); router.get('/github', passport.authenticate('github')); router.get('/github/callback', passport.authenticate('github', { failureRedirect: '/' }), function(req, res) { // Successful authentication, redirect home. res.redirect('/'); }); router.get('/logout', function(req, res) { req.logout(); res.redirect('/'); }); module.exports = router;
describe('weekNumbers', function() { beforeEach(function() { affix('#cal'); }); describe('when using month view', function() { describe('when using default weekNumbers', function() { it('should not display weekNumbers', function() { $('#cal').njCalendar({ defaultView: 'month' }); var weekNumbersCount = $('.fc-content-skeleton thead .fc-week-number').length; expect(weekNumbersCount).toEqual(0); }); }); describe('when setting weekNumbers to false', function() { it('should not display weekNumbers', function() { $('#cal').njCalendar({ defaultView: 'month', weekNumbers: false }); var weekNumbersCount = $('.fc-content-skeleton thead .fc-week-number').length; expect(weekNumbersCount).toEqual(0); }); }); describe('when setting weekNumbers to true', function() { it('should not display weekNumbers', function() { $('#cal').njCalendar({ defaultView: 'month', weekNumbers: true, weekMode: 'fixed' // will make 6 rows }); var weekNumbersCount = $('.fc-content-skeleton thead .fc-week-number').length; expect(weekNumbersCount).toEqual(6); }); }); }); describe('when using basicWeek view', function() { describe('with default weekNumbers ', function() { it('should not display weekNumbers', function() { $('#cal').njCalendar({ defaultView: 'basicWeek' }); var weekNumbersCount = $('.fc-content-skeleton thead .fc-week-number').length; expect(weekNumbersCount).toEqual(0); }); }); describe('with weekNumbers to false', function() { it('should not display weekNumbers', function() { $('#cal').njCalendar({ defaultView: 'basicWeek', weekNumbers: false }); var weekNumbersCount = $('.fc-content-skeleton thead .fc-week-number').length; expect(weekNumbersCount).toEqual(0); }); }); describe('with weekNumbers to true', function() { it('should display weekNumbers', function() { $('#cal').njCalendar({ defaultView: 'basicWeek', weekNumbers: true }); var weekNumbersCount = $('.fc-content-skeleton thead .fc-week-number').length; expect(weekNumbersCount).toEqual(1); }); }); }); describe('when using an agenda view', function() { describe('with default weekNumbers', function() { it('should not display weekNumbers', function() { $('#cal').njCalendar({ defaultView: 'agendaWeek' }); var weekNumbersCount = $('.fc-week-number').length; expect(weekNumbersCount).toEqual(0); }); }); describe('with weekNumbers to false', function() { it('should not display weekNumbers', function() { $('#cal').njCalendar({ defaultView: 'agendaWeek', weekNumbers: false }); var weekNumbersCount = $('.fc-week-number').length; expect(weekNumbersCount).toEqual(0); }); }); describe('with weekNumbers to true', function() { it('should display weekNumbers', function() { $('#cal').njCalendar({ defaultView: 'agendaWeek', weekNumbers: true }); var weekNumbersCount = $('.fc-week-number').length; // 1 row is axis expect(weekNumbersCount).toEqual(1); }); }); }); });
this.NesDb = this.NesDb || {}; NesDb[ '445819CCCAAF2C48D1A2864D3CE53DED33839B08' ] = { "$": { "name": "Cool World", "class": "Licensed", "catalog": "NES-CX-USA", "publisher": "Ocean", "developer": "Ocean", "region": "USA", "players": "1", "date": "1993-06" }, "cartridge": [ { "$": { "system": "NES-NTSC", "crc": "D73AA04C", "sha1": "445819CCCAAF2C48D1A2864D3CE53DED33839B08", "dump": "ok", "dumper": "bootgod", "datedumped": "2006-03-18" }, "board": [ { "$": { "type": "NES-SLROM", "pcb": "NES-SLROM-06", "mapper": "1" }, "prg": [ { "$": { "name": "NES-CX-0 PRG", "size": "128k", "crc": "BDD55EA1", "sha1": "6CFCE5B7659B3FC9409AD1861F061F26EB12F740" } } ], "chr": [ { "$": { "name": "NES-CX-0 CHR", "size": "128k", "crc": "59FEC08B", "sha1": "5F31A4F882BC94F10A1D95636AEC2A49D138A0D3" } } ], "chip": [ { "$": { "type": "MMC1B3" } } ], "cic": [ { "$": { "type": "6113B1" } } ] } ] } ], "gameGenieCodes": [ { "name": "Infinite lives", "codes": [ [ "GXUVTKVK" ] ] }, { "name": "Lots of erasers", "codes": [ [ "AZNZEYAE" ] ] }, { "name": "Start with 3 bombs", "codes": [ [ "LEVLGZPA" ] ] }, { "name": "Start with 6 bombs", "codes": [ [ "TEVLGZPA" ] ] }, { "name": "Start with 9 bombs", "codes": [ [ "PEVLGZPE" ] ] }, { "name": "Infinite bombs", "codes": [ [ "SXSTOTVG" ] ] }, { "name": "Infinite erasers", "codes": [ [ "SXVVKTVG" ] ] }, { "name": "Start with 2 lives", "codes": [ [ "PEKGYAZA", "PAKZKYZA" ] ] }, { "name": "Start with 7 lives", "codes": [ [ "TEKGYAZA", "TAKZKYZA" ] ] }, { "name": "Start with 10 lives", "codes": [ [ "PEKGYAZE", "PAKZKYZE" ] ] }, { "name": "Start with 3 erasers", "codes": [ [ "LEKKGAPA", "LAVXXYPA" ] ] }, { "name": "Start with 6 erasers", "codes": [ [ "TEKKGAPA", "TAVXXYPA" ] ] }, { "name": "Start with 9 erasers", "codes": [ [ "PEKKGAPE", "PAVXXYPE" ] ] } ] };
// __test__/image_fetcher_test.js jest.dontMock('../lib/image_fetcher.js'); describe("ImageFetcher#getImage", function() { it("calls the request method", function() { var ImageFetcher = require('../lib/image_fetcher.js'); var request = require('request'); var fetcher = new ImageFetcher('http://test.url'); var callback = jest.genMockFunction(); fetcher.getImage(callback); expect(request).toBeCalledWith({ url: 'http://test.url', method: 'GET', encoding: 'base64', timepit: 60*1000 }, callback); // ["no error", {statusCode: 200}, "image data"]); }); });
/** * @file class类 * @author rauschma * @link https://github.com/rauschma/class-js * @module Class */ define(function () { var Class = { /** * 扩展class * * @class * @name Class * @param {Object} properties 扩展对象,必须包含constructor方法 * @return {Function} 构造函数 */ extend: function (properties) { var superProto = this.prototype || Class; var proto = Object.create(superProto); // This method will be attached to many constructor functions // => must refer to "Class" via its global name (and not via "this") Class.copyOwnTo(properties, proto); var constr = proto.constructor; // if (!(constr instanceof Function)) { // throw new Error('You must define a method \'constructor\''); // } // Set up the constructor constr.prototype = proto; constr.super = superProto; // inherit class method constr.extend = this.extend; return constr; }, /** * 拷贝属性 * * @private * @param {Object} source 源 * @param {Object} target 目标 * @return {Object} 复制体 */ copyOwnTo: function (source, target) { Object.getOwnPropertyNames(source).forEach(function (propName) { Object.defineProperty(target, propName, Object.getOwnPropertyDescriptor(source, propName)); }); return target; } }; return Class; });
angular.module('app').directive('sortBy', [ function () { return { restrict: 'A', scope: { sortBy: '=', reverseModel: '=' }, controller: function ($scope) { $scope.sortAttributes = {}; $scope.setSortClassWithAttribute = function (attribute) { var sortClass, el = $scope.sortAttributes[attribute]; // remove previous sort classes $scope.resetSortClasses(); // if sortBy already equals attribute, reverse the sort class if ($scope.sortBy == attribute) { sortClass = $scope.reverseModel ? 'sort-down' : 'sort-up'; el.addClass(sortClass); } } this.onSortClick = function (attribute) { if ($scope.sortBy == attribute) { // if sortBy already equals attribute, switch reverseModel value $scope.reverseModel = !$scope.reverseModel; } else { // else set sortBy to the attribute and the reverseModel to default 'false' $scope.sortBy = attribute; $scope.reverseModel = false; } // since we are modifying the scope outside of the digest loop, call apply $scope.$apply(); } this.registerSortAttribute = function (header) { // register each sort attribute with the attribute value and element if (!$scope.sortAttributes[header.attribute]) { $scope.sortAttributes[header.attribute] = header.el; } } }, link: function ($scope, $element) { $scope.resetSortClasses = function () { // find child elements with sort classes and remove them $element.find('th').removeClass('sort-up'); $element.find('th').removeClass('sort-down'); } $scope.onSortByChange = function (value) { // called when the sort model updates $scope.setSortClassWithAttribute($scope.sortBy); } // we want to know when sortBy or reverseModel changes to update classes $scope.$watch('sortBy', $scope.onSortByChange); $scope.$watch('reverseModel', $scope.onSortByChange); } }; } ]); angular.module('app').directive('sortAttribute', [ function () { return { restrict: 'A', scope: {}, // sortAttribute requires sortBy as a parent require: '^sortBy', link: function ($scope, $element, $attrs, sortByCtrl) { $element.addClass('sortable'); $scope.onSortClick = function () { // call handler function on sortByCtrl sortByCtrl.onSortClick($attrs.sortAttribute); } sortByCtrl.registerSortAttribute({ attribute: $attrs.sortAttribute, el: $element }); // listen for click event on sortAttribute's element $element.on('click', $scope.onSortClick); } }; } ]);
export default function kumarHassebrook(a, b) { var ii = a.length; var p = 0; var p2 = 0; var q2 = 0; for (var i = 0; i < ii; i++) { p += a[i] * b[i]; p2 += a[i] * a[i]; q2 += b[i] * b[i]; } return p / (p2 + q2 - p); }
define([ './globalname', './extends', './core', './var/ZEROS' ],function(jHash,classExtends,InnerHash,ZEROS){ var hmac = function (hash) { var block_size = (new hash()).block_size; function getDigest(){ var digest = this.innerHash.getDigest(); this.outHash.addPart(digest); return this.outHash.getDigest(); } function InnerHMAC(key) { if(key.length > block_size) { var t = new hash(); t.addPart(key); key = t.getDigest(); } key += ZEROS.substr(0,hash.block_size - key.length); var i; var o_key_pad="",i_key_pad=""; for(i=0; i<block_size; i++){ o_key_pad += String.fromCharCode(key.charCodeAt(i) ^ 0x5c); i_key_pad += String.fromCharCode(key.charCodeAt(i) ^ 0x36); } this.outHash = new hash(); this.outHash.addPart(o_key_pad); this.innerHash = new hash(); this.innerHash.addPart(i_key_pad); } classExtends(InnerHMAC,InnerHash); InnerHMAC.prototype.reInit = function (){ InnerHMAC.apply(this,arguments); }; InnerHMAC.prototype.addPart = function (str){ return this.innerHash.addPart(str); }; InnerHMAC.prototype.getDigest = getDigest; var HMAC = function(key,str){ if(!(this instanceof HMAC)){ var h = new InnerHMAC(key); h.addPart(str); return h.getHexDigest(); } return new InnerHMAC(key); }; return HMAC; }; jHash.hmac = hmac; });
export const starburst = {"viewBox":"0 0 24 24","children":[{"name":"path","attribs":{"d":"M19.064 10.109l1.179-2.387c.074-.149.068-.327-.015-.471-.083-.145-.234-.238-.401-.249l-2.656-.172-.172-2.656c-.011-.167-.104-.317-.249-.401-.145-.084-.322-.09-.472-.015l-2.385 1.18-1.477-2.215c-.186-.278-.646-.278-.832 0l-1.477 2.215-2.385-1.18c-.151-.075-.327-.069-.472.015-.145.083-.238.234-.249.401l-.171 2.656-2.657.171c-.167.011-.318.104-.401.249-.084.145-.089.322-.015.472l1.179 2.386-2.214 1.477c-.139.093-.223.249-.223.416s.083.323.223.416l2.215 1.477-1.18 2.386c-.074.15-.068.327.015.472.083.144.234.238.401.248l2.656.171.171 2.657c.011.167.104.317.249.401.144.083.32.088.472.015l2.386-1.179 1.477 2.214c.093.139.249.223.416.223s.323-.083.416-.223l1.477-2.214 2.386 1.179c.15.073.327.068.472-.015s.238-.234.249-.401l.171-2.656 2.656-.172c.167-.011.317-.104.401-.249.083-.145.089-.322.015-.472l-1.179-2.385 2.214-1.478c.139-.093.223-.249.223-.416s-.083-.323-.223-.416l-2.214-1.475z"},"children":[]}]};
/* 所有接口 */ import request from './../service/'; // 测试 /** * 测试get请求 * @param {Object} sendDatas 向后台发送的参数 * @returns {Object} 返回的数据 */ const url = 'http://easy-mock.com/mock/5948977d8ac26d795f409ac7/test/test'; export const getTestData = async (sendData) => { const data = await request({ url: url, method: 'get', params: sendData }); return data; };
import { moduleForComponent, test } from 'ember-qunit'; import hbs from 'htmlbars-inline-precompile'; moduleForComponent('msg-show/pre', 'Integration | Component | msg show/pre', { integration: true }); test('it renders', function(assert) { // Set any properties with this.set('myProperty', 'value'); // Handle any actions with this.on('myAction', function(val) { ... }); this.render(hbs`{{msg-show/pre}}`); assert.equal(this.$().text().trim(), ''); // Template block usage: this.render(hbs` {{#msg-show/pre}} template block text {{/msg-show/pre}} `); assert.equal(this.$().text().trim(), 'template block text'); });
;(function($, hljs) { 'use strict'; $(function () { $('[data-code]').each(function (idx, el) { var $el = $(el); var html = escapeHtml($el.html()); $el.html(html); hljs.highlightBlock($el[0]); }); }); function escapeHtml(text) { var map = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', '\'': '&#039;' }; return text.replace(/[&<>"']/g, function(m) { return map[m]; }); } })(window.jQuery, window.hljs);
/*APP MODULES*/ var appControllers = angular.module('appControllers',[]); var appServices = angular.module('appServices',[]); var appDirectives = angular.module('appDirectives',[]); var appFilters = angular.module('appFilters',[]); var app = angular.module('project', [ 'ngRoute', 'appControllers', 'appServices', 'appDirectives', 'appFilters' ]); app.config(['$routeProvider', function($routeProvider) { $routeProvider. when('/', { templateUrl: 'scripts/views/home.html', controller: 'mainCtrl' }). /*when('/project', { templateUrl: 'partials/project.html', controller: 'ProjectCtrl' }). when('/artists/:id', { templateUrl: 'partials/artists.html', controller: 'artistsCtrl' }).*/ otherwise({ redirectTo: '/' }); } ]);
import React from 'react'; import { mount } from 'enzyme'; import Switch from '..'; import focusTest from '../../../tests/shared/focusTest'; import { resetWarned } from '../../_util/devWarning'; import mountTest from '../../../tests/shared/mountTest'; import rtlTest from '../../../tests/shared/rtlTest'; describe('Switch', () => { focusTest(Switch, { refFocus: true }); mountTest(Switch); rtlTest(Switch); it('should has click wave effect', async () => { const wrapper = mount(<Switch />); wrapper.find('.ant-switch').getDOMNode().click(); await new Promise(resolve => setTimeout(resolve, 0)); expect(wrapper.find('button').getDOMNode().getAttribute('ant-click-animating')).toBe('true'); }); it('warning if set `value`', () => { resetWarned(); const errorSpy = jest.spyOn(console, 'error').mockImplementation(() => {}); mount(<Switch value />); expect(errorSpy).toHaveBeenCalledWith( 'Warning: [antd: Switch] `value` is not a valid prop, do you mean `checked`?', ); errorSpy.mockRestore(); }); });
/** * Ventus example * Copyright © 2012 Ramón Lamana */ (function(Ventus) { document.addEventListener('DOMContentLoaded', function() { var wm = new Ventus.WindowManager(); // Terminal App. var terminalWin = wm.createWindow.fromQuery('.terminal-app', { title: 'Terminal', classname: 'terminal-window', width: 600, height: 300, x: 50, y: 60 }); terminalWin.signals.on('click', function(win){ terminal.display.focus(); }); var terminal = new Terminus('.terminal-app', { welcome: '<div class="identity"><img src="terminal/img/logo.png" /><h1>Terminus.js</h1> ' + Terminus.version + '</div>Copyright 2012-2013 Ramón Lamana.<br/>' + 'Press <span style="color:green">&lt; tab &gt;</span> to see a list of available commands.' }); terminal.shell.include([TestCommands, ShapeCommands]); terminal.display.events.on('prompt', function() { terminalWin.$content.el.scrollTo({ top: terminalWin.view.find('.terminusjs').height, behavior: 'smooth' }); }); // Todo App. var todoWin = wm.createWindow.fromQuery('.todo-app', { title: 'Todo', width: 330, height: 400, x: 670, y: 60 }); var playerWin = wm.createWindow.fromQuery('.player-app', { title: 'Video Player', classname: 'player-window', width: 635, height: 300, x: 490, y: 320, resizable: false, opacity: 1 // To fix problems with chrome video on Linux }); // About App. var aboutWin = wm.createWindow.fromQuery('.about-app', { title: 'About Ventus', width: 250, height: 280, x: 140, y: 380 }); // Hide loader when loaded. var loader = document.querySelector("#loading-screen"); // For look & feel reasons. function openWithDelay(win, delay) { setTimeout(function(){win.open();}, delay); } function init() { loader.classList.add('hide'); loader.addEventListener('animationend', function() { loader.style.display = 'none'; // Open windows openWithDelay(terminalWin, 0); openWithDelay(todoWin, 200); openWithDelay(aboutWin, 400); openWithDelay(playerWin, 600); }); } setTimeout(init, 3000); // Exposé test button. document.querySelector(".expose-button").addEventListener('click', function() { setTimeout(function() { wm.mode = 'expose' }, 100); }, false); }); })(Ventus);
import React, { Component } from 'react' import PropTypes from 'prop-types' import {Link} from 'react-router-dom' import {imgUrl} from '../util' class Banner extends Component { static propTypes = { top_stories: PropTypes.array } constructor(props) { super(props); this.renderBanner = this.renderBanner.bind(this) } refreshBanner () { $(this.refs.bannerSlider).slider({ height: '14rem' }) } componentDidMount() { setTimeout(()=>{ this.refreshBanner(); },1000) } componentWillReceiveProps () { // this.refreshBanner(); } renderBanner () { let top_stories = this.props.top_stories; return top_stories.map((item,i) => <li key={i}> <Link to={"/detail/"+item.id} onClick={this.props.getDetailData.bind(this,item.id)}> <img src={imgUrl(item.image)} alt={item.title} /> <div className="caption center-align"> <h5 className="light grey-text text-lighten-3 banner-text">{ item.title }</h5> </div> </Link> </li>) } render() { return ( <div className="slider" ref='bannerSlider'> <ul className="slides" id="banner"> {this.renderBanner()} </ul> </div> ); } } export default Banner
// WARNING: Make sure to mirror any changes in index_production.js import { AppContainer } from 'react-hot-loader' import React from 'react' import ReactDOM from 'react-dom' import App from './App' // To facilitate the temporary "auth" import jsCookie from 'js-cookie' window.jsCookie = jsCookie const rootEl = document.getElementById('root') ReactDOM.render( <AppContainer> <App /> </AppContainer>, rootEl ) if (module.hot) { module.hot.accept('./App', () => { // If you use Webpack 2 in ES modules mode, you can // use <App /> here rather than require() a <NextApp />. const NextApp = require('./App').default ReactDOM.render( <AppContainer> <NextApp /> </AppContainer>, rootEl ) }) }
/* jshint browser: true, curly: true, eqeqeq: true, forin: true, latedef: true, newcap: true, noarg: true, noempty: true, nonew: true, strict:true, undef: true, unused: true */ (function(App) { 'use strict'; var Components = App.Components || (App.Components = {}); Components.DomInsertMode = { append: 0, prepend: 1 }; })(window.App || (window.App = {}));
'use strict'; const chai = require('chai'), sinon = require('sinon'), expect = chai.expect, Support = require('../support'), dialect = Support.getTestDialect(); describe(Support.getTestDialectTeaser('Sequelize'), () => { describe('log', () => { beforeEach(function() { this.spy = sinon.spy(console, 'log'); }); afterEach(() => { console.log.restore(); }); describe('with disabled logging', () => { beforeEach(function() { this.sequelize = new Support.Sequelize('db', 'user', 'pw', { dialect, logging: false }); }); it('does not call the log method of the logger', function() { this.sequelize.log(); expect(this.spy.calledOnce).to.be.false; }); }); describe('with default logging options', () => { beforeEach(function() { this.sequelize = new Support.Sequelize('db', 'user', 'pw', { dialect }); }); describe('called with no arguments', () => { it('calls the log method', function() { this.sequelize.log(); expect(this.spy.calledOnce).to.be.true; }); it('logs an empty string as info event', function() { this.sequelize.log(''); expect(this.spy.calledOnce).to.be.true; }); }); describe('called with one argument', () => { it('logs the passed string as info event', function() { this.sequelize.log('my message'); expect(this.spy.withArgs('my message').calledOnce).to.be.true; }); }); describe('called with more than two arguments', () => { it('passes the arguments to the logger', function() { this.sequelize.log('error', 'my message', 1, { a: 1 }); expect(this.spy.withArgs('error', 'my message', 1, { a: 1 }).calledOnce).to.be.true; }); }); }); describe('with a custom function for logging', () => { beforeEach(function() { this.spy = sinon.spy(); this.sequelize = new Support.Sequelize('db', 'user', 'pw', { dialect, logging: this.spy }); }); it('calls the custom logger method', function() { this.sequelize.log('om nom'); expect(this.spy.calledOnce).to.be.true; }); it('calls the custom logger method with options', function() { const message = 'om nom'; const timeTaken = 5; const options = { correlationId: 'ABC001' }; this.sequelize.log(message, timeTaken, options); expect(this.spy.withArgs(message, timeTaken, options).calledOnce).to.be.true; }); }); }); });
var async = require('async') , underscore = require('underscore'); /** * After creating any "SourceModel" that has a valid "hasMany" association with any other "TargetModel", * automatically create the relating model/s if we haven't been specifically disabled. * * @todo this doesn't cater for when you have saved nested models and then specify them in the create call chain * * @param {Object} instance the model instance created by SourceModel.create() * @param {Object} values the data originally provided to SourceModel.create() * @param {Object} queryOptions the options originally provided to SourceModel.create() * @param {Function} callback the callback to allow SourceModel.create() to continue execution * @return {Promise} optionally return the promise for use in spread() */ module.exports = function findTargetModelsBeforeCreateSourceModel(as, association, targetModel, values, queryOptions, callback) { var valuesAs = values[as] ? (values[as] instanceof Array ? underscore.clone(values[as]) : [underscore.clone(values[as])]) : false , isSelfRef = this === targetModel , sourcePk = this.primaryKey , targetPK = targetModel.primaryKey , doubleLinked = association.doubleLinked; if (!!doubleLinked && !isSelfRef && !!valuesAs && valuesAs.length && valuesAs[0][targetPK] === undefined) { var targetIds = underscore.map(valuesAs, function(value) { return typeof value === 'object' ? value[targetPK] : value; }); targetModel .findAll({where: {id: {in: targetIds}}}, queryOptions) .then(function(targets) { var targetModels = underscore.map(targets, function(target) { return target.entity; }); values[as] = targetModels; callback(null, values); }) .catch(callback); } else { callback(null); } };
var semver = require('semver'); var which = require('which'); var fs = require('fs'); var path = require('path'); var Q = require('q'); var execFile = require('child_process').execFile; var Project = require('../core/Project'); var cli = require('bower-utils').cli; var defaultConfig = require('../config'); var createError = require('bower-utils').createError; function version(logger, versionArg, options, config) { var project; config = defaultConfig(config); project = new Project(config, logger); return bump(project, versionArg, options.message); } function bump(project, versionArg, message) { var newVersion; var doGitCommit = false; return checkGit() .then(function (hasGit) { doGitCommit = hasGit; }) .then(project.getJson.bind(project)) .then(function (json) { newVersion = getNewVersion(json.version, versionArg); json.version = newVersion; }) .then(project.saveJson.bind(project)) .then(function () { if (doGitCommit) { return gitCommitAndTag(newVersion, message); } }) .then(function () { console.log('v' + newVersion); }); } function getNewVersion(currentVersion, versionArg) { var newVersion = semver.valid(versionArg); if (!newVersion) { newVersion = semver.inc(currentVersion, versionArg); } if (!newVersion) { throw createError('Invalid version argument: `' + versionArg + '`. Usage: `bower version [<newversion> | major | minor | patch]`', 'EINVALIDVERSION'); } if (currentVersion === newVersion) { throw createError('Version not changed', 'EVERSIONNOTCHANGED'); } return newVersion; } function checkGit() { var gitDir = path.join(process.cwd(), '.git'); return Q.nfcall(fs.stat, gitDir) .then(function (stat) { if (stat.isDirectory()) { return checkGitStatus(); } return false; }, function () { //Ignore not found .git directory return false; }); } function checkGitStatus() { return Q.nfcall(which, 'git') .fail(function (err) { err.code = 'ENOGIT'; throw err; }) .then(function () { return Q.nfcall(execFile, 'git', ['status', '--porcelain'], {env: process.env}); }) .then(function (value) { var stdout = value[0]; var lines = filterModifiedStatusLines(stdout); if (lines.length) { throw createError('Git working directory not clean.\n' + lines.join('\n'), 'EWORKINGDIRECTORYDIRTY'); } return true; }); } function filterModifiedStatusLines(stdout) { return stdout.trim().split('\n') .filter(function (line) { return line.trim() && !line.match(/^\?\? /); }).map(function (line) { return line.trim(); }); } function gitCommitAndTag(newVersion, message) { var tag = 'v' + newVersion; message = message || tag; message = message.replace(/%s/g, newVersion); return Q.nfcall(execFile, 'git', ['add', 'bower.json'], {env: process.env}) .then(function () { return Q.nfcall(execFile, 'git', ['commit', '-m', message], {env: process.env}); }) .then(function () { return Q.nfcall(execFile, 'git', ['tag', tag, '-am', message], {env: process.env}); }); } // ------------------- version.line = function (logger, argv) { var options = version.options(argv); return version(logger, options.argv.remain[1], options); }; version.options = function (argv) { return cli.readOptions({ 'message': { type: String, shorthand: 'm'} }, argv); }; version.completion = function () { // TODO: }; module.exports = version;
// Simulate config options from your production environment by // customising the .env file in your project's root folder. // require('dotenv').load(); // Require keystone var keystone = require('keystone'); // Initialise Keystone with your project's configuration. // See http://keystonejs.com/guide/config for available options // and documentation. keystone.init({ 'name': 'Keystone Angular Skeleton', 'brand': 'Keystone Angular Skeleton', 'less': 'public', 'static': 'public', 'favicon': 'public/favicon.ico', 'views': 'templates/views', 'view engine': 'jade', 'auto update': true, 'session': true, 'auth': true, 'user model': 'User', 'cookie secret': '2|@"v4%q-V8F|3PLcHJgOa%0@W!"Rc]6r]#@K{C#G;p:xs@C/"@"4RI<]!c0=97w', 'mongo': process.env.MONGO_URI || process.env.MONGOLAB_URI || 'mongodb://localhost/keystone-angular-skeleton', 'cloudinary config': process.env.CLOUDINARY_URL || 'cloudinary://333779167276662:_8jbSi9FB3sWYrfimcl8VKh34rI@keystone-demo' }); // Load your project's Models keystone.import('models'); // Setup common locals for your templates. The following are required for the // bundled templates and layouts. Any runtime locals (that should be set uniquely // for each request) should be added to ./routes/middleware.js keystone.set('locals', { _: require('lodash'), env: keystone.get('env'), utils: keystone.utils, editable: keystone.content.editable }); // Load your project's Routes keystone.set('routes', require('./routes')); // Setup common locals for your emails. The following are required by Keystone's // default email templates, you may remove them if you're using your own. // Configure the navigation bar in Keystone's Admin UI keystone.set('nav', { 'posts': ['posts', 'post-categories'], 'galleries': 'galleries', 'enquiries': 'enquiries', 'users': 'users' }); // Start Keystone to connect to your database and initialise the web server keystone.start();
let assert = require("assert"); let Card = require("../lib/Card"); let Pair = require("../lib/Pair"); let Deck = require("../lib/Deck"); let deckGenerator = require("../lib/deckGenerator"); let debug = require('debug')('deckGeneratorTest'); describe('deckGenerator()', () => { it(`should return a function when called with no arguments`, () => { let generateDeck = deckGenerator(); assert.equal('function', typeof generateDeck); }); it(`should throw an error when called with anything other than a function`, () => { assert.throws(() => deckGenerator(42)); assert.throws(() => deckGenerator("42")); assert.throws(() => deckGenerator([42])); }); describe('deckGenerator().generateSymbol', () => { it(`should return a function when called without arguments`, () => { let generateDeck = deckGenerator(); assert.equal('function', typeof generateDeck.generateSymbol); }); }); describe('deckGenerator()()', () => { let tests = [{ dimensions: 2, expectedCards: 3, expectedSymbols: 2 }, { dimensions: 3, expectedCards: 7, expectedSymbols: 3 }, { dimensions: 4, expectedCards: 13, expectedSymbols: 4 }, { dimensions: 5, expectedCards: 21, expectedSymbols: 5 }, { dimensions: 6, expectedCards: 31, expectedSymbols: 6 }, { dimensions: 7, expectedCards: 43, expectedSymbols: 7 }, { dimensions: 8, expectedCards: 57, expectedSymbols: 8 }, { dimensions: 9, expectedCards: 73, expectedSymbols: 9 }]; tests.forEach(test => { it(`should return a deck with cards containing ${test.expectedSymbols} symbols when called with ${test.dimensions}`, () => { let generateDeck = deckGenerator(); let deck = generateDeck(test.dimensions); debug(`${deck}`); let cards = deck.cards; let invalidCards = cards.filter(c => { return c.symbols.length != test.expectedSymbols; }); assert.equal(0, invalidCards.length, `Found ${invalidCards.length} invalid cards\n${invalidCards.join('\n')}`); }); }); tests.forEach(test => { it(`should return a deck with ${test.expectedCards} cards when called with ${test.dimensions}`, () => { let generateDeck = deckGenerator(); let deck = generateDeck(test.dimensions); debug(`${deck}`); let cards = deck.cards; assert.equal(test.expectedCards, cards.length, `Expected ${test.expectedCards} cards, found ${cards.length}`); }); }); tests.forEach(test => { it(`should return a deck with valid cards and pairs when called with ${test.dimensions}`, () => { let generateDeck = deckGenerator(); let deck = generateDeck(test.dimensions); debug(`${deck}`); assert.ok(deck.isValid(), "Deck is invalid"); }); }); }); });
/** * @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 */ // THIS CODE IS GENERATED - DO NOT MODIFY // See angular/tools/gulp-tasks/cldr/extract.js (function(global) { global.ng = global.ng || {}; global.ng.common = global.ng.common || {}; global.ng.common.locales = global.ng.common.locales || {}; const u = undefined; function plural(n) { let i = Math.floor(Math.abs(n)), v = n.toString().replace(/^[^.]*\.?/, '').length; if (i === 1 && v === 0) return 1; return 5; } global.ng.common.locales['de-it'] = [ 'de-IT', [['AM', 'PM'], u, u], u, [ ['S', 'M', 'D', 'M', 'D', 'F', 'S'], ['So.', 'Mo.', 'Di.', 'Mi.', 'Do.', 'Fr.', 'Sa.'], ['Sonntag', 'Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag'], ['So.', 'Mo.', 'Di.', 'Mi.', 'Do.', 'Fr.', 'Sa.'] ], [ ['S', 'M', 'D', 'M', 'D', 'F', 'S'], ['So', 'Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa'], ['Sonntag', 'Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag'], ['So.', 'Mo.', 'Di.', 'Mi.', 'Do.', 'Fr.', 'Sa.'] ], [ ['J', 'F', 'M', 'A', 'M', 'J', 'J', 'A', 'S', 'O', 'N', 'D'], [ 'Jän.', 'Feb.', 'März', 'Apr.', 'Mai', 'Juni', 'Juli', 'Aug.', 'Sep.', 'Okt.', 'Nov.', 'Dez.' ], [ 'Jänner', 'Februar', 'März', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember' ] ], [ ['J', 'F', 'M', 'A', 'M', 'J', 'J', 'A', 'S', 'O', 'N', 'D'], ['Jän', 'Feb', 'Mär', 'Apr', 'Mai', 'Jun', 'Jul', 'Aug', 'Sep', 'Okt', 'Nov', 'Dez'], [ 'Jänner', 'Februar', 'März', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember' ] ], [['v. Chr.', 'n. Chr.'], u, u], 1, [6, 0], ['dd.MM.yy', 'dd.MM.y', 'd. MMMM y', 'EEEE, d. MMMM y'], ['HH:mm', 'HH:mm:ss', 'HH:mm:ss z', 'HH:mm:ss zzzz'], ['{1}, {0}', u, '{1} \'um\' {0}', u], [',', '.', ';', '%', '+', '-', 'E', '·', '‰', '∞', 'NaN', ':'], ['#,##0.###', '#,##0 %', '#,##0.00 ¤', '#E0'], '€', 'Euro', { 'ATS': ['öS'], 'AUD': ['AU$', '$'], 'BGM': ['BGK'], 'BGO': ['BGJ'], 'CUC': [u, 'Cub$'], 'DEM': ['DM'], 'FKP': [u, 'Fl£'], 'GNF': [u, 'F.G.'], 'KMF': [u, 'FC'], 'RON': [u, 'L'], 'RWF': [u, 'F.Rw'], 'SYP': [], 'THB': ['฿'], 'TWD': ['NT$'], 'XXX': [], 'ZMW': [u, 'K'] }, 'ltr', plural, [ [ ['Mitternacht', 'morgens', 'vorm.', 'mittags', 'nachm.', 'abends', 'nachts'], u, ['Mitternacht', 'morgens', 'vormittags', 'mittags', 'nachmittags', 'abends', 'nachts'] ], [ ['Mitternacht', 'Morgen', 'Vorm.', 'Mittag', 'Nachm.', 'Abend', 'Nacht'], u, ['Mitternacht', 'Morgen', 'Vormittag', 'Mittag', 'Nachmittag', 'Abend', 'Nacht'] ], [ '00:00', ['05:00', '10:00'], ['10:00', '12:00'], ['12:00', '13:00'], ['13:00', '18:00'], ['18:00', '24:00'], ['00:00', '05:00'] ] ] ]; })(typeof globalThis !== 'undefined' && globalThis || typeof global !== 'undefined' && global || typeof window !== 'undefined' && window);
/** * echarts组件类: 坐标轴 * * @desc echarts基于Canvas,纯Javascript图表库,提供直观,生动,可交互,可个性化定制的数据统计图表。 * @author Kener (@Kener-林峰, linzhifeng@baidu.com) * * 直角坐标系中坐标轴数组,数组中每一项代表一条横轴(纵轴)坐标轴。 * 标准(1.0)中规定最多同时存在2条横轴和2条纵轴 * 单条横轴时可指定安放于grid的底部(默认)或顶部,2条同时存在时则默认第一条安放于底部,第二天安放于顶部 * 单条纵轴时可指定安放于grid的左侧(默认)或右侧,2条同时存在时则默认第一条安放于左侧,第二天安放于右侧。 * 坐标轴有两种类型,类目型和数值型(区别详见axis): * 横轴通常为类目型,但条形图时则横轴为数值型,散点图时则横纵均为数值型 * 纵轴通常为数值型,但条形图时则纵轴为类目型。 * */ define(function (require) { /** * 构造函数 * @param {Object} messageCenter echart消息中心 * @param {ZRender} zr zrender实例 * @param {Object} option 图表选项 * @param {string=} option.xAxis.type 坐标轴类型,横轴默认为类目型'category' * @param {string=} option.yAxis.type 坐标轴类型,纵轴默认为类目型'value' * @param {Object} component 组件 * @param {string} axisType 横走or纵轴 */ function Axis(messageCenter, zr, option, component, axisType) { var Base = require('./base'); Base.call(this, zr); var ecConfig = require('../config'); var self = this; self.type = ecConfig.COMPONENT_TYPE_AXIS; var _axisList = []; /** * 参数修正&默认值赋值,重载基类方法 * @param {Object} opt 参数 */ function reformOption(opt) { // 不写或传了个空数值默认为数值轴 if (!opt || (opt instanceof Array && opt.length === 0) ) { opt = [{ type : ecConfig.COMPONENT_TYPE_AXIS_VALUE }]; } else if (!(opt instanceof Array)){ opt = [opt]; } // 最多两条,其他参数忽略 if (opt.length > 2) { opt = [opt[0],opt[1]]; } if (axisType == 'xAxis') { // 横轴位置默认配置 if (!opt[0].position // 没配置或配置错 || (opt[0].position != 'bottom' && opt[0].position != 'top') ) { opt[0].position = 'bottom'; } if (opt.length > 1) { opt[1].position = opt[0].position == 'bottom' ? 'top' : 'bottom'; } for (var i = 0, l = opt.length; i < l; i++) { // 坐标轴类型,横轴默认为类目型'category' opt[i].type = opt[i].type || 'category'; // 标识轴类型&索引 opt[i].xAxisIndex = i; opt[i].yAxisIndex = -1; } } else { // 纵轴位置默认配置 if (!opt[0].position // 没配置或配置错 || (opt[0].position != 'left' && opt[0].position != 'right') ) { opt[0].position = 'left'; } if (opt.length > 1) { opt[1].position = opt[0].position == 'left' ? 'right' : 'left'; } for (var i = 0, l = opt.length; i < l; i++) { // 坐标轴类型,纵轴默认为数值型'value' opt[i].type = opt[i].type || 'value'; // 标识轴类型&索引 opt[i].xAxisIndex = -1; opt[i].yAxisIndex = i; } } return opt; } /** * 构造函数默认执行的初始化方法,也用于创建实例后动态修改 * @param {Object} newZr * @param {Object} newOption * @param {Object} newCompoent */ function init(newOption, newCompoent, newAxisType) { component = newCompoent; axisType = newAxisType; self.clear(); var axisOption; if (axisType == 'xAxis') { option.xAxis =self.reformOption(newOption.xAxis); axisOption = option.xAxis; } else { option.yAxis = reformOption(newOption.yAxis); axisOption = option.yAxis; } var CategoryAxis = require('./categoryAxis'); var ValueAxis = require('./valueAxis'); for (var i = 0, l = axisOption.length; i < l; i++) { _axisList.push( axisOption[i].type == 'category' ? new CategoryAxis( messageCenter, zr, axisOption[i], component ) : new ValueAxis( messageCenter, zr, axisOption[i], component, option.series ) ); } } /** * 刷新 */ function refresh(newOption) { var axisOption; var series; if (newOption) { if (axisType == 'xAxis') { option.xAxis =self.reformOption(newOption.xAxis); axisOption = option.xAxis; } else { option.yAxis = reformOption(newOption.yAxis); axisOption = option.yAxis; } series = newOption.series; } for (var i = 0, l = _axisList.length; i < l; i++) { _axisList[i].refresh && _axisList[i].refresh( axisOption ? axisOption[i] : false, series ); } } /** * 根据值换算位置 * @param {number} idx 坐标轴索引0~1 */ function getAxis(idx) { return _axisList[idx]; } /** * 清除坐标轴子对象,实例仍可用,重载基类方法 */ function clear() { for (var i = 0, l = _axisList.length; i < l; i++) { _axisList[i].dispose && _axisList[i].dispose(); } _axisList = []; } // 重载基类方法 self.clear = clear; self.reformOption = reformOption; self.init = init; self.refresh = refresh; self.getAxis = getAxis; init(option, component, axisType); } require('../component').define('axis', Axis); return Axis; });
const _ = require('underscore') const mango = require('../mango') const clientMango = (q) => ({ selector: { _id: { $gt: null }, last_name: { $regex: `(?i)^(${q})` } } }) const searchClient = (req, res) => mango('clients', clientMango(req.query.q)) .then((clients) => res.json(_(clients).sortBy('first_name'))) module.exports = searchClient
/* * jQuery timepicker addon * By: Trent Richardson [http://trentrichardson.com] * Version 0.7 * Last Modified: 10/7/2010 * * Copyright 2010 Trent Richardson * Dual licensed under the MIT and GPL licenses. * http://trentrichardson.com/Impromptu/GPL-LICENSE.txt * http://trentrichardson.com/Impromptu/MIT-LICENSE.txt * * HERES THE CSS: * .ui-timepicker-div .ui-widget-header{ margin-bottom: 8px; } * .ui-timepicker-div dl{ text-align: left; } * .ui-timepicker-div dl dt{ height: 25px; } * .ui-timepicker-div dl dd{ margin: -25px 0 10px 65px; } * .ui-timepicker-div .ui_tpicker_hour div { padding-right: 2px; } * .ui-timepicker-div .ui_tpicker_minute div { padding-right: 6px; } * .ui-timepicker-div .ui_tpicker_second div { padding-right: 6px; } * .ui-timepicker-div td { font-size: 90%; } */ (function($) { function Timepicker(singleton) { if(typeof(singleton) === 'boolean' && singleton == true) { this.regional = []; // Available regional settings, indexed by language code this.regional[''] = { // Default regional settings currentText: 'Now', ampm: false, timeFormat: 'hh:mm tt', timeOnlyTitle: 'Choose Time', timeText: 'Time', hourText: 'Hour', minuteText: 'Minute', secondText: 'Second' }; this.defaults = { // Global defaults for all the datetime picker instances showButtonPanel: true, timeOnly: false, showHour: true, showMinute: true, showSecond: false, showTime: true, stepHour: 0.05, stepMinute: 0.05, stepSecond: 0.05, hour: 0, minute: 0, second: 0, hourMin: 0, minuteMin: 0, secondMin: 0, hourMax: 23, minuteMax: 59, secondMax: 59, hourGrid: 0, minuteGrid: 0, secondGrid: 0, alwaysSetTime: true }; $.extend(this.defaults, this.regional['']); } else { this.defaults = $.extend({}, $.timepicker.defaults); } }; Timepicker.prototype = { $input: null, $altInput: null, $timeObj: null, inst: null, hour_slider: null, minute_slider: null, second_slider: null, hour: 0, minute: 0, second: 0, ampm: '', formattedDate: '', formattedTime: '', formattedDateTime: '', //######################################################################## // add our sliders to the calendar //######################################################################## addTimePicker: function(dp_inst) { var tp_inst = this; var currDT; if ((this.$altInput) && this.$altInput != null) { currDT = this.$input.val() + ' ' + this.$altInput.val(); } else { currDT = this.$input.val(); } var regstr = this.defaults.timeFormat.toString() .replace(/h{1,2}/ig, '(\\d?\\d)') .replace(/m{1,2}/ig, '(\\d?\\d)') .replace(/s{1,2}/ig, '(\\d?\\d)') .replace(/t{1,2}/ig, '(am|pm|a|p)?') .replace(/\s/g, '\\s?') + '$'; if (!this.defaults.timeOnly) { //the time should come after x number of characters and a space. x = at least the length of text specified by the date format var dp_dateFormat = $.datepicker._get(dp_inst, 'dateFormat'); regstr = '.{' + dp_dateFormat.length + ',}\\s+' + regstr; } var order = this.getFormatPositions(); var treg = currDT.match(new RegExp(regstr, 'i')); if (treg) { if (order.t !== -1) { this.ampm = ((treg[order.t] === undefined || treg[order.t].length === 0) ? '' : (treg[order.t].charAt(0).toUpperCase() == 'A') ? 'AM' : 'PM').toUpperCase(); } if (order.h !== -1) { if (this.ampm == 'AM' && treg[order.h] == '12') { // 12am = 0 hour this.hour = 0; } else if (this.ampm == 'PM' && treg[order.h] != '12') { // 12pm = 12 hour, any other pm = hour + 12 this.hour = (parseFloat(treg[order.h]) + 12).toFixed(0); } else { this.hour = treg[order.h]; } } if (order.m !== -1) { this.minute = treg[order.m]; } if (order.s !== -1) { this.second = treg[order.s]; } } tp_inst.timeDefined = (treg) ? true : false; if (typeof(dp_inst.stay_open) !== 'boolean' || dp_inst.stay_open === false) { // wait for datepicker to create itself.. 60% of the time it works every time.. setTimeout(function() { tp_inst.injectTimePicker(dp_inst, tp_inst); }, 10); } else { tp_inst.injectTimePicker(dp_inst, tp_inst); } }, //######################################################################## // figure out position of time elements.. cause js cant do named captures //######################################################################## getFormatPositions: function() { var finds = this.defaults.timeFormat.toLowerCase().match(/(h{1,2}|m{1,2}|s{1,2}|t{1,2})/g); var orders = { h: -1, m: -1, s: -1, t: -1 }; if (finds) { for (var i = 0; i < finds.length; i++) { if (orders[finds[i].toString().charAt(0)] == -1) { orders[finds[i].toString().charAt(0)] = i + 1; } } } return orders; }, //######################################################################## // generate and inject html for timepicker into ui datepicker //######################################################################## injectTimePicker: function(dp_inst, tp_inst) { var $dp = dp_inst.dpDiv; var opts = tp_inst.defaults; // Added by Peter Medeiros: // - Figure out what the hour/minute/second max should be based on the step values. // - Example: if stepMinute is 15, then minMax is 45. var hourMax = opts.hourMax - (opts.hourMax % opts.stepHour); var minMax = opts.minuteMax - (opts.minuteMax % opts.stepMinute); var secMax = opts.secondMax - (opts.secondMax % opts.stepSecond); // Prevent displaying twice if ($dp.find("div#ui-timepicker-div-"+ dp_inst.id).length === 0) { var noDisplay = ' style="display:none;"'; var html = '<div class="ui-timepicker-div" id="ui-timepicker-div-' + dp_inst.id + '"><dl>' + '<dt class="ui_tpicker_time_label" id="ui_tpicker_time_label_' + dp_inst.id + '"' + ((opts.showTime) ? '' : noDisplay) + '>' + opts.timeText + '</dt>' + '<dd class="ui_tpicker_time" id="ui_tpicker_time_' + dp_inst.id + '"' + ((opts.showTime) ? '' : noDisplay) + '></dd>' + '<dt class="ui_tpicker_hour_label" id="ui_tpicker_hour_label_' + dp_inst.id + '"' + ((opts.showHour) ? '' : noDisplay) + '>' + opts.hourText + '</dt>'; if (opts.hourGrid > 0) { html += '<dd class="ui_tpicker_hour ui_tpicker_hour_' + opts.hourGrid + '">' + '<div id="ui_tpicker_hour_' + dp_inst.id + '"' + ((opts.showHour) ? '' : noDisplay) + '></div>' + '<div><table><tr>'; for (var h = 0; h < hourMax; h += opts.hourGrid) { var tmph = h; if(opts.ampm && h > 12) tmph = h-12; else tmph = h; if(tmph < 10) tmph = '0' + tmph; if(opts.ampm) { if(h == 0) tmph = 12 +'a'; else if(h < 12) tmph += 'a'; else tmph += 'p'; } html += '<td>' + tmph + '</td>'; } html += '</tr></table></div>' + '</dd>'; } else { html += '<dd class="ui_tpicker_hour" id="ui_tpicker_hour_' + dp_inst.id + '"' + ((opts.showHour) ? '' : noDisplay) + '></dd>'; } html += '<dt class="ui_tpicker_minute_label" id="ui_tpicker_minute_label_' + dp_inst.id + '"' + ((opts.showMinute) ? '' : noDisplay) + '>' + opts.minuteText + '</dt>'; if (opts.minuteGrid > 0) { html += '<dd class="ui_tpicker_minute ui_tpicker_minute_' + opts.minuteGrid + '">' + '<div id="ui_tpicker_minute_' + dp_inst.id + '"' + ((opts.showMinute) ? '' : noDisplay) + '></div>' + '<div><table><tr>'; for (var m = 0; m < minMax; m += opts.minuteGrid) { html += '<td>' + ((m < 10) ? '0' : '') + m + '</td>'; } html += '</tr></table></div>' + '</dd>'; } else { html += '<dd class="ui_tpicker_minute" id="ui_tpicker_minute_' + dp_inst.id + '"' + ((opts.showMinute) ? '' : noDisplay) + '></dd>' } html += '<dt class="ui_tpicker_second_label" id="ui_tpicker_second_label_' + dp_inst.id + '"' + ((opts.showSecond) ? '' : noDisplay) + '>' + opts.secondText + '</dt>'; if (opts.secondGrid > 0) { html += '<dd class="ui_tpicker_second ui_tpicker_second_' + opts.secondGrid + '">' + '<div id="ui_tpicker_second_' + dp_inst.id + '"' + ((opts.showSecond) ? '' : noDisplay) + '></div>' + '<table><table><tr>'; for (var s = 0; s < secMax; s += opts.secondGrid) { html += '<td>' + ((s < 10) ? '0' : '') + s + '</td>'; } html += '</tr></table></table>' + '</dd>'; } else { html += '<dd class="ui_tpicker_second" id="ui_tpicker_second_' + dp_inst.id + '"' + ((opts.showSecond) ? '' : noDisplay) + '></dd>'; } html += '</dl></div>'; $tp = $(html); // if we only want time picker... if (opts.timeOnly === true) { $tp.prepend( '<div class="ui-widget-header ui-helper-clearfix ui-corner-all">' + '<div class="ui-datepicker-title">'+ opts.timeOnlyTitle +'</div>' + '</div>'); $dp.find('.ui-datepicker-header, .ui-datepicker-calendar').hide(); } tp_inst.hour_slider = $tp.find('#ui_tpicker_hour_'+ dp_inst.id).slider({ orientation: "horizontal", value: tp_inst.hour, min: opts.hourMin, max: hourMax, step: opts.stepHour, slide: function(event, ui) { tp_inst.hour_slider.slider( "option", "value", ui.value ); tp_inst.onTimeChange(dp_inst, tp_inst); } }); // Updated by Peter Medeiros: // - Pass in Event and UI instance into slide function tp_inst.minute_slider = $tp.find('#ui_tpicker_minute_'+ dp_inst.id).slider({ orientation: "horizontal", value: tp_inst.minute, min: opts.minuteMin, max: minMax, step: opts.stepMinute, slide: function(event, ui) { // update the global minute slider instance value with the current slider value tp_inst.minute_slider.slider( "option", "value", ui.value ); tp_inst.onTimeChange(dp_inst, tp_inst); } }); tp_inst.second_slider = $tp.find('#ui_tpicker_second_'+ dp_inst.id).slider({ orientation: "horizontal", value: tp_inst.second, min: opts.secondMin, max: secMax, step: opts.stepSecond, slide: function(event, ui) { tp_inst.second_slider.slider( "option", "value", ui.value ); tp_inst.onTimeChange(dp_inst, tp_inst); } }); // Add grid functionality $tp.find(".ui_tpicker_hour td").each( function(index) { $(this).click( function() { var h = $(this).html(); if(opts.ampm) { var ap = h.substring(2).toLowerCase(); var aph = new Number(h.substring(0,2)); if(ap == 'a'){ if(aph == 12) h = 0; else h = aph; }else{ if(aph == 12) h = 12; else h = aph + 12; } } tp_inst.hour_slider.slider("option", "value", h); tp_inst.onTimeChange(dp_inst, tp_inst); } ); $(this).css({ 'cursor': "pointer", 'width': '1%', 'text-align': 'left' }); } ); $tp.find(".ui_tpicker_minute td").each( function(index) { $(this).click( function() { tp_inst.minute_slider.slider("option", "value", $(this).html()); tp_inst.onTimeChange(dp_inst, tp_inst); } ); $(this).css({ 'cursor': "pointer", 'width': '1%', 'text-align': 'left' }); } ); $tp.find(".ui_tpicker_second td").each( function(index) { $(this).click( function() { tp_inst.second_slider.slider("option", "value", $(this).html()); tp_inst.onTimeChange(dp_inst, tp_inst); } ); $(this).css({ 'cursor': "pointer", 'width': '1%', 'text-align': 'left' }); } ); $dp.find('.ui-datepicker-calendar').after($tp); tp_inst.$timeObj = $('#ui_tpicker_time_'+ dp_inst.id); if (dp_inst !== null) { var timeDefined = tp_inst.timeDefined; tp_inst.onTimeChange(dp_inst, tp_inst); tp_inst.timeDefined = timeDefined; } } }, //######################################################################## // when a slider moves.. // on time change is also called when the time is updated in the text field //######################################################################## onTimeChange: function(dp_inst, tp_inst) { var hour = tp_inst.hour_slider.slider('value'); var minute = tp_inst.minute_slider.slider('value'); var second = tp_inst.second_slider.slider('value'); var ampm = (hour < 11.5) ? 'AM' : 'PM'; hour = (hour >= 11.5 && hour < 12) ? 12 : hour; var hasChanged = false; // If the update was done in the input field, this field should not be updated. // If the update was done using the sliders, update the input field. if (tp_inst.hour != hour || tp_inst.minute != minute || tp_inst.second != second || (tp_inst.ampm.length > 0 && tp_inst.ampm != ampm)) { hasChanged = true; } tp_inst.hour = parseFloat(hour).toFixed(0); tp_inst.minute = parseFloat(minute).toFixed(0); tp_inst.second = parseFloat(second).toFixed(0); tp_inst.ampm = ampm; tp_inst.formatTime(tp_inst); tp_inst.$timeObj.text(tp_inst.formattedTime); if (hasChanged) { tp_inst.updateDateTime(dp_inst, tp_inst); tp_inst.timeDefined = true; } }, //######################################################################## // format the time all pretty... //######################################################################## formatTime: function(tp_inst) { var tmptime = tp_inst.defaults.timeFormat.toString(); var hour12 = ((tp_inst.ampm == 'AM') ? (tp_inst.hour) : (tp_inst.hour % 12)); hour12 = (Number(hour12) === 0) ? 12 : hour12; if (tp_inst.defaults.ampm === true) { tmptime = tmptime.toString() .replace(/hh/g, ((hour12 < 10) ? '0' : '') + hour12) .replace(/h/g, hour12) .replace(/mm/g, ((tp_inst.minute < 10) ? '0' : '') + tp_inst.minute) .replace(/m/g, tp_inst.minute) .replace(/ss/g, ((tp_inst.second < 10) ? '0' : '') + tp_inst.second) .replace(/s/g, tp_inst.second) .replace(/TT/g, tp_inst.ampm.toUpperCase()) .replace(/tt/g, tp_inst.ampm.toLowerCase()) .replace(/T/g, tp_inst.ampm.charAt(0).toUpperCase()) .replace(/t/g, tp_inst.ampm.charAt(0).toLowerCase()); } else { tmptime = tmptime.toString() .replace(/hh/g, ((tp_inst.hour < 10) ? '0' : '') + tp_inst.hour) .replace(/h/g, tp_inst.hour) .replace(/mm/g, ((tp_inst.minute < 10) ? '0' : '') + tp_inst.minute) .replace(/m/g, tp_inst.minute) .replace(/ss/g, ((tp_inst.second < 10) ? '0' : '') + tp_inst.second) .replace(/s/g, tp_inst.second); tmptime = $.trim(tmptime.replace(/t/gi, '')); } tp_inst.formattedTime = tmptime; return tp_inst.formattedTime; }, //######################################################################## // update our input with the new date time.. //######################################################################## updateDateTime: function(dp_inst, tp_inst) { var dt = new Date(dp_inst.selectedYear, dp_inst.selectedMonth, dp_inst.selectedDay); var dateFmt = $.datepicker._get(dp_inst, 'dateFormat'); var formatCfg = $.datepicker._getFormatConfig(dp_inst); this.formattedDate = $.datepicker.formatDate(dateFmt, (dt === null ? new Date() : dt), formatCfg); var formattedDateTime = this.formattedDate; var timeAvailable = dt !== null && tp_inst.timeDefined; if(this.defaults.timeOnly === true){ formattedDateTime = this.formattedTime; } else if (this.defaults.timeOnly !== true && (this.defaults.alwaysSetTime || timeAvailable)) { if ((this.$altInput) && this.$altInput != null) { this.$altInput.val(this.formattedTime); } else{ formattedDateTime += ' ' + this.formattedTime; } } this.formattedDateTime = formattedDateTime; this.$input.val(formattedDateTime); this.$input.trigger("change"); }, setDefaults: function(settings) { extendRemove(this.defaults, settings || {}); return this; } }; //######################################################################## // extend timepicker to datepicker //######################################################################## jQuery.fn.datetimepicker = function(o) { var opts = (o === undefined ? {} : o); var input = $(this); var tp = new Timepicker(); var inlineSettings = {}; for (var attrName in tp.defaults) { var attrValue = input.attr('time:' + attrName); if (attrValue) { try { inlineSettings[attrName] = eval(attrValue); } catch (err) { inlineSettings[attrName] = attrValue; } } } tp.defaults = $.extend(tp.defaults, inlineSettings); var beforeShowFunc = function(input, inst) { tp.hour = tp.defaults.hour; tp.minute = tp.defaults.minute; tp.second = tp.defaults.second; tp.ampm = ''; tp.$input = $(input); if(opts.altField != undefined && opts.altField != '') tp.$altInput = $($.datepicker._get(inst, 'altField')); tp.inst = inst; tp.addTimePicker(inst); if ($.isFunction(opts.beforeShow)) { opts.beforeShow(input, inst); } }; var onChangeMonthYearFunc = function(year, month, inst) { // Update the time as well : this prevents the time from disappearing from the input field. tp.updateDateTime(inst, tp); if ($.isFunction(opts.onChangeMonthYear)) { opts.onChangeMonthYear(year, month, inst); } }; var onCloseFunc = function(dateText, inst) { if(tp.timeDefined === true && input.val() != '') { tp.updateDateTime(inst, tp); } if ($.isFunction(opts.onClose)) { opts.onClose(dateText, inst); } }; tp.defaults = $.extend({}, tp.defaults, opts, { beforeShow: beforeShowFunc, onChangeMonthYear: onChangeMonthYearFunc, onClose: onCloseFunc, timepicker: tp // add timepicker as a property of datepicker: $.datepicker._get(dp_inst, 'timepicker'); }); $(this).datepicker(tp.defaults); }; //######################################################################## // shorthand just to use timepicker.. //######################################################################## jQuery.fn.timepicker = function(opts) { opts = $.extend(opts, { timeOnly: true }); $(this).datetimepicker(opts); }; //######################################################################## // the bad hack :/ override datepicker so it doesnt close on select // inspired: http://stackoverflow.com/questions/1252512/jquery-datepicker-prevent-closing-picker-when-clicking-a-date/1762378#1762378 //######################################################################## $.datepicker._base_selectDate = $.datepicker._selectDate; $.datepicker._selectDate = function (id, dateStr) { var target = $(id); var inst = this._getInst(target[0]); var tp_inst = $.datepicker._get(inst, 'timepicker'); if(tp_inst){ inst.inline = true; inst.stay_open = true; $.datepicker._base_selectDate(id, dateStr); inst.stay_open = false; inst.inline = false; this._notifyChange(inst); this._updateDatepicker(inst); } else{ $.datepicker._base_selectDate(id, dateStr); } }; //############################################################################################# // second bad hack :/ override datepicker so it triggers an event when changing the input field // and does not redraw the datepicker on every selectDate event //############################################################################################# $.datepicker._base_updateDatepicker = $.datepicker._updateDatepicker; $.datepicker._updateDatepicker = function(inst) { if (typeof(inst.stay_open) !== 'boolean' || inst.stay_open === false) { this._base_updateDatepicker(inst); // Reload the time control when changing something in the input text field. this._beforeShow(inst.input, inst); } }; $.datepicker._beforeShow = function(input, inst) { var beforeShow = this._get(inst, 'beforeShow'); if (beforeShow) { inst.stay_open = true; beforeShow.apply((inst.input ? inst.input[0] : null), [inst.input, inst]); inst.stay_open = false; } }; //####################################################################################### // third bad hack :/ override datepicker so it allows spaces and colan in the input field //####################################################################################### $.datepicker._base_doKeyPress = $.datepicker._doKeyPress; $.datepicker._doKeyPress = function(event) { var inst = $.datepicker._getInst(event.target); var tp_inst = $.datepicker._get(inst, 'timepicker'); if(tp_inst){ if ($.datepicker._get(inst, 'constrainInput')) { var dateChars = $.datepicker._possibleChars($.datepicker._get(inst, 'dateFormat')); var chr = String.fromCharCode(event.charCode === undefined ? event.keyCode : event.charCode); var chrl = chr.toLowerCase(); // keyCode == 58 => ":" // keyCode == 32 => " " return event.ctrlKey || (chr < ' ' || !dateChars || dateChars.indexOf(chr) > -1 || event.keyCode == 58 || event.keyCode == 32 || chr == ':' || chr == ' ' || chrl == 'a' || chrl == 'p' || chrl == 'm'); } } else{ return $.datepicker._base_doKeyPress(event); } }; //####################################################################################### // override "Today" button to also grab the time. //####################################################################################### $.datepicker._base_gotoToday = $.datepicker._gotoToday; $.datepicker._gotoToday = function(id) { $.datepicker._base_gotoToday(id); var target = $(id); var dp_inst = this._getInst(target[0]); var tp_inst = $.datepicker._get(dp_inst, 'timepicker'); if(tp_inst){ var date = new Date(); var hour = date.getHours(); var minute = date.getMinutes(); var second = date.getSeconds(); //check if within min/max times.. if( (hour < tp_inst.defaults.hourMin || hour > tp_inst.defaults.hourMax) || (minute < tp_inst.defaults.minuteMin || minute > tp_inst.defaults.minuteMax) || (second < tp_inst.defaults.secondMin || second > tp_inst.defaults.secondMax) ){ hour = tp_inst.defaults.hourMin; minute = tp_inst.defaults.minuteMin; second = tp_inst.defaults.secondMin; } tp_inst.hour_slider.slider('value', hour ); tp_inst.minute_slider.slider('value', minute ); tp_inst.second_slider.slider('value', second ); tp_inst.onTimeChange(dp_inst, tp_inst); } }; //####################################################################################### // jQuery extend now ignores nulls! //####################################################################################### function extendRemove(target, props) { $.extend(target, props); for (var name in props) if (props[name] == null || props[name] == undefined) target[name] = props[name]; return target; }; $.timepicker = new Timepicker(true); // singleton instance })(jQuery);
import MessageBoxLayout2 from './FunctionalLayout/MessageBoxFunctionalLayout'; export default MessageBoxLayout2;
/** * @license * * Bring * loads data with several options (cache, callback, progress bar ...) * @author idomusha / https://github.com/idomusha * * Dependencies: * - NProgress [OPTIONAL] */ (function(window, $) { var s; var Bring = { defaults: { // processing status ready: true, // processing class class: 'js-bring-loading', // debug mode debug: false, oDataCache: {} }, options: {}, settings: {}, init: function() { // merge defaults and options, without modifying defaults explicitly this.settings = $.extend({}, this.defaults, this.options); s = this.settings; if (s.debug) console.log('##################### init()'); }, /** * AJAX request * generic function to load data * * @method load * @param {String} url (default: The current page): A string containing the URL to which the request is sent (path relative to the 'ajax/' directory ). * @param {String} returned (default: Intelligent Guess (xml, json, script, or html)): The type of data that you're expecting back from the server. * @param {Function} success: A function to be called if the request succeeds. * @param {Object or String} param: Data to be sent to the server. It is converted to a query string, if not already a string. * @param {String} request (default: 'GET'): The type of request to make ("POST" or "GET"). * @param {Boolean} [loader=false]: Active or not the pre-request callback function beforeSend. * @param {Boolean} [fail=false]: Active or not the error callback function (if the request fails). */ load: function(options) { options = $.extend({ url: '', returned: 'html', callback: null, param: {}, request: 'GET', loader: null, fail: null }, options); if (s.debug) console.log('##################### load()'); var loading; var after; var succeed; var failed; loading = function(jqXHR, settings) { if (s.debug) console.log('~~~~~~~~ beforeSend ~~~~~~~~'); s.ready = false; $('body').addClass(s.class); // loader specified if ($.isFunction(options.loader)) { eval(options.loader()); } // NProgress (default loader) : start try { NProgress.start(); } catch (e) { console.info('Bring: NProgress is not installed.'); } } after = function(jqXHR, textStatus ){ if (s.debug) console.log('~~~~~~~~ complete ~~~~~~~~'); s.ready = true; $('body').removeClass(s.class); // NProgress (default loader) : end try { NProgress.done(); } catch (e) { //console.log(e); } } succeed = function(data) { if (s.debug) console.log('~~~~~~~~ success ~~~~~~~~'); s.oDataCache[options.url] = data; // default callback // callback specified if ($.isFunction(options.callback)) { eval(options.callback(data)); } } failed = function(jqXHR, textStatus, errorThrown) { if (s.debug) console.log('~~~~~~~~ error ~~~~~~~~'); // callback specified if ($.isFunction(options.fail)) { eval(options.fail()); } } // Relative URL /*if (!(url.match('^http'))) { url = settingsGlobal.pathAjax + url; }*/ //console.log('url: '+url); //console.log('datType: '+returned); //console.log('success: '+callback); //console.log('data: '+param); //console.log('type: '+request); //console.log('beforeSend: '+loader); //console.log('error: '+fail); $.ajax({ cache: false, type: options.request, url: options.url, data: options.param, dataType: options.returned, error: failed, beforeSend: loading, complete: after, success: succeed }); }, destroy: function() { if (s.debug) console.log('##################### destroy()'); $.removeData(Bring.get(0)); }, refresh: function() { if (s.debug) console.log('##################### refresh()'); Bring.destroy(); Bring.init(); } } window.Bring = Bring; Bring.init(); })(window, jQuery);
// console.log("jo"); import CollectionDecrypted from './clients/collection-decrypted.js' import Blubb from './clients/blubb.js' var func = (...test) => { console.log(test); } func("dada","blubb"); new Blubb();
import _ from 'underscore'; const ROLES = { admin: 1, member: 2, }; const ROLES_BY_VALUE = _.invert(ROLES); /** * Return true if member is the passed role * * @param {Member} member * @param {String} role * @returns {Boolean} */ export function isRole(user, role) { return user.role === ROLES[role]; } /** * Return role of member * TODO: i18n this * * @param {Member} member * @returns {String} */ export function getRole(member) { return ROLES_BY_VALUE[member.role]; } /** * Return user decorated with membership * * @param {Object} user * @param {Object} membership * @returns {Object} */ export function getMember(user, membership) { return { ...user, role: membership.role, }; }
// see http://vuejs-templates.github.io/webpack for documentation. var path = require('path') module.exports = { build: { env: require('./prod.env'), index: path.resolve(__dirname, '../dist/index.html'), assetsRoot: path.resolve(__dirname, '../dist'), assetsSubDirectory: 'static', assetsPublicPath: '/', productionSourceMap: false, // Gzip off by default as many popular static hosts such as // Surge or Netlify already gzip all static assets for you. // Before setting to `true`, make sure to: // npm install --save-dev compression-webpack-plugin productionGzip: false, productionGzipExtensions: ['js', 'css'], // Run the build command with an extra argument to // View the bundle analyzer report after build finishes: // `npm run build --report` // Set to `true` or `false` to always turn it on or off bundleAnalyzerReport: process.env.npm_config_report, port: 8080, autoOpenBrowser: true }, dev: { env: require('./dev.env'), port: 8080, autoOpenBrowser: true, assetsSubDirectory: 'static', assetsPublicPath: '/', proxyTable: { '/apis': { target: 'https://apis.map.qq.com', changeOrigin: true, pathRewrite: { '^/apis': '' } } }, // CSS Sourcemaps off by default because relative paths are "buggy" // with this option, according to the CSS-Loader README // (https://github.com/webpack/css-loader#sourcemaps) // In our experience, they generally work as expected, // just be aware of this issue when enabling this option. cssSourceMap: false } }
const { task, series, parallel, src, dest, watch } = require('gulp'); const browserify = require('browserify'); const source = require('vinyl-source-stream'); const buffer = require('vinyl-buffer'); const header = require('gulp-header'); const concat = require('gulp-concat'); const uglify = require('gulp-uglify'); const csso = require('gulp-csso'); const sourcemaps = require('gulp-sourcemaps'); const pkg = require('./package.json'); const banner = `/*! * <%= pkg.title %> - <%= pkg.version %> * <%= pkg.description %> * * <%= pkg.homepage %> * * Copyright <%= pkg.author %> * Released under the <%= pkg.license %> license. */` let browserifyConfig = { debug: false }; task('dev', done => { browserifyConfig = { debug: true }; done(); }); task('browserify', () => browserify(Object.assign({ entries: './src/ui.js' }, browserifyConfig)) .bundle() .pipe(source('astrobench.js')) .pipe(buffer()) .pipe(sourcemaps.init({ loadMaps: true })) .pipe(header(banner, { pkg: pkg })) .on('error', () => this.emit('end')) .pipe(sourcemaps.write('./')) .pipe(dest('./dist/'))); task('uglify', () => src('./dist/astrobench.js') .pipe(uglify({ output: { comments: 'some' } })) .pipe(concat('astrobench.min.js')) .pipe(dest('./dist/'))); task('copy-style', () => src('./src/style.css') .pipe(concat('astrobench.css')) .pipe(dest('./dist/'))); task('minify-style', () => src('./dist/astrobench.css') .pipe(sourcemaps.init()) .pipe(csso()) .pipe(sourcemaps.write('./')) .pipe(dest('./dist/'))); task('default', parallel( series('browserify', 'uglify'), series('copy-style', 'minify-style'))); task('watch', () => { watch(['src/**/*.js', 'src/**/*.html'], series('dev', 'browserify')); watch('src/**/*.css', series('copy-style')); });
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = preserveLineNumbers; var _jsdocRegex = _interopRequireDefault(require("jsdoc-regex")); var _countCharInRange = _interopRequireDefault(require("./countCharInRange")); var _stripWhitespace = _interopRequireDefault(require("./stripWhitespace")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function preserveLineNumbers(source) { var regex = (0, _jsdocRegex["default"])(); var doclets = {}; var lastIndex = 0; var linesCount = 1; var match = regex.exec(source); while (match !== null) { var _match = match, index = _match.index; var key = (0, _stripWhitespace["default"])(match[0]); linesCount += (0, _countCharInRange["default"])(source, lastIndex, index, '\n'); doclets[key] = linesCount; lastIndex = index; match = regex.exec(source); } return doclets; }
/** * @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 */ // THIS CODE IS GENERATED - DO NOT MODIFY // See angular/tools/gulp-tasks/cldr/extract.js (function(global) { global.ng = global.ng || {}; global.ng.common = global.ng.common || {}; global.ng.common.locales = global.ng.common.locales || {}; const u = undefined; function plural(n) { let i = Math.floor(Math.abs(n)); if (i === Math.floor(i) && i >= 0 && i <= 1) return 1; return 5; } global.ng.common.locales['pt-mz'] = [ 'pt-MZ', [['a.m.', 'p.m.'], u, ['da manhã', 'da tarde']], [['a.m.', 'p.m.'], u, ['manhã', 'tarde']], [ ['D', 'S', 'T', 'Q', 'Q', 'S', 'S'], ['domingo', 'segunda', 'terça', 'quarta', 'quinta', 'sexta', 'sábado'], [ 'domingo', 'segunda-feira', 'terça-feira', 'quarta-feira', 'quinta-feira', 'sexta-feira', 'sábado' ], ['domingo', 'segunda', 'terça', 'quarta', 'quinta', 'sexta', 'sábado'] ], u, [ ['J', 'F', 'M', 'A', 'M', 'J', 'J', 'A', 'S', 'O', 'N', 'D'], [ 'jan.', 'fev.', 'mar.', 'abr.', 'mai.', 'jun.', 'jul.', 'ago.', 'set.', 'out.', 'nov.', 'dez.' ], [ 'janeiro', 'fevereiro', 'março', 'abril', 'maio', 'junho', 'julho', 'agosto', 'setembro', 'outubro', 'novembro', 'dezembro' ] ], u, [['a.C.', 'd.C.'], u, ['antes de Cristo', 'depois de Cristo']], 0, [6, 0], ['dd/MM/yy', 'dd/MM/y', 'd \'de\' MMMM \'de\' y', 'EEEE, d \'de\' MMMM \'de\' y'], ['HH:mm', 'HH:mm:ss', 'HH:mm:ss z', 'HH:mm:ss zzzz'], ['{1}, {0}', u, '{1} \'às\' {0}', u], [',', ' ', ';', '%', '+', '-', 'E', '×', '‰', '∞', 'NaN', ':'], ['#,##0.###', '#,##0%', '#,##0.00 ¤', '#E0'], 'MTn', 'metical moçambicano', { 'AUD': ['AU$', '$'], 'JPY': ['JP¥', '¥'], 'MZN': ['MTn'], 'PTE': ['​'], 'RON': [u, 'L'], 'THB': ['฿'], 'TWD': ['NT$'], 'USD': ['US$', '$'] }, 'ltr', plural, [ [ ['meia-noite', 'meio-dia', 'manhã', 'tarde', 'noite', 'madrugada'], ['meia-noite', 'meio-dia', 'da manhã', 'da tarde', 'da noite', 'da madrugada'], u ], [['meia-noite', 'meio-dia', 'manhã', 'tarde', 'noite', 'madrugada'], u, u], [ '00:00', '12:00', ['06:00', '12:00'], ['12:00', '19:00'], ['19:00', '24:00'], ['00:00', '06:00'] ] ] ]; })(typeof globalThis !== 'undefined' && globalThis || typeof global !== 'undefined' && global || typeof window !== 'undefined' && window);
// polyfill String.prototype if (typeof String.prototype.startsWith != 'function') { String.prototype.startsWith = function (str) { return this.slice(0, str.length) === str; }; } if (typeof String.prototype.endsWith != 'function') { String.prototype.endsWith = function (str) { return this.slice(-str.length) === str; }; } if (!String.prototype.includes) { String.prototype.includes = function (str) { return this.indexOf(str) !== -1; }; } // polyfill Array.prototype if (!Array.prototype.includes) { Array.prototype.includes = function(searchElement /*, fromIndex*/ ) { 'use strict'; var O = Object(this); var len = parseInt(O.length) || 0; if (len === 0) { return false; } var n = parseInt(arguments[1]) || 0; var k; if (n >= 0) { k = n; } else { k = len + n; if (k < 0) {k = 0;} } var currentElement; while (k < len) { currentElement = O[k]; if (searchElement === currentElement || (searchElement !== searchElement && currentElement !== currentElement)) { return true; } k++; } return false; }; }
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import type {ReactNodeList, Wakeable} from 'shared/ReactTypes'; import type {Fiber} from './ReactInternalTypes'; import type {SuspenseInstance} from './ReactFiberHostConfig'; import type {Lane} from './ReactFiberLane.new'; import {SuspenseComponent, SuspenseListComponent} from './ReactWorkTags'; import {NoFlags, DidCapture} from './ReactFiberFlags'; import { isSuspenseInstancePending, isSuspenseInstanceFallback, } from './ReactFiberHostConfig'; export type SuspenseProps = {| children?: ReactNodeList, fallback?: ReactNodeList, // TODO: Add "unstable_" prefix? suspenseCallback?: (Set<Wakeable> | null) => mixed, unstable_expectedLoadTime?: number, |}; // A null SuspenseState represents an unsuspended normal Suspense boundary. // A non-null SuspenseState means that it is blocked for one reason or another. // - A non-null dehydrated field means it's blocked pending hydration. // - A non-null dehydrated field can use isSuspenseInstancePending or // isSuspenseInstanceFallback to query the reason for being dehydrated. // - A null dehydrated field means it's blocked by something suspending and // we're currently showing a fallback instead. export type SuspenseState = {| // If this boundary is still dehydrated, we store the SuspenseInstance // here to indicate that it is dehydrated (flag) and for quick access // to check things like isSuspenseInstancePending. dehydrated: null | SuspenseInstance, // Represents the lane we should attempt to hydrate a dehydrated boundary at. // OffscreenLane is the default for dehydrated boundaries. // NoLane is the default for normal boundaries, which turns into "normal" pri. retryLane: Lane, |}; export type SuspenseListTailMode = 'collapsed' | 'hidden' | void; export type SuspenseListRenderState = {| isBackwards: boolean, // The currently rendering tail row. rendering: null | Fiber, // The absolute time when we started rendering the most recent tail row. renderingStartTime: number, // The last of the already rendered children. last: null | Fiber, // Remaining rows on the tail of the list. tail: null | Fiber, // Tail insertions setting. tailMode: SuspenseListTailMode, // Last Effect before we rendered the "rendering" item. // Used to remove new effects added by the rendered item. lastEffect: null | Fiber, |}; export function shouldCaptureSuspense( workInProgress: Fiber, hasInvisibleParent: boolean, ): boolean { // If it was the primary children that just suspended, capture and render the // fallback. Otherwise, don't capture and bubble to the next boundary. const nextState: SuspenseState | null = workInProgress.memoizedState; if (nextState !== null) { if (nextState.dehydrated !== null) { // A dehydrated boundary always captures. return true; } return false; } const props = workInProgress.memoizedProps; // In order to capture, the Suspense component must have a fallback prop. if (props.fallback === undefined) { return false; } // Regular boundaries always capture. if (props.unstable_avoidThisFallback !== true) { return true; } // If it's a boundary we should avoid, then we prefer to bubble up to the // parent boundary if it is currently invisible. if (hasInvisibleParent) { return false; } // If the parent is not able to handle it, we must handle it. return true; } export function findFirstSuspended(row: Fiber): null | Fiber { let node = row; while (node !== null) { if (node.tag === SuspenseComponent) { const state: SuspenseState | null = node.memoizedState; if (state !== null) { const dehydrated: null | SuspenseInstance = state.dehydrated; if ( dehydrated === null || isSuspenseInstancePending(dehydrated) || isSuspenseInstanceFallback(dehydrated) ) { return node; } } } else if ( node.tag === SuspenseListComponent && // revealOrder undefined can't be trusted because it don't // keep track of whether it suspended or not. node.memoizedProps.revealOrder !== undefined ) { const didSuspend = (node.flags & DidCapture) !== NoFlags; if (didSuspend) { return node; } } else if (node.child !== null) { node.child.return = node; node = node.child; continue; } if (node === row) { return null; } while (node.sibling === null) { if (node.return === null || node.return === row) { return null; } node = node.return; } node.sibling.return = node.return; node = node.sibling; } return null; }
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import type {Dispatcher as DispatcherType} from 'react-reconciler/src/ReactInternalTypes'; import type { Destination, Chunk, BundlerConfig, ModuleMetaData, ModuleReference, ModuleKey, } from './ReactFlightServerConfig'; import { scheduleWork, beginWriting, writeChunk, completeWriting, flushBuffered, close, processModelChunk, processModuleChunk, processSymbolChunk, processErrorChunk, resolveModuleMetaData, getModuleKey, isModuleReference, } from './ReactFlightServerConfig'; import { REACT_ELEMENT_TYPE, REACT_FORWARD_REF_TYPE, REACT_FRAGMENT_TYPE, REACT_LAZY_TYPE, REACT_MEMO_TYPE, } from 'shared/ReactSymbols'; import ReactSharedInternals from 'shared/ReactSharedInternals'; import invariant from 'shared/invariant'; const isArray = Array.isArray; type ReactJSONValue = | string | boolean | number | null | $ReadOnlyArray<ReactJSONValue> | ReactModelObject; export type ReactModel = | React$Element<any> | string | boolean | number | null | Iterable<ReactModel> | ReactModelObject; type ReactModelObject = {+[key: string]: ReactModel}; type Segment = { id: number, query: () => ReactModel, ping: () => void, }; export type Request = { destination: Destination, bundlerConfig: BundlerConfig, cache: Map<Function, mixed>, nextChunkId: number, pendingChunks: number, pingedSegments: Array<Segment>, completedModuleChunks: Array<Chunk>, completedJSONChunks: Array<Chunk>, completedErrorChunks: Array<Chunk>, writtenSymbols: Map<Symbol, number>, writtenModules: Map<ModuleKey, number>, flowing: boolean, toJSON: (key: string, value: ReactModel) => ReactJSONValue, }; const ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher; export function createRequest( model: ReactModel, destination: Destination, bundlerConfig: BundlerConfig, ): Request { const pingedSegments = []; const request = { destination, bundlerConfig, cache: new Map(), nextChunkId: 0, pendingChunks: 0, pingedSegments: pingedSegments, completedModuleChunks: [], completedJSONChunks: [], completedErrorChunks: [], writtenSymbols: new Map(), writtenModules: new Map(), flowing: false, toJSON: function(key: string, value: ReactModel): ReactJSONValue { return resolveModelToJSON(request, this, key, value); }, }; request.pendingChunks++; const rootSegment = createSegment(request, () => model); pingedSegments.push(rootSegment); return request; } function attemptResolveElement( type: any, key: null | React$Key, ref: mixed, props: any, ): ReactModel { if (ref !== null && ref !== undefined) { // When the ref moves to the regular props object this will implicitly // throw for functions. We could probably relax it to a DEV warning for other // cases. invariant( false, 'Refs cannot be used in server components, nor passed to client components.', ); } if (typeof type === 'function') { // This is a server-side component. return type(props); } else if (typeof type === 'string') { // This is a host element. E.g. HTML. return [REACT_ELEMENT_TYPE, type, key, props]; } else if (typeof type === 'symbol') { if (type === REACT_FRAGMENT_TYPE) { // For key-less fragments, we add a small optimization to avoid serializing // it as a wrapper. // TODO: If a key is specified, we should propagate its key to any children. // Same as if a server component has a key. return props.children; } // This might be a built-in React component. We'll let the client decide. // Any built-in works as long as its props are serializable. return [REACT_ELEMENT_TYPE, type, key, props]; } else if (type != null && typeof type === 'object') { if (isModuleReference(type)) { // This is a reference to a client component. return [REACT_ELEMENT_TYPE, type, key, props]; } switch (type.$$typeof) { case REACT_FORWARD_REF_TYPE: { const render = type.render; return render(props, undefined); } case REACT_MEMO_TYPE: { return attemptResolveElement(type.type, key, ref, props); } } } invariant( false, 'Unsupported server component type: %s', describeValueForErrorMessage(type), ); } function pingSegment(request: Request, segment: Segment): void { const pingedSegments = request.pingedSegments; pingedSegments.push(segment); if (pingedSegments.length === 1) { scheduleWork(() => performWork(request)); } } function createSegment(request: Request, query: () => ReactModel): Segment { const id = request.nextChunkId++; const segment = { id, query, ping: () => pingSegment(request, segment), }; return segment; } function serializeByValueID(id: number): string { return '$' + id.toString(16); } function serializeByRefID(id: number): string { return '@' + id.toString(16); } function escapeStringValue(value: string): string { if (value[0] === '$' || value[0] === '@') { // We need to escape $ or @ prefixed strings since we use those to encode // references to IDs and as special symbol values. return '$' + value; } else { return value; } } function isObjectPrototype(object): boolean { if (!object) { return false; } // $FlowFixMe const ObjectPrototype = Object.prototype; if (object === ObjectPrototype) { return true; } // It might be an object from a different Realm which is // still just a plain simple object. if (Object.getPrototypeOf(object)) { return false; } const names = Object.getOwnPropertyNames(object); for (let i = 0; i < names.length; i++) { if (!(names[i] in ObjectPrototype)) { return false; } } return true; } function isSimpleObject(object): boolean { if (!isObjectPrototype(Object.getPrototypeOf(object))) { return false; } const names = Object.getOwnPropertyNames(object); for (let i = 0; i < names.length; i++) { const descriptor = Object.getOwnPropertyDescriptor(object, names[i]); if (!descriptor) { return false; } if (!descriptor.enumerable) { if ( (names[i] === 'key' || names[i] === 'ref') && typeof descriptor.get === 'function' ) { // React adds key and ref getters to props objects to issue warnings. // Those getters will not be transferred to the client, but that's ok, // so we'll special case them. continue; } return false; } } return true; } function objectName(object): string { const name = Object.prototype.toString.call(object); return name.replace(/^\[object (.*)\]$/, function(m, p0) { return p0; }); } function describeKeyForErrorMessage(key: string): string { const encodedKey = JSON.stringify(key); return '"' + key + '"' === encodedKey ? key : encodedKey; } function describeValueForErrorMessage(value: ReactModel): string { switch (typeof value) { case 'string': { return JSON.stringify( value.length <= 10 ? value : value.substr(0, 10) + '...', ); } case 'object': { if (isArray(value)) { return '[...]'; } const name = objectName(value); if (name === 'Object') { return '{...}'; } return name; } case 'function': return 'function'; default: // eslint-disable-next-line return String(value); } } function describeObjectForErrorMessage( objectOrArray: | {+[key: string | number]: ReactModel} | $ReadOnlyArray<ReactModel>, expandedName?: string, ): string { if (isArray(objectOrArray)) { let str = '['; // $FlowFixMe: Should be refined by now. const array: $ReadOnlyArray<ReactModel> = objectOrArray; for (let i = 0; i < array.length; i++) { if (i > 0) { str += ', '; } if (i > 6) { str += '...'; break; } const value = array[i]; if ( '' + i === expandedName && typeof value === 'object' && value !== null ) { str += describeObjectForErrorMessage(value); } else { str += describeValueForErrorMessage(value); } } str += ']'; return str; } else { let str = '{'; // $FlowFixMe: Should be refined by now. const object: {+[key: string | number]: ReactModel} = objectOrArray; const names = Object.keys(object); for (let i = 0; i < names.length; i++) { if (i > 0) { str += ', '; } if (i > 6) { str += '...'; break; } const name = names[i]; str += describeKeyForErrorMessage(name) + ': '; const value = object[name]; if ( name === expandedName && typeof value === 'object' && value !== null ) { str += describeObjectForErrorMessage(value); } else { str += describeValueForErrorMessage(value); } } str += '}'; return str; } } export function resolveModelToJSON( request: Request, parent: {+[key: string | number]: ReactModel} | $ReadOnlyArray<ReactModel>, key: string, value: ReactModel, ): ReactJSONValue { if (__DEV__) { // $FlowFixMe const originalValue = parent[key]; if (typeof originalValue === 'object' && originalValue !== value) { console.error( 'Only plain objects can be passed to client components from server components. ' + 'Objects with toJSON methods are not supported. Convert it manually ' + 'to a simple value before passing it to props. ' + 'Remove %s from these props: %s', describeKeyForErrorMessage(key), describeObjectForErrorMessage(parent), ); } } // Special Symbols switch (value) { case REACT_ELEMENT_TYPE: return '$'; case REACT_LAZY_TYPE: invariant( false, 'React Lazy Components are not yet supported on the server.', ); } // Resolve server components. while ( typeof value === 'object' && value !== null && value.$$typeof === REACT_ELEMENT_TYPE ) { // TODO: Concatenate keys of parents onto children. const element: React$Element<any> = (value: any); try { // Attempt to render the server component. value = attemptResolveElement( element.type, element.key, element.ref, element.props, ); } catch (x) { if (typeof x === 'object' && x !== null && typeof x.then === 'function') { // Something suspended, we'll need to create a new segment and resolve it later. request.pendingChunks++; const newSegment = createSegment(request, () => value); const ping = newSegment.ping; x.then(ping, ping); return serializeByRefID(newSegment.id); } else { // Something errored. We'll still send everything we have up until this point. // We'll replace this element with a lazy reference that throws on the client // once it gets rendered. request.pendingChunks++; const errorId = request.nextChunkId++; emitErrorChunk(request, errorId, x); return serializeByRefID(errorId); } } } if (value === null) { return null; } if (typeof value === 'object') { if (isModuleReference(value)) { const moduleReference: ModuleReference<any> = (value: any); const moduleKey: ModuleKey = getModuleKey(moduleReference); const writtenModules = request.writtenModules; const existingId = writtenModules.get(moduleKey); if (existingId !== undefined) { if (parent[0] === REACT_ELEMENT_TYPE && key === '1') { // If we're encoding the "type" of an element, we can refer // to that by a lazy reference instead of directly since React // knows how to deal with lazy values. This lets us suspend // on this component rather than its parent until the code has // loaded. return serializeByRefID(existingId); } return serializeByValueID(existingId); } try { const moduleMetaData: ModuleMetaData = resolveModuleMetaData( request.bundlerConfig, moduleReference, ); request.pendingChunks++; const moduleId = request.nextChunkId++; emitModuleChunk(request, moduleId, moduleMetaData); writtenModules.set(moduleKey, moduleId); if (parent[0] === REACT_ELEMENT_TYPE && key === '1') { // If we're encoding the "type" of an element, we can refer // to that by a lazy reference instead of directly since React // knows how to deal with lazy values. This lets us suspend // on this component rather than its parent until the code has // loaded. return serializeByRefID(moduleId); } return serializeByValueID(moduleId); } catch (x) { request.pendingChunks++; const errorId = request.nextChunkId++; emitErrorChunk(request, errorId, x); return serializeByValueID(errorId); } } if (__DEV__) { if (value !== null && !isArray(value)) { // Verify that this is a simple plain object. if (objectName(value) !== 'Object') { console.error( 'Only plain objects can be passed to client components from server components. ' + 'Built-ins like %s are not supported. ' + 'Remove %s from these props: %s', objectName(value), describeKeyForErrorMessage(key), describeObjectForErrorMessage(parent), ); } else if (!isSimpleObject(value)) { console.error( 'Only plain objects can be passed to client components from server components. ' + 'Classes or other objects with methods are not supported. ' + 'Remove %s from these props: %s', describeKeyForErrorMessage(key), describeObjectForErrorMessage(parent, key), ); } else if (Object.getOwnPropertySymbols) { const symbols = Object.getOwnPropertySymbols(value); if (symbols.length > 0) { console.error( 'Only plain objects can be passed to client components from server components. ' + 'Objects with symbol properties like %s are not supported. ' + 'Remove %s from these props: %s', symbols[0].description, describeKeyForErrorMessage(key), describeObjectForErrorMessage(parent, key), ); } } } } return value; } if (typeof value === 'string') { return escapeStringValue(value); } if ( typeof value === 'boolean' || typeof value === 'number' || typeof value === 'undefined' ) { return value; } if (typeof value === 'function') { if (/^on[A-Z]/.test(key)) { invariant( false, 'Event handlers cannot be passed to client component props. ' + 'Remove %s from these props if possible: %s\n' + 'If you need interactivity, consider converting part of this to a client component.', describeKeyForErrorMessage(key), describeObjectForErrorMessage(parent), ); } else { invariant( false, 'Functions cannot be passed directly to client components ' + "because they're not serializable. " + 'Remove %s (%s) from this object, or avoid the entire object: %s', describeKeyForErrorMessage(key), value.displayName || value.name || 'function', describeObjectForErrorMessage(parent), ); } } if (typeof value === 'symbol') { const writtenSymbols = request.writtenSymbols; const existingId = writtenSymbols.get(value); if (existingId !== undefined) { return serializeByValueID(existingId); } const name = value.description; invariant( Symbol.for(name) === value, 'Only global symbols received from Symbol.for(...) can be passed to client components. ' + 'The symbol Symbol.for(%s) cannot be found among global symbols. ' + 'Remove %s from this object, or avoid the entire object: %s', value.description, describeKeyForErrorMessage(key), describeObjectForErrorMessage(parent), ); request.pendingChunks++; const symbolId = request.nextChunkId++; emitSymbolChunk(request, symbolId, name); writtenSymbols.set(value, symbolId); return serializeByValueID(symbolId); } // $FlowFixMe: bigint isn't added to Flow yet. if (typeof value === 'bigint') { invariant( false, 'BigInt (%s) is not yet supported in client component props. ' + 'Remove %s from this object or use a plain number instead: %s', value, describeKeyForErrorMessage(key), describeObjectForErrorMessage(parent), ); } invariant( false, 'Type %s is not supported in client component props. ' + 'Remove %s from this object, or avoid the entire object: %s', typeof value, describeKeyForErrorMessage(key), describeObjectForErrorMessage(parent), ); } function emitErrorChunk(request: Request, id: number, error: mixed): void { // TODO: We should not leak error messages to the client in prod. // Give this an error code instead and log on the server. // We can serialize the error in DEV as a convenience. let message; let stack = ''; try { if (error instanceof Error) { message = '' + error.message; stack = '' + error.stack; } else { message = 'Error: ' + (error: any); } } catch (x) { message = 'An error occurred but serializing the error message failed.'; } const processedChunk = processErrorChunk(request, id, message, stack); request.completedErrorChunks.push(processedChunk); } function emitModuleChunk( request: Request, id: number, moduleMetaData: ModuleMetaData, ): void { const processedChunk = processModuleChunk(request, id, moduleMetaData); request.completedModuleChunks.push(processedChunk); } function emitSymbolChunk(request: Request, id: number, name: string): void { const processedChunk = processSymbolChunk(request, id, name); request.completedModuleChunks.push(processedChunk); } function retrySegment(request: Request, segment: Segment): void { const query = segment.query; let value; try { value = query(); while ( typeof value === 'object' && value !== null && value.$$typeof === REACT_ELEMENT_TYPE ) { // TODO: Concatenate keys of parents onto children. const element: React$Element<any> = (value: any); // Attempt to render the server component. // Doing this here lets us reuse this same segment if the next component // also suspends. segment.query = () => value; value = attemptResolveElement( element.type, element.key, element.ref, element.props, ); } const processedChunk = processModelChunk(request, segment.id, value); request.completedJSONChunks.push(processedChunk); } catch (x) { if (typeof x === 'object' && x !== null && typeof x.then === 'function') { // Something suspended again, let's pick it back up later. const ping = segment.ping; x.then(ping, ping); return; } else { // This errored, we need to serialize this error to the emitErrorChunk(request, segment.id, x); } } } function performWork(request: Request): void { const prevDispatcher = ReactCurrentDispatcher.current; const prevCache = currentCache; ReactCurrentDispatcher.current = Dispatcher; currentCache = request.cache; const pingedSegments = request.pingedSegments; request.pingedSegments = []; for (let i = 0; i < pingedSegments.length; i++) { const segment = pingedSegments[i]; retrySegment(request, segment); } if (request.flowing) { flushCompletedChunks(request); } ReactCurrentDispatcher.current = prevDispatcher; currentCache = prevCache; } let reentrant = false; function flushCompletedChunks(request: Request): void { if (reentrant) { return; } reentrant = true; const destination = request.destination; beginWriting(destination); try { // We emit module chunks first in the stream so that // they can be preloaded as early as possible. const moduleChunks = request.completedModuleChunks; let i = 0; for (; i < moduleChunks.length; i++) { request.pendingChunks--; const chunk = moduleChunks[i]; if (!writeChunk(destination, chunk)) { request.flowing = false; i++; break; } } moduleChunks.splice(0, i); // Next comes model data. const jsonChunks = request.completedJSONChunks; i = 0; for (; i < jsonChunks.length; i++) { request.pendingChunks--; const chunk = jsonChunks[i]; if (!writeChunk(destination, chunk)) { request.flowing = false; i++; break; } } jsonChunks.splice(0, i); // Finally, errors are sent. The idea is that it's ok to delay // any error messages and prioritize display of other parts of // the page. const errorChunks = request.completedErrorChunks; i = 0; for (; i < errorChunks.length; i++) { request.pendingChunks--; const chunk = errorChunks[i]; if (!writeChunk(destination, chunk)) { request.flowing = false; i++; break; } } errorChunks.splice(0, i); } finally { reentrant = false; completeWriting(destination); } flushBuffered(destination); if (request.pendingChunks === 0) { // We're done. close(destination); } } export function startWork(request: Request): void { request.flowing = true; scheduleWork(() => performWork(request)); } export function startFlowing(request: Request): void { request.flowing = true; flushCompletedChunks(request); } function unsupportedHook(): void { invariant(false, 'This Hook is not supported in Server Components.'); } function unsupportedRefresh(): void { invariant( currentCache, 'Refreshing the cache is not supported in Server Components.', ); } let currentCache: Map<Function, mixed> | null = null; const Dispatcher: DispatcherType = { useMemo<T>(nextCreate: () => T): T { return nextCreate(); }, useCallback<T>(callback: T): T { return callback; }, useDebugValue(): void {}, useDeferredValue<T>(value: T): T { return value; }, useTransition(): [(callback: () => void) => void, boolean] { return [() => {}, false]; }, getCacheForType<T>(resourceType: () => T): T { invariant( currentCache, 'Reading the cache is only supported while rendering.', ); let entry: T | void = (currentCache.get(resourceType): any); if (entry === undefined) { entry = resourceType(); // TODO: Warn if undefined? currentCache.set(resourceType, entry); } return entry; }, readContext: (unsupportedHook: any), useContext: (unsupportedHook: any), useReducer: (unsupportedHook: any), useRef: (unsupportedHook: any), useState: (unsupportedHook: any), useLayoutEffect: (unsupportedHook: any), useImperativeHandle: (unsupportedHook: any), useEffect: (unsupportedHook: any), useOpaqueIdentifier: (unsupportedHook: any), useMutableSource: (unsupportedHook: any), useCacheRefresh(): <T>(?() => T, ?T) => void { return unsupportedRefresh; }, };
/** * 从原dialog迁过来,做了模块化封装 * 功能比较成熟了,代码不做大的改动 * 图片引入路径改成本地,工程化管理 */ 'use strict'; var imageLoader = require('imageLoader'); var images = [ __uri("i-loading.gif"), __uri("loading_2.gif") ]; //图片预加载 imageLoader(images); var d = {}; var docElem = document.documentElement, timeoutId = 0, dvWall = null, dvWrap = null, dialog = null; /** * util */ var util = { /** * 判断一个对象是否为数组 */ isArray: function (obj) { return (typeof Array.isArray) ? Array.isArray(obj) : (Object.prototype.toString.call(obj) === '[object Array]'); }, /** * 往body中插入div */ insertDom: function (newNode) { document.body.appendChild(newNode); }, /** * 初始化配置及生成dom元素 */ genDom: function (opts, div_wall, div_wrap) { if (!opts) return; if (Object.prototype.toString.call(opts, null) === '[object Object]') { // 传入的object opts.type = opts.type || "loading"; div_wall.style.cssText = opts.wallCss; div_wrap.style.cssText = opts.wrapCss; //生成弹窗内容 var html = "<div class='" + opts.type + "'>"; html += this.genIcon(opts.icon); html += this.genTitle(opts.title); html += this.genTip(opts); html += this.genButtons(opts.btns, opts.ext) + "</div>"; html += this.genClose(opts.close); div_wrap.innerHTML = html; } else if (Object.prototype.toString.call(opts, null) === '[object String]') { // 配置为html div_wrap.innerHTML = opts; } else if (Object.prototype.toString.call(opts, null) === '[object HTMLDivElement]') { // 传入的dom opts.style.display = "inline-block"; div_wrap.appendChild(opts); } }, /** * 生成icon相关的html */ genIcon: function (icon) { //默认无icon,true为默认icon if (!icon) return ""; return '<p class="d-icon ' + icon + '"></p>'; }, /** * Title的样式和HTML */ genTitle: function (title) { title = title || {}; if(title.txt){ title.color = title.color || ''; title.size = title.size || ''; title.cssText = title.cssText || ''; var cssText = 'color:' + title.color + ';font-size: ' + title.size + ';' + title.cssText; return '<p class="d-title" style="' + cssText + '">' + title.txt + '</p>'; }else{ return ""; } }, /** * 生成提示信息 */ genTip: function (opts) { var tip = opts.tip || {}, title = opts.title || {}; if(tip.txt){ if (title.txt) { tip.color = tip.color || "#666"; tip.size = tip.size || '1.4rem'; } else { tip.color = tip.color || "#333"; tip.size = tip.size || '1.6rem'; } var cssText = 'color:' + tip.color + ';font-size:' + tip.size + ';'; return '<div class="d-tip" style="' + cssText + '">' + tip.txt + '</div>'; }else{ return ""; } }, /** * 右上角关闭按钮 */ genClose: function (close) { return close ? '<a class="d-close" href="javascript:void(0);" style="' + (close.cssText || "") + '"></a>' : ''; }, /** * 尾部红包 */ genButtons: function (btns, ext) { var res = ""; if (btns && this.isArray(btns)) { res += '<div class="d-btns clearfix">'; for (var i = 0, btn = null, l = btns.length; i < l; i++) { btn = btns[i]; res += '<a class="' + btn.kls + '" id="' + btn.id + '">' + btn.val + '</a>'; } res += '</div>'; } //按钮下面附加内容 if (ext && typeof ext === 'string') { res += '<p class="d-ext">' + ext + '</p>'; } return res; }, /** * 为按钮注册事件 */ addEvents: function (opts) { if (opts.close) { var close = dvWrap.getElementsByClassName("d-close")[0]; close.addEventListener("touchstart", function () { dialog.hide(); }, false); } if (!this.isArray(opts.btns) || !opts.btns.length) return; for (var i = 0, btn = null, l = opts.btns.length; i < l; i++) { btn = opts.btns[i]; if (btn) { var ev = btn.event || "click", ele = document.getElementById(btn.id); if (ele) { ele.removeEventListener(ev, btn.handler, false); ele.addEventListener(ev, btn.handler, false); } } } } }; /** * Dialog对象应该使用强制使用new模式 */ var Dialog = function (opts) { if (!(this instanceof Dialog)) { dialog = new Dialog(opts); return dialog; // 当不使用new的时候,会走到前一句,然后再走到dialog.fn.init,然后再执行return } else { new Dialog.fn.init(opts); } }; /** * Dialog prototype * @type {Function} */ Dialog.fn = Dialog.prototype = { constructor: Dialog, init: function (opts) { if (timeoutId) { clearTimeout(timeoutId); timeoutId = 0; } if (!opts) return; var div_wall = document.createElement('div'); var div_wrap = document.createElement("div"); div_wall.id = "d-wall"; div_wrap.id = "d-wrap"; //初始化配置 生成内容HTML util.genDom(opts, div_wall, div_wrap); //删除已存在的弹窗 dvWall && document.body.removeChild(dvWall); dvWrap && document.body.removeChild(dvWrap); //插入dom util.insertDom(div_wall); util.insertDom(div_wrap); dvWall = div_wall; dvWrap = div_wrap; if (Object.prototype.toString.call(opts, null) === '[object Object]') { window.setTimeout(function () { util.addEvents(opts); }, 400); } }, show: function () { var that = this; if (dvWall && dvWrap) { that.reset(); dvWall.style.display = "block"; dvWrap.style.display = "inline-block"; window.addEventListener("resize", reset, false); window.addEventListener("scroll", reset, false); window.addEventListener('orientationchange',reset,false); } function reset(event) { that.reset.call(that); } }, hide: function () { if (dvWall && dvWrap) { dvWall.style.display = "none"; dvWrap.style.display = "none"; } }, reset: function () { if (dvWall && dvWrap) { var currWidth = $(window).width(); dvWrap.style.top = (docElem.clientHeight - dvWrap.clientHeight - 20) / 2 + "px"; dvWrap.style.left = (docElem.clientWidth - dvWrap.clientWidth) / 2 + "px"; var scrollH = document.body.scrollHeight || document.documentElement.scrollHeight; //考虑到页面滚动和窗体重置 dvWall.style.width = currWidth + "px"; dvWall.style.height = scrollH + "px"; } } }; /** * alert弹出框 */ d.alert = function (cfg) { var opts = {}; if (typeof arguments[0] === "string" && arguments[0]) { opts.title = arguments[1] || ""; opts.tip = arguments[0]; opts.btn = { btnclass:'btn-orange', val: arguments[2] || "我知道了" }; } else if (cfg && typeof cfg === 'object') { opts = cfg; } dialog = Dialog({ type: "alert", icon: opts.icon || "icon-alert", wallCss: "", wrapCss: "background: #fff;width: 280px;text-align: center;", title: { txt: opts.title }, tip: { txt: opts.tip }, btns: [{ id: "btn-close", kls: (opts.btn && opts.btn.btnclass) || 'btn-orange', event: "click", val: (opts.btn && opts.btn.val) || "我知道了", handler: function (ev) { dialog.hide(); if(opts.btn){ if (typeof opts.btn.handler === 'function') { opts.btn.handler(ev); } } } }] }); dialog.show(); return dialog; }; /** * confirm dialog */ d.confirm = function (cfg) { var opts = {}; if (typeof arguments[0] === 'string' && arguments[0]) { opts.text = arguments[0] || ""; opts.confirm = {}; opts.confirm.handler = arguments[1]; } else if (cfg && typeof cfg === 'object') { opts = cfg; } var cancel = opts.cancel || {}; var confirm = opts.confirm || {}; dialog = Dialog({ type: "confirm", title: { txt: opts.tip ? opts.text : "" }, tip: { txt: opts.tip ? opts.tip : opts.text }, icon: "icon-confirm", wallCss: "", wrapCss: "background: #fff;width: 280px;text-align: center;", btns: [{ id: cancel.id || "btn-cancel", val: cancel.val || "取消", kls: cancel.kls || "btn-white", event: cancel.event || "click", handler: function (e) { dialog.hide(); if (typeof cancel.handler === 'function') { cancel.handler(e); } } }, { id: confirm.id || "btn-ok", val: confirm.val || "确定", kls: confirm.kls || "btn-orange", event: confirm.event || "click", handler: function (e) { dialog.hide(); if (typeof confirm.handler === 'function') { confirm.handler(e); } } }], ext: opts.ext }); dialog.show(); return dialog; }; /** * Loading Dialog */ d.loading = function (cfg) { var opts = {}; if (typeof arguments[0] !== "object") { opts.text = arguments[0]; opts.time = arguments[1] || 0 } else { opts = cfg; } dialog = Dialog({ type: "loading", wallCss: "", wrapCss: "background:#0c0d0d;opacity:0.7;width:140px;height:140px;", icon: "icon-loading", tip: { txt: opts.text || "正在加载", color: "#fff", size: "14px" } }); dialog.show(); if (!opts.time) { opts.time = 5000; } timeoutId = window.setTimeout(function () { dialog.hide(); console.log(typeof opts.hideCB === 'function') if (typeof opts.hideCB === 'function') { opts.hideCB(); } }, opts.time); return dialog; }; /** * 扁平化的loading */ d.flatLoading = function (cfg) { var opts = {}; if (typeof arguments[0] !== "object") { opts.text = arguments[0]; opts.time = arguments[1] || 0 } else { opts = cfg; } dialog = Dialog({ type: "floading", wallCss: "background:#fff;opacity:1;", wrapCss: "background:#fff;width:140px;height:140px;", icon: "icon-flat", tip: { txt: opts.text || "", color: "#666", size: "14px" } }); dialog.show(); if (!opts.time) { opts.time = 5000; } timeoutId = window.setTimeout(function () { dialog.hide(); if (typeof opts.hideCB === 'function') { opts.hideCB(); } }, opts.time); return dialog; }; /** * 滴滴打车logo的loading */ d.logoLoading = function (time, hideCB) { dialog = Dialog('<div class="loading-logo"></div>'); dialog.show(); if (!time) { time = 5000; } timeoutId = window.setTimeout(function () { dialog.hide(); if (typeof hideCB === 'function') { hideCB(); } }, time); return dialog; }; /** //提示 */ d.tip = function (cfg) { var _cfg = {}; if (typeof arguments[0] !== "object") { _cfg.text = arguments[0]; _cfg.time = arguments[1] || 0 } else { _cfg = cfg; } _cfg.time = parseInt(_cfg.time) || 600; dialog = Dialog({ type: "tip", icon: cfg.icon || "icon-tip", wallCss: "background:#fff;", wrapCss: cfg.wrapCss || "background:#0c0d0d;width:140px;height:140px;opacity:0.7;", tip: cfg.tip || { txt: _cfg.text || "温馨提醒", color: "#fff", size: "14px" } }); dialog.show(); timeoutId = window.setTimeout(function () { dialog.hide(); }, _cfg.time); }; d.Fn = Dialog; module.exports = d;
import { moduleForComponent, test } from 'ember-qunit'; import hbs from 'htmlbars-inline-precompile'; moduleForComponent('fd-uml-diagram-toolbars/fd-std-toolbar', 'Integration | Component | fd uml diagram toolbars/fd std toolbar', { integration: true }); test('it renders', function(assert) { // Set any properties with this.set('myProperty', 'value'); // Handle any actions with this.on('myAction', function(val) { ... }); this.set('actions.toolbarButtonClicked', function() { }); this.render(hbs`{{fd-uml-diagram-toolbars/fd-std-toolbar toolbarButtonClicked=(action "toolbarButtonClicked")}}`); //assert.equal(this.$().text().trim(), ''); assert.equal('', ''); });
var gulp = require('gulp'); //服务器,开发 var devServer = require('./gulp/dev/server.dev.js'); gulp.task('connect', devServer); //更新所有less文件 开发 var devLess = require('./gulp/dev/less.dev.js'); gulp.task('changeLessDev', devLess); //js合并,开发 var devJs = require('./gulp/dev/js.dev.js'); gulp.task('changeJsDev', devJs); //ejs模板引擎 html 开发 var devEjs = require('./gulp/dev/ejs.dev.js'); gulp.task('fileIncludeDev', devEjs); //图片压缩 开发 var devImg = require('./gulp/dev/img.dev.js'); gulp.task('imageMinDev', devImg); //监听文件变化 gulp.task('devWatch', function () { //less文件修改 ,注入css gulp.watch('src/component/**/*.less', ['changeLessDev']); //html,js文件修改,重新拼接,刷新 gulp.watch(['src/**/**/*.{ejs,html}'], ["fileIncludeDev"]); //html,js文件修改,重新拼接,刷新 gulp.watch(['src/**/**/*.js'], ['changeJsDev']); }); //开发环境 gulp.task('.myServer', ['imageMinDev', 'changeLessDev', 'changeJsDev', 'fileIncludeDev', 'devWatch', 'connect']); /* //js压缩 交付 var distJs = require('./gulp/dist/js.dist.js'); gulp.task('distJs', distJs); //css压缩 交付 var distCss = require('./gulp/dist/css.dist.js'); gulp.task('distCss', distCss); //图片移动 var distImg = require('./gulp/dist/img.dist.js'); gulp.task('distImg', distImg); //清除 var distClean = require('./gulp/dist/clean.dist'); gulp.task('distClean', distClean); //html var distHtml = require('./gulp/dist/html.dist.js'); gulp.task('distHtml', distHtml); gulp.task('.dist', ['imageMinDev', 'changeLessDev', 'changeJsDev', 'fileIncludeDev','distClean'],function () { gulp.start('distJs', 'distCss', 'distImg', 'distHtml') });*/
const array = []; const characterCodeCache = []; export default function leven(first, second) { if (first === second) { return 0; } const swap = first; // Swapping the strings if `a` is longer than `b` so we know which one is the // shortest & which one is the longest if (first.length > second.length) { first = second; second = swap; } let firstLength = first.length; let secondLength = second.length; // Performing suffix trimming: // We can linearly drop suffix common to both strings since they // don't increase distance at all // Note: `~-` is the bitwise way to perform a `- 1` operation while (firstLength > 0 && (first.charCodeAt(~-firstLength) === second.charCodeAt(~-secondLength))) { firstLength--; secondLength--; } // Performing prefix trimming // We can linearly drop prefix common to both strings since they // don't increase distance at all let start = 0; while (start < firstLength && (first.charCodeAt(start) === second.charCodeAt(start))) { start++; } firstLength -= start; secondLength -= start; if (firstLength === 0) { return secondLength; } let bCharacterCode; let result; let temporary; let temporary2; let index = 0; let index2 = 0; while (index < firstLength) { characterCodeCache[index] = first.charCodeAt(start + index); array[index] = ++index; } while (index2 < secondLength) { bCharacterCode = second.charCodeAt(start + index2); temporary = index2++; result = index2; for (index = 0; index < firstLength; index++) { temporary2 = bCharacterCode === characterCodeCache[index] ? temporary : temporary + 1; temporary = array[index]; // eslint-disable-next-line no-multi-assign result = array[index] = temporary > result ? (temporary2 > result ? result + 1 : temporary2) : (temporary2 > temporary ? temporary + 1 : temporary2); } } return result; }
//Constants var Windows = { "main" : 0, "sprites" : 1 }; var positions = ["C", "1B", "2B", "SS", "3B", "LF", "CF", "RF", "P"]; var teamVariables = ["city", "teamName", "teamShortName", "league", "stadiumName", "stadiumFile", "stadiumLocation", "teamLogoX", "teamLogoY", "stadiumLogoX", "stadiumLogoY", "managerFirstName", "managerLastName", "managerNickname"]; var teamUniformColorTypes = ["logoBase", "logoTrim", "cap", "capLogo", "shirtTrim", "socks", "undershirt", "pantsTrim", "belt", "number"]; var teamUniformVariables = ["shirtType", "pantsType", "logoType", "numberType"]; var playerColors = ["skinColor", "hairColor"]; var playerAttributes = ["endurance", "throwingArm", "fielding", "durability", "runningSpeed", "clutch", "battingPower", "battingContact", "pitchPower", "pitchControl", "pitchMovement"]; var playerVariables = ["position", "battingHand", "throwingHand", "height", "weight", "firstName", "lastName", "nickname", "number", "facialHairType", "hairType"]; var textureArray = null; //Where we store our loaded in textures var resourcesDirectory = null; var plistTextureKeys = []; var plistFiles = []; var rosterDataArray = {}; var selectedSprite = null; var prevSelectedSprite = null; var selectedSpriteX = null; //These are actually the identifiers to find this sprite within textureArray (textureArray[x][y]) var selectedSpriteY = null; var numberOfTeams = 0; var deletedTeamNumbers = []; //We hold all deleted team numbers here so we can reuse them. var selectedTeam = null; var prevSelectedTeam = null; var selectedPlayer = null; var prevSelectedPlayer = null; function resetGlobals(){ textureArray = null; //Where we store our loaded in textures resourcesDirectory = null; plistTextureKeys = []; plistFiles = []; rosterDataArray = {}; rosterDataArray["teams"] = {}; selectedSprite = null; prevSelectedSprite = null; selectedSpriteX = null; selectedSpriteY = null; numberOfTeams = 0; deletedTeamNumbers = []; selectedTeam = null; prevSelectedTeam = null; selectedPlayer = null; prevSelectedPlayer = null; } function init() { initMenu(); initHandlers(); resetGlobals(); initWindow(".window"); initSliders(); } function initHandlers(){ } function initSliders(){ $(".slider").slider({ min:1, max:10, step:1, value:1 }); $(".slider").slider({ slide: function(event, ui) { document.getElementById(this.id.replace("Slider","")).value = ui.value; } }); } function createMainMenu(){ var mainMenu = Titanium.UI.createMenu(); mainMenu.appendItem(Titanium.UI.createMenuItem("File")); var fileMenu = Titanium.UI.createMenu(); fileMenu.appendItem(Titanium.UI.createMenuItem("Open Roster File", function() { fileOpenRosterFile(); })); fileMenu.appendItem(Titanium.UI.createMenuItem("Save Roster File", function() { fileSaveRosterFile(); })); fileMenu.appendItem(Titanium.UI.createMenuItem("Close Roster File", function() { fileCloseRosterFile(); })); fileMenu.appendItem(Titanium.UI.createMenuItem("Quit", function() { fileQuit(); })); mainMenu.getItemAt(0).setSubmenu(fileMenu); mainMenu.appendItem(Titanium.UI.createMenuItem("Resources")); var resourcesMenu = Titanium.UI.createMenu(); resourcesMenu.appendItem(Titanium.UI.createMenuItem("Specify Resource Folder", function() { try{ resourcesSpecifyResourceFolder(); }catch(err){alert(err);} })); resourcesMenu.appendItem(Titanium.UI.createMenuItem("Reload Resources", function() { resourcesReloadResources(); })); mainMenu.getItemAt(1).setSubmenu(resourcesMenu); return mainMenu; }
'use strict'; const expect = require('chai').expect; const testQuarkTo = require('./testAtomicQuarkTo'); const testQuarkIs = require('./testAtomicQuarkIs'); const testQuarkIsIn = (testName, element, list, valueToTest) => { it('testando: '+element, () => { let validated = require('./../'+testName+'/'+testName)(element, list); expect(validated).to.equal(valueToTest); }); }; // Definimos os tipos de testes const typesTest = require('./config/testTypes'); module.exports = (testName, describes) => { const defineType = (element) => { return (testName.indexOf(element) > -1) } const defineTypeTest = (testName, types) => { return types.filter(defineType); }; // Pego apenas o primeiro pois ele eh mais específico // Ja que com isIN ele acha tanto isIn como is // Sendo esse o retorno [ 'isIn', 'is' ] const typesTest = require('./config/testTypes'); let typeToTest = defineTypeTest(testName, typesTest)[0]; const isTestTo = require('./config/isTest')(typeToTest, 'to'); const isTestIs = require('./config/isTest')(typeToTest, 'is'); const isTestIsIn = require('./config/isTest')(typeToTest, 'isIn'); let test = (values, valueToTest) => { if(isTestTo) testQuarkTo.test(testName, values, valueToTest, describes); else testQuarkIs.test(testName, values, valueToTest, describes); }; if(isTestIsIn) { if(describes[0].list) { const list = describes.splice(0,1)[0].list; test = (values, valueToTest) => { values.forEach( (element) => { testQuarkIsIn(testName, element, list, valueToTest); }); }; } } describe(testName, () => { describes.forEach( (element, index) => { if(element.type) { describe(element.message, () => { test(element.values, element.type); }); } else { describe(element.message, () => { test(element.values, element.type); }); } if(element.list) return true; }); }); };
import { SIGN_UP_SUCCESS, SIGNING_UP, SIGN_UP_FAILURE, } from '../actions/types'; const initialState = {}; const signUp = (state = initialState, action) => { switch (action.type) { case SIGN_UP_FAILURE: return { ...state, isSigningUp: false, user: null, }; case SIGNING_UP: return { ...state, isSigningUp: true, user: null, }; case SIGN_UP_SUCCESS: return { ...state, isSigningUp: false, user: action.user, }; default: return state; } }; export default signUp;
// To make use of this class instantiate a new instance and pass in an array with an element id at index 0, // optionally pass the interval time in milliseconds to index 1 in the array. After the array pass the words you // you want to use as individual arguments. Then call the runInfinitely() or runOnce() method on the new instance. // Example: // var cycle = new CycleText(["dynamic-text"], "collaborative", "thorough", "fun", "problem-solving", "modern", "Reax") // cycle.runInfinitely() || cycle.runOnce() export class CycleText { constructor([id, interval = 2500], ...words ) { this.words = words; this.adjectivesIndex = 0; this.hasTarget = !!(document.getElementById(id)); this.interval = interval; this.wordslength = this.words.length; this.target = document.getElementById(id); // Bind the lexical this scope from the class to the methods we need to access it in. this.setNextIndex = this.setNextIndex.bind(this); this.runInfinitely = this.runInfinitely.bind(this); this.runOnce = this.runOnce.bind(this); } addAnimateIn() { let div = this.target; div.classList.remove("embellish-text"); div.classList.remove("cycle-animate-out"); div.classList.add("cycle-animate-in"); this.addEmbelishTextIfOnLastWord(); } addAnimateOut() { let div = this.target; div.classList.remove("cycle-animate-in"); div.classList.add("cycle-animate-out"); } addEmbelishTextIfOnLastWord() { if (this.secondToLastWord()) this.target.classList.add("embellish-text"); } havntLoopedThroughListOnceAlready() {return this.adjectivesIndex > 0} insertNextWord() { this.addAnimateIn(); this.target.innerHTML = ` ${this.words[this.adjectivesIndex]}`; this.setNextIndex(); } runInfinitely () { let interval = this.secondToLastWord() ? this.interval*3.5 : this.interval; if (this.hasTarget) { this.insertNextWord(); window.setTimeout(()=>{ this.addAnimateOut(); window.setTimeout(()=> { this.runInfinitely(); }, interval*.30); }, interval*.70) } } runOnce() { if (this.hasTarget) { this.insertNextWord(); if (this.havntLoopedThroughListOnceAlready()) { window.setTimeout(()=>{ this.addAnimateOut(); window.setTimeout(()=> { this.runOnce(); }, this.interval*.20); }, this.interval*.80) } } } secondToLastWord() {return this.adjectivesIndex == this.wordslength -1} setNextIndex() { this.adjectivesIndex = this.adjectivesIndex < this.wordslength -1 ? this.adjectivesIndex += 1 : 0; } }
'use strict'; const path = require('path'); // Register TS compilation. require('ts-node').register({ project: path.join(__dirname, 'tools/gulp/tsconfig.json') }); require('./tools/gulp/gulpfile');
'use strict'; exports.__esModule = true; exports.load = load; exports.preload = preload; var _auth0Js = require('auth0-js'); var _auth0Js2 = _interopRequireDefault(_auth0Js); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } if (!global.Auth0) { global.Auth0 = {}; } var cbs = {}; function load(attrs) { var cb = attrs.cb, check = attrs.check, method = attrs.method, url = attrs.url; if (!cbs[method]) { cbs[method] = []; global.Auth0[method] = function () { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } cbs[method] = cbs[method].filter(function (x) { if (x.check.apply(x, args)) { setTimeout(function () { return x.cb.apply(x, [null].concat(args)); }, 0); return false; } else { return true; } }); }; } cbs[method].push({ cb: cb, check: check, url: url }); var count = cbs[method].reduce(function (r, x) { return r + (x.url === url ? 1 : 0); }, 0); if (count > 1) return; var script = global.document.createElement('script'); script.src = url; global.document.getElementsByTagName('head')[0].appendChild(script); var handleError = function handleError(err) { cbs[method] = cbs[method].filter(function (x) { if (x.url === url) { setTimeout(function () { return x.cb(err); }, 0); return false; } else { return true; } }); }; var timeoutID = setTimeout(function () { return handleError(new Error(url + ' timed out')); }, 20000); script.addEventListener('load', function () { return clearTimeout(timeoutID); }); script.addEventListener('error', function () { clearTimeout(timeoutID); handleError(new Error(url + ' could not be loaded.')); }); } function preload(_ref) { var method = _ref.method, cb = _ref.cb; global.Auth0[method] = cb; }
define(["jquery", "modules"], function ($, modules) { var url = modules.config.apiURL + "Message/All?teamWorkId="; function run(id) { //modules.request.get(url + id) //.then(function (requestData) { // $("#single-message").loadTemplate([requestData]); //}, function () { // // modules.redirect("#/messages/" + id); //}); //modules.request.get(modules.config.apiURL + "assignment/ByTeamwork/" + id) //.then(function (requestData) { // console.log(requestData); // $("#assignments").loadTemplate(requestData); //}, function () { // modules.redirect("#/teamwork/" + id); //}); } return { run: run } });
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _express = require('express'); var _express2 = _interopRequireDefault(_express); var router = _express2['default'].Router(); router.get('/', function (req, res, next) { res.redirect('/blog'); next(); }); router.use('/manager', _express2['default']['static']('manager/dist')); router.use('/manager', _express2['default']['static']('manager/.tmp/partials')); router.use('/about', _express2['default']['static']('public/about')); router.use('/manager/app', _express2['default']['static']('manager/.tmp/serve/app')); router.use('/lib', _express2['default']['static']('manager/lib')); router.use('/galleries', _express2['default']['static']('./galleries')); router.use('/blog', _express2['default']['static']('./public/uke-blog-web')); exports['default'] = router; module.exports = exports['default'];
var chai = require('chai'), assert = chai.assert, client = require('./client').client; chai.Assertion.includeStack = true; describe('Workplane', function() { before(function(done) { this.timeout(5000); client.initDesign(done); }); beforeEach(function(done) { this.timeout(5000); client.freshDesign(done); }); after(function(done) { client.end(done); }); // ---------- Cases ---------- it('can have different snap values', function(done) { this.timeout(10000); client .click('.toolbar .settings') .clearElement('#dialog .gridsize') .setValue('#dialog .gridsize', '5') .click('#dialog .button') .click('.toolbar .point') .moveToWorld(3,3,0) .assertCoordinateEqual('.vertex.editing .coordinate', 5, 5, 0, done); }); it('will not change the gridsize if there are errors', function(done) { this.timeout(10000); client .click('#dialog .settings') .clearElement('#dialog .gridsize') .setValue('#dialog .gridsize', '##') .click('#dialog .button') .hasClass('#dialog .gridsize', 'error', done) }); });
const fs = require("fs"); const path = require("path"); const test262Parser = require("test262-parser"); const glob = require("glob").sync; const test262Root = path.join(__dirname, "..", "deps", "test262"); const harnessDir = path.join(test262Root, "harness"); const root = path.join(test262Root, "test"); const dst = path.join(__dirname, "..", "samples", "src", "test262"); const ignore = [ // the tests are in global scope but we inject them into a function // however for the purposes it is not important, that's for parser "**/await-BindingIdentifier-in-global.js", "**/await-in-function.js", "**/await-in-nested-function.js", "**/await-in-generator.js", "**/await-in-nested-generator.js", "**/await-in-global.js", // some babylon problems? "**/async-func-decl-dstr-array-rest-nested-obj*.js", "**/async-gen-decl-dstr-array-rest-nested-obj*.js", "**/*rest-ary*.js", "**/*rest-obj*.js" ]; const includes = glob("*.js", { cwd: harnessDir }).map(i => fs.readFileSync(path.join(harnessDir, i), "utf-8") ); /* mochaBDD( `language/ expressions/ {async-*,yield,await} /*.js`.replace(/\s/g, ""), "expressions" ); mochaBDD( `language/ statements/ {async-*,for-await-of,generators} /*.js`.replace(/\s/g, ""), "statements" ); */ /** * converts files returned by glob `pat` and `opts` into mocha BDD test case * */ function mochaBDD(pat, suite) { const tests = {}; const res = [...includes]; for (const i of glob(pat, { cwd: root, ignore })) { const ext = path.extname(i); if (ext !== ".js") continue; const file = path.join(root, i); const contents = fs.readFileSync(file, "utf-8"); const result = { file, contents }; test262Parser.parseFile(result); if (result.attrs.negative && result.attrs.negative.phase === "early") continue; const dirs = []; for (let j = i; (j = path.dirname(j)) !== "."; ) dirs.unshift(path.basename(j)); let dir = tests; for (const j of dirs) dir = dir[j] || (dir[j] = {}); (dir.$ || (dir.$ = [])).push(result); } function walkDirs(obj, name) { res.push(`describe("${name}",function() {`); for (const i in obj) if (i !== "$") walkDirs(obj[i], i); if (obj.$) { for (const i of obj.$) { const descr = (!process.env.TEST262_NO_DESCR && i.attrs.description) || path.basename(i.file, ".js"); if (!process.env.TEST262_NO_STRICT) if (i.attrs.flags.raw || i.attrs.flags.noStrict) continue; res.push(`it("${trim(descr).replace(/"/g, '\\"')}", function(${i.async ? "$DONE" : ""}) {`); if (process.env.TEST262_NO_STRICT && i.attrs.strictOnly) res.push(`"use strict;"`); if (!process.env.TEST262_NO_DESCR) { res.push("/*"); res.push( JSON.stringify( i.attrs, i => i !== "description" && i !== "info" && i, 2 ) ); res.push(`PATH:${path.relative(test262Root, i.file)}`); res.push(i.copyright); res.push(i.attrs.info); res.push("*/"); } res.push(i.contents); res.push(`})/*${path.basename(i.file, ".js")}*/`); } } res.push(`})/*${name}*/`); } walkDirs(tests, `test262 ${suite}`); console.log(`generated test262 suite ${suite} at ${dst}`); fs.writeFileSync(path.join(dst, suite + ".js"), res.join("\n")); } function trim(str) { return str.trim().replace(/(\r\n|\n|\r)/gm, ""); }
/** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @providesModule ReactChildFiber * @flow */ 'use strict'; import type {ReactElement} from 'ReactElementType'; import type {ReactCoroutine, ReactPortal, ReactYield} from 'ReactTypes'; import type {Fiber} from 'ReactFiber'; import type {ExpirationTime} from 'ReactFiberExpirationTime'; var {REACT_COROUTINE_TYPE, REACT_YIELD_TYPE} = require('ReactCoroutine'); var {REACT_PORTAL_TYPE} = require('ReactPortal'); var ReactFiber = require('ReactFiber'); var ReactTypeOfSideEffect = require('ReactTypeOfSideEffect'); var ReactTypeOfWork = require('ReactTypeOfWork'); var emptyObject = require('fbjs/lib/emptyObject'); var invariant = require('fbjs/lib/invariant'); if (__DEV__) { var {getCurrentFiberStackAddendum} = require('ReactDebugCurrentFiber'); var warning = require('fbjs/lib/warning'); var didWarnAboutMaps = false; /** * Warn if there's no key explicitly set on dynamic arrays of children or * object keys are not valid. This allows us to keep track of children between * updates. */ var ownerHasKeyUseWarning = {}; var ownerHasFunctionTypeWarning = {}; var warnForMissingKey = (child: mixed) => { if (child === null || typeof child !== 'object') { return; } if (!child._store || child._store.validated || child.key != null) { return; } invariant( typeof child._store === 'object', 'React Component in warnForMissingKey should have a _store. ' + 'This error is likely caused by a bug in React. Please file an issue.', ); child._store.validated = true; var currentComponentErrorInfo = 'Each child in an array or iterator should have a unique ' + '"key" prop. See https://fb.me/react-warning-keys for ' + 'more information.' + (getCurrentFiberStackAddendum() || ''); if (ownerHasKeyUseWarning[currentComponentErrorInfo]) { return; } ownerHasKeyUseWarning[currentComponentErrorInfo] = true; warning( false, 'Each child in an array or iterator should have a unique ' + '"key" prop. See https://fb.me/react-warning-keys for ' + 'more information.%s', getCurrentFiberStackAddendum(), ); }; } const { createWorkInProgress, createFiberFromElement, createFiberFromFragment, createFiberFromText, createFiberFromCoroutine, createFiberFromYield, createFiberFromPortal, } = ReactFiber; const isArray = Array.isArray; const { FunctionalComponent, ClassComponent, HostText, HostPortal, CoroutineComponent, YieldComponent, Fragment, } = ReactTypeOfWork; const {NoEffect, Placement, Deletion} = ReactTypeOfSideEffect; const ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator; const FAUX_ITERATOR_SYMBOL = '@@iterator'; // Before Symbol spec. // The Symbol used to tag the ReactElement type. If there is no native Symbol // nor polyfill, then a plain number is used for performance. const REACT_ELEMENT_TYPE = (typeof Symbol === 'function' && Symbol.for && Symbol.for('react.element')) || 0xeac7; function getIteratorFn(maybeIterable: ?any): ?() => ?Iterator<*> { if (maybeIterable === null || typeof maybeIterable === 'undefined') { return null; } const iteratorFn = (ITERATOR_SYMBOL && maybeIterable[ITERATOR_SYMBOL]) || maybeIterable[FAUX_ITERATOR_SYMBOL]; if (typeof iteratorFn === 'function') { return iteratorFn; } return null; } function coerceRef(current: Fiber | null, element: ReactElement) { let mixedRef = element.ref; if (mixedRef !== null && typeof mixedRef !== 'function') { if (element._owner) { const owner: ?Fiber = (element._owner: any); let inst; if (owner) { const ownerFiber = ((owner: any): Fiber); invariant( ownerFiber.tag === ClassComponent, 'Stateless function components cannot have refs.', ); inst = ownerFiber.stateNode; } invariant( inst, 'Missing owner for string ref %s. This error is likely caused by a ' + 'bug in React. Please file an issue.', mixedRef, ); const stringRef = '' + mixedRef; // Check if previous string ref matches new string ref if ( current !== null && current.ref !== null && current.ref._stringRef === stringRef ) { return current.ref; } const ref = function(value) { const refs = inst.refs === emptyObject ? (inst.refs = {}) : inst.refs; if (value === null) { delete refs[stringRef]; } else { refs[stringRef] = value; } }; ref._stringRef = stringRef; return ref; } else { invariant( typeof mixedRef === 'string', 'Expected ref to be a function or a string.', ); invariant( element._owner, 'Element ref was specified as a string (%s) but no owner was ' + 'set. You may have multiple copies of React loaded. ' + '(details: https://fb.me/react-refs-must-have-owner).', mixedRef, ); } } return mixedRef; } function throwOnInvalidObjectType(returnFiber: Fiber, newChild: Object) { if (returnFiber.type !== 'textarea') { let addendum = ''; if (__DEV__) { addendum = ' If you meant to render a collection of children, use an array ' + 'instead.' + (getCurrentFiberStackAddendum() || ''); } invariant( false, 'Objects are not valid as a React child (found: %s).%s', Object.prototype.toString.call(newChild) === '[object Object]' ? 'object with keys {' + Object.keys(newChild).join(', ') + '}' : newChild, addendum, ); } } function warnOnFunctionType() { const currentComponentErrorInfo = 'Functions are not valid as a React child. This may happen if ' + 'you return a Component instead of <Component /> from render. ' + 'Or maybe you meant to call this function rather than return it.' + (getCurrentFiberStackAddendum() || ''); if (ownerHasFunctionTypeWarning[currentComponentErrorInfo]) { return; } ownerHasFunctionTypeWarning[currentComponentErrorInfo] = true; warning( false, 'Functions are not valid as a React child. This may happen if ' + 'you return a Component instead of <Component /> from render. ' + 'Or maybe you meant to call this function rather than return it.%s', getCurrentFiberStackAddendum() || '', ); } // This wrapper function exists because I expect to clone the code in each path // to be able to optimize each path individually by branching early. This needs // a compiler or we can do it manually. Helpers that don't need this branching // live outside of this function. function ChildReconciler(shouldClone, shouldTrackSideEffects) { function deleteChild(returnFiber: Fiber, childToDelete: Fiber): void { if (!shouldTrackSideEffects) { // Noop. return; } if (!shouldClone) { // When we're reconciling in place we have a work in progress copy. We // actually want the current copy. If there is no current copy, then we // don't need to track deletion side-effects. if (childToDelete.alternate === null) { return; } childToDelete = childToDelete.alternate; } // Deletions are added in reversed order so we add it to the front. // At this point, the return fiber's effect list is empty except for // deletions, so we can just append the deletion to the list. The remaining // effects aren't added until the complete phase. Once we implement // resuming, this may not be true. const last = returnFiber.lastEffect; if (last !== null) { last.nextEffect = childToDelete; returnFiber.lastEffect = childToDelete; } else { returnFiber.firstEffect = returnFiber.lastEffect = childToDelete; } childToDelete.nextEffect = null; childToDelete.effectTag = Deletion; } function deleteRemainingChildren( returnFiber: Fiber, currentFirstChild: Fiber | null, ): null { if (!shouldTrackSideEffects) { // Noop. return null; } // TODO: For the shouldClone case, this could be micro-optimized a bit by // assuming that after the first child we've already added everything. let childToDelete = currentFirstChild; while (childToDelete !== null) { deleteChild(returnFiber, childToDelete); childToDelete = childToDelete.sibling; } return null; } function mapRemainingChildren( returnFiber: Fiber, currentFirstChild: Fiber, ): Map<string | number, Fiber> { // Add the remaining children to a temporary map so that we can find them by // keys quickly. Implicit (null) keys get added to this set with their index // instead. const existingChildren: Map<string | number, Fiber> = new Map(); let existingChild = currentFirstChild; while (existingChild !== null) { if (existingChild.key !== null) { existingChildren.set(existingChild.key, existingChild); } else { existingChildren.set(existingChild.index, existingChild); } existingChild = existingChild.sibling; } return existingChildren; } function useFiber(fiber: Fiber, expirationTime: ExpirationTime): Fiber { // We currently set sibling to null and index to 0 here because it is easy // to forget to do before returning it. E.g. for the single child case. if (shouldClone) { const clone = createWorkInProgress(fiber, expirationTime); clone.index = 0; clone.sibling = null; return clone; } else { // We override the expiration time even if it is earlier, because if // we're reconciling at a later time that means that this was // down-prioritized. fiber.expirationTime = expirationTime; fiber.effectTag = NoEffect; fiber.index = 0; fiber.sibling = null; return fiber; } } function placeChild( newFiber: Fiber, lastPlacedIndex: number, newIndex: number, ): number { newFiber.index = newIndex; if (!shouldTrackSideEffects) { // Noop. return lastPlacedIndex; } const current = newFiber.alternate; if (current !== null) { const oldIndex = current.index; if (oldIndex < lastPlacedIndex) { // This is a move. newFiber.effectTag = Placement; return lastPlacedIndex; } else { // This item can stay in place. return oldIndex; } } else { // This is an insertion. newFiber.effectTag = Placement; return lastPlacedIndex; } } function placeSingleChild(newFiber: Fiber): Fiber { // This is simpler for the single child case. We only need to do a // placement for inserting new children. if (shouldTrackSideEffects && newFiber.alternate === null) { newFiber.effectTag = Placement; } return newFiber; } function updateTextNode( returnFiber: Fiber, current: Fiber | null, textContent: string, expirationTime: ExpirationTime, ) { if (current === null || current.tag !== HostText) { // Insert const created = createFiberFromText( textContent, returnFiber.internalContextTag, expirationTime, ); created.return = returnFiber; return created; } else { // Update const existing = useFiber(current, expirationTime); existing.pendingProps = textContent; existing.return = returnFiber; return existing; } } function updateElement( returnFiber: Fiber, current: Fiber | null, element: ReactElement, expirationTime: ExpirationTime, ): Fiber { if (current === null || current.type !== element.type) { // Insert const created = createFiberFromElement( element, returnFiber.internalContextTag, expirationTime, ); created.ref = coerceRef(current, element); created.return = returnFiber; return created; } else { // Move based on index const existing = useFiber(current, expirationTime); existing.ref = coerceRef(current, element); existing.pendingProps = element.props; existing.return = returnFiber; if (__DEV__) { existing._debugSource = element._source; existing._debugOwner = element._owner; } return existing; } } function updateCoroutine( returnFiber: Fiber, current: Fiber | null, coroutine: ReactCoroutine, expirationTime: ExpirationTime, ): Fiber { // TODO: Should this also compare handler to determine whether to reuse? if (current === null || current.tag !== CoroutineComponent) { // Insert const created = createFiberFromCoroutine( coroutine, returnFiber.internalContextTag, expirationTime, ); created.return = returnFiber; return created; } else { // Move based on index const existing = useFiber(current, expirationTime); existing.pendingProps = coroutine; existing.return = returnFiber; return existing; } } function updateYield( returnFiber: Fiber, current: Fiber | null, yieldNode: ReactYield, expirationTime: ExpirationTime, ): Fiber { if (current === null || current.tag !== YieldComponent) { // Insert const created = createFiberFromYield( yieldNode, returnFiber.internalContextTag, expirationTime, ); created.type = yieldNode.value; created.return = returnFiber; return created; } else { // Move based on index const existing = useFiber(current, expirationTime); existing.type = yieldNode.value; existing.return = returnFiber; return existing; } } function updatePortal( returnFiber: Fiber, current: Fiber | null, portal: ReactPortal, expirationTime: ExpirationTime, ): Fiber { if ( current === null || current.tag !== HostPortal || current.stateNode.containerInfo !== portal.containerInfo || current.stateNode.implementation !== portal.implementation ) { // Insert const created = createFiberFromPortal( portal, returnFiber.internalContextTag, expirationTime, ); created.return = returnFiber; return created; } else { // Update const existing = useFiber(current, expirationTime); existing.pendingProps = portal.children || []; existing.return = returnFiber; return existing; } } function updateFragment( returnFiber: Fiber, current: Fiber | null, fragment: Iterable<*>, expirationTime: ExpirationTime, ): Fiber { if (current === null || current.tag !== Fragment) { // Insert const created = createFiberFromFragment( fragment, returnFiber.internalContextTag, expirationTime, ); created.return = returnFiber; return created; } else { // Update const existing = useFiber(current, expirationTime); existing.pendingProps = fragment; existing.return = returnFiber; return existing; } } function createChild( returnFiber: Fiber, newChild: any, expirationTime: ExpirationTime, ): Fiber | null { if (typeof newChild === 'string' || typeof newChild === 'number') { // Text nodes doesn't have keys. If the previous node is implicitly keyed // we can continue to replace it without aborting even if it is not a text // node. const created = createFiberFromText( '' + newChild, returnFiber.internalContextTag, expirationTime, ); created.return = returnFiber; return created; } if (typeof newChild === 'object' && newChild !== null) { switch (newChild.$$typeof) { case REACT_ELEMENT_TYPE: { const created = createFiberFromElement( newChild, returnFiber.internalContextTag, expirationTime, ); created.ref = coerceRef(null, newChild); created.return = returnFiber; return created; } case REACT_COROUTINE_TYPE: { const created = createFiberFromCoroutine( newChild, returnFiber.internalContextTag, expirationTime, ); created.return = returnFiber; return created; } case REACT_YIELD_TYPE: { const created = createFiberFromYield( newChild, returnFiber.internalContextTag, expirationTime, ); created.type = newChild.value; created.return = returnFiber; return created; } case REACT_PORTAL_TYPE: { const created = createFiberFromPortal( newChild, returnFiber.internalContextTag, expirationTime, ); created.return = returnFiber; return created; } } if (isArray(newChild) || getIteratorFn(newChild)) { const created = createFiberFromFragment( newChild, returnFiber.internalContextTag, expirationTime, ); created.return = returnFiber; return created; } throwOnInvalidObjectType(returnFiber, newChild); } if (__DEV__) { if (typeof newChild === 'function') { warnOnFunctionType(); } } return null; } function updateSlot( returnFiber: Fiber, oldFiber: Fiber | null, newChild: any, expirationTime: ExpirationTime, ): Fiber | null { // Update the fiber if the keys match, otherwise return null. const key = oldFiber !== null ? oldFiber.key : null; if (typeof newChild === 'string' || typeof newChild === 'number') { // Text nodes doesn't have keys. If the previous node is implicitly keyed // we can continue to replace it without aborting even if it is not a text // node. if (key !== null) { return null; } return updateTextNode( returnFiber, oldFiber, '' + newChild, expirationTime, ); } if (typeof newChild === 'object' && newChild !== null) { switch (newChild.$$typeof) { case REACT_ELEMENT_TYPE: { if (newChild.key === key) { return updateElement( returnFiber, oldFiber, newChild, expirationTime, ); } else { return null; } } case REACT_COROUTINE_TYPE: { if (newChild.key === key) { return updateCoroutine( returnFiber, oldFiber, newChild, expirationTime, ); } else { return null; } } case REACT_YIELD_TYPE: { // Yields doesn't have keys. If the previous node is implicitly keyed // we can continue to replace it without aborting even if it is not a // yield. if (key === null) { return updateYield(returnFiber, oldFiber, newChild, expirationTime); } else { return null; } } case REACT_PORTAL_TYPE: { if (newChild.key === key) { return updatePortal( returnFiber, oldFiber, newChild, expirationTime, ); } else { return null; } } } if (isArray(newChild) || getIteratorFn(newChild)) { // Fragments doesn't have keys so if the previous key is implicit we can // update it. if (key !== null) { return null; } return updateFragment(returnFiber, oldFiber, newChild, expirationTime); } throwOnInvalidObjectType(returnFiber, newChild); } if (__DEV__) { if (typeof newChild === 'function') { warnOnFunctionType(); } } return null; } function updateFromMap( existingChildren: Map<string | number, Fiber>, returnFiber: Fiber, newIdx: number, newChild: any, expirationTime: ExpirationTime, ): Fiber | null { if (typeof newChild === 'string' || typeof newChild === 'number') { // Text nodes doesn't have keys, so we neither have to check the old nor // new node for the key. If both are text nodes, they match. const matchedFiber = existingChildren.get(newIdx) || null; return updateTextNode( returnFiber, matchedFiber, '' + newChild, expirationTime, ); } if (typeof newChild === 'object' && newChild !== null) { switch (newChild.$$typeof) { case REACT_ELEMENT_TYPE: { const matchedFiber = existingChildren.get( newChild.key === null ? newIdx : newChild.key, ) || null; return updateElement( returnFiber, matchedFiber, newChild, expirationTime, ); } case REACT_COROUTINE_TYPE: { const matchedFiber = existingChildren.get( newChild.key === null ? newIdx : newChild.key, ) || null; return updateCoroutine( returnFiber, matchedFiber, newChild, expirationTime, ); } case REACT_YIELD_TYPE: { // Yields doesn't have keys, so we neither have to check the old nor // new node for the key. If both are yields, they match. const matchedFiber = existingChildren.get(newIdx) || null; return updateYield( returnFiber, matchedFiber, newChild, expirationTime, ); } case REACT_PORTAL_TYPE: { const matchedFiber = existingChildren.get( newChild.key === null ? newIdx : newChild.key, ) || null; return updatePortal( returnFiber, matchedFiber, newChild, expirationTime, ); } } if (isArray(newChild) || getIteratorFn(newChild)) { const matchedFiber = existingChildren.get(newIdx) || null; return updateFragment( returnFiber, matchedFiber, newChild, expirationTime, ); } throwOnInvalidObjectType(returnFiber, newChild); } if (__DEV__) { if (typeof newChild === 'function') { warnOnFunctionType(); } } return null; } /** * Warns if there is a duplicate or missing key */ function warnOnInvalidKey( child: mixed, knownKeys: Set<string> | null, ): Set<string> | null { if (__DEV__) { if (typeof child !== 'object' || child === null) { return knownKeys; } switch (child.$$typeof) { case REACT_ELEMENT_TYPE: case REACT_COROUTINE_TYPE: case REACT_PORTAL_TYPE: warnForMissingKey(child); const key = child.key; if (typeof key !== 'string') { break; } if (knownKeys === null) { knownKeys = new Set(); knownKeys.add(key); break; } if (!knownKeys.has(key)) { knownKeys.add(key); break; } warning( false, 'Encountered two children with the same key, `%s`. ' + 'Keys should be unique so that components maintain their identity ' + 'across updates. Non-unique keys may cause children to be ' + 'duplicated and/or omitted — the behavior is unsupported and ' + 'could change in a future version.%s', key, getCurrentFiberStackAddendum(), ); break; default: break; } } return knownKeys; } function reconcileChildrenArray( returnFiber: Fiber, currentFirstChild: Fiber | null, newChildren: Array<*>, expirationTime: ExpirationTime, ): Fiber | null { // This algorithm can't optimize by searching from boths ends since we // don't have backpointers on fibers. I'm trying to see how far we can get // with that model. If it ends up not being worth the tradeoffs, we can // add it later. // Even with a two ended optimization, we'd want to optimize for the case // where there are few changes and brute force the comparison instead of // going for the Map. It'd like to explore hitting that path first in // forward-only mode and only go for the Map once we notice that we need // lots of look ahead. This doesn't handle reversal as well as two ended // search but that's unusual. Besides, for the two ended optimization to // work on Iterables, we'd need to copy the whole set. // In this first iteration, we'll just live with hitting the bad case // (adding everything to a Map) in for every insert/move. // If you change this code, also update reconcileChildrenIterator() which // uses the same algorithm. if (__DEV__) { // First, validate keys. let knownKeys = null; for (let i = 0; i < newChildren.length; i++) { const child = newChildren[i]; knownKeys = warnOnInvalidKey(child, knownKeys); } } let resultingFirstChild: Fiber | null = null; let previousNewFiber: Fiber | null = null; let oldFiber = currentFirstChild; let lastPlacedIndex = 0; let newIdx = 0; let nextOldFiber = null; for (; oldFiber !== null && newIdx < newChildren.length; newIdx++) { if (oldFiber.index > newIdx) { nextOldFiber = oldFiber; oldFiber = null; } else { nextOldFiber = oldFiber.sibling; } const newFiber = updateSlot( returnFiber, oldFiber, newChildren[newIdx], expirationTime, ); if (newFiber === null) { // TODO: This breaks on empty slots like null children. That's // unfortunate because it triggers the slow path all the time. We need // a better way to communicate whether this was a miss or null, // boolean, undefined, etc. if (oldFiber === null) { oldFiber = nextOldFiber; } break; } if (shouldTrackSideEffects) { if (oldFiber && newFiber.alternate === null) { // We matched the slot, but we didn't reuse the existing fiber, so we // need to delete the existing child. deleteChild(returnFiber, oldFiber); } } lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx); if (previousNewFiber === null) { // TODO: Move out of the loop. This only happens for the first run. resultingFirstChild = newFiber; } else { // TODO: Defer siblings if we're not at the right index for this slot. // I.e. if we had null values before, then we want to defer this // for each null value. However, we also don't want to call updateSlot // with the previous one. previousNewFiber.sibling = newFiber; } previousNewFiber = newFiber; oldFiber = nextOldFiber; } if (newIdx === newChildren.length) { // We've reached the end of the new children. We can delete the rest. deleteRemainingChildren(returnFiber, oldFiber); return resultingFirstChild; } if (oldFiber === null) { // If we don't have any more existing children we can choose a fast path // since the rest will all be insertions. for (; newIdx < newChildren.length; newIdx++) { const newFiber = createChild( returnFiber, newChildren[newIdx], expirationTime, ); if (!newFiber) { continue; } lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx); if (previousNewFiber === null) { // TODO: Move out of the loop. This only happens for the first run. resultingFirstChild = newFiber; } else { previousNewFiber.sibling = newFiber; } previousNewFiber = newFiber; } return resultingFirstChild; } // Add all children to a key map for quick lookups. const existingChildren = mapRemainingChildren(returnFiber, oldFiber); // Keep scanning and use the map to restore deleted items as moves. for (; newIdx < newChildren.length; newIdx++) { const newFiber = updateFromMap( existingChildren, returnFiber, newIdx, newChildren[newIdx], expirationTime, ); if (newFiber) { if (shouldTrackSideEffects) { if (newFiber.alternate !== null) { // The new fiber is a work in progress, but if there exists a // current, that means that we reused the fiber. We need to delete // it from the child list so that we don't add it to the deletion // list. existingChildren.delete( newFiber.key === null ? newIdx : newFiber.key, ); } } lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx); if (previousNewFiber === null) { resultingFirstChild = newFiber; } else { previousNewFiber.sibling = newFiber; } previousNewFiber = newFiber; } } if (shouldTrackSideEffects) { // Any existing children that weren't consumed above were deleted. We need // to add them to the deletion list. existingChildren.forEach(child => deleteChild(returnFiber, child)); } return resultingFirstChild; } function reconcileChildrenIterator( returnFiber: Fiber, currentFirstChild: Fiber | null, newChildrenIterable: Iterable<*>, expirationTime: ExpirationTime, ): Fiber | null { // This is the same implementation as reconcileChildrenArray(), // but using the iterator instead. const iteratorFn = getIteratorFn(newChildrenIterable); invariant( typeof iteratorFn === 'function', 'An object is not an iterable. This error is likely caused by a bug in ' + 'React. Please file an issue.', ); if (__DEV__) { // Warn about using Maps as children if (typeof newChildrenIterable.entries === 'function') { const possibleMap = (newChildrenIterable: any); if (possibleMap.entries === iteratorFn) { warning( didWarnAboutMaps, 'Using Maps as children is unsupported and will likely yield ' + 'unexpected results. Convert it to a sequence/iterable of keyed ' + 'ReactElements instead.%s', getCurrentFiberStackAddendum(), ); didWarnAboutMaps = true; } } // First, validate keys. // We'll get a different iterator later for the main pass. const newChildren = iteratorFn.call(newChildrenIterable); if (newChildren) { let knownKeys = null; let step = newChildren.next(); for (; !step.done; step = newChildren.next()) { const child = step.value; knownKeys = warnOnInvalidKey(child, knownKeys); } } } const newChildren = iteratorFn.call(newChildrenIterable); invariant(newChildren != null, 'An iterable object provided no iterator.'); let resultingFirstChild: Fiber | null = null; let previousNewFiber: Fiber | null = null; let oldFiber = currentFirstChild; let lastPlacedIndex = 0; let newIdx = 0; let nextOldFiber = null; let step = newChildren.next(); for ( ; oldFiber !== null && !step.done; newIdx++, (step = newChildren.next()) ) { if (oldFiber.index > newIdx) { nextOldFiber = oldFiber; oldFiber = null; } else { nextOldFiber = oldFiber.sibling; } const newFiber = updateSlot( returnFiber, oldFiber, step.value, expirationTime, ); if (newFiber === null) { // TODO: This breaks on empty slots like null children. That's // unfortunate because it triggers the slow path all the time. We need // a better way to communicate whether this was a miss or null, // boolean, undefined, etc. if (!oldFiber) { oldFiber = nextOldFiber; } break; } if (shouldTrackSideEffects) { if (oldFiber && newFiber.alternate === null) { // We matched the slot, but we didn't reuse the existing fiber, so we // need to delete the existing child. deleteChild(returnFiber, oldFiber); } } lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx); if (previousNewFiber === null) { // TODO: Move out of the loop. This only happens for the first run. resultingFirstChild = newFiber; } else { // TODO: Defer siblings if we're not at the right index for this slot. // I.e. if we had null values before, then we want to defer this // for each null value. However, we also don't want to call updateSlot // with the previous one. previousNewFiber.sibling = newFiber; } previousNewFiber = newFiber; oldFiber = nextOldFiber; } if (step.done) { // We've reached the end of the new children. We can delete the rest. deleteRemainingChildren(returnFiber, oldFiber); return resultingFirstChild; } if (oldFiber === null) { // If we don't have any more existing children we can choose a fast path // since the rest will all be insertions. for (; !step.done; newIdx++, (step = newChildren.next())) { const newFiber = createChild(returnFiber, step.value, expirationTime); if (newFiber === null) { continue; } lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx); if (previousNewFiber === null) { // TODO: Move out of the loop. This only happens for the first run. resultingFirstChild = newFiber; } else { previousNewFiber.sibling = newFiber; } previousNewFiber = newFiber; } return resultingFirstChild; } // Add all children to a key map for quick lookups. const existingChildren = mapRemainingChildren(returnFiber, oldFiber); // Keep scanning and use the map to restore deleted items as moves. for (; !step.done; newIdx++, (step = newChildren.next())) { const newFiber = updateFromMap( existingChildren, returnFiber, newIdx, step.value, expirationTime, ); if (newFiber !== null) { if (shouldTrackSideEffects) { if (newFiber.alternate !== null) { // The new fiber is a work in progress, but if there exists a // current, that means that we reused the fiber. We need to delete // it from the child list so that we don't add it to the deletion // list. existingChildren.delete( newFiber.key === null ? newIdx : newFiber.key, ); } } lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx); if (previousNewFiber === null) { resultingFirstChild = newFiber; } else { previousNewFiber.sibling = newFiber; } previousNewFiber = newFiber; } } if (shouldTrackSideEffects) { // Any existing children that weren't consumed above were deleted. We need // to add them to the deletion list. existingChildren.forEach(child => deleteChild(returnFiber, child)); } return resultingFirstChild; } function reconcileSingleTextNode( returnFiber: Fiber, currentFirstChild: Fiber | null, textContent: string, expirationTime: ExpirationTime, ): Fiber { // There's no need to check for keys on text nodes since we don't have a // way to define them. if (currentFirstChild !== null && currentFirstChild.tag === HostText) { // We already have an existing node so let's just update it and delete // the rest. deleteRemainingChildren(returnFiber, currentFirstChild.sibling); const existing = useFiber(currentFirstChild, expirationTime); existing.pendingProps = textContent; existing.return = returnFiber; return existing; } // The existing first child is not a text node so we need to create one // and delete the existing ones. deleteRemainingChildren(returnFiber, currentFirstChild); const created = createFiberFromText( textContent, returnFiber.internalContextTag, expirationTime, ); created.return = returnFiber; return created; } function reconcileSingleElement( returnFiber: Fiber, currentFirstChild: Fiber | null, element: ReactElement, expirationTime: ExpirationTime, ): Fiber { const key = element.key; let child = currentFirstChild; while (child !== null) { // TODO: If key === null and child.key === null, then this only applies to // the first item in the list. if (child.key === key) { if (child.type === element.type) { deleteRemainingChildren(returnFiber, child.sibling); const existing = useFiber(child, expirationTime); existing.ref = coerceRef(child, element); existing.pendingProps = element.props; existing.return = returnFiber; if (__DEV__) { existing._debugSource = element._source; existing._debugOwner = element._owner; } return existing; } else { deleteRemainingChildren(returnFiber, child); break; } } else { deleteChild(returnFiber, child); } child = child.sibling; } const created = createFiberFromElement( element, returnFiber.internalContextTag, expirationTime, ); created.ref = coerceRef(currentFirstChild, element); created.return = returnFiber; return created; } function reconcileSingleCoroutine( returnFiber: Fiber, currentFirstChild: Fiber | null, coroutine: ReactCoroutine, expirationTime: ExpirationTime, ): Fiber { const key = coroutine.key; let child = currentFirstChild; while (child !== null) { // TODO: If key === null and child.key === null, then this only applies to // the first item in the list. if (child.key === key) { if (child.tag === CoroutineComponent) { deleteRemainingChildren(returnFiber, child.sibling); const existing = useFiber(child, expirationTime); existing.pendingProps = coroutine; existing.return = returnFiber; return existing; } else { deleteRemainingChildren(returnFiber, child); break; } } else { deleteChild(returnFiber, child); } child = child.sibling; } const created = createFiberFromCoroutine( coroutine, returnFiber.internalContextTag, expirationTime, ); created.return = returnFiber; return created; } function reconcileSingleYield( returnFiber: Fiber, currentFirstChild: Fiber | null, yieldNode: ReactYield, expirationTime: ExpirationTime, ): Fiber { // There's no need to check for keys on yields since they're stateless. let child = currentFirstChild; if (child !== null) { if (child.tag === YieldComponent) { deleteRemainingChildren(returnFiber, child.sibling); const existing = useFiber(child, expirationTime); existing.type = yieldNode.value; existing.return = returnFiber; return existing; } else { deleteRemainingChildren(returnFiber, child); } } const created = createFiberFromYield( yieldNode, returnFiber.internalContextTag, expirationTime, ); created.type = yieldNode.value; created.return = returnFiber; return created; } function reconcileSinglePortal( returnFiber: Fiber, currentFirstChild: Fiber | null, portal: ReactPortal, expirationTime: ExpirationTime, ): Fiber { const key = portal.key; let child = currentFirstChild; while (child !== null) { // TODO: If key === null and child.key === null, then this only applies to // the first item in the list. if (child.key === key) { if ( child.tag === HostPortal && child.stateNode.containerInfo === portal.containerInfo && child.stateNode.implementation === portal.implementation ) { deleteRemainingChildren(returnFiber, child.sibling); const existing = useFiber(child, expirationTime); existing.pendingProps = portal.children || []; existing.return = returnFiber; return existing; } else { deleteRemainingChildren(returnFiber, child); break; } } else { deleteChild(returnFiber, child); } child = child.sibling; } const created = createFiberFromPortal( portal, returnFiber.internalContextTag, expirationTime, ); created.return = returnFiber; return created; } // This API will tag the children with the side-effect of the reconciliation // itself. They will be added to the side-effect list as we pass through the // children and the parent. function reconcileChildFibers( returnFiber: Fiber, currentFirstChild: Fiber | null, newChild: any, expirationTime: ExpirationTime, ): Fiber | null { // This function is not recursive. // If the top level item is an array, we treat it as a set of children, // not as a fragment. Nested arrays on the other hand will be treated as // fragment nodes. Recursion happens at the normal flow. // Handle object types const isObject = typeof newChild === 'object' && newChild !== null; if (isObject) { switch (newChild.$$typeof) { case REACT_ELEMENT_TYPE: return placeSingleChild( reconcileSingleElement( returnFiber, currentFirstChild, newChild, expirationTime, ), ); case REACT_COROUTINE_TYPE: return placeSingleChild( reconcileSingleCoroutine( returnFiber, currentFirstChild, newChild, expirationTime, ), ); case REACT_YIELD_TYPE: return placeSingleChild( reconcileSingleYield( returnFiber, currentFirstChild, newChild, expirationTime, ), ); case REACT_PORTAL_TYPE: return placeSingleChild( reconcileSinglePortal( returnFiber, currentFirstChild, newChild, expirationTime, ), ); } } if (typeof newChild === 'string' || typeof newChild === 'number') { return placeSingleChild( reconcileSingleTextNode( returnFiber, currentFirstChild, '' + newChild, expirationTime, ), ); } if (isArray(newChild)) { return reconcileChildrenArray( returnFiber, currentFirstChild, newChild, expirationTime, ); } if (getIteratorFn(newChild)) { return reconcileChildrenIterator( returnFiber, currentFirstChild, newChild, expirationTime, ); } if (isObject) { throwOnInvalidObjectType(returnFiber, newChild); } if (__DEV__) { if (typeof newChild === 'function') { warnOnFunctionType(); } } if (typeof newChild === 'undefined') { // If the new child is undefined, and the return fiber is a composite // component, throw an error. If Fiber return types are disabled, // we already threw above. switch (returnFiber.tag) { case ClassComponent: { if (__DEV__) { const instance = returnFiber.stateNode; if (instance.render._isMockFunction) { // We allow auto-mocks to proceed as if they're returning null. break; } } } // Intentionally fall through to the next case, which handles both // functions and classes // eslint-disable-next-lined no-fallthrough case FunctionalComponent: { const Component = returnFiber.type; invariant( false, '%s(...): Nothing was returned from render. This usually means a ' + 'return statement is missing. Or, to render nothing, ' + 'return null.', Component.displayName || Component.name || 'Component', ); } } } // Remaining cases are all treated as empty. return deleteRemainingChildren(returnFiber, currentFirstChild); } return reconcileChildFibers; } exports.reconcileChildFibers = ChildReconciler(true, true); exports.reconcileChildFibersInPlace = ChildReconciler(false, true); exports.mountChildFibersInPlace = ChildReconciler(false, false); exports.cloneChildFibers = function( current: Fiber | null, workInProgress: Fiber, ): void { invariant( current === null || workInProgress.child === current.child, 'Resuming work not yet implemented.', ); if (workInProgress.child === null) { return; } let currentChild = workInProgress.child; let newChild = createWorkInProgress( currentChild, currentChild.expirationTime, ); // TODO: Pass this as an argument, since it's easy to forget. newChild.pendingProps = currentChild.pendingProps; workInProgress.child = newChild; newChild.return = workInProgress; while (currentChild.sibling !== null) { currentChild = currentChild.sibling; newChild = newChild.sibling = createWorkInProgress( currentChild, currentChild.expirationTime, ); newChild.pendingProps = currentChild.pendingProps; newChild.return = workInProgress; } newChild.sibling = null; };
version https://git-lfs.github.com/spec/v1 oid sha256:af7485c245bb889f84d304fe8621a1e0523f92f9f3223a767a8a02ac3a33e637 size 4665
angular.module("exambazaar").controller("addBotCredentialController", [ '$scope', 'botCredentialList', 'examList','botCredentialService','$http','$state', 'Notification', '$cookies', function($scope, botCredentialList, examList, botCredentialService, $http, $state, Notification, $cookies){ $scope.botCredentials = botCredentialList.data; $scope.exams = examList.data; var examIds = $scope.exams.map(function(a) {return a._id;}); if($cookies.getObject('sessionuser')){ $scope.user = $cookies.getObject('sessionuser'); if($scope.user.userType == 'Master'){ $scope.authorized = true; } if($scope.user._id == '5a1831f0bd2adb260055e352'){ $scope.authorized = true; } }else{ console.log('Could not find user'); $scope.authorized = false; }; $scope.col1 = 25; $scope.botCredential = { name:'', platform:'Telegram', type:'EQAD', token:'', exam: null, active: true }; $scope.addBotCredential = function () { console.log($scope.botCredential); var saveBotCredential = botCredentialService.saveBotCredential($scope.botCredential).success(function (data, status, headers) { Notification.primary({message: "Bot Credential saved: " + $scope.botCredential.name, positionY: 'top', positionX: 'right', delay: 1000}); $state.reload(); }) .error(function (data, status, header, config) { console.log('Error ' + data + ' ' + status); }); }; $scope.setBotCredential = function(botCredential){ $scope.botCredential = botCredential; /*if(botCredential.exam){ console.log(botCredential); var eIndex = examIds.indexOf(botCredential.exam); console.log(eIndex); if(eIndex != -1){ $scope.botCredential.exam = $scope.exams[eIndex]; } }*/ }; }]);
var rc = require('rhoconnect_helpers'); var <%=class_name%> = function(){ this.login = function(resp){ // TODO: Login to your data source here if necessary resp.send(true); }; this.query = function(resp){ var result = {}; // TODO: Query your backend data source and assign the records // to a nested hash structure. Then return your result. // For example: // // { // "1": {"name": "Acme", "industry": "Electronics"}, // "2": {"name": "Best", "industry": "Software"} // } resp.send(result); }; this.create = function(resp){ // TODO: Create a new record in your backend data source. Then // return the result. resp.send('someId'); }; this.update = function(resp){ // TODO: Update an existing record in your backend data source. // Then return the result. resp.send(true); }; this.del = function(resp){ // TODO: Delete an existing record in your backend data source // if applicable. Be sure to have a hash key and value for // "object" and return the result. resp.send(true); }; this.logoff = function(resp){ // TODO: Logout from the data source if necessary. resp.send(true); }; this.storeBlob = function(resp){ // TODO: Handle post requests for blobs here. // Reference the blob object's path with resp.params.path. new rc.Exception( resp, "Please provide some code to handle blobs if you are using them." ); }; }; module.exports = new <%=class_name%>();
$(function () { //Preloader Images. var images = []; var urls = []; var lengthIndex; function preloadImages(array) { if (!preloadImages.list) { preloadImages.list = []; } var list = preloadImages.list; for (var i = 0; i < array.length; i++) { var img = new Image(); img.onload = function() { var index = list.indexOf(this); if (index !== -1) { // remove image from the array once it's loaded // for memory consumption reasons list.splice(index, 1); } if(list.length === 0){ $('.load-container').fadeOut(); } } list.push(img); img.src = array[i]; images.push(img.src); } } for (var i = 1; i <= 110; i++) { lengthIndex = i.toString().length; switch (lengthIndex) { case 1: urls.push("img/sequence/Frame000"+ i +".jpg"); break; case 2: urls.push("img/sequence/Frame00"+ i +".jpg"); break; case 3: urls.push("img/sequence/Frame0"+ i +".jpg"); break; case 4: urls.push("img/sequence/Frame"+ i +".jpg"); break; } } preloadImages(urls); // init controller var controller = new ScrollMagic.Controller(); // TweenMax can tween any property of any object. We use this object to cycle through the array var obj = {curImg: 0}; // create tween var tween = TweenMax.to(obj, 0.5, { curImg: images.length - 1, // animate propery curImg to number of images roundProps: "curImg", // only integers so it can be used as an array index //repeat: 3, // repeat 3 times immediateRender: true, // load first image automatically ease: Linear.easeNone, // show every image the same ammount of time onUpdate: function () { $("#myimg").attr("src", images[obj.curImg]); // set the image source } } ); // Remain fixed the box. var scene = new ScrollMagic.Scene({triggerElement: "#trigger", duration: 6150}) .setPin("#fixed-box") //.addIndicators({name: "1 (duration: 5800)"}) // add indicators (requires plugin) .addTo(controller); // Make the sequence. var scene = new ScrollMagic.Scene({triggerElement: "#trigger", duration: 5800}) .setTween(tween) //.addIndicators() // add indicators (requires plugin) .addTo(controller); // build tween var tween = TweenMax.from("#animate", 0.5, {autoAlpha: 0, scale: 0.7}); // Link jumpers. var scene = new ScrollMagic.Scene({triggerElement: "a#A", duration: 200, triggerHook: "onLeave"}) .setTween(tween) //.addIndicators() // add indicators (requires plugin) .addTo(controller); // change behaviour of controller to animate scroll instead of jump controller.scrollTo(function (newpos) { TweenMax.to(window, 0.5, {scrollTo: {y: newpos}}); }); // bind scroll to anchor links $('.letter').on("click", function (e) { var id = $(this).attr("href"); if ($(id).length > 0) { e.preventDefault(); // trigger scroll controller.scrollTo(id); // if supported by the browser we can even update the URL. if (window.history && window.history.pushState) { history.pushState("", document.title, id); } } }); });
$(function () { var FLYBY_DURATION = 3000; var FLYBY_DELAY = FLYBY_DURATION; var images = _.shuffle([ {label: 'Long Tail', src: 'images/blackswan.png'}, {label: 'Lean Thinking', src: 'images/lean-startup.jpeg'}, {label: 'System Thinking', src: 'images/system-thinking.jpg'}, {label: 'Randomness', src: 'images/fooled-by-randomness.jpg'}, {label: 'Design Thinking', src: 'images/design-thinking.png'}, {label: 'AntiFragile', src: 'images/antifragile.png'}, {label: 'Intuitions', src: 'images/invisible-gorilla.png'}, {label: 'Evolution', src: 'images/selfish-gene.jpg'}, {label: 'Optionality', src: 'images/thales.jpg'}, {label: 'Falsification', src: 'images/popper.jpg'}, {label: 'Expert Fallacy', src: 'images/damocles.jpg'}, {label: 'Knowledge', src: 'images/plato.jpg'}, {label: 'Continuous Delivery', src: 'images/cd.jpg'}, {label: 'Irrationality', src: 'images/irrationality.jpg'} ]); var w = d3.select("body").node().clientWidth; var h = 600; images.forEach(function (image, i) { var body = d3.select("body"); animateImages(body, image, i); animateLabels(body, image, i); }); spread(); function animateImages(body, image, i) { var IMAGE_START_POS = "-600px"; var IMAGE_END_POS = w + 100 + "px"; var top = 200 * Math.random(); var imageDiv = body .append("div") .attr("class", "flyer") .style({opacity: 0.5, position: "absolute", top: top + "px", left: IMAGE_START_POS}); imageDiv.append("img") .attr("src", image.src); imageDiv.transition().duration(duration() / 2) .delay(function () { return i * FLYBY_DELAY; }) .style("opacity", 1) .style("left", w / 2 - 150 + "px") .transition().duration(duration() / 2) .style("opacity", 0.5) .style("left", IMAGE_END_POS) .each("end", function () { d3.select(this).remove(); }); } function animateLabels(body, image, i) { var LABEL_START_POS = w + 100 + "px"; var LABEL_END_POS = "-800px"; var top = 30 + 400 * Math.random(); var labelDiv = body .append("div") .attr("class", "flyer") .style({opacity: 0.3, position: "absolute", width: "530px", top: top + "px", left: LABEL_START_POS}); labelDiv.append("span") .text(image.label); labelDiv.transition().duration(duration() / 2) .delay(function () { return i * FLYBY_DELAY; }) .style("opacity", 1) .style("left", w / 2 + "px") .transition().duration(duration() / 2) .style("opacity", 0.3) .style("left", LABEL_END_POS) .each("end", function () { d3.select(this).remove(); }); } function duration() { return FLYBY_DURATION; } function displayHeadline() { d3.select("body").append('div') .attr("class", 'call') .style("opacity", 0) .text('From Agile to AntiFragile - a practitioner\'s guide') .transition().duration(3000) .style('opacity', 1); } function spread() { setTimeout(function () { var force = d3.layout.force() .size([w, h]) .gravity(0) .charge(0) .friction(0.9); force.on("tick", function () { d3.select("body").selectAll("div.surface") .style("top", function (d) { return d.y + "px"; }) .style("left", function (d) { return d.x + "px"; }); }); images.forEach(function (image, i) { var spread = 40; if (i % 2 == 0) { image.x = w / 2 + Math.random() * spread; image.y = h / 2 + Math.random() * spread; } else { image.x = w / 2 - Math.random() * spread; image.y = h / 2 - Math.random() * spread; } image.px = w / 2; image.py = h / 2; force.nodes().push(image); }); d3.select("body") .selectAll("div.surface") .data(force.nodes()) .enter() .append("div") .attr("class", "surface") .call(force.drag) .style("position", "absolute") .style("top", function (d) { return d.y + "px"; }) .style("left", function (d) { return d.x + "px"; }) .append("img") .attr("src", function (d) { return d.src; }); force.start(); displayHeadline(); }, FLYBY_DURATION * images.length); } });