hexsha
string
size
int64
ext
string
lang
string
max_stars_repo_path
string
max_stars_repo_name
string
max_stars_repo_head_hexsha
string
max_stars_repo_licenses
list
max_stars_count
int64
max_stars_repo_stars_event_min_datetime
string
max_stars_repo_stars_event_max_datetime
string
max_issues_repo_path
string
max_issues_repo_name
string
max_issues_repo_head_hexsha
string
max_issues_repo_licenses
list
max_issues_count
int64
max_issues_repo_issues_event_min_datetime
string
max_issues_repo_issues_event_max_datetime
string
max_forks_repo_path
string
max_forks_repo_name
string
max_forks_repo_head_hexsha
string
max_forks_repo_licenses
list
max_forks_count
int64
max_forks_repo_forks_event_min_datetime
string
max_forks_repo_forks_event_max_datetime
string
content
string
avg_line_length
float64
max_line_length
int64
alphanum_fraction
float64
7df665872666b08e0e00367973cf9b20f615d30f
4,048
js
JavaScript
lib/relue/math/generators.js
jeremyagray/relue
ccac0a5e0bc5f870029920b59dd0cdd0681b6029
[ "MIT" ]
null
null
null
lib/relue/math/generators.js
jeremyagray/relue
ccac0a5e0bc5f870029920b59dd0cdd0681b6029
[ "MIT" ]
null
null
null
lib/relue/math/generators.js
jeremyagray/relue
ccac0a5e0bc5f870029920b59dd0cdd0681b6029
[ "MIT" ]
null
null
null
'use strict'; const nt = require('./number-theory.js'); /** * Generates the sequence of perfect cubes. * * @generator * @name cubes * @memberof math * @api public * * @param {number} n - The first perfect cube. * @yields {number} The next perfect cube. * * @example * const generator = relue.math.cubes(); * * // Returns next perfect cube. * console.log(generator.next().value); */ exports.cubes = function*(n=0) { while (true) { yield n * n * n; n++; } }; /** * Generates the sequence of even numbers. * * @generator * @name evens * @memberof math * @api public * * @yields {number} The next even number, beginning at 0. * * @example * const generator = relue.math.evens(); * * // Returns next even number. * console.log(generator.next().value); */ exports.evens = function*() { let n = 0; while (true) { yield n; n += 2; } }; /** * Generates the sequence of odd numbers. * * @generator * @name odds * @memberof math * @api public * * @yields {number} The next odd number, beginning at 1. * * @example * const generator = relue.math.odds(); * * // Returns next odd number. * console.log(generator.next().value); */ exports.odds = function*() { let n = 1; while (true) { yield n; n += 2; } }; /** * Generates the Fibonacci sequence. * * @generator * @name fibonaccis * @memberof math * @api public * * @yields {number} The next Fibonacci number. * * @example * const generator = relue.math.fibonaccis(); * * // Returns next Fibonacci number. * console.log(generator.next().value); */ exports.fibonaccis = function*() { let a = 0; let b = 1; let tmp = 0; while (true) { yield a; tmp = a; a = b; b = b + tmp; } }; /** * Generates the hailstone sequence for n. * * @generator * @name hailstone * @memberof math * @api public * * @param {number} n - The starting number of the hailstone sequence. * @yields {number} The next number in the hailstone sequence for n. * * @example * const generator = relue.math.hailstone(27); * * // Prints 82. * console.log(generator.next().value); */ exports.hailstone = function*(n) { if (n === undefined || n === null || typeof n === 'boolean' || typeof n === 'string' || Number.isNaN(n)) { return null; } let m = n; // First time. if (m < 1) { return 0; } else if (m === 1) { return m; } else { yield m; } // Sequence generation. while (true) { if (m === 1) { return m; } else if (m % 2 === 0) { m = m / 2; } else { m = 3 * m + 1; } yield m; } }; /** * Generates the pentagonal sequence. * * @generator * @name pentagonal * @memberof math * @api public * * @yields {number} n - The next number in the pentagonal sequence. * * @example * const generator = relue.math.pentagonal(); * * // Prints 1, 2, 5, 7, 12, 15, 20, ... * console.log(generator.next().value); */ exports.pentagonal = function*() { let k = 1; while (true) { yield (k * (3 * k - 1) / 2); k = -k; yield (k * (3 * k - 1) / 2); k = -k; k++; } }; /** * Generates prime numbers. * * @generator * @name primes * @memberof math * @api public * * @param {number} [n=2] - The number to start searching for primes. * @yields {number} The next prime number. * * @example * const generator = relue.math.primes(); * * // Returns next prime. * console.log(generator.next().value); */ exports.primes = function*(n=2) { let i = n; while (true) { if (nt.isPrime(i)) { yield i; } i++; } }; /** * Generates the sequence of perfect squares. * * @generator * @name squares * @memberof math * @api public * * @param {number} n - The first perfect square. * @yields {number} The next perfect square. * * @example * const generator = relue.math.squares(); * * // Returns next perfect square. * console.log(generator.next().value); */ exports.squares = function*(n=0) { while (true) { yield n * n; n++; } };
17.373391
69
0.57164
7df823fa4808f0f81d8a6cfcc348e5e628793a25
13,352
js
JavaScript
src/lib/viewers/box3d/model3d/Model3DViewer.js
boxmoji/box-content-preview
f10b14c2701e9fecdc2d82df78dbabb287d564a7
[ "Apache-2.0" ]
null
null
null
src/lib/viewers/box3d/model3d/Model3DViewer.js
boxmoji/box-content-preview
f10b14c2701e9fecdc2d82df78dbabb287d564a7
[ "Apache-2.0" ]
null
null
null
src/lib/viewers/box3d/model3d/Model3DViewer.js
boxmoji/box-content-preview
f10b14c2701e9fecdc2d82df78dbabb287d564a7
[ "Apache-2.0" ]
null
null
null
import autobind from 'autobind-decorator'; import Box3DViewer from '../Box3DViewer'; import Model3DControls from './Model3DControls'; import Model3DRenderer from './Model3DRenderer'; import { CAMERA_PROJECTION_PERSPECTIVE, EVENT_CANVAS_CLICK, EVENT_ROTATE_ON_AXIS, EVENT_SELECT_ANIMATION_CLIP, EVENT_SET_CAMERA_PROJECTION, EVENT_SET_QUALITY_LEVEL, EVENT_SET_RENDER_MODE, EVENT_SET_SKELETONS_VISIBLE, EVENT_SET_WIREFRAMES_VISIBLE, EVENT_SET_GRID_VISIBLE, EVENT_TOGGLE_ANIMATION, EVENT_TOGGLE_HELPERS, RENDER_MODE_LIT } from './model3DConstants'; import { CSS_CLASS_INVISIBLE, EVENT_LOAD } from '../box3DConstants'; import './Model3D.scss'; const DEFAULT_AXIS_UP = '+Y'; const DEFAULT_AXIS_FORWARD = '+Z'; const DEFAULT_RENDER_GRID = true; const LOAD_TIMEOUT = 180000; // 3 minutes /** * Model3d * This is the entry point for the model3d preview. * @class */ @autobind class Model3DViewer extends Box3DViewer { /** @property {Object[]} - List of Box3D instances added to the scene */ instances = []; /** @property {Object} - Tracks up and forward axes for the model alignment in the scene */ axes = { up: null, forward: null }; /** * @inheritdoc */ setup() { // Call super() first to set up common layout super.setup(); this.wrapperEl.classList.add(CSS_CLASS_INVISIBLE); this.loadTimeout = LOAD_TIMEOUT; } /** * @inheritdoc */ createSubModules() { this.controls = new Model3DControls(this.wrapperEl); this.renderer = new Model3DRenderer(this.wrapperEl, this.boxSdk); } /** * @inheritdoc */ attachEventHandlers() { super.attachEventHandlers(); if (this.controls) { this.controls.on(EVENT_ROTATE_ON_AXIS, this.handleRotateOnAxis); this.controls.on(EVENT_SELECT_ANIMATION_CLIP, this.handleSelectAnimationClip); this.controls.on(EVENT_SET_CAMERA_PROJECTION, this.handleSetCameraProjection); this.controls.on(EVENT_SET_QUALITY_LEVEL, this.handleSetQualityLevel); this.controls.on(EVENT_SET_RENDER_MODE, this.handleSetRenderMode); this.controls.on(EVENT_SET_SKELETONS_VISIBLE, this.handleShowSkeletons); this.controls.on(EVENT_SET_WIREFRAMES_VISIBLE, this.handleShowWireframes); this.controls.on(EVENT_SET_GRID_VISIBLE, this.handleShowGrid); this.controls.on(EVENT_TOGGLE_ANIMATION, this.handleToggleAnimation); this.controls.on(EVENT_TOGGLE_HELPERS, this.handleToggleHelpers); } if (this.renderer) { this.renderer.on(EVENT_CANVAS_CLICK, this.handleCanvasClick); } } /** * @inheritdoc */ detachEventHandlers() { super.detachEventHandlers(); if (this.controls) { this.controls.removeListener(EVENT_ROTATE_ON_AXIS, this.handleRotateOnAxis); this.controls.removeListener(EVENT_SELECT_ANIMATION_CLIP, this.handleSelectAnimationClip); this.controls.removeListener(EVENT_SET_CAMERA_PROJECTION, this.handleSetCameraProjection); this.controls.removeListener(EVENT_SET_QUALITY_LEVEL, this.handleSetQualityLevel); this.controls.removeListener(EVENT_SET_RENDER_MODE, this.handleSetRenderMode); this.controls.removeListener(EVENT_SET_SKELETONS_VISIBLE, this.handleShowSkeletons); this.controls.removeListener(EVENT_SET_WIREFRAMES_VISIBLE, this.handleShowWireframes); this.controls.removeListener(EVENT_SET_GRID_VISIBLE, this.handleShowGrid); this.controls.removeListener(EVENT_TOGGLE_ANIMATION, this.handleToggleAnimation); this.controls.removeListener(EVENT_TOGGLE_HELPERS, this.handleToggleHelpers); } if (this.renderer) { this.renderer.removeListener(EVENT_CANVAS_CLICK, this.handleCanvasClick); } } /** * Sets the scale used to render the model. This is the size of the largest dimension of * the model in meters. Default is 1. * @method setModelScale * @public * @param {Float} newSize - The size of the largest dimension of the model in metres. * Default is 1 m. * @return {void} */ /* istanbul ignore next: @mbond has gotten rid of this in his incoming branch */ setModelScale(newSize) { if (!this.renderer) { return; } this.renderer.modelSize = newSize; if (!this.renderer.instance || this.renderer.vrEnabled) { return; } this.renderer.instance.scaleToSize(newSize); this.renderer.reset(); } /** * Set the position of the model relative a point and the model's bounding box. * @method setModelAlignment * @public * @param {Vector3} position The position in world space to position the model * relative to. * @param {Vector3} alignmentVector - An object of the form { x: x, y: y, z: z} where - the * values for x, y and z are between -1 and +1 and specify how the object is aligned to * the edges of the model. e.g. { x: 0, y: -1, z: 0 } will align the bottom, centre of the * object to the specified position. * @return {void} */ /* istanbul ignore next: @mbond has gotten rid of this in his incoming branch */ setModelAlignment(position, alignmentVector) { if (!this.renderer) { return; } this.renderer.modelAlignmentPosition = position; this.renderer.modelAlignmentVector = alignmentVector; if (!this.renderer.instance) { return; } this.renderer.instance.alignToPosition(position, alignmentVector); this.renderer.reset(); } /** * Handle animation clip selection. * @method handleSelectAnimationClip * @private * @param {string} clipId - The ID of the clip that was selected. * @return {void} */ handleSelectAnimationClip(clipId) { this.renderer.setAnimationClip(clipId); } /** * Handle model rotation event * @param {Object} axis An object describing the axis to rotate on * @return {void} */ handleRotateOnAxis(axis) { this.renderer.rotateOnAxis(axis); } /** * Handle hard set of axes * @param {string} upAxis - Up axis for model * @param {string} forwardAxis - Forward axis for model * @param {boolean} transition - True to trigger a smooth rotationd transition, false for snap to rotation * @return {void} */ handleRotationAxisSet(upAxis, forwardAxis, transition = true) { this.renderer.setAxisRotation(upAxis, forwardAxis, transition); } /** * @inheritdoc */ handleSceneLoaded() { this.loaded = true; // Get scene defaults for up/forward axes, and render mode return this.boxSdk .getMetadataClient() .get(this.options.file.id, 'global', 'box3d') .then((response) => { // Treat non-200 responses as errors. if (response.status !== 200) { throw new Error(`Received unsuccessful response status: ${response.status}`); } return response.response; }) .catch(this.onMetadataError) .then((defaults) => { if (this.controls) { this.controls.addUi(); } this.axes.up = defaults.upAxis || DEFAULT_AXIS_UP; this.axes.forward = defaults.forwardAxis || DEFAULT_AXIS_FORWARD; this.renderMode = defaults.defaultRenderMode || RENDER_MODE_LIT; this.projection = defaults.cameraProjection || CAMERA_PROJECTION_PERSPECTIVE; if (defaults.renderGrid === 'true') { this.renderGrid = true; } else if (defaults.renderGrid === 'false') { this.renderGrid = false; } else { this.renderGrid = DEFAULT_RENDER_GRID; } if (this.axes.up !== DEFAULT_AXIS_UP || this.axes.forward !== DEFAULT_AXIS_FORWARD) { this.handleRotationAxisSet(this.axes.up, this.axes.forward, false); } // Update controls ui this.handleReset(); // Initialize animation controls when animations are present. this.populateAnimationControls(); this.showWrapper(); this.renderer.initVr(); this.renderer.initVrGamepadControls(); this.emit(EVENT_LOAD); return true; }); } /** * Handle error triggered by metadata load issues * * @param {Error} err - The error thrown when trying to load metadata * @return {void} */ onMetadataError(err) { /* eslint-disable no-console */ console.error('Error loading metadata:', err.toString()); /* eslint-enable no-console */ // Continue with default settings. return {}; } /** * Populate control bar with animation playback UI. * * @method populateAnimationControls * @private * @return {void} */ populateAnimationControls() { if (!this.controls) { return; } const animations = this.renderer.box3d.getEntitiesByType('animation'); if (animations.length > 0) { const clipIds = animations[0].getClipIds(); clipIds.forEach((clipId) => { const clip = animations[0].getClip(clipId); const duration = clip.stop - clip.start; this.controls.addAnimationClip(clipId, clip.name, duration); }); if (clipIds.length > 0) { this.controls.showAnimationControls(); this.controls.selectAnimationClip(clipIds[0]); } } } /** * Handle animation playback (play / pause). * @method handleToggleAnimation * @private * @param {boolean} play True to force the animation to play. * @return {void} */ handleToggleAnimation(play) { this.renderer.toggleAnimation(play); } /** * Handle canvas focus events. * @method handleCanvasClick * @private * @return {void} */ handleCanvasClick() { this.controls.hidePullups(); } /** * Show the preview wrapper container element * * @return {void} */ showWrapper() { this.wrapperEl.classList.remove(CSS_CLASS_INVISIBLE); } /** * @inheritdoc */ handleReset() { super.handleReset(); if (this.controls) { this.controls.handleSetRenderMode(this.renderMode); this.controls.setCurrentProjectionMode(this.projection); this.controls.handleSetSkeletonsVisible(false); this.controls.handleSetWireframesVisible(false); this.controls.handleSetGridVisible(this.renderGrid); } if (this.renderer) { this.handleRotationAxisSet(this.axes.up, this.axes.forward, true); this.renderer.stopAnimation(); } } /** * Handle set render mode event * * @param {string} mode - The selected render mode string * @return {void} */ handleSetRenderMode(mode = 'Lit') { this.renderer.setRenderMode(mode); } /** * Show, hide or toggle the 'helpers' in the scene. These include the grid display * and axis markings. * * @method handleToggleHelpers * @private * @param {boolean} show - True or false to show or hide. If not specified, the helpers will be toggled. * @return {void} */ handleToggleHelpers(show) { this.renderer.toggleHelpers(show); } /** * Handle setting camera projection * * @private * @param {string} projection - Camera projection * @return {void} */ handleSetCameraProjection(projection) { this.renderer.setCameraProjection(projection); } /** * Handle setting quality level for rendering * * @private * @param {string} level - Quality level * @return {void} */ handleSetQualityLevel(level) { this.renderer.setQualityLevel(level); } /** * Handle setting skeleton visibility. * * @private * @param {boolean} visible - Indicates whether or not skeletons are visible. * @return {void} */ handleShowSkeletons(visible) { this.renderer.setSkeletonsVisible(visible); } /** * Handle setting wireframe visibility. * * @private * @param {boolean} visible - Indicates whether or not wireframes are visible. * @return {void} */ handleShowWireframes(visible) { this.renderer.setWireframesVisible(visible); } /** * Handle setting grid visibility. * * @private * @param {boolean} visible - Indicates whether or not the grid is visible. * @return {void} */ handleShowGrid(visible) { this.renderer.setGridVisible(visible); } } export default Model3DViewer;
31.866348
110
0.613466
7df875f0a4e7de66f37d6a7bd95d7e3a5583a760
209
js
JavaScript
routes/admin.js
zamaninemat9/quiz
6a7c35b8b84fd62722a99311589990972413537a
[ "MIT" ]
null
null
null
routes/admin.js
zamaninemat9/quiz
6a7c35b8b84fd62722a99311589990972413537a
[ "MIT" ]
null
null
null
routes/admin.js
zamaninemat9/quiz
6a7c35b8b84fd62722a99311589990972413537a
[ "MIT" ]
null
null
null
const app = require('express').Router(); app.use('/login', require('./adminLogin')); app.use('/users', require('./admin/adminUsers')); app.use('/question', require('./admin/adminUsers')); module.exports = app;
41.8
52
0.674641
7df8af205b9152692eb56db64343698c9c981f51
207
js
JavaScript
webpack.config.js
libao-sir/egg-vue-asset
7f5807ece00d75619c890a121fcbab6e6dca307a
[ "MIT" ]
null
null
null
webpack.config.js
libao-sir/egg-vue-asset
7f5807ece00d75619c890a121fcbab6e6dca307a
[ "MIT" ]
null
null
null
webpack.config.js
libao-sir/egg-vue-asset
7f5807ece00d75619c890a121fcbab6e6dca307a
[ "MIT" ]
null
null
null
'use strict'; // Document:https://www.yuque.com/easy-team/easywebpack 和 https://www.yuque.com/easy-team/egg-vue module.exports = { target: 'web', entry: { index: 'app/web/page/admin/index.js' } };
25.875
98
0.661836
7df8b6890636b48e37bdc3ac224167a364c98896
365
js
JavaScript
javascript/0001.a-b-problem.js
Ubastic/lintcode
9f600eece075410221a24859331a810503c76014
[ "MIT" ]
null
null
null
javascript/0001.a-b-problem.js
Ubastic/lintcode
9f600eece075410221a24859331a810503c76014
[ "MIT" ]
null
null
null
javascript/0001.a-b-problem.js
Ubastic/lintcode
9f600eece075410221a24859331a810503c76014
[ "MIT" ]
1
2020-08-27T11:58:03.000Z
2020-08-27T11:58:03.000Z
/** * @param a: An integer * @param b: An integer * @return: The sum of a and b */ const aplusb = function (a, b) { // a >>> 0 b>>> 0是把有符号数转换为无符号数 // 最终结果 >> 0 是把无符号数转化为有符号数 return helper(a>>>0,b>>>0) >> 0 } function helper(a,b){ if(a === 0){ return b; } if(b === 0){ return a; } return helper(a^b,(a&b)<<1); }
17.380952
35
0.484932
7df995c05672ecc6e381093b3d1fc4a979ea997e
1,320
js
JavaScript
components/CategoryGridTile.js
hirashahid/ReactNative-TheMealApp
35e86294218983b92d630e0b865f87144b92b48d
[ "MIT" ]
null
null
null
components/CategoryGridTile.js
hirashahid/ReactNative-TheMealApp
35e86294218983b92d630e0b865f87144b92b48d
[ "MIT" ]
null
null
null
components/CategoryGridTile.js
hirashahid/ReactNative-TheMealApp
35e86294218983b92d630e0b865f87144b92b48d
[ "MIT" ]
null
null
null
import React from 'react'; import { TouchableOpacity, View, Text, StyleSheet, Platform, TouchableNativeFeedback } from 'react-native'; const CategoryGridTile = props => { let TouchableCmp = TouchableOpacity; if (Platform.OS === 'android' && Platform.Version >= 21) { TouchableCmp = TouchableNativeFeedback; } return ( <View style={styles.gridItem}> <TouchableCmp style={{ flex: 1 }} onPress={props.onSelect}> <View style={{ ...styles.container, ...{ backgroundColor: props.color } }} > <Text style={styles.title} numberOfLines={2}> {props.title} </Text> </View> </TouchableCmp> </View> ); }; const styles = StyleSheet.create({ gridItem: { flex: 1, margin: 15, height: 150, borderRadius: 10, elevation: 5, overflow: Platform.OS === 'android' && Platform.Version >=21 ? 'hidden' : 'visible', }, container: { flex: 1, borderRadius: 10, shadowColor: 'black', shadowOpacity: 0.26, shadowOffset: { width: 0, height: 2 }, shadowRadius: 10, padding: 15, justifyContent: 'flex-end', alignItems: 'flex-end' }, title: { fontFamily: 'open-sans-bold', fontSize: 22, textAlign: 'right' } }); export default CategoryGridTile;
21.290323
78
0.593939
7dfab6f7b12406d2521b074e619954f096b9ae33
8,261
js
JavaScript
public/static/work/workflow-att.3.0.js
zedisdog/laravelworkflow
d438e53a31bec457e32771ae3bbef16d7a3aa91d
[ "MIT" ]
71
2019-03-07T09:15:53.000Z
2021-11-07T20:26:35.000Z
public/static/work/workflow-att.3.0.js
zedisdog/laravelworkflow
d438e53a31bec457e32771ae3bbef16d7a3aa91d
[ "MIT" ]
6
2019-03-13T03:02:03.000Z
2021-08-06T10:13:15.000Z
public/static/work/workflow-att.3.0.js
zedisdog/laravelworkflow
d438e53a31bec457e32771ae3bbef16d7a3aa91d
[ "MIT" ]
18
2019-03-07T10:54:39.000Z
2021-07-19T14:38:05.000Z
//-----条件设置--strat---------------- function _id(id) { return !id ? null : document.getElementById(id); } function trim(str) { return (str + '').replace(/(\s+)$/g, '').replace(/^\s+/g, ''); } function fnCheckExp(text){ //检查公式 if( text.indexOf("(")>=0 ){ var num1 = text.split("(").length; var num2 = text.split(")").length; if( num1!=num2 ) { return false; } } return true; } /** * 增加左括号表达式,会断行 */ function fnAddLeftParenthesis(id){ var oObj = _id('conList_' + id); var current = 0; if(oObj.options.length>0){ //检查是否有条件 for ( var i = 0;i < oObj.options.length;i++ ){ if( oObj.options[i].selected ) { current = oObj.selectedIndex; break; } } if(current==0){ current = oObj.options.length-1; } } else { //有条件才能添加左括号表达式 alert("请先添加条件,再选择括号"); return; } var sText = oObj.options[current].text,sValue = oObj.options[current].value; //已经有条件的话 if( (trim(sValue).substr(-3,3) == 'AND') || (trim(sValue).substr(-2,2) == 'OR') ){ alert("无法编辑已经存在关系的条件"); return; } var sRelation = _id('relation_'+id).value; if( sValue.indexOf('(')>=0 ){ if( !fnCheckExp(sValue) ){ alert("条件表达式书写错误,请检查括号匹配"); return; } else { sValue = sValue + " " + sRelation; sText = sText + " " + sRelation; } } else { sValue = sValue + " " + sRelation; sText = sText + " " + sRelation; } oObj.options[current].value = sValue; oObj.options[current].text = sText; // $('#conList_'+id+' option').eq(current).text(sText) $('#conList_'+id).append('<option value="( ">( </option>'); } /** * 增加右括号表达式 */ function fnAddRightParenthesis(id){ var oObj = _id('conList_' + id); var current = 0; if( oObj.options.length>0 ){ for ( var i = 0;i < oObj.options.length;i++ ){ if( oObj.options[i].selected ) { current = oObj.selectedIndex; break; } } if( current == 0 ){ current = oObj.options.length-1; } } else { alert("请先添加条件,再选择括号"); return; } var sText = oObj.options[current].text,sValue = oObj.options[current].value; if( (trim(sValue).substr(-3,3)=='AND') || (trim(sValue).substr(-2,2)=='OR') ){ alert("无法编辑已经存在关系的条件"); return; } if( (trim(sValue).length==1) ){ alert("请添加条件"); return; } if( !fnCheckExp(sValue) ){ sValue = sValue + ")"; sText = sText + ")"; } oObj.options[current].value = sValue; oObj.options[current].text = sText; } function fnAddConditions(id){ var sField = $('#field_'+id).val(),sField_text = $('#field_'+id).find('option:selected').text(),sCon = $('#condition_'+id).val(),sValue = $('#item_value_'+id).val(); var bAdd = true; if( sField!=='' && sCon!=='' && sValue!=='' ){ var oObj = _id('conList_'+id); if( oObj.length>0 ){ var sLength = oObj.options.length; var sText = oObj.options[sLength-1].text; if(!fnCheckExp(sText)){ bAdd = false; } } if( sValue.indexOf("'")>=0 ){ alert("值中不能含有'号"); return; } var sNewText = "" + sField + "" + sCon + " '" + sValue + "'"; var sNewText_text = "" + sField + "" + sCon + " '" + sValue + "'"; for( var i=0;i<oObj.options.length;i++ ){ if( oObj.options[i].value.indexOf(sNewText)>=0 ){ alert("条件重复"); return; } } var sRelation = $('#relation_'+id).val(); if( bAdd ){ var nPos = oObj.options.length; $('#conList_'+id).append('<option value="'+sNewText+'">'+sNewText_text+'</option>'); if( nPos>0 ){ oObj.options[nPos-1].text += " " + sRelation; oObj.options[nPos-1].value += " " + sRelation; } } else { if( trim(oObj.options[sLength-1].text).length==1 ){ oObj.options[sLength-1].text += sNewText_text; oObj.options[sLength-1].value += sNewText; } else { oObj.options[sLength-1].text += " " + sRelation + " " + sNewText_text; oObj.options[sLength-1].value += " " + sRelation + " " + sNewText; } } check_from(); } else { alert("请补充完整条件"); return; } } function check_from(){ //条件检测 var cond_data = $("#process_condition").val(); if( cond_data !== ''){ var pcarr = cond_data.split(','); for( var i = 0;i < pcarr.length;i++ ){ if( pcarr[i]!=='' ){ var obj = _id('conList_'+pcarr[i]); if(obj.length>0){ var constr = ''; for( var j=0;j<obj.options.length;j++){ constr += obj.options[j].value+'@wf@'; if(!fnCheckExp(constr)){ alert("条件表达式书写错误,请检查括号匹配"); $('#condition').click(); return false; } } _id('process_in_set_'+pcarr[i]).value = constr; } else { _id('process_in_set_'+pcarr[i]).value = ''; } } } } }; function fnDelCon(id){ var oObj = _id('conList_'+id); var maxOpt = oObj.options.length; if(maxOpt<0) maxOpt = 0; for (var i = 0;i < oObj.options.length;i++ ){ if( oObj.options[i].selected ) { if((i+1)==maxOpt){ if(typeof oObj.options[i-1] !== 'undefined'){ oObj.options[i-1].text = oObj.options[i-1].text.replace(/(AND|OR)$/,''); oObj.options[i-1].value = oObj.options[i-1].value.replace(/(AND|OR)$/,''); } } oObj.removeChild(oObj.options[i]); i--; } check_from(); } } function fnClearCon(id){ $('#conList_' + id).html(''); } $(function(){ //选人方式 $("#auto_person_id").on('change',function(){ var apid = $(this).val(); if(apid==3)//指定用户 { $("#auto_person_3").show(); }else{ $("#auto_person_3").hide(); } if(apid==4)//指定用户 { $("#auto_person_4").show(); }else{ $("#auto_person_4").hide(); } if(apid==5)//指定角色 { $("#auto_person_5").show(); }else{ $("#auto_person_5").hide(); } }); $("#wf_mode_id").on('change',function(){ var apid = $(this).val(); if(apid==0)//单一转出模式 { $("#wf_mode_2").hide(); } if(apid==2)//转出模式 { $("#wf_mode_2").hide(); } if(apid==1)//同步模式 { $("#wf_mode_2").show(); }else{ $("#wf_mode_2").hide(); } }); /*样式*/ $('.colors li').click(function() { var self = $(this); if (!self.hasClass('active')) { self.siblings().removeClass('active'); } var color = self.attr('org-data') ? self.attr('org-data') : ''; var parentDiv = self.parents(".colors"); var orgBind = parentDiv.attr("org-bind"); $("#"+orgBind).css({ color:'#fff',background: color }); $("#"+orgBind).val(color); self.addClass('active'); }); });
31.895753
173
0.422951
7dfb065652683b2d870b5b5f63cab6f60b8bb1b9
1,244
js
JavaScript
examples/select/src/Components/MainComponent.js
leoleoleonid/uikernel
fd432595c581b17234f632c2e4df352061eff57e
[ "BSD-3-Clause" ]
22
2015-08-31T21:21:04.000Z
2021-12-18T07:51:33.000Z
examples/select/src/Components/MainComponent.js
leoleoleonid/uikernel
fd432595c581b17234f632c2e4df352061eff57e
[ "BSD-3-Clause" ]
48
2015-10-19T21:03:07.000Z
2022-03-23T12:34:11.000Z
examples/select/src/Components/MainComponent.js
leoleoleonid/uikernel
fd432595c581b17234f632c2e4df352061eff57e
[ "BSD-3-Clause" ]
30
2015-09-09T08:27:25.000Z
2021-04-19T05:43:39.000Z
/* * Copyright (с) 2015-present, SoftIndex LLC. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. */ import React from 'react'; import UIKernel from 'uikernel'; class MainComponent extends React.Component { constructor(props) { super(props); this.state = { value: 2, label: 'Option 2' }; this.options = [[null, ''], [1, 'Option 1'], [2, 'Option 2'], [3, 'Option 3'], [4, 'Option 4'], [5, 'Option 5']]; this.handleChange = this.handleChange.bind(this); this.handleLabelChange = this.handleLabelChange.bind(this); } handleChange(newValue) { this.setState({value: newValue}); } handleLabelChange(newLabel) { this.setState({label: newLabel}); } render() { return ( <div className="container"> <span>Selected: {this.state.label}</span> <br /> <UIKernel.Editors.Select ref={(select) => this.select = select} onChange={this.handleChange} onLabelChange={this.handleLabelChange} value={this.state.value} options={this.options} /> </div> ); } } export default MainComponent
24.392157
117
0.614952
7dfb42e9a774ee3ea7cf9f907109175b0b2c9cdd
2,148
js
JavaScript
test/transaction/input/publickey.js
POPChainFoundation/bitcore-lib-pch
9cc088a7b902ea69b74494fc4be19603b22aece2
[ "MIT" ]
4
2017-12-30T19:20:57.000Z
2020-08-11T19:43:17.000Z
test/transaction/input/publickey.js
POPChainFoundation/bitcore-lib-pch
9cc088a7b902ea69b74494fc4be19603b22aece2
[ "MIT" ]
4
2020-04-27T00:03:48.000Z
2022-02-12T12:34:09.000Z
test/transaction/input/publickey.js
POPChainFoundation/bitcore-lib-pch
9cc088a7b902ea69b74494fc4be19603b22aece2
[ "MIT" ]
18
2017-05-25T11:48:17.000Z
2020-08-01T16:18:23.000Z
'use strict'; var should = require('chai').should(); var bitcore = require('../../..'); var Transaction = bitcore.Transaction; var PrivateKey = bitcore.PrivateKey; describe('PublicKeyInput', function() { var utxo = { txid: '7f3b688cb224ed83e12d9454145c26ac913687086a0a62f2ae0bc10934a4030f', vout: 0, address: 'yjA6k167XHU4FqZbFWpSLTe5ivngfiJhKc', scriptPubKey: '2103c9594cb2ebfebcb0cfd29eacd40ba012606a197beef76f0269ed8c101e56ceddac', amount: 50, confirmations: 104, spendable: true }; var privateKey = PrivateKey.fromWIF('cQ7tSSQDEwaxg9usnnP1Aztqvm9nCQVfNWz9kU2rdocDjknF2vd6'); var address = privateKey.toAddress(); utxo.address.should.equal(address.toString()); var destKey = new PrivateKey(); it('will correctly sign a publickey out transaction', function() { var tx = new Transaction(); tx.from(utxo); tx.to(destKey.toAddress(), 10000); tx.sign(privateKey); tx.inputs[0].script.toBuffer().length.should.be.above(0); }); it('count can count missing signatures', function() { var tx = new Transaction(); tx.from(utxo); tx.to(destKey.toAddress(), 10000); var input = tx.inputs[0]; input.isFullySigned().should.equal(false); tx.sign(privateKey); input.isFullySigned().should.equal(true); }); it('it\'s size can be estimated', function() { var tx = new Transaction(); tx.from(utxo); tx.to(destKey.toAddress(), 10000); var input = tx.inputs[0]; input._estimateSize().should.equal(73); }); it('it\'s signature can be removed', function() { var tx = new Transaction(); tx.from(utxo); tx.to(destKey.toAddress(), 10000); var input = tx.inputs[0]; tx.sign(privateKey); input.isFullySigned().should.equal(true); input.clearSignatures(); input.isFullySigned().should.equal(false); }); it('returns an empty array if private key mismatches', function() { var tx = new Transaction(); tx.from(utxo); tx.to(destKey.toAddress(), 10000); var input = tx.inputs[0]; var signatures = input.getSignatures(tx, new PrivateKey(), 0); signatures.length.should.equal(0); }); });
29.833333
94
0.675512
7dfbac8a26dea0040c67996ed9c829f3330e300a
3,085
js
JavaScript
server/server.js
LasmGratel/wuziqi
d9b21db47dbbae1bb7f9528740a0b7584a8c7aa7
[ "MIT" ]
2
2019-07-25T11:38:37.000Z
2019-07-26T03:34:31.000Z
server/server.js
NanamiArihara/wuziqi
d9b21db47dbbae1bb7f9528740a0b7584a8c7aa7
[ "MIT" ]
null
null
null
server/server.js
NanamiArihara/wuziqi
d9b21db47dbbae1bb7f9528740a0b7584a8c7aa7
[ "MIT" ]
null
null
null
const fs = require('fs'); const WebSocket = require('ws'); const uuid = require('uuid/v4'); const wss = new WebSocket.Server({ host: '0.0.0.0', port: 8888 }); const connections = {}; const rooms = {}; const clientPair = {}; function createData() { const data = { name: undefined, boardSize: 15, board: [], chats: [], player: 0, gaming: true, winner: 0, clients: [] }; for (let i = 0; i < data.boardSize; i++) { data.board.push(new Array(data.boardSize).fill(-1)); } return data; } wss.on('listening', ws => { console.log("Server started"); }); wss.on('error', (ws, err) => { console.error("Socket " + ws + " throws an error " + err); }); wss.on('connection', ws => { ws.on('message', message => { const data = JSON.parse(message); switch (data.method) { case 'sendData': Object.assign(clientPair[data.client], data.data); clientPair[data.client].clients.map(client => connections[client]).filter(conn => conn).forEach(conn => conn.send(JSON.stringify(clientPair[data.client]))); break; case "getData": ws.send(JSON.stringify(clientPair[data.client])); connections[data.client] = ws; break; case "getRooms": ws.send(JSON.stringify({ rooms })); console.log("Client queryed rooms"); break; case "join": if (rooms[data.name]) { const clientId = uuid(); clientPair[clientId] = rooms[data.name]; rooms[data.name].name = data.name; rooms[data.name].clients.push(clientId); ws.send(JSON.stringify({ clientId, player: 1 })); } else { ws.send(JSON.stringify({ errorId: 1, errorDesc: "Rooms not exist!" })); } case "queue": if (rooms[data.name]) { ws.send(JSON.stringify({ errorId: 0, errorDesc: "Cannot create same room again!" })); } else { rooms[data.name] = createData(); const clientId = uuid(); ws.send(JSON.stringify({ clientId, rooms, player: 0 })); clientPair[clientId] = rooms[data.name]; rooms[data.name].clients.push(clientId); console.log("Created room: " + data.name); } } }); });
33.172043
173
0.412318
7dfbacf4548052a50fb357149282dc229406d36e
2,328
js
JavaScript
src/menuConfig.js
guateam/Project-Agent-Admin
542eb24d6171a0b12517b4f9124f2df343ca57f9
[ "MIT" ]
null
null
null
src/menuConfig.js
guateam/Project-Agent-Admin
542eb24d6171a0b12517b4f9124f2df343ca57f9
[ "MIT" ]
null
null
null
src/menuConfig.js
guateam/Project-Agent-Admin
542eb24d6171a0b12517b4f9124f2df343ca57f9
[ "MIT" ]
null
null
null
/* eslint-disable */ import util from './libs/util.ice'; // 菜单配置 // 侧栏菜单配置 // ice 会在新建页面的时候 push 数据 // ice 自动添加的菜单记录是以下格式:(不会有嵌套) // { // name: 'Nav', // path: '/page', // icon: 'home', // }, const asideMenuConfig = [ { name: '人员管理', icon: 'folder-o', children: [ { name: '从业者管理', path: '/user/', }, { name: '企业账号', path: '/company/', }, { name: '实名认证', path: '/verified/', }, ], }, { name: '内容审核', icon: 'folder-o', children: [ { name: '问题审核', path: '/question/', }, { name: '回答审核', path: '/answer/', }, { name: '文章审核', path: '/article/', }, { name: '举报审核', path: '/report/', }, ], }, { name: '通知发布', icon: 'folder-o', children: [ { name: '通知发布', path: '/notice/', }, ], }, { name: '系统日志', icon: 'folder-o', children: [ { name: '系统日志', path: '/log/', }, ], }, ]; // 顶栏菜单配置 // ice 不会修改 headerMenuConfig // 如果你需要功能开发之前就配置出菜单原型,可以只设置 name 字段 // D2Admin 会自动添加不重复 id 生成菜单,并在点击时提示这是一个临时菜单 const headerMenuConfig = [ { name: '空菜单', icon: 'flask', children: [ { name: 'menu 1', children: [ { name: 'menu 1-1', children: [ { name: 'menu 1-1-1', }, { name: 'menu 1-1-2', }, ], }, { name: 'menu 1-2', }, ], }, { name: 'menu 2', }, { name: 'menu 3', }, ], }, { name: '演示页面', icon: 'folder-o', children: [ { name: '演示 1', path: '/demo1/', }, { name: '演示 2', path: '/demo2/', }, ], }, ]; // 请根据自身业务逻辑修改导出设置,并在合适的位置赋给对应的菜单 // 参考 // 设置顶栏菜单的方法 (vuex) // $store.commit('d2adminMenuHeaderSet', menus) // 设置侧边栏菜单的方法 (vuex) // $store.commit('d2adminMenuAsideSet', menus) // 你可以在任何地方使用上述方法修改顶栏和侧边栏菜单 // 导出顶栏菜单 export const menuHeader = util.recursiveMenuConfig(headerMenuConfig); // 导出侧边栏菜单 export const menuAside = util.recursiveMenuConfig(asideMenuConfig);
17.117647
80
0.417096
7dfbea0b8783259a9a9de1e48ed824449adee604
7,827
js
JavaScript
lib/context2d.js
vweevers/node-canvas
138abe9aa30b75e8406ceddd9177bff20ac44ceb
[ "Unlicense", "MIT" ]
707
2015-01-01T18:54:07.000Z
2022-03-31T07:53:48.000Z
lib/context2d.js
vweevers/node-canvas
138abe9aa30b75e8406ceddd9177bff20ac44ceb
[ "Unlicense", "MIT" ]
5
2018-06-04T03:53:12.000Z
2019-01-10T10:48:01.000Z
lib/context2d.js
vweevers/node-canvas
138abe9aa30b75e8406ceddd9177bff20ac44ceb
[ "Unlicense", "MIT" ]
211
2015-01-09T15:44:51.000Z
2021-12-21T17:05:59.000Z
/*! * Canvas - Context2d * Copyright (c) 2010 LearnBoost <tj@learnboost.com> * MIT Licensed */ /** * Module dependencies. */ var canvas = require('./bindings') , Context2d = canvas.CanvasRenderingContext2d , CanvasGradient = canvas.CanvasGradient , CanvasPattern = canvas.CanvasPattern , ImageData = canvas.ImageData , PixelArray = canvas.CanvasPixelArray; /** * Export `Context2d` as the module. */ var Context2d = exports = module.exports = Context2d; /** * Cache color string RGBA values. */ var cache = {}; /** * Text baselines. */ var baselines = ['alphabetic', 'top', 'bottom', 'middle', 'ideographic', 'hanging']; /** * Font RegExp helpers. */ var weights = 'normal|bold|bolder|lighter|[1-9]00' , styles = 'normal|italic|oblique' , units = 'px|pt|pc|in|cm|mm|%' , string = '\'([^\']+)\'|"([^"]+)"|[\\w-]+'; /** * Font parser RegExp; */ var fontre = new RegExp('^ *' + '(?:(' + weights + ') *)?' + '(?:(' + styles + ') *)?' + '([\\d\\.]+)(' + units + ') *' + '((?:' + string + ')( *, *(?:' + string + '))*)' ); /** * Parse font `str`. * * @param {String} str * @return {Object} * @api private */ var parseFont = exports.parseFont = function(str){ var font = {} , captures = fontre.exec(str); // Invalid if (!captures) return; // Cached if (cache[str]) return cache[str]; // Populate font object font.weight = captures[1] || 'normal'; font.style = captures[2] || 'normal'; font.size = parseFloat(captures[3]); font.unit = captures[4]; font.family = captures[5].replace(/["']/g, '').split(',')[0]; // TODO: dpi // TODO: remaining unit conversion switch (font.unit) { case 'pt': font.size /= .75; break; case 'in': font.size *= 96; break; case 'mm': font.size *= 96.0 / 25.4; break; case 'cm': font.size *= 96.0 / 2.54; break; } return cache[str] = font; }; /** * Enable or disable image smoothing. * * @api public */ Context2d.prototype.__defineSetter__('imageSmoothingEnabled', function(val){ this._imageSmoothing = !! val; this.patternQuality = val ? 'best' : 'fast'; }); /** * Get image smoothing value. * * @api public */ Context2d.prototype.__defineGetter__('imageSmoothingEnabled', function(val){ return !! this._imageSmoothing; }); /** * Create a pattern from `Image` or `Canvas`. * * @param {Image|Canvas} image * @param {String} repetition * @return {CanvasPattern} * @api public */ Context2d.prototype.createPattern = function(image, repetition){ // TODO Use repetition (currently always 'repeat') return new CanvasPattern(image); }; /** * Create a linear gradient at the given point `(x0, y0)` and `(x1, y1)`. * * @param {Number} x0 * @param {Number} y0 * @param {Number} x1 * @param {Number} y1 * @return {CanvasGradient} * @api public */ Context2d.prototype.createLinearGradient = function(x0, y0, x1, y1){ return new CanvasGradient(x0, y0, x1, y1); }; /** * Create a radial gradient at the given point `(x0, y0)` and `(x1, y1)` * and radius `r0` and `r1`. * * @param {Number} x0 * @param {Number} y0 * @param {Number} r0 * @param {Number} x1 * @param {Number} y1 * @param {Number} r1 * @return {CanvasGradient} * @api public */ Context2d.prototype.createRadialGradient = function(x0, y0, r0, x1, y1, r1){ return new CanvasGradient(x0, y0, r0, x1, y1, r1); }; /** * Reset transform matrix to identity, then apply the given args. * * @param {...} * @api public */ Context2d.prototype.setTransform = function(){ this.resetTransform(); this.transform.apply(this, arguments); }; /** * Set the fill style with the given css color string. * * @api public */ Context2d.prototype.__defineSetter__('fillStyle', function(val){ if (!val) return; if ('CanvasGradient' == val.constructor.name || 'CanvasPattern' == val.constructor.name) { this.lastFillStyle = val; this._setFillPattern(val); } else if ('string' == typeof val) { this._setFillColor(val); } }); /** * Get previous fill style. * * @return {CanvasGradient|String} * @api public */ Context2d.prototype.__defineGetter__('fillStyle', function(){ return this.lastFillStyle || this.fillColor; }); /** * Set the stroke style with the given css color string. * * @api public */ Context2d.prototype.__defineSetter__('strokeStyle', function(val){ if (!val) return; if ('CanvasGradient' == val.constructor.name || 'CanvasPattern' == val.constructor.name) { this.lastStrokeStyle = val; this._setStrokePattern(val); } else if ('string' == typeof val) { this._setStrokeColor(val); } }); /** * Get previous stroke style. * * @return {CanvasGradient|String} * @api public */ Context2d.prototype.__defineGetter__('strokeStyle', function(){ return this.lastStrokeStyle || this.strokeColor; }); /** * Register `font` for usage. * * @param {Font} font * @api public */ Context2d.prototype.addFont = function(font) { this._fonts = this._fonts || {}; if (this._fonts[font.name]) return; this._fonts[font.name] = font; }; /** * Set font. * * @see exports.parseFont() * @api public */ Context2d.prototype.__defineSetter__('font', function(val){ if (!val) return; if ('string' == typeof val) { var font; if (font = parseFont(val)) { this.lastFontString = val; var fonts = this._fonts; if (fonts && fonts[font.family]) { var fontObj = fonts[font.family]; var type = font.weight + '-' + font.style; var fontFace = fontObj.getFace(type); this._setFontFace(fontFace, font.size); } else { this._setFont( font.weight , font.style , font.size , font.unit , font.family); } } } }); /** * Get the current font. * * @api public */ Context2d.prototype.__defineGetter__('font', function(){ return this.lastFontString || '10px sans-serif'; }); /** * Set text baseline. * * @api public */ Context2d.prototype.__defineSetter__('textBaseline', function(val){ if (!val) return; var n = baselines.indexOf(val); if (~n) { this.lastBaseline = val; this._setTextBaseline(n); } }); /** * Get the current baseline setting. * * @api public */ Context2d.prototype.__defineGetter__('textBaseline', function(){ return this.lastBaseline || 'alphabetic'; }); /** * Set text alignment. * * @api public */ Context2d.prototype.__defineSetter__('textAlign', function(val){ switch (val) { case 'center': this._setTextAlignment(0); this.lastTextAlignment = val; break; case 'left': case 'start': this._setTextAlignment(-1); this.lastTextAlignment = val; break; case 'right': case 'end': this._setTextAlignment(1); this.lastTextAlignment = val; break; } }); /** * Get the current font. * * @see exports.parseFont() * @api public */ Context2d.prototype.__defineGetter__('textAlign', function(){ return this.lastTextAlignment || 'start'; }); /** * Get `ImageData` with the given rect. * * @param {Number} x * @param {Number} y * @param {Number} width * @param {Number} height * @return {ImageData} * @api public */ Context2d.prototype.getImageData = function(x, y, width, height){ var arr = new PixelArray(this.canvas, x, y, width, height); return new ImageData(arr); }; /** * Create `ImageData` with the given dimensions or * `ImageData` instance for dimensions. * * @param {Number|ImageData} width * @param {Number} height * @return {ImageData} * @api public */ Context2d.prototype.createImageData = function(width, height){ if ('ImageData' == width.constructor.name) { height = width.height; width = width.width; } return new ImageData(new PixelArray(width, height)); };
20.224806
84
0.621311
7dfc5dc056cd55ba789578ce2fc5a7849de1ed18
1,104
js
JavaScript
uploadMultipleFormFile/app.js
yuexihuachen/examples
df5bb41ec06758d7552cb54c5ea09b45a3667a23
[ "Apache-2.0" ]
null
null
null
uploadMultipleFormFile/app.js
yuexihuachen/examples
df5bb41ec06758d7552cb54c5ea09b45a3667a23
[ "Apache-2.0" ]
null
null
null
uploadMultipleFormFile/app.js
yuexihuachen/examples
df5bb41ec06758d7552cb54c5ea09b45a3667a23
[ "Apache-2.0" ]
null
null
null
const express = require('express') const fileUpload = require('express-fileupload'); const fs = require("fs") const path = require("path") const util = require('util'); const app = express() const port = 3000 app.use(express.static('.')) app.use(express.json({ limit: 50 * 1024 * 1024 })); app.use(fileUpload({ limit: 50 * 1024 * 1024 })); app.post("/uploadFormFile", async (req, res) => { let sampleFile; let uploadPath; if (!req.files || Object.keys(req.files).length === 0) { return res.status(400).send('No files were uploaded.'); } sampleFile = req.files.sampleFile; let result = {msg:"success"} for (const file of sampleFile) { uploadPath = __dirname + '/files/' + file.name; result = await new Promise((resolve, reject) => { file.mv(uploadPath, function(err) { if (err) { reject({msg:"failed"}) } resolve({msg:"success"}) }); }) } res.send(result); }) app.get('/', (req, res) => { res.send('Hello World!') }) app.listen(port, () => { console.log(`Example app listening at http://localhost:${port}`) })
22.530612
66
0.605978
7dfcd01dc353b3699738c524fff6e202b678ddb1
535
js
JavaScript
examples/streams.js
Anupam-dagar/zulip-js
901466d961adb1b87c311c2c786c73a065cf48a3
[ "MIT" ]
null
null
null
examples/streams.js
Anupam-dagar/zulip-js
901466d961adb1b87c311c2c786c73a065cf48a3
[ "MIT" ]
null
null
null
examples/streams.js
Anupam-dagar/zulip-js
901466d961adb1b87c311c2c786c73a065cf48a3
[ "MIT" ]
null
null
null
const zulip = require('../lib/'); const config = { username: process.env.ZULIP_USERNAME, apiKey: process.env.ZULIP_API_KEY, realm: process.env.ZULIP_REALM, }; zulip(config).then((z) => { // Fetch all streams z.streams.retrieve() .then(console.log) // Fetch user's subscriptions .then(() => z.streams.subscriptions.retrieve()) .then(console.log) // Get all the topics in the stream with ID 15 .then(() => z.streams.topics.retrieve({ stream_id: 15 })) .then(console.log); }).catch(err => console.log(err.msg));
26.75
59
0.669159
7dfd53fb16f74db974a9cf1c4de9f7d423a668ff
2,506
js
JavaScript
repos/keg-components/build/cjs/native/grid.js
simpleviewinc/sv-keg
337f1b07675d646641e7e283bb4964f1ec7b8879
[ "MIT" ]
2
2020-10-08T20:23:01.000Z
2020-11-18T15:44:13.000Z
repos/keg-components/build/cjs/native/grid.js
simpleviewinc/sv-keg
337f1b07675d646641e7e283bb4964f1ec7b8879
[ "MIT" ]
85
2020-09-02T18:35:50.000Z
2022-03-29T05:51:10.000Z
repos/keg-components/build/cjs/native/grid.js
simpleviewinc/sv-keg
337f1b07675d646641e7e283bb4964f1ec7b8879
[ "MIT" ]
4
2020-08-27T16:04:00.000Z
2021-01-06T07:25:38.000Z
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var _rollupPluginBabelHelpers = require('./_rollupPluginBabelHelpers-95f0bff4.js'); var React = require('react'); var container = require('./container.js'); var row = require('./row.js'); var reTheme = require('@keg-hub/re-theme'); var jsutils = require('@keg-hub/jsutils'); var useClassList_native = require('./useClassList.native-9e7810c9.js'); require('./view.native-5d72f4dd.js'); require('react-native'); require('./useClassName.native-3d1a229b.js'); require('./getPressHandler.js'); require('./getPlatform-24228c6c.js'); require('@keg-hub/re-theme/colors'); function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } var React__default = /*#__PURE__*/_interopDefaultLegacy(React); var _excluded = ["className", "children", "style"]; var buildCenterStyles = function buildCenterStyles(isCenter) { return isCenter === 'x' || isCenter === 'xaxis' || isCenter === 'x-axis' ? { justifyContent: 'center' } : isCenter === 'y' || isCenter === 'yaxis' || isCenter === 'y-axis' ? { alignItems: 'center' } : isCenter && { alignItems: 'center', justifyContent: 'center' } || {}; }; var getChildAttrs = function getChildAttrs(children) { children = jsutils.isArr(children) && children || [children]; return children.reduce(function (attrs, child) { if (attrs.isRow && attrs.isCenter) return attrs; if (!attrs.isRow && child && child.type === row.Row) attrs.isRow = true; if (!attrs.isCenter && child && child.props && child.props.center) attrs.isCenter = child.props.center.toString().toLowerCase(); return attrs; }, { isRow: false, isCenter: false }); }; var Grid = function Grid(_ref) { _ref.className; var children = _ref.children, style = _ref.style, props = _rollupPluginBabelHelpers._objectWithoutProperties(_ref, _excluded); var theme = reTheme.useTheme(); var _getChildAttrs = getChildAttrs(children), isRow = _getChildAttrs.isRow, isCenter = _getChildAttrs.isCenter; return React__default['default'].createElement(container.Container, _rollupPluginBabelHelpers._extends({}, props, { className: useClassList_native.useClassList(), flexDir: isRow ? 'column' : 'row', size: 1, style: [jsutils.get(theme, ['layout', 'grid', 'wrapper']), style, isCenter && buildCenterStyles(isCenter)] }), children); }; exports.Grid = Grid; //# sourceMappingURL=grid.js.map
38.553846
132
0.681564
7dfd707e347c7bf4114dca7213740c4449f4e7f1
376
js
JavaScript
app/containers/species/SpeciesDetailSearch.js
dancer2090/csn-tool-dev
0e3bd7b36c62b89c13bae05ae13d56c71ccaa224
[ "MIT" ]
1
2016-12-01T13:38:43.000Z
2016-12-01T13:38:43.000Z
app/containers/species/SpeciesDetailSearch.js
dancer2090/csn-tool-dev
0e3bd7b36c62b89c13bae05ae13d56c71ccaa224
[ "MIT" ]
78
2016-10-26T14:47:49.000Z
2020-04-14T16:09:08.000Z
app/containers/species/SpeciesDetailSearch.js
dancer2090/csn-tool-dev
0e3bd7b36c62b89c13bae05ae13d56c71ccaa224
[ "MIT" ]
1
2021-02-01T14:39:28.000Z
2021-02-01T14:39:28.000Z
import { connect } from 'react-redux'; import SearchFilter from 'components/common/SearchFilter'; import { setSearchFilter } from 'actions/species'; const mapStateToProps = () => ({}); const mapDispatchToProps = (dispatch) => ({ setSearchFilter: (search) => dispatch(setSearchFilter(search)) }); export default connect(mapStateToProps, mapDispatchToProps)(SearchFilter);
31.333333
74
0.75
7dfe31a532562bbde38fe567e3aa2a5861399256
175
js
JavaScript
Community/iot_device_registration/js/iotdeviceregistration_page.js
TMAers/gateway-workflows
38f22f1b31d0a4d18db0ad7466ce72f518c17076
[ "Apache-2.0" ]
null
null
null
Community/iot_device_registration/js/iotdeviceregistration_page.js
TMAers/gateway-workflows
38f22f1b31d0a4d18db0ad7466ce72f518c17076
[ "Apache-2.0" ]
null
null
null
Community/iot_device_registration/js/iotdeviceregistration_page.js
TMAers/gateway-workflows
38f22f1b31d0a4d18db0ad7466ce72f518c17076
[ "Apache-2.0" ]
null
null
null
// Copyright 2019 BlueCat Networks. All rights reserved. $(document).ready(function() { $("#file").prop("disabled", false); $("#submit").prop("disabled", false); });
25
56
0.628571
7dfe9f90e1544bcbce06b83dec0457fc075e0ee6
20,378
js
JavaScript
sketch.js
test1374/wallmaker
bca7ce3f5ad20dc6db2ef3fd21bd79280e3423a7
[ "MIT" ]
null
null
null
sketch.js
test1374/wallmaker
bca7ce3f5ad20dc6db2ef3fd21bd79280e3423a7
[ "MIT" ]
null
null
null
sketch.js
test1374/wallmaker
bca7ce3f5ad20dc6db2ef3fd21bd79280e3423a7
[ "MIT" ]
1
2021-12-21T21:14:21.000Z
2021-12-21T21:14:21.000Z
let tabs = ['floor', 'wall', 'door','ground'], blockSize = 20, wallcolour, doorcolour, doorcolours, floortexture, wallcolours, floortextures, walltype, door, doorframe, door2, doorframe2, groundcolours, lines = true, dgrey, lgrey, wall1, wall2, wall3, wall4, brick1, tool, mansion, house, barn, bank, bunker1, bunker2, tab = 'floor' , underground = false, jura, menu = false, backgroundcolour, walls = [], floors = []; function preload() { wall1 = loadImage("wall1.png"); wall2 = loadImage("wall2.png"); wall3 = loadImage("wall3.png"); wall4 = loadImage("wall4.png"); brick1 = loadImage("brick1.png"); bank = loadImage('pattern-bank.png'); barn = loadImage('pattern-barn.png'); house = loadImage('pattern-house.png'); mansion = loadImage('pattern-mansion.png'); bunker1 = loadImage('whitefloorbunker.png'); bunker2 = loadImage('blackfloorbunker.png'); dgrey = loadImage('darkgrey.png'); lgrey = loadImage('lightgrey.png'); jura = loadFont('Jura-Bold.ttf'); door = loadImage('door.png'); doorframe = loadImage('doorframe.png'); door2 = loadImage('door2.png'); doorframe2 = loadImage('doorframe2.png'); floortextures = [brick1, bank, barn, house, bunker1, bunker2, dgrey, lgrey]; wallcolours = ['#ffffff', '#a18168', '#775529', '#a3977d', '#6d7645', '#233742', '#6c6c6b', '#814100', '#42060b', '#483737ff', '#119099']; groundcolours = [['#80AF49', '#1B0D03'], ['#BDBDBD', '#1B0D03'], ['#DFA757', '#3D0D03'], ['#4E6128', '#1B0D03'], ['#8E832A', '#1B0D03'], ['#212404', '#120801'], ['#B4B02E', '#3D0D03'], ['#4D5A68', '#1B0D03'], ['#2F5737', '#1B0D03'], ['#58657E', '#1B0D03'], ['#2D385D', '#1B0D03'], ['#3d3d3d', '#1d0a02']]; doorcolours = ['#ffffff', '#4b4b4b', '#eff542', '#0e1466', '#CC9966', '#332211', '#119099']; } function setup() { createCanvas(windowWidth, windowHeight); blockSize = 20; backgroundcolour = 0; tool = 'floor'; floortexture = bunker1; wallcolour = '#ffffff'; doorcolour = '#ffffff'; walltype = 'wall'; for(var y = 0; y < ceil(height / blockSize); y++) { for(var x = 0; x < floor(width / blockSize); x++) { if(x == 0) { walls.push([]); floors.push([]); } walls[y].push([0, '#ffffff', '#ffffff']); floors[y].push(0); } } } imageButton = function(img, x, y, w, h, v, e, c, t) { rectMode(CORNER); imageMode(CORNER); if(img !== null) { image(img, x, y, w, h); } noStroke(); if(c !== null) { fill(c); rect(x, y, w, h); } strokeWeight(1); noFill(); stroke(255); if(mouseX >= x && mouseX <= x + w && mouseY >= y && mouseY <= y + h) { cursor('pointer'); rect(x, y, w, h); if(mouseIsPressed) { switch(v) { case 'wall': wallcolour = e; break; case 'floor': floortexture = e; break; case 'ground': backgroundcolour = e; break; case 'tab': tab = e; break; case 'tool': tool = e; break; case 'walltype': walltype = e; break; case 'line': lines = e; break; case 'above/below': underground = e; break; case 'doorcolour': doorcolour = e; break; } } } if(t) { text(t, x + w / 2, y + h / 2); } } keyReleased = function() { if(key.toLowerCase() == 'm' && menu == false) { menu = true; } else if(key.toLowerCase() == 'm' && menu == true) { menu = false; } } function draw() { rectMode(CORNER); cursor('none'); if(underground == false) { background(groundcolours[backgroundcolour][0]); } else { background(groundcolours[backgroundcolour][1]); } //background(20); stroke(0, 0, 0, 100); if(lines == true && underground == false) { for(var h = 0; h < width / blockSize * 4; h++) { line(0, h * blockSize * 4, width, h * blockSize * 4) } for(var j = 0; j < height / blockSize * 4; j++) { line(j * blockSize * 4, 0, j * blockSize * 4, height); } } imageMode(CENTER); angleMode(DEGREES); noTint(); noFill(); for(var i = 0; i < floors.length; i++) { for(var b = 0; b < floors[i].length; b++) { noStroke(); rectMode(CENTER); if(floors[i][b] !== 0 && floors[i][b] !== 1) { if(mouseIsPressed && floor(mouseX / blockSize) === b && floor(mouseY / blockSize) === i && mouseButton === LEFT && tool === 'floor' && menu == false) { floors[i][b] = 0; } var l = false, r = false, a = false, u = false; if(floors[i][b - 1] === 2) { l = true; } if(floors[i][b + 1] === 2) { r = true; } if(floors[i+1][b] === 2) { u = true; } if(floors[i-1][b] === 2) { a = true; } translate(b * blockSize + blockSize, i * blockSize + blockSize); switch(floors[i][b]) { case 2: image(bunker1, 0, 0, blockSize, blockSize); break; case 3: image(bunker2, 0, 0, blockSize, blockSize); break; case 4: image(mansion, 0, 0, blockSize, blockSize); break; case 5: image(house, 0, 0, blockSize, blockSize); break; case 6: image(barn, 0, 0, blockSize, blockSize); break; case 7: image(bank, 0, 0, blockSize, blockSize); break; case 8: image(brick1, 0, 0, blockSize, blockSize); break; case 9: image(dgrey, 0, 0, blockSize, blockSize); break; case 10: image(lgrey, 0, 0, blockSize, blockSize); break; } translate(-(b * blockSize + blockSize), -(i * blockSize + blockSize)); } } } noFill(); rectMode(CORNER); for(var y = 0; y < walls.length; y++) { for(var x = 0; x < walls[y].length; x++) { if(walls[y][x][0] == 3) { var L = false, R = false, A = false, U = false; if(walls[y][x - 1][0] == 2) { L = true; } if(walls[y][x + 1][0] == 2) { R = true; } if(walls[y+1][x][0] == 2) { U = true; } if(walls[y-1][x][0] == 2) { A = true; } translate(x * blockSize + blockSize / 2, y * blockSize + blockSize / 2); tint(walls[y][x][1]); if(A == true && U == true || A == false && U == false && L == false && R == false) { image(doorframe, 0, 0, blockSize, blockSize); noTint(); tint(walls[y][x][2]); image(door, 0, 0, blockSize, blockSize); } else if(L == true && R == true) { rotate(90); image(doorframe, 0, 0, blockSize, blockSize); noTint(); tint(walls[y][x][2]); image(door, 0, 0, blockSize, blockSize); rotate(-90); } else if(U == true && A == false && L == false && R == false) { image(doorframe2, 0, 0, blockSize, blockSize); noTint(); tint(walls[y][x][2]); image(door2, 0, 0, blockSize, blockSize); } else if(A == true && U == false && L == false && R == false) { rotate(180); image(doorframe2, 0, 0, blockSize, blockSize); noTint(); tint(walls[y][x][2]); image(door2, 0, 0, blockSize, blockSize); rotate(-180); } else if(A == false && U == false && L == true && R == false) { rotate(90); image(doorframe2, 0, 0, blockSize, blockSize); noTint(); tint(walls[y][x][2]); image(door2, 0, 0, blockSize, blockSize); rotate(-90); } else if(U == false && A == false && L == false && R == true) { rotate(270); image(doorframe2, 0, 0, blockSize, blockSize); noTint(); tint(walls[y][x][2]); image(door2, 0, 0, blockSize, blockSize); rotate(-270); } else if(A == true && U == false && R == false && L == true) { rotate(90); image(doorframe2, 0, 0, blockSize, blockSize); noTint(); tint(walls[y][x][2]); image(door2, 0, 0, blockSize, blockSize); rotate(-90); } else if(A == true && U == false && R == true && L == false) { rotate(270); image(doorframe2, 0, 0, blockSize, blockSize); noTint(); tint(walls[y][x][2]); image(door2, 0, 0, blockSize, blockSize); rotate(-270); } else if(A == false && U == true && R == false && L == true) { image(doorframe2, 0, 0, blockSize, blockSize); noTint(); tint(walls[y][x][2]); image(door2, 0, 0, blockSize, blockSize); } else if(A == false && U == true && R == true && L == false) { image(doorframe2, 0, 0, blockSize, blockSize); noTint(); tint(walls[y][x][2]); image(door2, 0, 0, blockSize, blockSize); } translate(-(x * blockSize + blockSize / 2), -(y * blockSize + blockSize / 2)); } else if(walls[y][x][0] == 2) { var left = false, right = false, above = false, under = false; if(walls[y][x - 1][0] >= 2) { left = true; } if(walls[y][x + 1][0] >= 2) { right = true; } if(walls[y+1][x][0] >= 2) { under = true; } if(walls[y-1][x][0] >= 2) { above = true; } translate(x * blockSize + blockSize / 2, y * blockSize + blockSize / 2); tint(walls[y][x][1]); if(above === true && under === true && left === true && right === true) { image(wall4, 0, 0, blockSize, blockSize); } if(right === true && left === true && under === false && above === false || right === true && left === false && above === false && under === false || right === false && left === true && above === false && under === false) { rotate(90); image(wall1, 0, 0, blockSize, blockSize); rotate(-90); } if(above === true && under === true && right === false && left === false || right === false && left === false && above === true && under === false || right === false && left === false && above === false && under === true) { image(wall1, 0, 0, blockSize, blockSize); } if(right === true && left === false && above === true && under === false) { rotate(-90); image(wall2, 0, 0, blockSize, blockSize); rotate(90); } if(right === true && left === false && above === false && under === true) { image(wall2, 0, 0, blockSize, blockSize); } if(left === true && right === false && above === false && under === true) { rotate(90); image(wall2, 0, 0, blockSize, blockSize); rotate(-90); } if(left === true && right === false && above === true && under === false) { rotate(180); image(wall2, 0, 0, blockSize, blockSize); rotate(-180); } if(left === true && right === true && above === true && under === false) { rotate(-90); image(wall3, 0, 0, blockSize, blockSize); rotate(90); } if(left === true && right === true && above === false && under === true) { rotate(90); image(wall3, 0, 0, blockSize, blockSize); rotate(-90); } if(above === true && under === true && right === true && left === false) { image(wall3, 0, 0, blockSize, blockSize); } if(above === true && under === true && right === false && left === true) { rotate(180); image(wall3, 0, 0, blockSize, blockSize); rotate(-180); } if(above === false && under === false && right === false && left === false) { image(wall1, 0, 0, blockSize, blockSize); } translate(-(x * blockSize + blockSize / 2), -(y * blockSize + blockSize / 2)); fill(0); if(walls[y][x - 1][1] !== walls[y][x][1] && walls[y][x - 1][0] !== 0) { rect(x * blockSize - blockSize / 40, y * blockSize + blockSize / 2.8, blockSize / 20, blockSize / 3.8); } if(walls[y - 1][x][1] !== walls[y][x][1] && walls[y - 1][x][0] !== 0) { rect(x * blockSize + blockSize / 2.8, y * blockSize - blockSize / 40, blockSize / 3.8, blockSize / 20); } noFill(); } } } noTint(); if(underground == false) { stroke(0); } else { stroke(255); } if(tool === 'wall' && menu == false) { rect(floor(mouseX / blockSize) * blockSize, floor(mouseY / blockSize) * blockSize, blockSize, blockSize); fill(255, 20, 20); noStroke(); ellipse(mouseX, mouseY, blockSize / 2, blockSize / 2); } if(tool === 'floor' && menu == false) { rect(floor(mouseX / blockSize) * blockSize + blockSize / 2, floor(mouseY / blockSize) * blockSize + blockSize / 2, blockSize, blockSize); fill(255, 20, 20); noStroke(); ellipse(mouseX + blockSize / 2, mouseY + blockSize / 2, blockSize / 2, blockSize / 2); } document.addEventListener("contextmenu", (event) => event.preventDefault()); if(key.toLowerCase() === 'a') { tool = 'wall'; } if(key.toLowerCase() === 's') { tool = 'floor'; } noStroke(); if(menu == true) { fill(0); rect(blockSize, blockSize, width - blockSize * 2, height - blockSize * 2); cursor('default'); textFont(jura); textAlign(CENTER, CENTER); textSize(blockSize * 1.4); for(var c = 0; c < tabs.length; c++) { imageButton(null, blockSize + ((width - blockSize * 2) / tabs.length) * c, blockSize, (width - blockSize * 2) / tabs.length, blockSize * 2, 'tab', tabs[c], '#000000', tabs[c].toUpperCase()); } if(tab == 'floor') { textSize(20); text("Floor textures", width / 2, blockSize * 6); for(let i = 0; i < floortextures.length; i++) { let x = blockSize * 4 + i * (blockSize * 4), y = blockSize * 7; if(x >= width - blockSize * 4) { x -= floor(width / blockSize) * blockSize - (blockSize * 7); y += blockSize * 4; } imageButton(floortextures[i], x, y, blockSize * 4, blockSize * 4, 'floor', floortextures[i], null); if(floortexture == floortextures[i]) { noFill(); stroke(0, 255, 0); strokeWeight(4); rect(x + 1, y + 1, blockSize * 4 - 2, blockSize * 4 - 2); } } } if(tab == 'wall') { textSize(20); text("Wall Colours", width / 2, blockSize * 6); for(let i = 0; i < wallcolours.length; i++) { let x = blockSize * 4 + i * (blockSize * 4), y = blockSize * 7; if(x >= width - blockSize * 4) { x -= floor(width / blockSize) * blockSize - (blockSize * 7); y += blockSize * 4; } imageButton(null, x, y, blockSize * 4, blockSize * 4, 'wall', wallcolours[i], wallcolours[i]); if(wallcolour == wallcolours[i]) { noFill(); stroke(0, 255, 0); strokeWeight(4); rect(x + 1, y + 1, blockSize * 4 - 2, blockSize * 4 - 2); } } fill(0); stroke(255); strokeWeight(2); text("Select door or walls", width / 2, blockSize * 17); image(doorframe, width / 2 - blockSize * 4, blockSize * 18, blockSize * 4, blockSize * 4); imageButton(door, width / 2 - blockSize * 4, blockSize * 18, blockSize * 4, blockSize * 4, 'walltype', 'door', null); imageButton(wall1, width / 2, blockSize * 18, blockSize * 4, blockSize * 4, 'walltype', 'wall', null); } if(tab == 'door') { textSize(20); text('Door Colours', width / 2, blockSize * 6); for(let i = 0; i < doorcolours.length; i++) { let x = blockSize * 4 + i * (blockSize * 4), y = blockSize * 7; if(x >= width - blockSize * 6) { x -= round(width / blockSize) * blockSize - (blockSize * 7); y += blockSize * 4; } if(x >= width - blockSize * 6) { x -= round(width / blockSize) * blockSize - (blockSize * 7); y += blockSize * 4; } imageButton(null, x, y, blockSize * 4, blockSize * 4, 'doorcolour', doorcolours[i], doorcolours[i], null); if(doorcolour == i) { noFill(); stroke(0, 255, 0); strokeWeight(4); rect(x + 1, y + 1, blockSize * 4 - 2, blockSize * 4 - 2); } } } if(tab == 'ground') { textSize(20); text("Ground Colours", width / 2, blockSize * 6); for(let i = 0; i < groundcolours.length; i++) { let x = blockSize * 4 + i * (blockSize * 4), y = blockSize * 7; if(x >= width - blockSize * 6) { x -= round(width / blockSize) * blockSize - (blockSize * 7); y += blockSize * 4; } if(x >= width - blockSize * 6) { x -= round(width / blockSize) * blockSize - (blockSize * 7); y += blockSize * 4; } imageButton(null, x, y, blockSize * 4, blockSize * 4, 'ground', i, groundcolours[i][0]); if(backgroundcolour == i) { noFill(); stroke(0, 255, 0); strokeWeight(4); rect(x + 1, y + 1, blockSize * 4 - 2, blockSize * 4 - 2); } } fill(0); stroke(255); strokeWeight(2); text("Above or below ground", width / 2, blockSize * 17); imageButton(null, width / 2 - blockSize * 4, blockSize * 18, blockSize * 4, blockSize * 4, 'above/below', false, groundcolours[backgroundcolour][0]); imageButton(null, width / 2, blockSize * 18, blockSize * 4, blockSize * 4, 'above/below', true, groundcolours[backgroundcolour][1]); } } strokeWeight(1); noStroke(); fill(255, 0, 0); text(round(frameRate()), 20, 20); if(floor(mouseX / blockSize) < floor(width / blockSize) - 1 && floor(mouseY / blockSize) < ceil(height / blockSize) - 1 && floor(mouseX / blockSize) > 0 && floor(mouseY / blockSize) !== 0 && floor(mouseY / blockSize) > 0) { if(floors[floor(mouseY / blockSize)][floor(mouseX / blockSize)] === 0 && mouseButton == RIGHT && tool == 'floor' && menu == false && mouseIsPressed) { switch(floortexture) { case bunker1: floors[floor(mouseY / blockSize)][floor(mouseX / blockSize)] = 2; break; case bunker2: floors[floor(mouseY / blockSize)][floor(mouseX / blockSize)] = 3; break; case mansion: floors[floor(mouseY / blockSize)][floor(mouseX / blockSize)] = 4; break; case house: floors[floor(mouseY / blockSize)][floor(mouseX / blockSize)] = 5; break; case barn: floors[floor(mouseY / blockSize)][floor(mouseX / blockSize)] = 6; break; case bank: floors[floor(mouseY / blockSize)][floor(mouseX / blockSize)] = 7; break; case brick1: floors[floor(mouseY / blockSize)][floor(mouseX / blockSize)] = 8; break; case dgrey: floors[floor(mouseY / blockSize)][floor(mouseX / blockSize)] = 9; break; case lgrey: floors[floor(mouseY / blockSize)][floor(mouseX / blockSize)] = 10; break; } } if(walls[floor(mouseY / blockSize)][floor(mouseX / blockSize)][0] === 0 && mouseIsPressed && tool === 'wall' && mouseButton === RIGHT && menu == false && walltype == 'wall') { walls[floor(mouseY / blockSize)][floor(mouseX / blockSize)] = [2, wallcolour]; } if(walls[floor(mouseY / blockSize)][floor(mouseX / blockSize)][0] === 0 && mouseIsPressed && tool === 'wall' && mouseButton === RIGHT && menu == false && walltype == 'door') { walls[floor(mouseY / blockSize)][floor(mouseX / blockSize)] = [3, wallcolour, doorcolour]; } if(walls[floor(mouseY / blockSize)][floor(mouseX / blockSize)][0] >= 2 && mouseIsPressed && tool === 'wall' && mouseButton === LEFT && menu == false && walls[floor(mouseY / blockSize)][floor(mouseX / blockSize)][0] >= 2) { walls[floor(mouseY / blockSize)][floor(mouseX / blockSize)][0] = 0; } } width = windowWidth; height = windowHeight; }
37.667283
418
0.505741
7dfeaae5227efdfba1d304f3465710cbe5f9e529
1,952
js
JavaScript
node_modules/@bitauth/libauth/build/main/lib/transaction/verify-transaction.js
a-cladys/fortellisapi-wrapper-library
39f56b4112afe7f87857ad56d10bce3a31926fe2
[ "MIT" ]
null
null
null
node_modules/@bitauth/libauth/build/main/lib/transaction/verify-transaction.js
a-cladys/fortellisapi-wrapper-library
39f56b4112afe7f87857ad56d10bce3a31926fe2
[ "MIT" ]
null
null
null
node_modules/@bitauth/libauth/build/main/lib/transaction/verify-transaction.js
a-cladys/fortellisapi-wrapper-library
39f56b4112afe7f87857ad56d10bce3a31926fe2
[ "MIT" ]
null
null
null
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.verifyTransaction = void 0; /** * Statelessly verify a transaction given an `AuthenticationVirtualMachine` and * a list of spent outputs (the `lockingBytecode` and `satoshis` being spent by * each input). * * Note, while the virtual machine will evaluate locktime-related operations * against the transactions own `locktime`, this method does not verify the * transaction's `locktime` property itself (allowing verification to be * stateless). * * Before a statelessly verified transaction can be added to the blockchain, * node implementations must confirm that: * - all `spentOutputs` are still unspent, and * - both relative and absolute locktime consensus requirements have been met. * (See BIP65, BIP68, and BIP112 for details.) * * @param spentOutputs - an array of the `Output`s spent by the transaction's * `inputs` in matching order (`inputs[0]` spends `spentOutputs[0]`, etc.) * @param transaction - the transaction to verify * @param vm - the authentication virtual machine to use in validation */ exports.verifyTransaction = ({ spentOutputs, transaction, vm, }) => { if (transaction.inputs.length !== spentOutputs.length) { return [ 'Unable to verify transaction: a spent output must be provided for each transaction input.', ]; } const errors = transaction.inputs.reduce((all, _, index) => { const program = { inputIndex: index, sourceOutput: spentOutputs[index], spendingTransaction: transaction, }; const state = vm.evaluate(program); const verify = vm.verify(state); if (verify === true) { return all; } return [...all, `Error in evaluating input index "${index}": ${verify}`]; }, []); return errors.length === 0 ? true : errors; }; //# sourceMappingURL=verify-transaction.js.map
42.434783
104
0.676742
b4011c0e5055a3066700755fe7bec395ab383386
3,800
js
JavaScript
server.js
daemonraco/node-simple-site
7d7d3ee3097aaabf6196be7fbf5df76b74d79f3b
[ "MIT" ]
null
null
null
server.js
daemonraco/node-simple-site
7d7d3ee3097aaabf6196be7fbf5df76b74d79f3b
[ "MIT" ]
null
null
null
server.js
daemonraco/node-simple-site
7d7d3ee3097aaabf6196be7fbf5df76b74d79f3b
[ "MIT" ]
null
null
null
'use strict'; // // What port should be use? const port = process.env.PORT || 3000; // // Basic required libraries. const HttpStatusCodes = require('http-status-codes'); const bodyParser = require('body-parser'); const chalk = require('chalk'); const express = require('express'); const http = require('http'); const path = require('path'); // // Importing DRTools. const { ConfigsManager, EndpointsManager, ExpressConnector, LoadersManager, MiddlewaresManager, RoutesManager, PluginsManager, TasksManager, } = require('drtools'); // // Creating an express application. global.expressApp = express(); // // Loading steps. const loadingSteps = []; // // Loading DRTools configs. loadingSteps.push(async () => { global.configs = new ConfigsManager(path.join(__dirname, 'configs')); global.env = global.configs.get('environment'); global.envName = global.configs.environmentName(); global.expressApp.use(global.configs.publishExports()); }); // // Setting up a logs manager. loadingSteps.push(async () => { require('./includes/logger'); }); // // Loading parser. loadingSteps.push(async () => { global.expressApp.use(bodyParser.json()); global.expressApp.use(bodyParser.urlencoded({ extended: false })); }); // // Loading DRTools ExpressJS connector. loadingSteps.push(async () => { ExpressConnector.attach(global.expressApp, { webUi: global.configs.get('environment').drtools.webUi, }); }); // // Loading DRTools loaders. loadingSteps.push(async () => { const manager = new LoadersManager(path.join(__dirname, 'includes/loaders'), {}, global.configs); await manager.load(); }); // // Loading DRTools middlewares. loadingSteps.push(async () => { const manager = new MiddlewaresManager(global.expressApp, path.join(__dirname, 'includes/middlewares'), {}, global.configs); await manager.load(); }); // // Loading DRTools plugins. loadingSteps.push(async () => { const manager = new PluginsManager(path.join(__dirname, 'plugins'), {}, global.configs); await manager.load(); }); // // Loading DRTools routes. loadingSteps.push(async () => { const manager = new RoutesManager(global.expressApp, path.join(__dirname, 'includes/routes'), {}, global.configs); await manager.load(); }); // // Loading DRTools tasks. loadingSteps.push(async () => { const manager = new TasksManager(path.join(__dirname, 'includes/tasks'), {}, global.configs); await manager.load(); }); // // Loading DRTools mock-endpoints. loadingSteps.push(async () => { const endpoints = new EndpointsManager({ directory: path.join(__dirname, 'includes/mock-endpoints'), uri: 'mock-api/v1.0', }, global.configs); global.expressApp.use(endpoints.provide()); }); // // Setting static folders. loadingSteps.push(async () => { global.expressApp.use(express.static(path.join(__dirname, 'public'))); }); // // Setting default routes. loadingSteps.push(async () => { global.expressApp.use(function (req, res, next) { if (req.xhr || req.headers['accept'] === 'application/json' || req.headers['content-type'] === 'application/json') { res.status(HttpStatusCodes.NOT_FOUND).json({ message: 'Not Found', uri: req.url, isAjax: req.xhr, }); } else { res.sendFile(path.join(__dirname, '/public/index.html')); } }); }); // // Steps loaders. (async () => { try { for (const step of loadingSteps) { await step(); } // // Starting server. http.createServer(global.expressApp).listen(port, () => { console.log(`\nListening on port '${port}'...`); }); } catch (err) { console.error(chalk.red(err)); } })();
28.787879
128
0.637895
b4012213ef4153bd245c63a30c66555d855fb2d2
22,526
js
JavaScript
public/javascripts/textile-editor.js
galeki/chito
5bb1fd6941b5f00445ff4cc907e6f10d7ecb49a8
[ "MIT" ]
32
2015-01-28T14:46:25.000Z
2022-02-02T14:40:13.000Z
public/javascripts/textile-editor.js
galeki/chito
5bb1fd6941b5f00445ff4cc907e6f10d7ecb49a8
[ "MIT" ]
null
null
null
public/javascripts/textile-editor.js
galeki/chito
5bb1fd6941b5f00445ff4cc907e6f10d7ecb49a8
[ "MIT" ]
9
2015-10-26T06:22:18.000Z
2020-06-04T03:54:18.000Z
/* Textile Editor v0.2 (ZIP Version) created by: dave olsen, wvu web services updated on: october 1, 2007 created on: march 17, 2007 project page: slateinfo.blogs.wvu.edu inspired by: - Patrick Woods, http://www.hakjoon.com/code/38/textile-quicktags-redirect & - Alex King, http://alexking.org/projects/js-quicktags features: - supports: IE7, FF2, Safari2 - ability to use "simple" vs. "extended" editor - supports all block elements in textile except footnote - supports all block modifier elements in textile - supports simple ordered and unordered lists - supports most of the phrase modifiers, very easy to add the missing ones - supports multiple-paragraph modification - can have multiple "editors" on one page, access key use in this environment is flaky - access key support - select text to add and remove tags, selection stays highlighted - seamlessly change between tags and modifiers - doesn't need to be in the body onload tag - can supply your own, custom IDs for the editor to be drawn around todo: - a clean way of providing image and link inserts - get the selection to properly show in IE more on textile: - Textism, http://www.textism.com/tools/textile/index.php - Textile Reference, http://hobix.com/textile/ */ var TEH_PATH = ''; // Path to TEH plugin, include /'s if needed // Define Button Object function TextileEditorButton(id, display, tagStart, tagEnd, access, title, sve, open) { this.id = id; // used to name the toolbar button this.display = display; // label on button this.tagStart = tagStart; // open tag this.tagEnd = tagEnd; // close tag this.access = access; // set to -1 if tag does not need to be closed this.title = title; // sets the title attribute of the button to give 'tool tips' this.sve = sve; // sve = simple vs. extended. add an 's' to make it show up in the simple toolbar this.open = open; // set to -1 if tag does not need to be closed this.standard = true; // this is a standard button } function TextileEditorButtonSeparator(sve) { this.separator = true; this.sve = sve; } var TextileEditor = Class.create(); TextileEditor.buttons = new Array(); TextileEditor.Methods = { // class methods // create the toolbar (edToolbar) initialize: function(canvas, view) { var toolbar = document.createElement("div"); toolbar.id = "textile-toolbar-" + canvas; toolbar.className = 'textile-toolbar'; this.canvas = document.getElementById(canvas); this.canvas.parentNode.insertBefore(toolbar, this.canvas); this.openTags = new Array(); // Create the local Button array by assigning theButtons array to edButtons var edButtons = new Array(); edButtons = this.buttons; var standardButtons = new Array(); for(var i = 0; i < edButtons.length; i++) { var thisButton = this.prepareButton(edButtons[i]); if (view == 's') { if (edButtons[i].sve == 's') { toolbar.appendChild(thisButton); standardButtons.push(thisButton); } } else { if (typeof thisButton == 'string') { toolbar.innerHTML += thisButton; } else { toolbar.appendChild(thisButton); standardButtons.push(thisButton); } } } // end for var te = this; $A(toolbar.getElementsByTagName('button')).each(function(button) { if (!button.onclick) { button.onclick = function() { te.insertTag(button); return false; } } // end if button.tagStart = button.getAttribute('tagStart'); button.tagEnd = button.getAttribute('tagEnd'); button.open = button.getAttribute('open'); button.textile_editor = te; button.canvas = te.canvas; }); }, // end initialize // draw individual buttons (edShowButton) prepareButton: function(button) { if (button.separator) { var theButton = document.createElement('span'); theButton.className = 'ed_sep'; return theButton; } if (button.standard) { var theButton = document.createElement("button"); theButton.id = button.id; theButton.setAttribute('class', 'standard'); theButton.setAttribute('tagStart', button.tagStart); theButton.setAttribute('tagEnd', button.tagEnd); theButton.setAttribute('open', button.open); var img = document.createElement('img'); img.src = '/images/textile-editor/' + button.display; theButton.appendChild(img); } else { return button; } // end if !custom theButton.accessKey = button.access; theButton.title = button.title; return theButton; }, // end prepareButton // if clicked, no selected text, tag not open highlight button // (edAddTag) addTag: function(button) { if (button.tagEnd != '') { this.openTags[this.openTags.length] = button; //var el = document.getElementById(button.id); //el.className = 'selected'; button.className = 'selected'; } }, // end addTag // if clicked, no selected text, tag open lowlight button // (edRemoveTag) removeTag: function(button) { for (i = 0; i < this.openTags.length; i++) { if (this.openTags[i] == button) { this.openTags.splice(button, 1); //var el = document.getElementById(button.id); //el.className = 'unselected'; button.className = 'unselected'; } } }, // end removeTag // see if there are open tags. for the remove tag bit... // (edCheckOpenTags) checkOpenTags: function(button) { var tag = 0; for (i = 0; i < this.openTags.length; i++) { if (this.openTags[i] == button) { tag++; } } if (tag > 0) { return true; // tag found } else { return false; // tag not found } }, // end checkOpenTags // insert the tag. this is the bulk of the code. // (edInsertTag) insertTag: function(button, tagStart, tagEnd) { var myField = button.canvas; myField.focus(); if (tagStart) { button.tagStart = tagStart; button.tagEnd = tagEnd ? tagEnd : '\n'; } var textSelected = false; var finalText = ''; var FF = false; // grab the text that's going to be manipulated, by browser if (document.selection) { // IE support sel = document.selection.createRange(); // set-up the text vars var beginningText = ''; var followupText = ''; var selectedText = sel.text; // check if text has been selected if (sel.text.length > 0) { textSelected = true; } // set-up newline regex's so we can swap tags across multiple paragraphs var newlineReplaceRegexClean = /\r\n\s\n/g; var newlineReplaceRegexDirty = '\\r\\n\\s\\n'; var newlineReplaceClean = '\r\n\n'; } else if (myField.selectionStart || myField.selectionStart == '0') { // MOZ/FF/NS/S support // figure out cursor and selection positions var startPos = myField.selectionStart; var endPos = myField.selectionEnd; var cursorPos = endPos; var scrollTop = myField.scrollTop; FF = true; // note that is is a FF/MOZ/NS/S browser // set-up the text vars var beginningText = myField.value.substring(0, startPos); var followupText = myField.value.substring(endPos, myField.value.length); // check if text has been selected if (startPos != endPos) { textSelected = true; var selectedText = myField.value.substring(startPos, endPos); } // set-up newline regex's so we can swap tags across multiple paragraphs var newlineReplaceRegexClean = /\n\n/g; var newlineReplaceRegexDirty = '\\n\\n'; var newlineReplaceClean = '\n\n'; } // if there is text that has been highlighted... if (textSelected) { // set-up some defaults for how to handle bad new line characters var newlineStart = ''; var newlineStartPos = 0; var newlineEnd = ''; var newlineEndPos = 0; var newlineFollowup = ''; // set-up some defaults for how to handle placing the beginning and end of selection var posDiffPos = 0; var posDiffNeg = 0; var mplier = 1; // remove newline from the beginning of the selectedText. if (selectedText.match(/^\n/)) { selectedText = selectedText.replace(/^\n/,''); newlineStart = '\n'; newlineStartpos = 1; } // remove newline from the end of the selectedText. if (selectedText.match(/\n$/g)) { selectedText = selectedText.replace(/\n$/g,''); newlineEnd = '\n'; newlineEndPos = 1; } // no clue, i'm sure it made sense at the time i wrote it if (followupText.match(/^\n/)) { newlineFollowup = ''; } else { newlineFollowup = '\n\n'; } // first off let's check if the user is trying to mess with lists if ((button.tagStart == ' * ') || (button.tagStart == ' # ')) { listItems = 0; // sets up a default to be able to properly manipulate final selection // set-up all of the regex's re_start = new RegExp('^ (\\*|\\#) ','g'); if (button.tagStart == ' # ') { re_tag = new RegExp(' \\# ','g'); // because of JS regex stupidity i need an if/else to properly set it up, could have done it with a regex replace though } else { re_tag = new RegExp(' \\* ','g'); } re_replace = new RegExp(' (\\*|\\#) ','g'); // try to remove bullets in text copied from ms word **Mac Only!** re_word_bullet_m_s = new RegExp('• ','g'); // mac/safari re_word_bullet_m_f = new RegExp('∑ ','g'); // mac/firefox selectedText = selectedText.replace(re_word_bullet_m_s,'').replace(re_word_bullet_m_f,''); // if the selected text starts with one of the tags we're working with... if (selectedText.match(re_start)) { // if tag that begins the selection matches the one clicked, remove them all if (selectedText.match(re_tag)) { finalText = beginningText + newlineStart + selectedText.replace(re_replace,'') + newlineEnd + followupText; if (matches = selectedText.match(/ (\*|\#) /g)) { listItems = matches.length; } posDiffNeg = listItems*3; // how many list items were there because that's 3 spaces to remove from final selection } // else replace the current tag type with the selected tag type else { finalText = beginningText + newlineStart + selectedText.replace(re_replace,button.tagStart) + newlineEnd + followupText; } } // else try to create the list type // NOTE: the items in a list will only be replaced if a newline starts with some character, not a space else { finalText = beginningText + newlineStart + button.tagStart + selectedText.replace(newlineReplaceRegexClean,newlineReplaceClean + button.tagStart).replace(/\n(\S)/g,'\n' + button.tagStart + '$1') + newlineEnd + followupText; if (matches = selectedText.match(/\n(\S)/g)) { listItems = matches.length; } posDiffPos = 3 + listItems*3; } } // now lets look and see if the user is trying to muck with a block or block modifier else if (button.tagStart.match(/^(h1|h2|h3|h4|h5|h6|bq|p|\>|\<\>|\<|\=|\(|\))/g)) { var insertTag = ''; var insertModifier = ''; var tagPartBlock = ''; var tagPartModifier = ''; var tagPartModifierOrig = ''; // ugly hack but it's late var drawSwitch = ''; var captureIndentStart = false; var captureListStart = false; var periodAddition = '\\. '; var periodAdditionClean = '. '; var listItemsAddition = 0; var re_list_items = new RegExp('(\\*+|\\#+)','g'); // need this regex later on when checking indentation of lists var re_block_modifier = new RegExp('^(h1|h2|h3|h4|h5|h6|bq|p| [\\*]{1,} | [\\#]{1,} |)(\\>|\\<\\>|\\<|\\=|[\\(]{1,}|[\\)]{1,6}|)','g'); if (tagPartMatches = re_block_modifier.exec(selectedText)) { tagPartBlock = tagPartMatches[1]; tagPartModifier = tagPartMatches[2]; tagPartModifierOrig = tagPartMatches[2]; tagPartModifierOrig = tagPartModifierOrig.replace(/\(/g,"\\("); } // if tag already up is the same as the tag provided replace the whole tag if (tagPartBlock == button.tagStart) { insertTag = tagPartBlock + tagPartModifierOrig; // use Orig because it's escaped for regex drawSwitch = 0; } // else if let's check to add/remove block modifier else if ((tagPartModifier == button.tagStart) || (newm = tagPartModifier.match(/[\(]{2,}/g))) { if ((button.tagStart == '(') || (button.tagStart == ')')) { var indentLength = tagPartModifier.length; if (button.tagStart == '(') { indentLength = indentLength + 1; } else { indentLength = indentLength - 1; } for (var i = 0; i < indentLength; i++) { insertModifier = insertModifier + '('; } insertTag = tagPartBlock + insertModifier; } else { if (button.tagStart == tagPartModifier) { insertTag = tagPartBlock; } // going to rely on the default empty insertModifier else { if (button.tagStart.match(/(\>|\<\>|\<|\=)/g)) { insertTag = tagPartBlock + button.tagStart; } else { insertTag = button.tagStart + tagPartModifier; } } } drawSwitch = 1; } // indentation of list items else if (listPartMatches = re_list_items.exec(tagPartBlock)) { var listTypeMatch = listPartMatches[1]; var indentLength = tagPartBlock.length - 2; var listInsert = ''; if (button.tagStart == '(') { indentLength = indentLength + 1; } else { indentLength = indentLength - 1; } if (listTypeMatch.match(/[\*]{1,}/g)) { var listType = '*'; var listReplace = '\\*'; } else { var listType = '#'; var listReplace = '\\#'; } for (var i = 0; i < indentLength; i++) { listInsert = listInsert + listType; } if (listInsert != '') { insertTag = ' ' + listInsert + ' '; } else { insertTag = ''; } tagPartBlock = tagPartBlock.replace(/(\*|\#)/g,listReplace); drawSwitch = 1; captureListStart = true; periodAddition = ''; periodAdditionClean = ''; if (matches = selectedText.match(/\n\s/g)) { listItemsAddition = matches.length; } } // must be a block modification e.g. p>. to p<. else { // if this is a block modification/addition if (button.tagStart.match(/(h1|h2|h3|h4|h5|h6|bq|p)/g)) { if (tagPartBlock == '') { drawSwitch = 2; } else { drawSwitch = 1; } insertTag = button.tagStart + tagPartModifier; } // else this is a modifier modification/addition else { if ((tagPartModifier == '') && (tagPartBlock != '')) { drawSwitch = 1; } else if (tagPartModifier == '') { drawSwitch = 2; } else { drawSwitch = 1; } // if no tag part block but a modifier we need at least the p tag if (tagPartBlock == '') { tagPartBlock = 'p'; } //make sure to swap out outdent if (button.tagStart == ')') { tagPartModifier = ''; } else { tagPartModifier = button.tagStart; captureIndentStart = true; // ugly hack to fix issue with proper selection handling } insertTag = tagPartBlock + tagPartModifier; } } mplier = 0; if (captureListStart || (tagPartModifier.match(/[\(\)]{1,}/g))) { re_start = new RegExp(insertTag.escape + periodAddition,'g'); // for tags that mimic regex properties, parens + list tags } else { re_start = new RegExp(insertTag + periodAddition,'g'); // for tags that don't, why i can't just escape everything i have no clue } re_old = new RegExp(tagPartBlock + tagPartModifierOrig + periodAddition,'g'); re_middle = new RegExp(newlineReplaceRegexDirty + insertTag.escape + periodAddition.escape,'g'); re_tag = new RegExp(insertTag.escape + periodAddition.escape,'g'); // ************************************************************************************************************************* // this is where everything gets swapped around or inserted, bullets and single options have their own if/else statements // ************************************************************************************************************************* if ((drawSwitch == 0) || (drawSwitch == 1)) { if (drawSwitch == 0) { // completely removing a tag finalText = beginningText + newlineStart + selectedText.replace(re_start,'').replace(re_middle,newlineReplaceClean) + newlineEnd + followupText; if (matches = selectedText.match(newlineReplaceRegexClean)) { mplier = mplier + matches.length; } posDiffNeg = insertTag.length + 2 + (mplier*4); } else { // modifying a tag, though we do delete bullets here finalText = beginningText + newlineStart + selectedText.replace(re_old,insertTag + periodAdditionClean) + newlineEnd + followupText; if (matches = selectedText.match(newlineReplaceRegexClean)) { mplier = mplier + matches.length; } // figure out the length of various elements to modify the selection position if (captureIndentStart) { // need to double-check that this wasn't the first indent tagPreviousLength = tagPartBlock.length; tagCurrentLength = insertTag.length; } else if (captureListStart) { // if this is a list we're manipulating if (button.tagStart == '(') { // if indenting tagPreviousLength = listTypeMatch.length + 2; tagCurrentLength = insertTag.length + listItemsAddition; } else if (insertTag.match(/(\*|\#)/g)) { // if removing but still has bullets tagPreviousLength = insertTag.length + listItemsAddition; tagCurrentLength = listTypeMatch.length; } else { // if removing last bullet tagPreviousLength = insertTag.length + listItemsAddition; tagCurrentLength = listTypeMatch.length - (3*listItemsAddition) - 1; } } else { // everything else tagPreviousLength = tagPartBlock.length + tagPartModifier.length; tagCurrentLength = insertTag.length; } if (tagCurrentLength > tagPreviousLength) { posDiffPos = (tagCurrentLength - tagPreviousLength) + (mplier*(tagCurrentLength - tagPreviousLength)); } else { posDiffNeg = (tagPreviousLength - tagCurrentLength) + (mplier*(tagPreviousLength - tagCurrentLength)); } } } else { // for adding tags other then bullets (have their own statement) finalText = beginningText + newlineStart + insertTag + '. ' + selectedText.replace(newlineReplaceRegexClean,button.tagEnd + '\n' + insertTag + '. ') + newlineFollowup + newlineEnd + followupText; if (matches = selectedText.match(newlineReplaceRegexClean)) { mplier = mplier + matches.length; } posDiffPos = insertTag.length + 2 + (mplier*4); } } // swap in and out the simple tags around a selection like bold else { mplier = 1; // the multiplier for the tag length re_start = new RegExp('^\\' + button.tagStart,'g'); re_end = new RegExp('\\' + button.tagEnd + '$','g'); re_middle = new RegExp('\\' + button.tagEnd + newlineReplaceRegexDirty + '\\' + button.tagStart,'g'); if (selectedText.match(re_start) && selectedText.match(re_end)) { finalText = beginningText + newlineStart + selectedText.replace(re_start,'').replace(re_end,'').replace(re_middle,newlineReplaceClean) + newlineEnd + followupText; if (matches = selectedText.match(newlineReplaceRegexClean)) { mplier = mplier + matches.length; } posDiffNeg = button.tagStart.length*mplier + button.tagEnd.length*mplier; } else { finalText = beginningText + newlineStart + button.tagStart + selectedText.replace(newlineReplaceRegexClean,button.tagEnd + newlineReplaceClean + button.tagStart) + button.tagEnd + newlineEnd + followupText; if (matches = selectedText.match(newlineReplaceRegexClean)) { mplier = mplier + matches.length; } posDiffPos = (button.tagStart.length*mplier) + (button.tagEnd.length*mplier); } } cursorPos += button.tagStart.length + button.tagEnd.length; } // just swap in and out single values, e.g. someone clicks b they'll get a * else { var buttonStart = ''; var buttonEnd = ''; var re_p = new RegExp('(\\<|\\>|\\=|\\<\\>|\\(|\\))','g'); var re_h = new RegExp('^(h1|h2|h3|h4|h5|h6|p|bq)','g'); if (!this.checkOpenTags(button) || button.tagEnd == '') { // opening tag if (button.tagStart.match(re_h)) { buttonStart = button.tagStart + '. '; } else { buttonStart = button.tagStart; } if (button.tagStart.match(re_p)) { // make sure that invoking block modifiers don't do anything finalText = beginningText + followupText; cursorPos = startPos; } else { finalText = beginningText + buttonStart + followupText; this.addTag(button); cursorPos = startPos + buttonStart.length; } } else { // closing tag if (button.tagStart.match(re_p)) { buttonEnd = '\n\n'; } else if (button.tagStart.match(re_h)) { buttonEnd = '\n\n'; } else { buttonEnd = button.tagEnd } finalText = beginningText + button.tagEnd + followupText; this.removeTag(button); cursorPos = startPos + button.tagEnd.length; } } // set the appropriate DOM value with the final text if (FF == true) { myField.value = finalText; myField.scrollTop = scrollTop; } else { sel.text = finalText; } // build up the selection capture, doesn't work in IE if (textSelected) { myField.selectionStart = startPos + newlineStartPos; myField.selectionEnd = endPos + posDiffPos - posDiffNeg - newlineEndPos; //alert('s: ' + myField.selectionStart + ' e: ' + myField.selectionEnd + ' sp: ' + startPos + ' ep: ' + endPos + ' pdp: ' + posDiffPos + ' pdn: ' + posDiffNeg) } else { myField.selectionStart = cursorPos; myField.selectionEnd = cursorPos; } } // end insertTag }; // end class // add class methods Object.extend(TextileEditor, TextileEditor.Methods); document.write('<script src="' +'/javascripts/textile-editor-config.js" type="text/javascript"></script>');
33.620896
162
0.620305
b4013b6ce1103439313d034ded5302cf6893e7e4
1,006
js
JavaScript
src/components/SuggestedCities.js
Rezan92/weather-app
5edbbae85d80f4307c538f80c4226f8c72e7eb34
[ "MIT" ]
null
null
null
src/components/SuggestedCities.js
Rezan92/weather-app
5edbbae85d80f4307c538f80c4226f8c72e7eb34
[ "MIT" ]
null
null
null
src/components/SuggestedCities.js
Rezan92/weather-app
5edbbae85d80f4307c538f80c4226f8c72e7eb34
[ "MIT" ]
null
null
null
import React, { useState, useEffect } from "react"; import { cities } from "../project-data/cities"; const SuggestedCities = ({ cityName, setCityName }) => { const [matchedCitiesName, setMatchedCitiesName] = useState([]); useEffect(() => { const capitalizeCityName = cityName.length > 0 ? cityName.toUpperCase() : null; const citiesList = [...new Set(cities)]; // to remove duplicates from cities array const matchedCities = citiesList.filter((city) => city.toUpperCase().startsWith(capitalizeCityName) ); setMatchedCitiesName(matchedCities.slice(0, 4)); }, [cityName]); return ( <div className="suggestion__container"> <ul className="suggestion__list"> {matchedCitiesName.map((city, i) => ( <li key={i} className="suggestion__item" onClick={() => setCityName(city + " ")} > {city} </li> ))} </ul> </div> ); }; export default SuggestedCities;
27.189189
86
0.597416
b4015741256ed64f249337e2523b0eac6175fd17
1,402
js
JavaScript
Script/Devanagari/symbols.js
aral/unicode-10.0.0
58332218cee84902a2a4b985e864dcafe1f1ecea
[ "MIT" ]
1
2020-12-17T06:28:28.000Z
2020-12-17T06:28:28.000Z
Script/Devanagari/symbols.js
aral/unicode-10.0.0
58332218cee84902a2a4b985e864dcafe1f1ecea
[ "MIT" ]
null
null
null
Script/Devanagari/symbols.js
aral/unicode-10.0.0
58332218cee84902a2a4b985e864dcafe1f1ecea
[ "MIT" ]
null
null
null
module.exports=['\u0900','\u0901','\u0902','\u0903','\u0904','\u0905','\u0906','\u0907','\u0908','\u0909','\u090A','\u090B','\u090C','\u090D','\u090E','\u090F','\u0910','\u0911','\u0912','\u0913','\u0914','\u0915','\u0916','\u0917','\u0918','\u0919','\u091A','\u091B','\u091C','\u091D','\u091E','\u091F','\u0920','\u0921','\u0922','\u0923','\u0924','\u0925','\u0926','\u0927','\u0928','\u0929','\u092A','\u092B','\u092C','\u092D','\u092E','\u092F','\u0930','\u0931','\u0932','\u0933','\u0934','\u0935','\u0936','\u0937','\u0938','\u0939','\u093A','\u093B','\u093C','\u093D','\u093E','\u093F','\u0940','\u0941','\u0942','\u0943','\u0944','\u0945','\u0946','\u0947','\u0948','\u0949','\u094A','\u094B','\u094C','\u094D','\u094E','\u094F','\u0950','\u0953','\u0954','\u0955','\u0956','\u0957','\u0958','\u0959','\u095A','\u095B','\u095C','\u095D','\u095E','\u095F','\u0960','\u0961','\u0962','\u0963','\u0966','\u0967','\u0968','\u0969','\u096A','\u096B','\u096C','\u096D','\u096E','\u096F','\u0970','\u0971','\u0972','\u0973','\u0974','\u0975','\u0976','\u0977','\u0978','\u0979','\u097A','\u097B','\u097C','\u097D','\u097E','\u097F','\uA8E0','\uA8E1','\uA8E2','\uA8E3','\uA8E4','\uA8E5','\uA8E6','\uA8E7','\uA8E8','\uA8E9','\uA8EA','\uA8EB','\uA8EC','\uA8ED','\uA8EE','\uA8EF','\uA8F0','\uA8F1','\uA8F2','\uA8F3','\uA8F4','\uA8F5','\uA8F6','\uA8F7','\uA8F8','\uA8F9','\uA8FA','\uA8FB','\uA8FC','\uA8FD']
1,402
1,402
0.558488
b4016abd79848db9106dfbb1a7cbbecd4df00aea
1,158
js
JavaScript
src/routes/sms.js
sdawood/throttled-api-server
dc7ee3cb326fd05b7f12f75abd7af3c9ac01a3a6
[ "MIT" ]
null
null
null
src/routes/sms.js
sdawood/throttled-api-server
dc7ee3cb326fd05b7f12f75abd7af3c9ac01a3a6
[ "MIT" ]
null
null
null
src/routes/sms.js
sdawood/throttled-api-server
dc7ee3cb326fd05b7f12f75abd7af3c9ac01a3a6
[ "MIT" ]
null
null
null
const {RateLimiter} = require('limiter'); const express = require('express'); const capacity = require('../api/middleware/capacity'); const checkAuth = require('../api/middleware/check-auth'); // eslint-disable-next-line new-cap const router = express.Router(); /* GET users listing. */ const {endpoints: {sms: {capacity: {limit, interval} = {}} = {}}} = require('../config'); const twilio = require('twilio'); router.post('/', capacity(limit, interval), checkAuth, (req, res, next) => { const accountSid = process.env['TWILIO_ACCOUNT_SID']; const authToken = process.env['TWILIO_AUTH_TOKEN']; const messagingServiceSid = process.env['TWILIO_MESSAGING_SERVICE_SID']; const fromNumber = process.env['TWILIO_FROM_NUMBER']; // eslint-disable-next-line new-cap const client = new twilio(accountSid, authToken); client.messages.create({ to: req.body.to, from: req.body.from || fromNumber, body: req.body.body, messagingServiceSid }) .then(message => res.json(message)) .catch(error => res.status(500).json({...error, details: 'No backup service configured'})); }); module.exports = router;
36.1875
95
0.676166
b401caf83567c0f14eac4ac8ce019a774179710a
1,576
js
JavaScript
core/frontend/helpers/register.js
monovisual/Ghost
9cdab379afeddeebb666cd39e9bf4d9c3fbe9e09
[ "MIT" ]
null
null
null
core/frontend/helpers/register.js
monovisual/Ghost
9cdab379afeddeebb666cd39e9bf4d9c3fbe9e09
[ "MIT" ]
3
2021-05-11T22:27:43.000Z
2022-01-22T14:23:44.000Z
core/frontend/helpers/register.js
monovisual/Ghost
9cdab379afeddeebb666cd39e9bf4d9c3fbe9e09
[ "MIT" ]
null
null
null
const Promise = require('bluebird'); const {config, hbs, errors, logging} = require('../services/proxy'); // Register an async handlebars helper for a given handlebars instance function asyncHelperWrapper(hbs, name, fn) { hbs.registerAsyncHelper(name, function returnAsync(context, options, cb) { // Handle the case where we only get context and cb if (!cb) { cb = options; options = undefined; } // Wrap the function passed in with a when.resolve so it can return either a promise or a value Promise.resolve(fn.call(this, context, options)).then(function asyncHelperSuccess(result) { cb(result); }).catch(function asyncHelperError(err) { var wrappedErr = err instanceof errors.GhostError ? err : new errors.IncorrectUsageError({ err: err, context: 'registerAsyncThemeHelper: ' + name, errorDetails: { originalError: err } }), result = config.get('env') === 'development' ? wrappedErr : ''; logging.error(wrappedErr); cb(new hbs.SafeString(result)); }); }); } // Register a handlebars helper for themes module.exports.registerThemeHelper = function registerThemeHelper(name, fn) { hbs.registerHelper(name, fn); }; // Register an async handlebars helper for themes module.exports.registerAsyncThemeHelper = function registerAsyncThemeHelper(name, fn) { asyncHelperWrapper(hbs, name, fn); };
37.52381
103
0.618655
b401f041a92eb5f03e4634cdaca5c7ec5a080b14
1,477
js
JavaScript
resources/assets/js/partials/order.js
JanTrnavsky/da-test-webapp
c35c4943478263990a4333f6c314eb16e23a7554
[ "MIT" ]
null
null
null
resources/assets/js/partials/order.js
JanTrnavsky/da-test-webapp
c35c4943478263990a4333f6c314eb16e23a7554
[ "MIT" ]
null
null
null
resources/assets/js/partials/order.js
JanTrnavsky/da-test-webapp
c35c4943478263990a4333f6c314eb16e23a7554
[ "MIT" ]
5
2021-03-16T15:24:16.000Z
2022-02-28T19:28:29.000Z
module.exports = { init: function (app, webSection) { if (webSection != 'orders') { return; } this.ares.init(app); }, ares: { init: function () { $('input#ico').change(this.icoFilled.bind(this)); }, icoFilled: function (e) { var t = $(e.target); if (t.val() == '') { return; } if (t.val().match(/^[0-9]{4,8}$/) == null) { toastr.error(CzechitasApp.config('orders.notFoundMsg')); return; } var url = CzechitasApp.config('orders.aresUrl'); if (!url) { console.log('Missing route for ARES'); return; } this.inputsDisabled(true); $.ajax({ type: 'POST', url: url, data: { ico: t.val() }, success: this.dataReceived.bind(this), error: this.dataError.bind(this), complete: this.inputsDisabled.bind(this, false), }); }, dataReceived: function (data) { $('#address').val(data.address); $('#client').val(data.company); toastr.success(CzechitasApp.config('orders.successMsg')); }, dataError: function (jqXHR) { toastr.error(CzechitasApp.config(jqXHR.status == 404 ? 'orders.notFoundMsg' : 'orders.errorMsg')); }, inputsDisabled: function (disable) { var placeholder = disable ? CzechitasApp.config('orders.ares_searching') : ''; $('#address, #client').prop('disabled', disable).attr('placeholder', placeholder); }, }, };
26.854545
104
0.553825
b402cf2ea28c592c62905a3796582e7b8ae41d87
1,525
js
JavaScript
frontend/webpack.dev.config.js
sevenfoxes/gardyn
ef155e27fa1a3dada824e17ec9753d8c514b3551
[ "Apache-2.0" ]
5
2021-06-14T20:12:08.000Z
2022-01-11T18:18:07.000Z
frontend/webpack.dev.config.js
sevenfoxes/gardyn
ef155e27fa1a3dada824e17ec9753d8c514b3551
[ "Apache-2.0" ]
null
null
null
frontend/webpack.dev.config.js
sevenfoxes/gardyn
ef155e27fa1a3dada824e17ec9753d8c514b3551
[ "Apache-2.0" ]
null
null
null
const path = require("path"); const webpack = require("webpack"); const MiniCssExtractPlugin = require("mini-css-extract-plugin"); const ReactRefreshWebpackPlugin = require("@pmmmwh/react-refresh-webpack-plugin"); module.exports = { mode: "development", entry: ["./index.js"], output: { path: path.resolve(__dirname, "../static"), filename: "bundle.js", publicPath: "/static/", }, module: { rules: [ { test: /\.js$/, loader: "babel-loader", exclude: /node_modules/, options: { presets: ["@babel/preset-env", "@babel/preset-react"], plugins: ["react-refresh/babel"], }, }, { test: /\.css$/, use: [MiniCssExtractPlugin.loader, "css-loader"], }, { test: /\.svg$/, use: [ { loader: "svg-url-loader", options: { limit: 10000, }, }, ], }, ], }, plugins: [ new MiniCssExtractPlugin({ filename: `bundle.css`, }), new webpack.HotModuleReplacementPlugin(), new ReactRefreshWebpackPlugin({ overlay: { sockPort: 8090, }, }), ], devServer: { port: 8090, hotOnly: true, writeToDisk: true, headers: { "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, PATCH, OPTIONS", "Access-Control-Allow-Headers": "X-Requested-With, content-type, Authorization", }, }, };
23.461538
82
0.527869
b40304a992ca6dddf69541c205ca1c3f36bb4a55
232
js
JavaScript
src/components/ContainerEthDenver.js
vegaprotocol/vega.xyz
2b0c3d20a7531280f9ab4e70581ab343a30ee62c
[ "MIT" ]
1
2022-02-20T12:21:29.000Z
2022-02-20T12:21:29.000Z
src/components/ContainerEthDenver.js
vegaprotocol/vega.xyz
2b0c3d20a7531280f9ab4e70581ab343a30ee62c
[ "MIT" ]
2
2022-02-07T17:20:59.000Z
2022-02-23T11:00:17.000Z
src/components/ContainerEthDenver.js
vegaprotocol/vega.xyz
2b0c3d20a7531280f9ab4e70581ab343a30ee62c
[ "MIT" ]
null
null
null
import React from "react"; const ContainerEthDenver = ({ children }) => { return ( <div className="max-w-[45rem] mx-auto px-4 md:px-6 lg:px-8 2xl:pt-8"> {children} </div> ); }; export default ContainerEthDenver;
19.333333
73
0.625
b403c853403530fb1265c1fd17bc71b727bd0bd9
1,812
js
JavaScript
dist/esm/l10n/cy.js
jaredloman/flatpickr
23bf90d4972dbb7cff917b5a254f4232a5244a62
[ "MIT" ]
1
2015-01-28T06:10:40.000Z
2015-01-28T06:10:40.000Z
dist/esm/l10n/cy.js
jaredloman/flatpickr
23bf90d4972dbb7cff917b5a254f4232a5244a62
[ "MIT" ]
24
2015-01-02T10:27:07.000Z
2015-02-12T13:39:37.000Z
dist/esm/l10n/cy.js
jaredloman/flatpickr
23bf90d4972dbb7cff917b5a254f4232a5244a62
[ "MIT" ]
null
null
null
var fp = typeof window !== "undefined" && window.flatpickr !== undefined ? window.flatpickr : { l10ns: {}, }; export var Welsh = { weekdays: { shorthand: ["Sul", "Llun", "Maw", "Mer", "Iau", "Gwe", "Sad"], longhand: [ "Dydd Sul", "Dydd Llun", "Dydd Mawrth", "Dydd Mercher", "Dydd Iau", "Dydd Gwener", "Dydd Sadwrn", ], }, months: { shorthand: [ "Ion", "Chwef", "Maw", "Ebr", "Mai", "Meh", "Gorff", "Awst", "Medi", "Hyd", "Tach", "Rhag", ], longhand: [ "Ionawr", "Chwefror", "Mawrth", "Ebrill", "Mai", "Mehefin", "Gorffennaf", "Awst", "Medi", "Hydref", "Tachwedd", "Rhagfyr", ], }, firstDayOfWeek: 1, ordinal: function (nth) { if (nth === 1) return "af"; if (nth === 2) return "ail"; if (nth === 3 || nth === 4) return "ydd"; if (nth === 5 || nth === 6) return "ed"; if ((nth >= 7 && nth <= 10) || nth == 12 || nth == 15 || nth == 18 || nth == 20) return "fed"; if (nth == 11 || nth == 13 || nth == 14 || nth == 16 || nth == 17 || nth == 19) return "eg"; if (nth >= 21 && nth <= 39) return "ain"; return ""; }, time_24hr: true, }; fp.l10ns.cy = Welsh; export default fp.l10ns;
22.65
72
0.325055
b403e914aab7900d0776801730e8c9aae725c4f0
1,595
js
JavaScript
demo/index.js
tangyuhui/wechat-node-jssdk
3d457b5a80d0e3b5565b6129cc63a45356ed98b6
[ "MIT" ]
null
null
null
demo/index.js
tangyuhui/wechat-node-jssdk
3d457b5a80d0e3b5565b6129cc63a45356ed98b6
[ "MIT" ]
null
null
null
demo/index.js
tangyuhui/wechat-node-jssdk
3d457b5a80d0e3b5565b6129cc63a45356ed98b6
[ "MIT" ]
null
null
null
'use strict'; const express = require('express'); const http = require('http'); const swig = require('swig'); const { Wechat, Payment } = require('../lib'); const path = require('path'); const debug = require('debug')('wechat-demo'); const bodyParser = require('body-parser'); const isEmpty = require('lodash.isempty'); const utils = require('../lib/utils'); const cookieParser = require('cookie-parser'); const session = require('express-session'); const wechatConfig = require('./wechat-config'); const wx = new Wechat(wechatConfig); const app = express(); swig.setDefaults({ cache: false, }); app.engine('html', swig.renderFile); app.set('view engine', 'html'); app.enable('trust proxy'); app.set('views', path.join(__dirname)); app.use(cookieParser()); app.use( session({ name: 'sid', secret: 'wechat-app', saveUninitialized: true, resave: true, }) ); app.use(function(req, res, next) { res.locals.appId = wechatConfig.appId; next(); }); app.get('/get-signature', function(req, res) { console.log(req.query); wx.jssdk.getSignature(req.query.url).then( data => { console.log('OK', data); res.json(data); }, reason => { console.error(reason); res.json(reason); } ); }); const server = http.createServer(app); const port = process.env.PORT || 3000; //should use like nginx to proxy the request to 3000, the signature domain must be on PORT 80. server.listen(port); server.on('listening', function() { debug('Express listening on port %d', port); }); process.on('exit', function() { wx.store.flush(); });
21.849315
94
0.653292
b404508f06ef23cf714a18337edcee2fd54821ca
6,874
js
JavaScript
dojoLib/toolkit/dojo/dojo/cldr/nls/sw/currency.js
Zodia/poc-tijari-mobile
c5aad1b2b13c7105de2166fe47f65dd5d493d656
[ "Apache-2.0" ]
1
2022-02-21T15:25:19.000Z
2022-02-21T15:25:19.000Z
dojoLib/toolkit/dojo/dojo/cldr/nls/sw/currency.js
Zodia/poc-tijari-mobile
c5aad1b2b13c7105de2166fe47f65dd5d493d656
[ "Apache-2.0" ]
null
null
null
dojoLib/toolkit/dojo/dojo/cldr/nls/sw/currency.js
Zodia/poc-tijari-mobile
c5aad1b2b13c7105de2166fe47f65dd5d493d656
[ "Apache-2.0" ]
null
null
null
define( //begin v1.x content { "KHR_displayName": "Riel ya Kambodia", "FJD_displayName": "Dola ya Fiji", "KPW_displayName": "Won ya Korea Kaskazini", "XCD_displayName": "Dola ya Karibea ya Mashariki", "HUF_displayName": "Forint ya Hangaria", "IQD_displayName": "Dinari ya Irak", "MZM_displayName": "metikali ya Msumbiji", "EGP_displayName": "pauni ya Misri", "TTD_displayName": "Dola ya Trinidad na Tobago", "GHS_displayName": "Cedi ya Ghana", "BTN_displayName": "Ngultrum ya Bhutan", "SBD_displayName": "Dola ya Visiwa vya Solomon", "CZK_displayName": "Koruna ya Jamhuri ya Cheki", "NOK_displayName": "Krone ya Norwe", "MNT_displayName": "Tugrik ya Mongolia", "INR_displayName": "rupia ya India", "KRW_displayName": "Won ya Korea Kusini", "BMD_displayName": "Dola ya Bermuda", "BDT_displayName": "Taka ya Bangladesh", "KGS_displayName": "Som ya Kirigistani", "DJF_displayName": "faranga ya Jibuti", "ANG_displayName": "Guilder ya Antili za Kiholanzi", "USD_displayName": "dola ya Marekani", "TMT_displayName": "Manat ya Turukimenistani", "HTG_displayName": "Gourde ya Haiti", "BWP_displayName": "pula ya Botswana", "RSD_displayName": "Dinar ya Serbia", "SSP_displayName": "Pauni ya Sudani Kusini", "DKK_displayName": "Krone ya Denmaki", "PAB_displayName": "Balboa ya Panama", "AWG_displayName": "Florin ya Aruba", "NAD_displayName": "dola ya Namibia", "UGX_displayName": "shilingi ya Uganda", "ZMW_displayName": "kwacha ya Zambia", "HNL_displayName": "Lempira ya Hondurasi", "BHD_displayName": "dinari ya Bahareni", "VEF_displayName": "Bolivar ya Venezuela", "BIF_displayName": "faranga ya Burundi", "MKD_displayName": "Denar ya Masedonia", "SRD_displayName": "Dola ya Suriname", "XAF_displayName": "faranga CFA BEAC", "XOF_displayName": "faranga CFA BCEAO", "LTL_displayName": "Litas ya Lithuania", "GYD_displayName": "Dola ya Guyana", "COP_displayName": "Peso ya Kolombia", "MMK_displayName": "Kyat ya Myama", "MVR_displayName": "Rufiyaa ya Maldivi", "KES_symbol": "Ksh", "SAR_displayName": "riyal ya Saudia", "CHF_displayName": "faranga ya Uswisi", "STD_displayName": "dobra ya Sao Tome na Principe", "IDR_displayName": "Rupiah ya Indonesia", "PYG_displayName": "Guarani ya Paragwai", "IRR_displayName": "Rial ya Iran", "UYU_displayName": "Peso ya Urugwai", "EUR_displayName": "yuro", "SLL_displayName": "leoni", "SDG_displayName": "dinari ya Sudani", "LKR_displayName": "Rupee ya Sri Lanka", "GMD_displayName": "dalasi ya Gambia", "SZL_displayName": "lilangeni", "GNF_displayName": "Franc ya Guinea", "SCR_displayName": "rupia ya Shelisheli", "ALL_displayName": "Lek ya Albania", "GEL_displayName": "Lari ya Georgia", "GNS_displayName": "faranga ya Gine", "AMD_displayName": "Dram ya Armenia", "NZD_displayName": "Dola ya Nyuzilandi", "AFN_displayName": "Afghani ya Afuganistani", "JMD_displayName": "Dola ya Jamaica", "GTQ_displayName": "Quetzal ya Guatemala", "LVL_displayName": "Lats ya Lativia", "NIO_displayName": "Kodoba ya Nikaragua", "OMR_displayName": "Rial ya Oman", "KMF_displayName": "faranga ya Komoro", "GBP_displayName": "pauni ya Uingereza", "AOA_displayName": "kwanza ya Angola", "VUV_displayName": "Vatu ya Vanuatu", "TOP_displayName": "Paʻanga ya Tonga", "GIP_displayName": "Pauni ya Gibraltar", "BZD_displayName": "Dola ya Belize", "MAD_displayName": "dirham ya Moroko", "CLP_displayName": "Peso ya Chile", "TZS_symbol": "TSh", "SYP_displayName": "Pauni ya Syria", "NPR_displayName": "Rupee ya Nepali", "UZS_displayName": "Som ya Uzibekistani", "JOD_displayName": "Dinar ya Yordani", "YER_displayName": "Rial ya Yemen", "BRL_displayName": "Real ya Brazil", "TRY_displayName": "Lira ya Uturuki", "CVE_displayName": "eskudo ya Kepuvede", "BSD_displayName": "Dola ya Bahamas", "LYD_displayName": "dinari ya Libya", "BAM_displayName": "Mark ya Bosnia na Hezegovina Inayoweza Kubadilishwa", "NGN_displayName": "naira ya Nijeria", "SDP_displayName": "pauni ya Sudani", "WST_displayName": "Tala ya Samoa", "TND_displayName": "dinari ya Tunisia", "LRD_displayName": "dola ya Liberia", "ILS_displayName": "Sheqel Mpya ya Israeli", "KZT_displayName": "Tenge ya Kazakistani", "CUC_displayName": "Peso ya Cuba Inayoweza Kubadilishwa", "BGN_displayName": "Lev ya Bulgaria", "MXN_displayName": "Peso ya Meksiko", "CUP_displayName": "Peso ya Cuba", "BYR_displayName": "Ruble ya Belarusi", "LSL_displayName": "loti ya Lesoto", "ZWD_displayName": "dola ya Zimbabwe", "UAH_displayName": "Hryvnia ya Ukrania", "BND_displayName": "Dola ya Brunei", "SEK_displayName": "Krona ya Uswidi", "MUR_displayName": "rupia ya Morisi", "ETB_displayName": "bir ya Uhabeshi", "ARS_displayName": "Peso ya Ajentina", "TWD_displayName": "Dola ya Taiwan", "JPY_displayName": "sarafu ya Kijapani", "MZN_displayName": "Metikali ya Msumbiji", "TJS_displayName": "Somoni ya Tajikistani", "PEN_displayName": "Nuevo Sol ya Peru", "XPF_displayName": "Franc ya CFP", "KWD_displayName": "Dinar ya Kuwait", "LAK_displayName": "Kip ya Laosi", "RON_displayName": "Leu ya Romania", "HRK_displayName": "Kuna ya Kroeshia", "THB_displayName": "Baht ya Tailandi", "PLN_displayName": "Zloty ya Polandi", "DZD_displayName": "dinari ya Aljeria", "AZN_displayName": "Manat ya Azebaijan", "PGK_displayName": "Kina ya Papua New Guinea", "LBP_displayName": "Pauni ya Lebanon", "RWF_displayName": "faranga ya Rwanda", "SHP_displayName": "pauni ya Santahelena", "TZS_displayName": "shilingi ya Tanzania", "MGA_displayName": "faranga ya Bukini", "ERN_displayName": "nakfa ya Eritrea", "MDL_displayName": "Leu ya Moldova", "PHP_displayName": "Peso ya Ufilipino", "AED_displayName": "dirham ya Falme za Kiarabu", "BOB_displayName": "Boliviano ya Bolivia", "KYD_displayName": "Dola ya Visiwa vya Cayman", "BBD_displayName": "Dola ya Barbados", "XXX_displayName": "Fedha Isiyojulikana", "CAD_displayName": "dola ya Kanada", "GHC_displayName": "sedi ya Ghana", "DOP_displayName": "Peso ya Dominika", "MRO_displayName": "ugwiya ya Moritania", "ZMK_displayName": "kwacha ya Zambia (1968-2012)", "RUB_displayName": "Ruble ya Urusi", "QAR_displayName": "Rial ya Katari", "MOP_displayName": "Pataca ya Macau", "SOS_displayName": "shilingi ya Somalia", "SGD_displayName": "Dola ya Singapuri", "MWK_displayName": "kwacha ya Malawi", "KES_displayName": "shilingi ya Kenya", "CRC_displayName": "Colon ya Kostarika", "ZAR_displayName": "randi ya Afrika Kusini", "AUD_displayName": "dola ya Australia", "PKR_displayName": "Rupee ya Pakistan", "VND_displayName": "Dong ya Kivietinamu", "HKD_displayName": "Dola ya Hong Kong", "MYR_displayName": "Ringgit ya Malaysia", "CNY_displayName": "yuan Renminbi ya China", "CDF_displayName": "faranga ya Kongo", "ISK_displayName": "Krona ya Isilandi", "FKP_displayName": "Pauni ya Visiwa vya Falkland" } //end v1.x content );
39.965116
74
0.727379
b40566f5052417c6cdbc774039ebf9a4c9c451da
2,251
js
JavaScript
packages/nuxt-module/plugins/api-client.js
AndresNuricumbo/shopware-pwa
e405e9660fa95497dc519fb4f3b7947f65157a0e
[ "MIT" ]
null
null
null
packages/nuxt-module/plugins/api-client.js
AndresNuricumbo/shopware-pwa
e405e9660fa95497dc519fb4f3b7947f65157a0e
[ "MIT" ]
null
null
null
packages/nuxt-module/plugins/api-client.js
AndresNuricumbo/shopware-pwa
e405e9660fa95497dc519fb4f3b7947f65157a0e
[ "MIT" ]
null
null
null
import { createInstance } from "@shopware-pwa/shopware-6-client"; import { useUser, useCart, useSessionContext, useSharedState, } from "@shopware-pwa/composables"; import { reactive } from "@vue/composition-api"; export default async ({ app }, inject) => { if (!app.$cookies) { throw "Error cookie-universal-nuxt module is not applied in nuxt.config.js"; } const contextToken = app.$cookies.get("sw-context-token") || ""; const languageId = app.$cookies.get("sw-language-id") || ""; /** * Setup Shopware API client */ const instance = createInstance({ endpoint: "<%= options.shopwareEndpoint %>", accessToken: "<%= options.shopwareAccessToken %>", timeout: "<%= options.shopwareApiClient.timeout %>", auth: { username: "<%= options.shopwareApiClient.auth ? options.shopwareApiClient.auth.username : undefined %>", password: "<%= options.shopwareApiClient.auth ? options.shopwareApiClient.auth.password : undefined %>", }, contextToken, languageId, }); if (process.server) { const sharedStore = reactive({}); app.context.ssrContext.nuxt.sharedStore = sharedStore; inject("sharedStore", sharedStore); } else { // Client side const sharedStore = reactive(window.__NUXT__.sharedStore || {}); inject("sharedStore", sharedStore); } inject("shopwareApiInstance", instance); inject("interceptors", {}); // functionality for useIntercept composable /** * Save current contextToken when its change */ instance.onConfigChange(({ config }) => { try { app.$cookies.set("sw-context-token", config.contextToken, { maxAge: 60 * 60 * 24 * 365, sameSite: "Lax", path: "/", }); app.$cookies.set("sw-language-id", config.languageId, { maxAge: 60 * 60 * 24 * 365, sameSite: "Lax", path: "/", }); } catch (e) { // Sometimes cookie is set on server after request is send, it can fail silently } }); if (process.client) { const { refreshSessionContext } = useSessionContext(app); refreshSessionContext(); const { refreshUser } = useUser(app); refreshUser(); const { refreshCart } = useCart(app); refreshCart(); } };
29.618421
103
0.630831
b405fde9988fd7b2cd01ae882356dfe3c3cfaabd
4,660
js
JavaScript
dist/useFetch.js
indiana-department-of-transportation/usefetch
6d0390242757001580a18a87287146a79a7e4cea
[ "MIT" ]
null
null
null
dist/useFetch.js
indiana-department-of-transportation/usefetch
6d0390242757001580a18a87287146a79a7e4cea
[ "MIT" ]
null
null
null
dist/useFetch.js
indiana-department-of-transportation/usefetch
6d0390242757001580a18a87287146a79a7e4cea
[ "MIT" ]
1
2020-01-11T14:19:31.000Z
2020-01-11T14:19:31.000Z
"use strict"; /* eslint-disable react-hooks/exhaustive-deps */ /** * useFetch.js * * @description Custom fetch hook for TMC applications. * @author jarsmith@indot.in.gov * @license MIT * @copyright INDOT, 2019 */ Object.defineProperty(exports, "__esModule", { value: true }); const react_1 = require("react"); const REQUEST_CACHE = {}; /** * @description Custom hook for AJAX data. Takes either a Request object or a url and returns * a state from a call to useState that gets updated REQUEST_CACHE a result comes back. * * @param {Request|string} request The string url or URL object or Request object to fetch. * **NOTE:** if using a Request object it *must* be wrapped in a call to useState to prevent * an infinite render loop. * @param {number} timeout The timeout, defaults to none. * @param {Any} initialData The initial data to pass to useState. Defaults to null. * @param {boolean} cache Whether or not to cache the request to prevent unnecessary fetches. * @returns {Object} The current status of the fetch. */ function useFetch({ request, timeout = 0, initialData = {}, cache = false, fetchFn = fetch, }) { const isMounted = react_1.useRef(true); const [isCancelled, setCancelled] = react_1.useState(false); const [data, updateData] = react_1.useState(initialData); const [isLoading, setLoading] = react_1.useState(false); const [error, setError] = react_1.useState(); const cancel = () => setCancelled(true); const update = (fn, arg) => { if (isMounted.current && !isCancelled) fn(arg); }; react_1.useEffect(() => { const fetchData = async (url) => { if (!isLoading) { try { update(setLoading, true); const tout = timeout && timeout > 0 ? new Promise((_, rej) => setTimeout(rej, timeout, new Error('Request timed out.'))) : null; // Type assertion is ok here because the other branch will throw const req = (tout ? Promise.race([tout, fetchFn(request)]) : fetchFn(request)); const resp = await req; if (resp.status < 200 || resp.status >= 400) { throw new Error(`HTTP error ${resp.status}`); } const text = await resp.text(); let data; try { data = JSON.parse(text); } catch (err) { data = text; } if (!data) { throw new Error('Empty response'); } if (cache) { REQUEST_CACHE[url] = data; } update(setError, undefined); update(updateData, data); } catch (e) { if (cache) REQUEST_CACHE[url] = e; update(setError, e); } finally { update(setLoading, false); } } if (!request && data !== initialData) { updateData(initialData); } }; if (request && !isCancelled && !isLoading) { const url = (() => { switch (true) { case request instanceof Request: return request.url; case typeof request === 'string': return request; default: update(setError, new Error(`Unknown request type for '${request}'.`)); return ''; } })(); if (url) { if (!REQUEST_CACHE.hasOwnProperty(url)) { fetchData(url); } else { const cached = REQUEST_CACHE[url]; if (cached instanceof Error) { update(setError, cached); } else { update(updateData, cached); } } } } }, [request]); react_1.useEffect(() => { return () => { isMounted.current = false; }; }, []); return { data, isLoading, isCancelled, cancel, error, }; } exports.default = useFetch; //# sourceMappingURL=useFetch.js.map
37.28
108
0.472747
b40600ced1432c8b78ebf85159d9c3cd56bc8d7c
709
js
JavaScript
new-bootcamp-prep-assessments-master/final_evaluation/final_eval/problems/1_word_sandwich.js
skullbaselab/instructor_documents
09d3f293d79b3b7f6cbc83f91421c986f3a4a700
[ "MIT" ]
null
null
null
new-bootcamp-prep-assessments-master/final_evaluation/final_eval/problems/1_word_sandwich.js
skullbaselab/instructor_documents
09d3f293d79b3b7f6cbc83f91421c986f3a4a700
[ "MIT" ]
null
null
null
new-bootcamp-prep-assessments-master/final_evaluation/final_eval/problems/1_word_sandwich.js
skullbaselab/instructor_documents
09d3f293d79b3b7f6cbc83f91421c986f3a4a700
[ "MIT" ]
null
null
null
/************************************************************************************** Write a function `wordSandwich(outerWord, innerWord)` that takes in two strings and returns a string representing a word sandwich. See the examples below. Examples: wordSandwich('bread', 'cheese'); // => 'BREADcheeseBREAD' wordSandwich('BREAD', 'CHEESE'); // => 'BREADcheeseBREAD' wordSandwich('HeLLo', 'worLD'); // => 'HELLOworldHELLO' Difficulty: Easy *************************************************************************************/ function wordSandwich(outerWord, innerWord) { } /******************** DO NOT MODIFY ANYTHING UNDER THIS LINE *************************/ module.exports = wordSandwich;
33.761905
87
0.504937
b4062022604fd8e0ff6bbcce9b52fd36fea8e71b
366
js
JavaScript
public/js/myJs.js
manohisoa-dev/investirenaustralie
e4a4072af10fb339461c1d50c9f16193e6c07836
[ "MIT" ]
null
null
null
public/js/myJs.js
manohisoa-dev/investirenaustralie
e4a4072af10fb339461c1d50c9f16193e6c07836
[ "MIT" ]
null
null
null
public/js/myJs.js
manohisoa-dev/investirenaustralie
e4a4072af10fb339461c1d50c9f16193e6c07836
[ "MIT" ]
null
null
null
$(document).ready(function(){ $('.inputGroupFile').on('change',function(){ var file_name = ($(this).val()).split('\\')[2]; $('.inputGroupFileName').text(file_name); }); $('.inputGroupFile02').on('change',function(){ var file_name = ($(this).val()).split('\\')[2]; $('.inputGroupFileName02').text(file_name); }); });
28.153846
55
0.538251
b40621c6b6c3518f301db8893b2ced1a3f287778
4,158
js
JavaScript
nerdlets/nrql-tutorial-nerdlet/levels/level2/lessons/Wildcards.js
nrkk-azuma/nr1-learn-nrql
950b1e7c259b0169d95e2a099d602f6f1d18c418
[ "Apache-2.0" ]
11
2020-08-05T15:49:30.000Z
2022-01-13T22:44:40.000Z
nerdlets/nrql-tutorial-nerdlet/levels/level2/lessons/Wildcards.js
nrkk-azuma/nr1-learn-nrql
950b1e7c259b0169d95e2a099d602f6f1d18c418
[ "Apache-2.0" ]
35
2020-07-29T15:31:47.000Z
2022-02-23T23:16:17.000Z
nerdlets/nrql-tutorial-nerdlet/levels/level2/lessons/Wildcards.js
newrelic/nr1-learn-nrql
54a300a490350c3afe3195767d828f840df5f226
[ "Apache-2.0" ]
4
2020-07-31T20:21:04.000Z
2020-10-15T13:52:04.000Z
import React from 'react'; import SampleQuery from '../../../components/SampleQuery'; import { Trans } from 'react-i18next'; export default function Wildcards() { return ( <div> <p> <Trans i18nKey="Contents.P1"> We now know how to use a <code>WHERE</code> clause to filter the results in our query. Aside from using standard comparison operators, we can also use <code>LIKE</code> and <code>NOT LIKE</code> if we want to determine whether an attribute contains or does not contain a specified substring. In order to achieve this, we need to use the percent (<code>%</code>) symbol as a wildcard anywhere in the string.{' '} </Trans> </p> <p> <Trans i18nKey="Contents.P2"> In our sample query, we are getting the number of transactions with the term "Web" anywhere (beginning, middle or end) in the name. </Trans> </p> <SampleQuery nrql="SELECT count(\*) FROM Transaction WHERE name **LIKE '%Web%'** FACET name SINCE 1 day ago" span="6" /> <p> <Trans i18nKey="Contents.P3"> {' '} If we change our query to use <code>NOT LIKE</code> instead, then we will get the number of transactions that do not contain the word "Web" in its name. </Trans> </p> <SampleQuery nrql="SELECT count(\*) FROM Transaction WHERE name **NOT LIKE '%Web%'** FACET name SINCE 1 day ago" span="6" /> <p> <Trans i18nKey="Contents.P4"> We used the wild card <code>%</code> at the beginning and end, which means that we are checking the value of the attribute we chose if it contains "Web" anywhere in the text. Equally, you could use{' '} <code>%Web</code> OR <code>Web%</code> to match something that ends in "Web" or starts with "Web", respectively. </Trans> </p> <p> <Trans i18nKey="Contents.P5"> You can also add the wildcard in between strings for a more refined search. This query will check for a transaction name that contains the word "Web" followed by any text, but then also contains the word "index" followed by any number of characters. So, the results will only be transactions with "Web" <em>and</em> "index" in the name. </Trans> </p> <SampleQuery nrql="SELECT count(\*) FROM Transaction WHERE name **LIKE '%Web%index%'** FACET name SINCE 1 day ago" span="6" /> <p> <Trans i18nKey="Contents.P6"> What if you need to be extremely specific and the names don't have a common string you can match using wildcards. The <code>IN</code> and{' '} <code>NOT IN</code> operators allow us to specify a set of values that we would like to check against an attribute. Instead of specifying multiple <code>WHERE</code> clauses with <code>AND</code> or{' '} <code>OR</code> operators, we can simplify our condition by listing the values in parentheses separated by commas.{' '} </Trans> </p> <p> <Trans i18nKey="Contents.P7"> In this sample query, we are counting the number of transactions whose subtype is either "SpringController" or "StrutsAction". If you change our query to use <code>NOT IN</code> instead, then we will get the number of transactions whose subtype is neither "SpringController" nor "StrutsAction". </Trans> </p> <SampleQuery nrql="SELECT count(\*) FROM Transaction WHERE transactionSubType **IN ('SpringController', 'StrutsAction')** SINCE 1 day ago" span="6" /> <h2> <Trans i18nKey="Contents.H1">Lesson Summary</Trans> </h2> <p> <Trans i18nKey="Contents.P8"> You can now control your data and manipulate it to do what you need, allowing you to construct powerful, meaningful dashboards and alerts. </Trans> </p> </div> ); }
38.146789
133
0.60101
b4077a1a07958d960573843fe452f2b7139ad171
22,705
js
JavaScript
newens/index.js
enesozdemirim/newens
b54a1213f01b15133a101834bc06d2053127c14b
[ "MIT" ]
3
2021-07-10T07:46:36.000Z
2021-12-04T21:34:02.000Z
newens/index.js
enesozdemirim/newens
b54a1213f01b15133a101834bc06d2053127c14b
[ "MIT" ]
null
null
null
newens/index.js
enesozdemirim/newens
b54a1213f01b15133a101834bc06d2053127c14b
[ "MIT" ]
null
null
null
const Discord = require('discord.js'); const client = new Discord.Client(); const ayarlar = require('./ayarlar.json'); const { Client, Util } = require('discord.js'); require('./util/eventLoader.js')(client); const fs = require('fs'); const db = require("wio.db"); const { GiveawaysManager } = require('discord-giveaways'); var prefix = ayarlar.prefix; const log = message => { console.log(`${message}`); }; client.commands = new Discord.Collection(); client.aliases = new Discord.Collection(); fs.readdir('./komutlar/', (err, files) => { if (err) console.error(err); log(`${files.length} komut yüklenecek.`); files.forEach(f => { let props = require(`./komutlar/${f}`); log(`Yüklenen komut: ${props.help.name}.`); client.commands.set(props.help.name, props); props.conf.aliases.forEach(alias => { client.aliases.set(alias, props.help.namee); }); }); }); client.reload = command => { return new Promise((resolve, reject) => { try { delete require.cache[require.resolve(`./komutlar/${command}`)]; let cmd = require(`./komutlar/${command}`); client.commands.delete(command); client.aliases.forEach((cmd, alias) => { if (cmd === command) client.aliases.delete(alias); }); client.commands.set(command, cmd); cmd.conf.aliases.forEach(alias => { client.aliases.set(alias, cmd.help.name); }); resolve(); } catch (e) { reject(e); } }); }; client.load = command => { return new Promise((resolve, reject) => { try { let cmd = require(`./komutlar/${command}`); client.commands.set(command, cmd); cmd.conf.aliases.forEach(alias => { client.aliases.set(alias, cmd.help.name); }); resolve(); } catch (e) { reject(e); } }); }; client.unload = command => { return new Promise((resolve, reject) => { try { delete require.cache[require.resolve(`./komutlar/${command}`)]; let cmd = require(`./komutlar/${command}`); client.commands.delete(command); client.aliases.forEach((cmd, alias) => { if (cmd === command) client.aliases.delete(alias); }); resolve(); } catch (e) { reject(e); } }); }; client.on('message', msg => { if (msg.content === '.eval') { if (!["789164345585565706"].includes(message.author.id))//eval kullanack kişilerin id'lerini girin return message.reply("`code` komutunu kullanmak için gerekli izne sahip değilsiniz!").catch(); let result = eval(args.join(" ")) message.channel.send(result) } }); client.elevation = message => { if (!message.guild) { return; } let permlvl = 0; if (message.member.hasPermission("BAN_MEMBERS")) permlvl = 2; if (message.member.hasPermission("ADMINISTRATOR")) permlvl = 3; if (message.author.id === ayarlar.sahip) permlvl = 4; return permlvl; }; var regToken = /[\w\d]{24}\.[\w\d]{6}\.[\w\d-_]{27}/g; // client.on('debug', e => { // console.log(chalk.bgBlue.green(e.replace(regToken, 'that was redacted'))); // }); client.on('warn', e => { console.log(chalk.bgYellow(e.replace(regToken, 'that was redacted'))); }); client.on('error', e => { console.log(chalk.bgRed(e.replace(regToken, 'that was redacted'))); }); ///////////////////////eklendim atıldım client.on('guildDelete', guild => { let ENSBotembed = new Discord.MessageEmbed() .setColor("RED") .setTitle(" ATILDIM !") .addField("Sunucu Adı:", guild.name) .addField("Sunucu sahibi", guild.owner) .addField("Sunucudaki Kişi Sayısı:", guild.memberCount) client.channels.cache.get('786143386254966804').send(ENSBotembed); }); client.on('guildCreate', guild => { let ENSBotembed = new Discord.MessageEmbed() .setColor("GREEN") .setTitle("EKLENDİM !") .addField("Sunucu Adı:", guild.name) .addField("Sunucu sahibi", guild.owner) .addField("Sunucudaki Kişi Sayısı:", guild.memberCount) client.channels.cache.get('786143386254966804').send(ENSBotembed); }); //-------------------EKLENDİM ATILDIM SON ---------------// //-------------------- Afk Sistemi --------------------// client.on("message", async message => { if (message.author.bot || message.channel.type === "dm") return; var afklar = await db.fetch(`afk_${message.author.id}, ${message.guild.id}`); if (afklar) { db.delete(`afk_${message.author.id}, ${message.guild.id}`); db.delete(`afk-zaman_${message.author.id}, ${message.guild.id}`); message.reply(`Afklıktan Çıktın!`) try { let isim = message.member.nickname.replace("[AFK]", ""); message.member.setNickname(isim).catch(err => console.log(err)); } catch (err) { console.log(err.message); } } let ms = require("ms"); var kullanıcı = message.mentions.users.first(); if (!kullanıcı) return; let zaman = await db.fetch(`afk-zaman_${kullanıcı.id}, ${message.guild.id}`); var süre = ms(new Date().getTime() - zaman); var sebep = await db.fetch(`afk_${kullanıcı.id}, ${message.guild.id}`); if ( await db.fetch( `afk_${message.mentions.users.first().id}, ${message.guild.id}` ) ) { if (süre.days !== 0) { const nrc = new Discord.MessageEmbed() .setTitle("<a:uyar:814178449131569223> Uyarı!") .setDescription("Etiketlediniz Kullanıcı Afk!") .addField("Afk Nedeni:",`> ${sebep}`) .setColor("RANDOM") .setThumbnail(message.author.avatarURL()) .addField("Afk Olma Süresi",`> ${süre}`); message.channel.send(nrc) return; } } }); //-------------------- Afk Sistemi Son --------------------// //-------------------- Reklam Engel Sistemi --------------------// ///reklam/// client.on("message", async msg => { let antoxd = await db.fetch(`antoxd${msg.guild.id}`); if (antoxd === "acik") { //Lord Creative const reklam = ["discord.gg", "https://discordapp.com/invite/"]; if (reklam.some(word => msg.content.includes(word))) { msg.delete(); } } }); //----------------------------LİNK ENGEL ----------------------------------------------------|| client.on("message", async msg => { var mayfe = await db.fetch(`reklam_${msg.guild.id}`) if (mayfe == 'acik') { const birisireklammidedi = [".com", ".net", ".xyz", ".tk", ".pw", ".io", ".me", ".gg", "www.", "https", "http", ".gl", ".org", ".com.tr", ".biz", "net", ".rf.gd", ".az", ".party", "discord.gg",]; if (birisireklammidedi.some(word => msg.content.includes(word))) { try { if (!msg.member.hasPermission("BAN_MEMBERS")) { msg.delete(); return msg.reply('Bu Sunucuda Reklam Engelleme Filtresi Aktiftir. Reklam Yapmana İzin Veremem !').then(msg => msg.delete(3000)); msg.delete(3000); } } catch(err) { console.log(err); } } } else if (mayfe == 'kapali') { } if (!mayfe) return; }) ; //----------------------------LİNK ENGEL SON----------------------------------------------------|| client.on("message", async msg => { if (msg.content === `<@774765565466116126>`){///BOT İD NİZİ GİRİNİZ return msg.channel.send( new Discord.MessageEmbedİ() .setTitle("Merhaba Ben Cowboy") .setDescription("Prefixim: `.`\n Komutlarıma bakmak için: `.yardım yazabilirsin :)`")) }}); ////son //capsengel a. client.on("message", async message => { var anahtar = db.fetch(`caps_${message.guild.id}`) if(anahtar === "acik"){ if(message.author.bot) return; if(message.content.length < 5) return; let capsengel = message.content.toUpperCase(); let beyazliste = message.mentions.users.first() || message.mentions.channels.first() || message.mentions.roles.first() if(message.content == capsengel){ if(!beyazliste && !message.content.includes("@everyone") && !message.content.includes("@here") && !message.member.hasPermission("BAN_MEMBERS")) { message.delete().then(message.channel.send("Büyük harf kullanmamalısın.!!!").then(i => i.delete(10000))) }} } if(!anahtar) return }) //capsengel son //-------------------- Reklam Engel Sistemi --------------------// client.on("message", async message => { let uyarisayisi = await db.fetch(`reklamuyari_${message.author.id}`); let reklamkick = await db.fetch(`kufur_${message.guild.id}`); let kullanici = message.member; if (!reklamkick) return; if (reklamkick == "Açık") { const reklam = [ "discord.app", "discord.gg", ".com", ".net", ".xyz", ".tk", ".pw", ".io", ".me", ".gg", "www.", "https", "http", ".gl", ".org", ".com.tr", ".biz", ".party", ".link", ".tc", ".tk", ".rf.gd", ".az", ".hub" ]; if (reklam.some(word => message.content.toLowerCase().includes(word))) { if (!message.member.hasPermission("BAN_MEMBERS")) { message.delete(); db.add(`reklamuyari_${message.author.id}`, 1); //uyarı puanı ekleme if (uyarisayisi === null) { let uyari = new Discord.MessageEmbed() .setColor("BLACK") .setTitle("Reklam-Engel!") .setDescription( `<@${message.author.id}> Reklam Yapmayı Kes! Bu İlk Uyarın! (1/3)` ) .setFooter(client.user.username, client.user.avatarURL()) .setTimestamp(); message.channel.send(uyari); } if (uyarisayisi === 1) { let uyari = new Discord.MessageEmbed() .setColor("BLACK") .setTitle("Reklam-Engel!") .setDescription( `<@${message.author.id}> Reklam Yapmayı Kes! Bu İkinci Uyarın! (2/3)` ) .setFooter(client.user.username, client.user.avatarURL()) .setTimestamp(); message.channel.send(uyari); } if (uyarisayisi === 2) { message.delete(); await kullanici.kick({ reason: `Reklam-Engel Sistemi!` }); let uyari = new Discord.MessageEmbed() .setColor("BLACK") .setTitle("Reklam-Engel!") .setDescription( `<@${message.author.id}> Reklam Yaptığı İçin Sunucudan Atıldı! (3/3)` ) .setFooter(client.user.username, client.user.avatarURL()) .setTimestamp(); message.channel.send(uyari); } if (uyarisayisi === 3) { message.delete(); await kullanici.members.ban({ reason: `Reklam-Engel Sistemi!` }); db.delete(`reklamuyari_${message.author.id}`); let uyari = new Discord.MessageEmbed() .setColor("BLACK") .setTitle("Reklam Kick Sistemi") .setDescription( `<@${message.author.id}> Atıldıktan Sonra Tekrar Reklam Yaptığı İçin Sunucudan Yasaklandı!` ) .setFooter(client.user.username, client.user.avatarURL()) .setTimestamp(); message.channel.send(uyari); } } } } }); //-------------------- Reklam Engel Sistemi --------------------// //kanalkoruma client.on('channelDelete', async channel => { var logk= await db.fetch(`kanalklog_${channel.guild.id}`) if(logk){ let kategori = channel.parentID; channel.clone(channel.name).then(channels => { let newkanal = channel.guild.channels.cache.find("name", channel.name) channels.setParent(channel.guild.channels.cache.find(channelss => channelss.id === kategori)); client.channels.cache.get(logk).send(`${channel.name} adlı kanal silindi yeniden açıp izinlerini ayarladım.`); }); }else return; }); //kanalkoruma son //-------------------- Ever Here Engel --------------------// client.on("message", async msg => { let hereengelle = await db.fetch(`hereengel_${msg.guild.id}`); if (hereengelle == "acik") { const here = ["@here", "@everyone"]; if (here.some(word => msg.content.toLowerCase().includes(word))) { if (!msg.member.hasPermission("ADMINISTRATOR")) { msg.delete(); msg.channel .send(`<@${msg.author.id}>`) .then(message => message.delete()); var e = new Discord.MessageEmbed() .setColor("BLACK") .setDescription(`Bu Sunucuda Everyone ve Here Yasak!`); msg.channel.send(e); } } } else if (hereengelle == "kapali") { } }); //-------------------- Ever Here Engel --------------------// //-------------------- Sa As Sistemi --------------------// client.on("message", async message => { const Bdgo = message.content.toLocaleLowerCase(); if ( Bdgo === "selam" || Bdgo === "sa" || Bdgo === "selamün aleyküm" || Bdgo === "selamun aleyküm" || Bdgo === "slm" || Bdgo === "sea" ) { let e = await db.fetch(`sa-as_${message.guild.id}`); if (e === "acik") { const embed = new Discord.MessageEmbed() .setDescription(`Aleyküm Selam, Hoş Geldin ^-^`) .setColor("GREEN") return message.channel.send(embed) } } }); //-------------------- Sa As Sistemi --------------------// //KanalKoruma client.on("message", async message => { if (message.content === "ens bot eklendi") { try { await message.react("814187207631306772"); } catch (error) { console.error("Faild."); } } }); //-------------------- Prefix Sistemi --------------------// //-------------------- Prefix Sistemi --------------------// //-------------------- Prefix Sistemi --------------------// client.on('ready', () => { setInterval(function() { let egehanss = client.channels.cache.get("826002446588444713") if(egehanss){ egehanss.send("**YouTube Kanalım'daki Hangi Videonun Kaynak Kodlarına Erişmek İstiyorsanız, O Videonun Beğenildiğine,Abone Olunduğuna,Yorum Yapıldığına Dair SS'ini ( Ekran Görüntüsünü ) Buraya Atmanız ve SABIRLA BEKLEMENİZ Gerekmektedir . Yetkilileri Etiketkeyerek Spam Yapanlar Sunucudan Atılacaktır ! @🎁 Youtube Abonesi Rolünüz Verildikten Sonra Sunucumuzda Bulunan Oyunlar Kategorisinin Altında Karakol Kategorisinin Üstünde Kaynak Kodlar, Altyapılar Ve Abone Rolü ile verilen kaynak kod odaları açılacaktır !**") } }, 1800000) //1000 = 1sn }) //////seviye baş client.on("message", async msg => { if(msg.content.startsWith(ayarlar.prefix)) return; const db = require('wio.db'); var id = msg.author.id; var gid = msg.guild.id; var xp = await db.fetch(`xp_${id}_${gid}`); var lvl = await db.fetch(`lvl_${id}_${gid}`); let seviyexp = await db.fetch(`seviyexp${msg.guild.id}`) const skanal = await db.fetch(`seviyekanal${msg.guild.id}`) let kanal = msg.guild.channels.cache.get(skanal) if (msg.author.bot === true) return; let seviyeEmbed = new Discord.MessageEmbed() seviyeEmbed.setDescription(`Tebrik ederim <@${msg.author.id}>! Seviye atladın ve **${lvl+1}** seviye oldun!`) seviyeEmbed.setFooter(`${client.user.username} | Seviye Sistemi`) seviyeEmbed.setColor("RANDOM") if(!lvl) { db.set(`xp_${id}_${gid}`, 5); db.set(`lvl_${id}_${gid}`, 1); db.set(`xpToLvl_${id}_${gid}`, 100); db.set(`top_${id}`, 1) } let veri1 = []; if(seviyexp) veri1 = seviyexp if(!seviyexp) veri1 = 5 if (msg.content.length > 7) { db.add(`xp_${id}_${gid}`, veri1) }; let seviyesınır = await db.fetch(`seviyesınır${msg.guild.id}`) let veri2 = []; if(seviyesınır) veri2 = seviyesınır if(!seviyesınır) veri2 = 250 if (await db.fetch(`xp_${id}_${gid}`) > veri2) { if(skanal) { kanal.send(new Discord.MessageEmbed() .setDescription(`Tebrik ederim <@${msg.author.id}>! Seviye atladın ve **${lvl+1}** seviye oldun:tada:`) .setFooter(`${client.user.username} | Seviye Sistemi`) .setColor("RANDOM")) } db.add(`lvl_${id}_${gid}`, 1) db.delete(`xp_${id}_${gid}`)}; db.set(`top_${id}`, Math.floor(lvl+1)) }); //SEVİYE-ROL----------------------------------- client.on('message', async message => { var id = message.author.id; var gid = message.guild.id; let rrol = await db.fetch(`rrol.${message.guild.id}`) var level = await db.fetch(`lvl_${id}_${gid}`); if(rrol) { rrol.forEach(async rols => { var rrol2 = await db.fetch(`rrol2.${message.guild.id}.${rols}`) if(Math.floor(rrol2) <= Math.floor(level)) { let author = message.guild.member(message.author) author.roles.add(rols) } else if(Math.floor(rrol2) >= Math.floor(level)) { let author = message.guild.member(message.author) author.roles.remove(rols) } }) } if(message.content == '!rütbeler') { if(!rrol) { message.channel.send(new Discord.MessageEmbed() .setColor("RANDOM") .setFooter(`${client.user.username} Seviye-Rol Sistemi!`, client.user.avatarURL) .setDescription(`Herhangi bir rol oluşturulmadı.`)) return; } const { MessageEmbed } = require('discord.js') let d = rrol.map(x => '<@&'+message.guild.roles.cache.get(x).id+'>' + ' **' + db.get(`rrol3.${message.guild.id}.${x}`)+' Seviye**' ).join("\n") message.channel.send(new MessageEmbed() .setColor("RANDOM") .setFooter(`${client.user.username} Seviye-Rol Sistemi!`, client.user.avatarURL) .setDescription(`${d}`)) } }) client.on('message', async message => { var id = message.author.id; var gid = message.guild.id; let srol = await db.fetch(`srol.${message.guild.id}`) var level = await db.fetch(`lvl_${id}_${gid}`); if(srol) { srol.forEach(async rols => { var srol2 = await db.fetch(`srol2.${message.guild.id}.${rols}`) if(Math.floor(srol2) <= Math.floor(level)) { let author = message.guild.member(message.author) author.roles.add(rols) } else if(Math.floor(srol2) >= Math.floor(level)) { let author = message.guild.member(message.author) } }) } if(message.content == '!seviyerolleri' || message.content == "!levelroles") { if(!srol) { message.channel.send(new Discord.MessageEmbed() .setColor("RANDOM") .setFooter(`${client.user.username} Seviye-Rol Sistemi!`, client.user.avatarURL) .setDescription(`Herhangi bir rol oluşturulmadı.`)) return; } const { MessageEmbed } = require('discord.js') let d = srol.map(x => '<@&'+message.guild.roles.cache.get(x).id+'>' + ' **' + db.get(`srol3.${message.guild.id}.${x}`)+' Seviye**' ).join("\n") message.channel.send(new MessageEmbed() .setColor("RANDOM") //.setColor(message.guild.member(message.author).highestRole.hexColor) .setFooter(`${client.user.username} Seviye-Rol Sistemi!`, client.user.avatarURL) .setDescription(`${d}`)) } }) client.on("guildMemberAdd", member =>{ const gereksiz = db.fetch(`dmhgbb_${member.guild.id}`); if (gereksiz === "aktif") { const hg = new Discord.MessageEmbed() .setColor('RANDOM') .setTitle(member.guild.name + '\n Sunucusuna Hoşgeldin!') .setDescription(`Umarım sunucumuzda eğlenirsin! İyi vakit geçirmen dileği ile...`) .setFooter('Hoşgeldin') .setTimestamp() member.send(hg) }else if (gereksiz === "deaktif") { } if (!gereksiz) return; }); //////////////////// client.on("guildMemberRemove", member =>{ const gereksiz = db.fetch(`dmhgbb_${member.guild.id}`); if (gereksiz === "aktif") { const hg = new Discord.MessageEmbed() .setColor('RANDOM') .setTitle(member.guild.name + '\n Görüşürüz!') .setDescription(`Umarım bizimle vakit geçirirken mutlu olmuşsundur!`) .setFooter('Görüşürüz') .setTimestamp() member.send(hg) }else if (gereksiz === "deaktif") { } if (!gereksiz) return; }); ///////////// ///// client.on("roleDelete", async role => { let rol = await db.fetch(`rolk_${role.guild.id}`); if (rol) { const entry = await role.guild.fetchAuditLogs({ type: "ROLE_DELETE" }).then(audit => audit.entries.first()); if (entry.executor.id == client.user.id) return; role.guild.roles.create({ data: { name: role.name, color: role.color, hoist: role.hoist, permissions: role.permissions, mentionable: role.mentionable, position: role.position }, reason: 'Rol koruma açık olduğundan yetkili tarafından silinen rol tekrar açıldı.'}) } }) ////--------------BOTA DM ATANLAR BAŞLANGIÇ-------------//// client.on("message", msg => { var dm = client.channels.cache.get("786143386254966804"); if (msg.channel.type === "dm") { if (msg.author.id === client.user.id) return; const botdm = new Discord.MessageEmbed() .setTitle(`${client.user.username} Dm`) .setTimestamp() .setColor("RANDOM") .setThumbnail(`${msg.author.avatarURL()}`) .addField("Gönderen", msg.author.tag) .addField("Gönderen ID", msg.author.id) .addField("Gönderilen Mesaj", msg.content); dm.send(botdm); } if (msg.channel.bot) return; }); ///--------BOTA DM ATANLAR SONU-------------//// client.login(ayarlar.token);
28.813452
518
0.537018
b407d6a6239a05d42109e4843c166e183bcba8a3
1,069
js
JavaScript
src/internal/mixins/popup/Overlay.js
ifishnet/muse-ui
74f78dfe6ae64776cfbd620e594daf3924abded4
[ "MIT" ]
9,427
2016-09-19T00:54:49.000Z
2022-03-31T01:38:50.000Z
src/internal/mixins/popup/Overlay.js
ifishnet/muse-ui
74f78dfe6ae64776cfbd620e594daf3924abded4
[ "MIT" ]
1,352
2016-10-06T00:48:19.000Z
2022-03-03T04:02:35.000Z
src/internal/mixins/popup/Overlay.js
ifishnet/muse-ui
74f78dfe6ae64776cfbd620e594daf3924abded4
[ "MIT" ]
1,276
2016-10-12T10:17:17.000Z
2022-03-31T11:27:11.000Z
import '../../../styles/components/overlay.less'; import { FadeTransition } from '../../transitions'; export default { name: 'mu-overlay', props: { show: Boolean, fixed: Boolean, onClick: Function, opacity: { type: Number, default: 0.4 }, color: String, zIndex: Number }, computed: { overlayStyle () { return { 'opacity': this.opacity, 'background-color': this.color, 'position': this.fixed ? 'fixed' : '', 'z-index': this.zIndex }; } }, methods: { prevent (event) { event.preventDefault(); event.stopPropagation(); }, handleClick () { if (this.onClick) { this.onClick(); } } }, render (h) { return h(FadeTransition, [ h('div', { staticClass: 'mu-overlay', style: this.overlayStyle, directives: [{ name: 'show', value: this.show }], on: { click: this.handleClick, touchmove: this.prevent } }) ]); } };
19.436364
51
0.496726
b40804adea41fc5130e6cc35e23df8063e8ae1f4
14,191
js
JavaScript
plugin/animate/plugin.js
wvwang/webpages
4a4b016baf3a3139a8291616622367a7a0d4d023
[ "MIT" ]
597
2016-01-05T15:12:52.000Z
2022-03-21T22:23:16.000Z
plugin/animate/plugin.js
wvwang/webpages
4a4b016baf3a3139a8291616622367a7a0d4d023
[ "MIT" ]
126
2016-01-05T11:09:32.000Z
2022-03-24T08:42:42.000Z
plugin/animate/plugin.js
wvwang/webpages
4a4b016baf3a3139a8291616622367a7a0d4d023
[ "MIT" ]
284
2016-02-02T08:53:00.000Z
2022-03-20T14:08:55.000Z
/***************************************************************** ** Author: Asvin Goel, goel@telematique.eu ** ** A plugin for animating slide content. ** ** Version: 0.1.0 ** ** License: MIT license (see LICENSE.md) ** ******************************************************************/ window.RevealAnimate = window.RevealAnimate || { id: 'RevealAnimate', init: function(deck) { initAnimate(deck); }, play: function() { play(); }, pause: function() { pause(); }, seek: function(timestamp) { seek(timestamp); }, }; const initAnimate = function(Reveal){ var config = Reveal.getConfig().animate || {}; var autoplay = config.autoplay; var playback = false; var isRecording = false; var timer = null; var initialized = 0; function parseJSON(str) { str = str.replace(/(\r\n|\n|\r|\t)/gm,""); // remove line breaks and tabs var json; try { json = JSON.parse(str, function (key, value) { if (value && (typeof value === 'string') && value.indexOf("function") === 0) { // we can only pass a function as string in JSON ==> doing a real function // eval("var jsFunc = " + value); var jsFunc = new Function('return ' + value)(); return jsFunc; } return value; }); } catch (e) { return null; } return json; } function load( element, config, filename, callback ) { var xhr = new XMLHttpRequest(); xhr.onload = function() { if (xhr.readyState === 4) { callback( element, config, xhr.responseText ); } else { callback( "Failed to get file. ReadyState: " + xhr.readyState + ", Status: " + xhr.status ); } }; xhr.open( 'GET', filename, true ); xhr.send(); } function parseComments( element ) { var config = {}; var comments = element.innerHTML.trim().match(/<!--[\s\S]*?-->/g); //console.log(comments) if ( comments !== null ) for (var k = 0; k < comments.length; k++ ){ comments[k] = comments[k].replace(/<!--/,''); comments[k] = comments[k].replace(/-->/,''); var config = parseJSON(comments[k]); //console.warn(comments[k], config); if ( config ) { if ( config.animation && Array.isArray(config.animation) && config.animation.length && !Array.isArray(config.animation[0]) ) { // without fragments the animation can be specified as a single array (animation steps) config.animation = [ config.animation ]; } break; } } //console.warn(element, config); return config; } function getAnimatedSVG( container ) { var elements = SVG.find('svg'); var svg = elements.toArray().find(element => element.node.parentElement == container); //console.warn("FOUND",svg.node); return svg; } /***************************************************************** ** Set up animations ******************************************************************/ function setupAnimations( container, config ) { //console.warn("setupAnimations"); if ( !config ) return; container.svg = getAnimatedSVG( container ); // pre-animation setup var setup = config.setup; if ( setup ) { for (var i = 0; i < setup.length; i++ ){ try { if ( setup[i].element ) { //console.log(setup[i].element,setup[i].modifier,setup[i].parameters); var elements = container.svg.find(setup[i].element); if ( !elements.length ) { console.warn("Cannot find element to set up with selector: " + setup[i].element + "!"); } //console.warn(elements); //console.log("element(" + setup[i].element + ")." + setup[i].modifier + "(" + setup[i].parameters + ")"); //console.log("element(" + setup[i].element + ")." + setup[i].modifier + "(" + setup[i].parameters + ")"); for (var j = 0; j < elements.length; j++ ){ if ( typeof setup[i].modifier === "function" ) { // if modifier is function execute it setup[i].modifier.apply(elements[j],setup[i].parameters); } else { // apply modifier to element elements[j][setup[i].modifier].apply(elements[j],setup[i].parameters); } } } else { // no element is provided if ( typeof setup[i].modifier === "function" ) { // if modifier is function execute it setup[i].modifier.apply(container.svg,setup[i].parameters); } else { // apply modifier to root container.svg[setup[i].modifier].apply(container.svg,setup[i].parameters); } } } catch( error ) { console.error("Error '" + error + "' setting up element " + JSON.stringify(setup[i])); } } //console.warn(container.svg.node.getAttribute("style")); } container.animation = new SVG.Timeline().persist(true); container.animationSchedule = []; // completion time of each fragment animation // setup animation var animations = config.animation; if ( animations ) { container.animationSchedule.length = animations.length; var timestamp = 0; for (var fragment = 0; fragment < animations.length; fragment++ ){ container.animationSchedule[fragment] = {}; container.animationSchedule[fragment].begin = timestamp; for (var i = 0; i < animations[fragment].length; i++ ){ try { // add each animation step var elements = container.svg.find(animations[fragment][i].element); //console.log("element(" + animations[fragment][i].element + ")." + animations[fragment][i].modifier + "(" + animations[fragment][i].parameters + ")"); if ( !elements.length ) { console.warn("Cannot find element to animate with selector: " + animations[fragment][i].element + "!"); } for (var j = 0; j < elements.length; j++ ){ elements[j].timeline( container.animation ); var anim = elements[j].animate(animations[fragment][i].duration,animations[fragment][i].delay,animations[fragment][i].when) anim[animations[fragment][i].modifier].apply(anim,animations[fragment][i].parameters); } //console.log("Duration:", anim.duration()); timestamp = anim.duration(); } catch( error ) { console.error("Error '" + error + "' setting up animation " + JSON.stringify(animations[fragment][i])); } } // set animationSchedule for each fragment animation var schedule = container.animation.schedule(); if ( schedule.length ) { timestamp = schedule[schedule.length-1].end; } container.animationSchedule[fragment].end = timestamp; } container.animation.stop(); //console.warn(container.animation.schedule()); // console.warn("Schedule", container.animationSchedule); } // setup current slide if ( Reveal.getCurrentSlide().contains( container ) ) { Reveal.layout(); // Update layout to account for svg size animateSlide(0); } initialized += 1; } function initialize() { //console.log("Initialize animations"); // Get all animations var elements = document.querySelectorAll("[data-animate]"); for (var i = 0; i < elements.length; i++ ){ var config = parseComments( elements[i] ); var src = elements[i].getAttribute("data-src"); if ( src ) { var element = elements[i]; load( elements[i], config, src, function( element, config, response ) { if ( printMode ) { // do not load svg multiple times element.removeAttribute("data-src") } element.innerHTML = response + element.innerHTML; setupAnimations( element, config ); }); } else { setupAnimations( elements[i], config ); } } } function play() { //console.log("Play",Reveal.getCurrentSlide()); var elements = Reveal.getCurrentSlide().querySelectorAll("[data-animate]"); for (var i = 0; i < elements.length; i++ ){ //console.warn("Play",elements[i]); if ( elements[i].animation ) { elements[i].animation.play(); } } autoPause(); } function pause() { //console.log("Pause"); if ( timer ) { clearTimeout( timer ); timer = null; } var elements = Reveal.getCurrentSlide().querySelectorAll("[data-animate]"); for (var i = 0; i < elements.length; i++ ){ if ( elements[i].animation ) { elements[i].animation.pause(); } } } function autoPause() { if ( timer ) { clearTimeout( timer ); timer = null; } var fragment = Reveal.getIndices().f + 1 || 0; // in reveal.js fragments start with index 0, here with index 1 var elements = Reveal.getCurrentSlide().querySelectorAll("[data-animate]"); for (var i = 0; i < elements.length; i++ ){ if ( elements[i].animation && elements[i].animationSchedule[fragment] ) { //console.log( elements[i].animationSchedule[fragment].end, elements[i].animation.time()); var timeout = elements[i].animationSchedule[fragment].end - elements[i].animation.time(); timer = setTimeout(pause,timeout); } //console.log("Auto pause",elements[i], timeout); } } function seek( timestamp ) { //console.log("Seek", timestamp); var elements = Reveal.getCurrentSlide().querySelectorAll("[data-animate]"); var fragment = Reveal.getIndices().f + 1 || 0; // in reveal.js fragments start with index 0, here with index 1 for (var i = 0; i < elements.length; i++ ){ //console.log("Seek",timestamp,elements[i].animationSchedule[fragment].begin + (timestamp || 0) ); if ( elements[i].animation && elements[i].animationSchedule[fragment] ) { elements[i].animation.time( elements[i].animationSchedule[fragment].begin + (timestamp || 0) ); } } if ( timer ) { // update time if animation is running autoPause(); } } // Control animation function animateSlide( timestamp ) { // pause(); //console.log("Animate slide", timestamp); if ( timestamp !== undefined ) { seek( timestamp); } if ( Reveal.isAutoSliding() || autoplay || playback || isRecording ) { //console.log("Start animation"); play(); } else { pause(); } //console.log("Done"); } /***************************************************************** ** Print ******************************************************************/ var printMode = ( /print-pdf/gi ).test( window.location.search ); //console.log("createPrintout" + printMode) function initializePrint( ) { //return; //console.log("initializePrint", document.querySelectorAll(".pdf-page").length); if ( !document.querySelectorAll(".pdf-page").length ) { // wait for pdf pages to be created setTimeout( initializePrint, 500 ); return; } initialize(); createPrintout(); } function createPrintout( ) { //console.log("createPrintout", document.querySelectorAll(".pdf-page").length, document.querySelectorAll("[data-animate]").length ); if ( initialized < document.querySelectorAll("[data-animate]").length ) { //console.log("wait"); // wait for animations to be loaded setTimeout( createPrintout, 500 ); return; } var pages = document.querySelectorAll(".pdf-page"); for ( var i = 0; i < pages.length; i++ ) { var fragment = -1; var current = pages[i].querySelectorAll(".current-fragment"); for ( var j = 0; j < current.length; j++ ) { if ( Number(current[j].getAttribute("data-fragment-index")) > fragment ) { fragment = Number(current[j].getAttribute("data-fragment-index") ); } } fragment += 1; var elements = pages[i].querySelectorAll("[data-animate]"); for ( var j = 0; j < elements.length; j++ ) { //console.log(i,fragment, elements[j]); if ( elements[j].animation && elements[j].animationSchedule && elements[j].animationSchedule[fragment] ) { //console.log(i,fragment, elements[j].animationSchedule[fragment].begin); elements[j].animation.time( elements[j].animationSchedule[fragment].end ); } var fragments = elements[j].querySelectorAll("svg > [data-fragment-index]"); //console.log(i,fragment, elements[j], fragments); for ( var k = 0; k < fragments.length; k++ ) { if ( fragments[k].getAttribute("data-fragment-index") < fragment ) { fragments[k].classList.add("visible"); } } } } } /***************************************************************** ** Event listeners ******************************************************************/ Reveal.addEventListener( 'ready', function( event ) { //console.log('ready '); /* if ( printMode ) { initializePrint(); return; } */ initialize(); if ( printMode ) { initializePrint(); return; } Reveal.addEventListener('slidechanged', function(){ //console.log('slidechanged',Reveal.getIndices()); animateSlide(0); }); Reveal.addEventListener( 'overviewshown', function( event ) { // pause animation pause(); } ); /* Reveal.addEventListener( 'overviewhidden', function( event ) { } ); */ Reveal.addEventListener( 'paused', function( event ) { //console.log('paused '); // pause animation pause(); } ); /* Reveal.addEventListener( 'resumed', function( event ) { console.log('resumed '); // resume animation } ); */ Reveal.addEventListener( 'fragmentshown', function( event ) { //console.log("fragmentshown",event); animateSlide(0); } ); Reveal.addEventListener( 'fragmenthidden', function( event ) { //console.log("fragmentshown",event); animateSlide(0); } ); } ); /***************************************************************** ** Playback ******************************************************************/ document.addEventListener('seekplayback', function( event ) { //console.log('event seekplayback ' + event.timestamp); // set animation to event.timestamp animateSlide(event.timestamp); }); document.addEventListener('startplayback', function( event ) { //console.log('event startplayback ' + event.timestamp); playback = true; animateSlide(event.timestamp); }); document.addEventListener('stopplayback', function( event ) { //console.log('event stopplayback ', event); playback = false; animateSlide(); }); document.addEventListener('startrecording', function( event ) { //console.log('event startrecording ' + event.timestamp); isRecording = true; animateSlide(0); }); document.addEventListener('stoprecording', function( event ) { //console.log('event stoprecording ' + event.timestamp); isRecording = false; animateSlide(); }); this.play = play; this.pause = pause; this.seek = seek; return this; };
30.984716
151
0.608202
b40822c19dfc64fb3a67da77105c315672367733
728
js
JavaScript
Vuejs_presentation/slides/flask-reveal/static/js/code.js
jadsonlucio/Presentations
c608361ca518d6dc106455671be2a73df13af4f7
[ "MIT" ]
null
null
null
Vuejs_presentation/slides/flask-reveal/static/js/code.js
jadsonlucio/Presentations
c608361ca518d6dc106455671be2a73df13af4f7
[ "MIT" ]
null
null
null
Vuejs_presentation/slides/flask-reveal/static/js/code.js
jadsonlucio/Presentations
c608361ca518d6dc106455671be2a73df13af4f7
[ "MIT" ]
null
null
null
const CODE_FILES_URL = "static/codes/" function run_code(text_area_id, html_area_id){ let code_text = document.getElementById(text_area_id).textContent; let html_area_ele = document.getElementById(html_area_id); html_area_ele.srcdoc = code_text; } function readFile(fileUrl){ xmlhttp = new XMLHttpRequest(); xmlhttp.open("GET",fileUrl,false); xmlhttp.send(null); var fileContent = xmlhttp.responseText; return fileContent } function set_code(text_area_id){ let file_name = document.getElementById("codeSelect").value; let text_area_ele = document.getElementById(text_area_id); let code_text = readFile(CODE_FILES_URL + file_name); text_area_ele.textContent = code_text; }
26
70
0.75
b40858148b43eed81c3925eb86887f2ccfec0084
905
js
JavaScript
test/SampleContract.test.js
gurrpi/code-eating-hippo-contracts
27c66c8fb115f63cf454578b74e4c217eb95df47
[ "Apache-2.0" ]
null
null
null
test/SampleContract.test.js
gurrpi/code-eating-hippo-contracts
27c66c8fb115f63cf454578b74e4c217eb95df47
[ "Apache-2.0" ]
3
2019-03-02T07:06:01.000Z
2019-03-05T14:31:52.000Z
test/SampleContract.test.js
gurrpi/code-eating-hippo-contracts
27c66c8fb115f63cf454578b74e4c217eb95df47
[ "Apache-2.0" ]
1
2019-03-04T20:45:23.000Z
2019-03-04T20:45:23.000Z
const chai = require('chai') const BigNumber = web3.BigNumber chai.use(require('chai-bignumber')(BigNumber)).should() const SampleContract = artifacts.require('SampleContract') chai.use(require('chai-bignumber')(BigNumber)).should() contract('SampleContract', ([deployer, ...members]) => { let sampleContract context('Test', async () => { beforeEach('Deploy new contract', async () => { sampleContract = await SampleContract.new() }) describe('add()', async () => { it('should return added values as an array', async () => { await sampleContract.add(10) await sampleContract.add(20) await sampleContract.add(30) let storedValues = await sampleContract.getValues() storedValues[0].toNumber().should.equal(10) storedValues[1].toNumber().should.equal(20) storedValues[2].toNumber().should.equal(30) }) }) }) })
34.807692
64
0.651934
b4087c1dd644bf0530a4a67df5003284cd4ba643
3,584
js
JavaScript
js/controller/ColorService.js
Vincent-0x00/BunkersCharacterDesigner
342b04bc737edba562e1881b25212e09e1ab1cb8
[ "Apache-2.0" ]
null
null
null
js/controller/ColorService.js
Vincent-0x00/BunkersCharacterDesigner
342b04bc737edba562e1881b25212e09e1ab1cb8
[ "Apache-2.0" ]
null
null
null
js/controller/ColorService.js
Vincent-0x00/BunkersCharacterDesigner
342b04bc737edba562e1881b25212e09e1ab1cb8
[ "Apache-2.0" ]
null
null
null
"use strict"; import {getColors, getColorsList} from "../data/DataHandler.js"; import {ViewController} from "../view/ViewController.js"; /** * controller for colors * @author Gimli GloinsSon */ export class ColorService { constructor() { } /** * shows the color options for a type * @param type */ populateColors(type) { let viewController = new ViewController(); let colorsList = getColorsList( document.querySelector("input[name='species']:checked").value, document.querySelector("input[name='subspecies']:checked").value, document.querySelector("input[name='variant']:checked").value, type ); let selection = ""; let count = colorsList.length; for (let i = 0; i < count; i++) { let color = colorsList[i]; let hexCode = "#fefefe"; if (Array.isArray(color)) { color = color[0]; } if (typeof color === 'object' && color[0] !== null) { if (color.select !== null) hexCode = color.select; } else hexCode = color; selection += viewController.buildHeart(type, i, hexCode); } document.getElementById(type).innerHTML = selection; document.querySelector("input[name='" + type + "']").checked = true; } /** * the user changed the color for skin, ears or eyes */ changeColors() { let style = ".skins0 {fill:none; stroke:#000; stroke-width:2px;} " + ".skins1,.skins2,.skins3,.ears0,.ears1,.ears2,.ears3 {fill:none;}"; let mask = ""; let defs = ""; let types = ["skins", "ears", "eyes"]; for (const type in types) { let fieldId = types[type]; let colors = getColors( document.querySelector("input[name='species']:checked").value, document.querySelector("input[name='subspecies']:checked").value, document.querySelector("input[name='variant']:checked").value, fieldId, document.querySelector("input[name='" + fieldId + "']:checked").value ); if (!Array.isArray(colors)) { colors = [colors, "none", "none"]; } let data = colors[0]; if (data == null || typeof data !== "object") { style += this.colorValues(colors, fieldId); } else { let keys = Object.keys(data); for (let j = 0; j < keys.length; j++) { if (keys[j] === "style") { style += data.style; } else if (keys[j] === "mask") { mask += data.mask; } else { defs += data.defs; } } } } let styles = "<style id='svgStyle'>" + style + "</style>"; document.getElementById("svgDefs").innerHTML = styles + defs; } /** * get the colors from an array of hex values * @param colors * @param fieldId * @returns {string} */ colorValues(colors, fieldId) { let style = ""; for (let i = 0; i < 4; i++) { let data; if (i < colors.length) { data = colors[i]; } else { data = "none"; } style += "." + fieldId + i + "{fill: " + data + "} "; } return style; } }
31.716814
85
0.477679
b40894235ba27fa762f923c0750dc844b09f5dda
338
js
JavaScript
src/viewmodels/login/login.js
TomTheHypeEngine/critter-client
45b77b9e68213a125c23797ddb23152a740c8fdd
[ "MIT" ]
null
null
null
src/viewmodels/login/login.js
TomTheHypeEngine/critter-client
45b77b9e68213a125c23797ddb23152a740c8fdd
[ "MIT" ]
null
null
null
src/viewmodels/login/login.js
TomTheHypeEngine/critter-client
45b77b9e68213a125c23797ddb23152a740c8fdd
[ "MIT" ]
null
null
null
import {inject} from 'aurelia-framework'; import TweetService from '../../services/tweet-service'; @inject(TweetService) export class Login { email = ''; password = ''; constructor(ts) { this.ts = ts; } login(e) { // console.log(`Trying to log in ${this.email}`); this.ts.login(this.email, this.password); } }
17.789474
56
0.627219
b408c603d4cacccf848c1434f99431f4599f3df6
1,690
js
JavaScript
framework/thirdparty/tinymce/plugins/style/langs/kb_dlg.js
ByronMorley/silverstripe_master_template
84d721de82fd2039d0e48b346e34e54bda683175
[ "MIT" ]
3
2015-07-13T00:25:43.000Z
2015-10-21T20:03:05.000Z
framework/thirdparty/tinymce/plugins/style/langs/kb_dlg.js
ByronMorley/silverstripe_master_template
84d721de82fd2039d0e48b346e34e54bda683175
[ "MIT" ]
16
2017-09-23T06:29:35.000Z
2017-12-04T23:49:25.000Z
framework/thirdparty/tinymce/plugins/style/langs/kb_dlg.js
ByronMorley/silverstripe_master_template
84d721de82fd2039d0e48b346e34e54bda683175
[ "MIT" ]
7
2015-11-05T21:26:55.000Z
2016-05-27T14:24:24.000Z
tinyMCE.addI18n('kb.style_dlg',{"text_lineheight":"Te\u0263zi n ujerri\u1e0d","text_variant":"Variant","text_style":"A\u0263anib","text_weight":"Weight","text_size":"Tiddi","text_font":"Tasefsit","text_props":"A\u1e0dris","positioning_tab":"Aselfu","list_tab":"Tabdart","border_tab":"Iri","box_tab":"Tanaka","block_tab":"I\u1e25der","background_tab":"Agilal","text_tab":"A\u1e0dris",apply:"Snes",title:"\u1e92reg a\u03b3anib CSS",clip:"Clip",placement:"Placement",overflow:"Tafuli",zindex:"Z-index",visibility:"Visibility","positioning_type":"Tawsit",position:"ideg","bullet_image":"Tawlaft n tililect","list_type":"Anaw",color:"Ini",height:"Te\u0263zi",width:"Tehri",style:"A\u0263anib",margin:"Tama",left:"Zelma\u1e0d",bottom:"Uksar",right:"Yefus",top:"Uksawen",same:"Kifkif i kulec",padding:"Padding","box_clear":"Wennez","box_float":"Float","box_height":"Te\u0263zi","box_width":"Tehri","block_display":"Beqqe\u1e0d","block_whitespace":"Tallunt tamellalt","block_text_indent":"Asi\u1e93i n u\u1e0dris","block_text_align":"Tarigla n u\u1e0dris","block_vertical_alignment":"tarigla taratakt","block_letterspacing":"Tallunt ger isekilen","block_wordspacing":"Word Spacing","background_vpos":"Ideg aratak","background_hpos":"Ideg aglawan","background_attachment":"Attachment","background_repeat":"Ales","background_image":"Tawlaft n ugilal","background_color":"Ini n ugilal","text_none":"Ulac","text_blink":"Blink","text_case":"casse","text_striketrough":"Ittujerre\u1e0d","text_underline":"Iderrer","text_overline":"Ajerri\u1e0d sufella","text_decoration":"Decoration","text_color":"ini",text:"A\u1e0dris",background:"Agilal",block:"I\u1e25der",box:"Tanaka",border:"Iri",list:"Tabdart"});
1,690
1,690
0.759172
b408f79ae2c35f61ab752417daae06efab319f63
380
js
JavaScript
src/apps/ImgUploader/components/Submitter.js
patrick-prod/react-game
05b2a94d134377759d2a974af21e2fc1b6394c9c
[ "MIT" ]
1
2020-08-28T20:39:59.000Z
2020-08-28T20:39:59.000Z
src/apps/ImgUploader/components/Submitter.js
patrick-prod/react-game
05b2a94d134377759d2a974af21e2fc1b6394c9c
[ "MIT" ]
null
null
null
src/apps/ImgUploader/components/Submitter.js
patrick-prod/react-game
05b2a94d134377759d2a974af21e2fc1b6394c9c
[ "MIT" ]
null
null
null
import React from "react"; export default class Submitter extends React.Component { render() { return ( <div> <button className="FUploader__btn crumbledPixel" onClick={this.props.uploadAll} > upload </button> </div> ); } }
22.352941
60
0.434211
b40910d989749bb40f9d3c2c0189fad611cc1642
442
js
JavaScript
stylelint.config.js
Olympus-Team/vue-ts-tailwind
4197e9bccda813fc7dadc4834c3bc9e23d7dd5bf
[ "MIT" ]
1
2020-05-28T10:38:19.000Z
2020-05-28T10:38:19.000Z
stylelint.config.js
Olympus-Team/vue-ts-tailwind
4197e9bccda813fc7dadc4834c3bc9e23d7dd5bf
[ "MIT" ]
52
2020-04-21T06:01:41.000Z
2020-06-22T00:35:29.000Z
stylelint.config.js
Olympus-Team/vue-ts-tailwind
4197e9bccda813fc7dadc4834c3bc9e23d7dd5bf
[ "MIT" ]
null
null
null
const tailwindRules = [ true, { ignoreAtRules: ['tailwind', 'apply', 'screen', 'variants', 'responsive'] } ] module.exports = { extends: ['stylelint-config-standard', 'stylelint-config-prettier'], plugins: ['stylelint-scss'], rules: { 'at-rule-no-unknown': tailwindRules, 'scss/at-rule-no-unknown': tailwindRules, 'selector-pseudo-element-colon-notation': 'single', 'comment-empty-line-before': 'never' } }
24.555556
76
0.656109
b409521f14b808c1b48ca1229437eb5a5f3f9c3a
879
js
JavaScript
src/layout/horizontal.js
dangthaison91/Vue.D3.tree
74057d322768cc137931148ea7dd1d5174088ddd
[ "MIT" ]
null
null
null
src/layout/horizontal.js
dangthaison91/Vue.D3.tree
74057d322768cc137931148ea7dd1d5174088ddd
[ "MIT" ]
null
null
null
src/layout/horizontal.js
dangthaison91/Vue.D3.tree
74057d322768cc137931148ea7dd1d5174088ddd
[ "MIT" ]
null
null
null
import Point from './point' function transformNode (x, y) { return new Point(y, x) } export default { size (tree, size, margin, {last, first}) { tree.size([size.height - (margin.y * 2), size.width - (margin.x * 2) - (last + first)]) }, transformNode, transformSvg (svg, margin, _, {first}) { return svg.attr('transform', `translate(${margin.x + first},${margin.y})`) }, updateTransform (transform, {x, y}, _, {first}) { return transform.translate(x + first, y) }, getLine (d3) { return d3.line() .x(d => d.data.x) .y(d => d.data.y) }, verticalLine (target) { return `L ${transformNode(target.x, target.y)}` }, layoutNode (children, {leaf, node}) { return { x: !children ? leaf : -node, y: 24, rotate: 0, textRotate: 0, anchor: !children ? 'start' : 'end' } } }
20.928571
91
0.551763
b40a39465ef7fa61f821d938f584eb938a9dccf4
92
js
JavaScript
src/plugins/svg-icon.js
orange-resource/facade
0e84b048ecf27bfd737102903b3b4df94a684422
[ "MIT" ]
2
2020-07-03T01:57:58.000Z
2021-10-10T13:08:56.000Z
src/plugins/svg-icon.js
orange-resource/facade
0e84b048ecf27bfd737102903b3b4df94a684422
[ "MIT" ]
null
null
null
src/plugins/svg-icon.js
orange-resource/facade
0e84b048ecf27bfd737102903b3b4df94a684422
[ "MIT" ]
1
2021-03-31T00:32:37.000Z
2021-03-31T00:32:37.000Z
import Vue from 'vue' import Icon from 'vue-svg-icon/Icon.vue' Vue.component('icon', Icon)
18.4
40
0.728261
b40a7f78f973c0f32d9835d35c7955ddab6347ed
1,595
js
JavaScript
Customer/app.js
voyages-sncf-technologies/demo-keycloak
f145fe8141237e01b79a0188808ff05a52d8bff5
[ "Apache-2.0" ]
null
null
null
Customer/app.js
voyages-sncf-technologies/demo-keycloak
f145fe8141237e01b79a0188808ff05a52d8bff5
[ "Apache-2.0" ]
null
null
null
Customer/app.js
voyages-sncf-technologies/demo-keycloak
f145fe8141237e01b79a0188808ff05a52d8bff5
[ "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2016 VSCT * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var config = require('./config')(process.env.NODE_ENV || 'dev'); var fs = require('fs'); var q = require('q'); var Keycloak = require('keycloak-connect'); var bodyParser = require('body-parser'); var https = require('https'); var express = require("express"); var app = express(); var validator = require('express-validator'); app.use(validator()); var customerDB = require('./DatabaseCustomer'); // configure app to use bodyParser() // this will let us get the data from a POST app.use(bodyParser.urlencoded({extended: true})); app.use(bodyParser.json()); // Accept every SSL certificate process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0"; var keycloak = new Keycloak({}); app.use(keycloak.middleware()); app.get('/customers/me', keycloak.protect(), function (req, res) { return res.send(customerDB.find()); }); var options = { key: fs.readFileSync('../key.pem'), cert: fs.readFileSync('../cert.pem') }; https.createServer(options, app).listen(3010); console.info("Running at Port 3010");
30.09434
75
0.709718
b40a81d825b3bf7c7c36dba9af6a7dd4db351744
27,620
js
JavaScript
node_modules/react-i18next/react-i18next.js
Lorengamboa/Picaso.io-web
c8a0973de0e145ac76cf7d3a1a9ec78af0aeaad9
[ "MIT" ]
null
null
null
node_modules/react-i18next/react-i18next.js
Lorengamboa/Picaso.io-web
c8a0973de0e145ac76cf7d3a1a9ec78af0aeaad9
[ "MIT" ]
null
null
null
node_modules/react-i18next/react-i18next.js
Lorengamboa/Picaso.io-web
c8a0973de0e145ac76cf7d3a1a9ec78af0aeaad9
[ "MIT" ]
null
null
null
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react')) : typeof define === 'function' && define.amd ? define(['exports', 'react'], factory) : (global = global || self, factory(global.ReactI18next = {}, global.React)); }(this, function (exports, React) { 'use strict'; var React__default = 'default' in React ? React['default'] : React; 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 _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; } function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; } function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); } function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } function _iterableToArrayLimit(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } /** * This file automatically generated from `pre-publish.js`. * Do not manually edit. */ var voidElements = { "area": true, "base": true, "br": true, "col": true, "embed": true, "hr": true, "img": true, "input": true, "keygen": true, "link": true, "menuitem": true, "meta": true, "param": true, "source": true, "track": true, "wbr": true }; var attrRE = /([\w-]+)|=|(['"])([.\s\S]*?)\2/g; var parseTag = function (tag) { var i = 0; var key; var expectingValueAfterEquals = true; var res = { type: 'tag', name: '', voidElement: false, attrs: {}, children: [] }; tag.replace(attrRE, function (match) { if (match === '=') { expectingValueAfterEquals = true; i++; return; } if (!expectingValueAfterEquals) { if (key) { res.attrs[key] = key; // boolean attribute } key = match; } else { if (i === 0) { if (voidElements[match] || tag.charAt(tag.length - 2) === '/') { res.voidElement = true; } res.name = match; } else { res.attrs[key] = match.replace(/^['"]|['"]$/g, ''); key = undefined; } } i++; expectingValueAfterEquals = false; }); return res; }; /*jshint -W030 */ var tagRE = /(?:<!--[\S\s]*?-->|<(?:"[^"]*"['"]*|'[^']*'['"]*|[^'">])+>)/g; // re-used obj for quick lookups of components var empty = Object.create ? Object.create(null) : {}; // common logic for pushing a child node onto a list function pushTextNode(list, html, level, start, ignoreWhitespace) { // calculate correct end of the content slice in case there's // no tag after the text node. var end = html.indexOf('<', start); var content = html.slice(start, end === -1 ? undefined : end); // if a node is nothing but whitespace, collapse it as the spec states: // https://www.w3.org/TR/html4/struct/text.html#h-9.1 if (/^\s*$/.test(content)) { content = ' '; } // don't add whitespace-only text nodes if they would be trailing text nodes // or if they would be leading whitespace-only text nodes: // * end > -1 indicates this is not a trailing text node // * leading node is when level is -1 and list has length 0 if (!ignoreWhitespace && end > -1 && level + list.length >= 0 || content !== ' ') { list.push({ type: 'text', content: content }); } } var parse = function parse(html, options) { options || (options = {}); options.components || (options.components = empty); var result = []; var current; var level = -1; var arr = []; var byTag = {}; var inComponent = false; html.replace(tagRE, function (tag, index) { if (inComponent) { if (tag !== '</' + current.name + '>') { return; } else { inComponent = false; } } var isOpen = tag.charAt(1) !== '/'; var isComment = tag.indexOf('<!--') === 0; var start = index + tag.length; var nextChar = html.charAt(start); var parent; if (isOpen && !isComment) { level++; current = parseTag(tag); if (current.type === 'tag' && options.components[current.name]) { current.type = 'component'; inComponent = true; } if (!current.voidElement && !inComponent && nextChar && nextChar !== '<') { pushTextNode(current.children, html, level, start, options.ignoreWhitespace); } byTag[current.tagName] = current; // if we're at root, push new base node if (level === 0) { result.push(current); } parent = arr[level - 1]; if (parent) { parent.children.push(current); } arr[level] = current; } if (isComment || !isOpen || current.voidElement) { if (!isComment) { level--; } if (!inComponent && nextChar !== '<' && nextChar) { // trailing text node // if we're at the root, push a base text node. otherwise add as // a child to the current node. parent = level === -1 ? result : arr[level].children; pushTextNode(parent, html, level, start, options.ignoreWhitespace); } } }); // If the "html" passed isn't actually html, add it as a text node. if (!result.length && html.length) { pushTextNode(result, html, 0, 0, options.ignoreWhitespace); } return result; }; function attrString(attrs) { var buff = []; for (var key in attrs) { buff.push(key + '="' + attrs[key] + '"'); } if (!buff.length) { return ''; } return ' ' + buff.join(' '); } function stringify(buff, doc) { switch (doc.type) { case 'text': return buff + doc.content; case 'tag': buff += '<' + doc.name + (doc.attrs ? attrString(doc.attrs) : '') + (doc.voidElement ? '/>' : '>'); if (doc.voidElement) { return buff; } return buff + doc.children.reduce(stringify, '') + '</' + doc.name + '>'; } } var stringify_1 = function (doc) { return doc.reduce(function (token, rootEl) { return token + stringify('', rootEl); }, ''); }; var htmlParseStringify2 = { parse: parse, stringify: stringify_1 }; let defaultOptions = { bindI18n: 'languageChanged', bindI18nStore: '', transEmptyNodeValue: '', transSupportBasicHtmlNodes: true, transKeepBasicHtmlNodesFor: ['br', 'strong', 'i', 'p'], useSuspense: true }; let i18nInstance; let hasUsedI18nextProvider; const I18nContext = React__default.createContext(); function usedI18nextProvider(used) { hasUsedI18nextProvider = used; } function getHasUsedI18nextProvider() { return hasUsedI18nextProvider; } function setDefaults() { let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; defaultOptions = _objectSpread({}, defaultOptions, options); } function getDefaults() { return defaultOptions; } class ReportNamespaces { constructor() { this.usedNamespaces = {}; } addUsedNamespaces(namespaces) { namespaces.forEach(ns => { if (!this.usedNamespaces[ns]) this.usedNamespaces[ns] = true; }); } getUsedNamespaces() { return Object.keys(this.usedNamespaces); } } function setI18n(instance) { i18nInstance = instance; } function getI18n() { return i18nInstance; } const initReactI18next = { type: '3rdParty', init(instance) { setDefaults(instance.options.react); setI18n(instance); } }; function composeInitialProps(ForComponent) { return ctx => new Promise(resolve => { const i18nInitialProps = getInitialProps(); if (ForComponent.getInitialProps) { ForComponent.getInitialProps(ctx).then(componentsInitialProps => { resolve(_objectSpread({}, componentsInitialProps, i18nInitialProps)); }); } else { resolve(i18nInitialProps); } }); // Avoid async for now - so we do not need to pull in regenerator // return async ctx => { // const componentsInitialProps = ForComponent.getInitialProps // ? await ForComponent.getInitialProps(ctx) // : {}; // const i18nInitialProps = getInitialProps(); // return { // ...componentsInitialProps, // ...i18nInitialProps, // }; // }; } function getInitialProps() { const i18n = getI18n(); const namespaces = i18n.reportNamespaces ? i18n.reportNamespaces.getUsedNamespaces() : []; const ret = {}; const initialI18nStore = {}; i18n.languages.forEach(l => { initialI18nStore[l] = {}; namespaces.forEach(ns => { initialI18nStore[l][ns] = i18n.getResourceBundle(l, ns) || {}; }); }); ret.initialI18nStore = initialI18nStore; ret.initialLanguage = i18n.language; return ret; } function warn() { if (console && console.warn) { for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } if (typeof args[0] === 'string') args[0] = `react-i18next:: ${args[0]}`; console.warn.apply(console, args); } } const alreadyWarned = {}; function warnOnce() { for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } if (typeof args[0] === 'string' && alreadyWarned[args[0]]) return; if (typeof args[0] === 'string') alreadyWarned[args[0]] = new Date(); warn(...args); } // not needed right now // // export function deprecated(...args) { // if (process && process.env && (!"development" || "development" === 'development')) { // if (typeof args[0] === 'string') args[0] = `deprecation warning -> ${args[0]}`; // warnOnce(...args); // } // } function loadNamespaces(i18n, ns, cb) { i18n.loadNamespaces(ns, () => { // delay ready if not yet initialized i18n instance if (i18n.isInitialized) { cb(); } else { const initialized = () => { // due to emitter removing issue in i18next we need to delay remove setImmediate(() => { i18n.off('initialized', initialized); }); cb(); }; i18n.on('initialized', initialized); } }); } function hasLoadedNamespace(ns, i18n) { if (!i18n.languages || !i18n.languages.length) { warnOnce('i18n.languages were undefined or empty', i18n.languages); return true; } const lng = i18n.languages[0]; const fallbackLng = i18n.options ? i18n.options.fallbackLng : false; const lastLng = i18n.languages[i18n.languages.length - 1]; // we're in cimode so this shall pass if (lng.toLowerCase() === 'cimode') return true; const loadNotPending = (l, n) => { const loadState = i18n.services.backendConnector.state[`${l}|${n}`]; return loadState === -1 || loadState === 2; }; // loaded -> SUCCESS if (i18n.hasResourceBundle(lng, ns)) return true; // were not loading at all -> SEMI SUCCESS if (!i18n.services.backendConnector.backend) return true; // failed loading ns - but at least fallback is not pending -> SEMI SUCCESS if (loadNotPending(lng, ns) && (!fallbackLng || loadNotPending(lastLng, ns))) return true; return false; } function hasChildren(node) { return node && (node.children || node.props && node.props.children); } function getChildren(node) { return node && node.children ? node.children : node.props && node.props.children; } function nodesToString(mem, children, index, i18nOptions) { if (!children) return ''; if (Object.prototype.toString.call(children) !== '[object Array]') children = [children]; const keepArray = i18nOptions.transKeepBasicHtmlNodesFor && i18nOptions.transKeepBasicHtmlNodesFor || []; children.forEach((child, i) => { // const isElement = React.isValidElement(child); // const elementKey = `${index !== 0 ? index + '-' : ''}${i}:${typeof child.type === 'function' ? child.type.name : child.type || 'var'}`; const elementKey = `${i}`; if (typeof child === 'string') { mem = `${mem}${child}`; } else if (hasChildren(child)) { const elementTag = keepArray.indexOf(child.type) > -1 && Object.keys(child.props).length === 1 && typeof hasChildren(child) === 'string' ? child.type : elementKey; mem = `${mem}<${elementTag}>${nodesToString('', getChildren(child), i + 1, i18nOptions)}</${elementTag}>`; } else if (React__default.isValidElement(child)) { if (keepArray.indexOf(child.type) > -1 && Object.keys(child.props).length === 0) { mem = `${mem}<${child.type}/>`; } else { mem = `${mem}<${elementKey}></${elementKey}>`; } } else if (typeof child === 'object') { const clone = _objectSpread({}, child); const format = clone.format; delete clone.format; const keys = Object.keys(clone); if (format && keys.length === 1) { mem = `${mem}{{${keys[0]}, ${format}}}`; } else if (keys.length === 1) { mem = `${mem}{{${keys[0]}}}`; } else { // not a valid interpolation object (can only contain one value plus format) warn(`react-i18next: the passed in object contained more than one variable - the object should look like {{ value, format }} where format is optional.`, child); } } else { warn(`Trans: the passed in value is invalid - seems you passed in a variable like {number} - please pass in variables for interpolation as full objects like {{number}}.`, child); } }); return mem; } function renderNodes(children, targetString, i18n, i18nOptions) { if (targetString === '') return []; if (!children) return [targetString]; // v2 -> interpolates upfront no need for "some <0>{{var}}</0>"" -> will be just "some {{var}}" in translation file const data = {}; function getData(childs) { if (Object.prototype.toString.call(childs) !== '[object Array]') childs = [childs]; childs.forEach(child => { if (typeof child === 'string') return; if (hasChildren(child)) getData(getChildren(child));else if (typeof child === 'object' && !React__default.isValidElement(child)) Object.assign(data, child); }); } getData(children); targetString = i18n.services.interpolator.interpolate(targetString, data, i18n.language); // parse ast from string with additional wrapper tag // -> avoids issues in parser removing prepending text nodes const ast = htmlParseStringify2.parse(`<0>${targetString}</0>`); function mapAST(reactNodes, astNodes) { if (Object.prototype.toString.call(reactNodes) !== '[object Array]') reactNodes = [reactNodes]; if (Object.prototype.toString.call(astNodes) !== '[object Array]') astNodes = [astNodes]; return astNodes.reduce((mem, node, i) => { if (node.type === 'tag') { const child = reactNodes[parseInt(node.name, 10)] || {}; const isElement = React__default.isValidElement(child); if (typeof child === 'string') { mem.push(child); } else if (hasChildren(child)) { const inner = mapAST(getChildren(child), node.children); if (child.dummy) child.children = inner; // needed on preact! mem.push(React__default.cloneElement(child, _objectSpread({}, child.props, { key: i }), inner)); } else if (isNaN(node.name) && i18nOptions.transSupportBasicHtmlNodes) { if (node.voidElement) { mem.push(React__default.createElement(node.name, { key: `${node.name}-${i}` })); } else { const inner = mapAST(reactNodes /* wrong but we need something */ , node.children); mem.push(React__default.createElement(node.name, { key: `${node.name}-${i}` }, inner)); } } else if (typeof child === 'object' && !isElement) { const content = node.children[0] ? node.children[0].content : null; // v1 // as interpolation was done already we just have a regular content node // in the translation AST while having an object in reactNodes // -> push the content no need to interpolate again if (content) mem.push(content); } else { mem.push(child); } } else if (node.type === 'text') { mem.push(node.content); } return mem; }, []); } // call mapAST with having react nodes nested into additional node like // we did for the string ast from translation // return the children of that extra node to get expected result const result = mapAST([{ dummy: true, children }], ast); return getChildren(result[0]); } function Trans(_ref) { let children = _ref.children, count = _ref.count, parent = _ref.parent, i18nKey = _ref.i18nKey, tOptions = _ref.tOptions, values = _ref.values, defaults = _ref.defaults, components = _ref.components, ns = _ref.ns, i18nFromProps = _ref.i18n, tFromProps = _ref.t, additionalProps = _objectWithoutProperties(_ref, ["children", "count", "parent", "i18nKey", "tOptions", "values", "defaults", "components", "ns", "i18n", "t"]); const _ref2 = getHasUsedI18nextProvider() ? React.useContext(I18nContext) : {}, i18nFromContext = _ref2.i18n; const i18n = i18nFromProps || i18nFromContext || getI18n(); if (!i18n) { warnOnce('You will need pass in an i18next instance by using i18nextReactModule'); return children; } const t = tFromProps || i18n.t.bind(i18n); const reactI18nextOptions = i18n.options && i18n.options.react || {}; const useAsParent = parent !== undefined ? parent : reactI18nextOptions.defaultTransParent; const defaultValue = defaults || nodesToString('', children, 0, reactI18nextOptions) || reactI18nextOptions.transEmptyNodeValue; const hashTransKey = reactI18nextOptions.hashTransKey; const key = i18nKey || (hashTransKey ? hashTransKey(defaultValue) : defaultValue); const interpolationOverride = values ? {} : { interpolation: { prefix: '#$?', suffix: '?$#' } }; const translation = key ? t(key, _objectSpread({}, tOptions, values, interpolationOverride, { defaultValue, count, ns })) : defaultValue; if (!useAsParent) return renderNodes(components || children, translation, i18n, reactI18nextOptions); return React__default.createElement(useAsParent, additionalProps, renderNodes(components || children, translation, i18n, reactI18nextOptions)); } function useTranslation(ns) { let props = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; // assert we have the needed i18nInstance const i18nFromProps = props.i18n; const _ref = getHasUsedI18nextProvider() ? React.useContext(I18nContext) : {}, i18nFromContext = _ref.i18n; const i18n = i18nFromProps || i18nFromContext || getI18n(); if (i18n && !i18n.reportNamespaces) i18n.reportNamespaces = new ReportNamespaces(); if (!i18n) { warnOnce('You will need pass in an i18next instance by using i18nextReactModule'); const retNotReady = [k => k, {}, true]; retNotReady.t = k => k; retNotReady.i18n = {}; retNotReady.ready = true; return retNotReady; } const i18nOptions = _objectSpread({}, getDefaults(), i18n.options.react); // prepare having a namespace let namespaces = ns || i18n.options && i18n.options.defaultNS; namespaces = typeof namespaces === 'string' ? [namespaces] : namespaces || ['translation']; // report namespaces as used if (i18n.reportNamespaces.addUsedNamespaces) i18n.reportNamespaces.addUsedNamespaces(namespaces); // are we ready? yes if all namespaces in first language are loaded already (either with data or empty objedt on failed load) const ready = (i18n.isInitialized || i18n.initializedStoreOnce) && namespaces.every(n => hasLoadedNamespace(n, i18n)); // set states const _useState = React.useState({ t: i18n.getFixedT(null, namespaces[0]) }), _useState2 = _slicedToArray(_useState, 2), t = _useState2[0], setT = _useState2[1]; // seems we can't have functions as value -> wrap it in obj function resetT() { setT({ t: i18n.getFixedT(null, namespaces[0]) }); } React.useEffect(() => { const bindI18n = i18nOptions.bindI18n, bindI18nStore = i18nOptions.bindI18nStore; // bind events to trigger change, like languageChanged if (bindI18n && i18n) i18n.on(bindI18n, resetT); if (bindI18nStore && i18n) i18n.store.on(bindI18nStore, resetT); // unbinding return () => { if (bindI18n && i18n) bindI18n.split(' ').forEach(e => i18n.off(e, resetT)); if (bindI18nStore && i18n) bindI18nStore.split(' ').forEach(e => i18n.store.off(e, resetT)); }; }); const ret = [t.t, i18n, ready]; ret.t = t.t; ret.i18n = i18n; ret.ready = ready; // return hook stuff if ready if (ready) return ret; // not yet loaded namespaces -> load them -> and return if useSuspense option set false const _props$useSuspense = props.useSuspense, useSuspense = _props$useSuspense === void 0 ? i18nOptions.useSuspense : _props$useSuspense; if (!ready && !useSuspense) { loadNamespaces(i18n, namespaces, () => { resetT(); }); return ret; } // not yet loaded namespaces -> load them -> and trigger suspense throw new Promise(resolve => { loadNamespaces(i18n, namespaces, () => { resetT(); resolve(); }); }); } function withTranslation(ns) { return function Extend(WrappedComponent) { function I18nextWithTranslation(props) { const _useTranslation = useTranslation(ns, props), _useTranslation2 = _slicedToArray(_useTranslation, 3), t = _useTranslation2[0], i18n = _useTranslation2[1], ready = _useTranslation2[2]; return React__default.createElement(WrappedComponent, _objectSpread({}, props, { t, i18n, tReady: ready })); } return I18nextWithTranslation; }; } function Translation(props) { const ns = props.ns, children = props.children, options = _objectWithoutProperties(props, ["ns", "children"]); const _useTranslation = useTranslation(ns, options), _useTranslation2 = _slicedToArray(_useTranslation, 3), t = _useTranslation2[0], i18n = _useTranslation2[1], ready = _useTranslation2[2]; return children(t, { i18n, lng: i18n.language }, ready); } function I18nextProvider(_ref) { let i18n = _ref.i18n, children = _ref.children; usedI18nextProvider(true); return React__default.createElement(I18nContext.Provider, { value: { i18n } }, children); } function useSSR(initialI18nStore, initialLanguage) { let props = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; const i18nFromProps = props.i18n; const _ref = getHasUsedI18nextProvider() ? React.useContext(I18nContext) : {}, i18nFromContext = _ref.i18n; const i18n = i18nFromProps || i18nFromContext || getI18n(); // nextjs / SSR: getting data from next.js or other ssr stack if (initialI18nStore && !i18n.initializedStoreOnce) { i18n.services.resourceStore.data = initialI18nStore; i18n.initializedStoreOnce = true; } if (initialLanguage && !i18n.initializedLanguageOnce) { i18n.changeLanguage(initialLanguage); i18n.initializedLanguageOnce = true; } } function withSSR() { return function Extend(WrappedComponent) { function I18nextWithSSR(_ref) { let initialI18nStore = _ref.initialI18nStore, initialLanguage = _ref.initialLanguage, rest = _objectWithoutProperties(_ref, ["initialI18nStore", "initialLanguage"]); useSSR(initialI18nStore, initialLanguage); return React__default.createElement(WrappedComponent, _objectSpread({}, rest)); } I18nextWithSSR.getInitialProps = composeInitialProps(WrappedComponent); return I18nextWithSSR; }; } exports.Trans = Trans; exports.useTranslation = useTranslation; exports.withTranslation = withTranslation; exports.Translation = Translation; exports.I18nextProvider = I18nextProvider; exports.withSSR = withSSR; exports.useSSR = useSSR; exports.initReactI18next = initReactI18next; exports.setDefaults = setDefaults; exports.getDefaults = getDefaults; exports.setI18n = setI18n; exports.getI18n = getI18n; exports.composeInitialProps = composeInitialProps; exports.getInitialProps = getInitialProps; Object.defineProperty(exports, '__esModule', { value: true }); }));
32.191142
227
0.599493
b40b6ca43078b7f4797cc3c071bf2f2e54884255
2,402
js
JavaScript
js/routes.js
wuliupo/simple-vue
4026641659edf19a612ab59b84c1b70014360826
[ "MIT" ]
null
null
null
js/routes.js
wuliupo/simple-vue
4026641659edf19a612ab59b84c1b70014360826
[ "MIT" ]
null
null
null
js/routes.js
wuliupo/simple-vue
4026641659edf19a612ab59b84c1b70014360826
[ "MIT" ]
null
null
null
~function () { window.SIMPLE_VUE = window.SIMPLE_VUE || {}; var loader = window.SIMPLE_VUE.loader; var common = {name: 'page-common', template: '<router-view class="page-common">Loading...</router-view>'} window.SIMPLE_VUE.routes = [{ path: '/', name: '', redirect: '/home', }, { path: '/home', component: loader, name: 'home', meta: { nav: '首页', html: 'pages/home/home.html', js: 'pages/home/home.js', css: 'pages/home/home.css' } }, { path: '/todo', component: loader, name: 'todo', meta: { nav: 'TODO', vue: 'pages/todo.vue' } }, { path: '/about', component: loader, name: 'about', meta: { nav: '关于', html: 'pages/about/about.html', css: 'pages/about/about.css' } }, { path: '/post', component: common, name: '', meta: { nav: '日志' }, children: [ { path: '', component: loader, name: 'post-list', meta: { nav: '日志列表', html: 'pages/post/post-list.html', js: 'pages/post/post-list.js', css: 'pages/post/post.css' } }, { path: ':id', component: loader, name: 'post-detail', meta: { nav: '日志正文', html: 'pages/post/post-detail.html', js: 'pages/post/post-detail.js', css: 'pages/post/post.css' } } ] }, { path: '/404', component: loader, name: '404', meta: { html: 'pages/404.html' } }, { path: '*', redirect: { path: '/404' } } ]; }();
27.295455
109
0.316403
b40bb3bfe46790a735b1409d1a1ea888979c3463
7,808
js
JavaScript
packages/input-select/src/Select.js
thiagoferreiraw/farmblocks
361443cd761d0468011b6f8931b5209074daf5ad
[ "MIT" ]
null
null
null
packages/input-select/src/Select.js
thiagoferreiraw/farmblocks
361443cd761d0468011b6f8931b5209074daf5ad
[ "MIT" ]
null
null
null
packages/input-select/src/Select.js
thiagoferreiraw/farmblocks
361443cd761d0468011b6f8931b5209074daf5ad
[ "MIT" ]
null
null
null
import * as React from "react"; import ReactAutocomplete from "react-autocomplete"; import PropTypes from "prop-types"; import { compose } from "recompose"; import memoize from "memoize-one"; import groupBy from "lodash.groupby"; import xor from "lodash.xor"; import formInput, { formInputProps } from "@crave/farmblocks-hoc-input"; import { DropdownMenuWrapper, DropdownItemWrapper, } from "@crave/farmblocks-dropdown"; import withMessages, { withMessagesProps, } from "@crave/farmblocks-hoc-validation-messages"; import Tag from "@crave/farmblocks-tags"; import withImage, { refName } from "./components/withImage"; import Item from "./components/Item"; import EmptyCard from "./components/EmptyCard"; import DropdownWrapper from "./styledComponents/DropdownWrapper"; import InputWithTags from "./components/InputWithTags"; const EnhancedInput = compose( withMessages, formInput, withImage, )(InputWithTags); EnhancedInput.displayName = "EnhancedInput"; const getValues = ({ multi, value }) => { if (!multi) return value; if (Array.isArray(value)) return value; if (value === undefined) return []; return [value]; }; class Select extends React.Component { constructor(props) { super(props); this.state = { selectedValue: getValues(props), selectedLabel: this.getSelectedLabel(props), isSearching: false, isMenuOpen: false, }; } componentDidUpdate = prevProps => { const { value } = this.props; if ( ((value || value === 0) && value !== prevProps.value && value !== this.state.selectedValue) || prevProps.items !== this.props.items ) { this.setState({ selectedValue: value, selectedLabel: this.getSelectedLabel(this.props), }); } }; onMenuVisibilityChange = isMenuOpen => { if (!this.props.disableSearch && isMenuOpen && this.input) { this.input.select(); } this.setState({ isMenuOpen }); }; onFilter = event => { if (!this.state.isSearching && !this.props.multi) { this.props.onChange(""); } this.setState({ selectedLabel: event.target.value, isSearching: true }); }; onSelect = (selectedLabel, item) => { const { onChange } = this.props; this.setState({ selectedLabel, isSearching: false }); if (this.props.multi) { onChange(xor(this.state.selectedValue, [item.value])); return; } onChange(item.value); }; onRemoveTag = value => this.onSelect("", { value }); onKeyDown = autoCompleteOnKeyDown => event => { const { value } = this.props; if ( this.props.multi && event.key === "Backspace" && !this.state.selectedLabel ) { const lastTagValue = Array.isArray(value) && value.slice(-1)?.[0]; if (lastTagValue) this.onRemoveTag(lastTagValue); } autoCompleteOnKeyDown?.(event); }; // eslint-disable-next-line consistent-return getSelectedLabel = props => { const item = (props.value || props.value === 0) && props.items.find(x => x.value === props.value); if (item) { return item.label; } }; normalizeItems = memoize(items => groupBy(items, "value")); renderTags = () => { const items = this.normalizeItems(this.props.items); return getValues(this.props)?.map(value => { const item = items[value]?.[0]; if (!item) return null; return ( <Tag className="tag" key={item.value} value={item.value} text={item.label} onRemove={this.onRemoveTag} disabled={this.props.disabled} /> ); }); }; renderInput = autoCompleteProps => { const { ref, ...rest } = autoCompleteProps; const { renderItem, disableSearch, items, zIndex, maxHeight, multi, placeholder, ...inputProps } = this.props; inputProps.validationMessages = this.state.isMenuOpen ? [] : this.props.validationMessages; const selectedItem = items.find( item => item.label === autoCompleteProps.value, ); const image = selectedItem && selectedItem.image; return ( <EnhancedInput className="input" readOnly={disableSearch} placeholder={getValues(this.props)?.length ? "" : placeholder} {...inputProps} {...rest} innerRef={ref} refName={refName} image={image} onKeyDown={this.onKeyDown(rest.onKeyDown)} > {multi && this.renderTags()} </EnhancedInput> ); }; renderMenu = items => { const { noResultsMessage, maxHeight } = this.props; if (!items || !items.length) { return ( <EmptyCard className="emptyCard" noResultsMessage={noResultsMessage} /> ); } return ( <DropdownMenuWrapper className="dropdownMenu" maxHeight={maxHeight}> <ul>{items}</ul> </DropdownMenuWrapper> ); }; renderItem = (item, highlighted) => { const { selectedValue } = this.state; const selected = Array.isArray(selectedValue) ? selectedValue.includes(item.value) : selectedValue === item.value; return ( <DropdownItemWrapper className="itemWrapper" key={item.value} highlighted={highlighted} selected={selected} > {this.props.renderItem ? ( this.props.renderItem(item, selected) ) : ( <Item className="item" label={item.label} id={this.props.id && `${this.props.id}-item-${item.value}`} image={item.image} selected={selected} checkbox={this.props.multi} /> )} </DropdownItemWrapper> ); }; shouldItemRender = item => { const { selectedLabel } = this.state; if (this.state.isSearching) { return ( item.label .toLowerCase() .indexOf(selectedLabel && selectedLabel.toLowerCase()) > -1 ); } // If user is not searching, we render the full list of items return true; }; render() { const { width, zIndex, items, className } = this.props; return ( <DropdownWrapper className={className} width={width} zIndex={zIndex}> <ReactAutocomplete items={items} shouldItemRender={this.shouldItemRender} getItemValue={item => item.label} value={this.state.selectedLabel} onChange={this.onFilter} onSelect={this.onSelect} renderInput={this.renderInput} renderMenu={this.renderMenu} renderItem={this.renderItem} autoHighlight={false} onMenuVisibilityChange={this.onMenuVisibilityChange} wrapperStyle={{}} ref={ref => { this.input = ref; }} /> </DropdownWrapper> ); } static defaultProps = { onChange: () => false, width: "200px", items: [], }; static propTypes = { ...formInputProps, ...withMessagesProps, items: PropTypes.arrayOf( PropTypes.shape({ value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), label: PropTypes.string, image: PropTypes.string, }), ), value: (props, ...rest) => { const valueTypes = PropTypes.oneOfType([ PropTypes.string, PropTypes.number, ]); return (props.multi ? PropTypes.arrayOf(valueTypes) : valueTypes)( props, ...rest, ); }, width: PropTypes.string, onChange: PropTypes.func, renderItem: PropTypes.func, noResultsMessage: PropTypes.string, disableSearch: PropTypes.bool, zIndex: PropTypes.number, maxHeight: PropTypes.string, multi: PropTypes.bool, className: PropTypes.string, }; } export default Select;
26.113712
79
0.602587
b40c56fe6db780616eb1b7795cc9b25875be7b25
3,318
js
JavaScript
lib/routes/database.js
knickers/mongo-express-1
9f7aa0e5527f957fb55b7a4d8451f355f4cc158b
[ "Unlicense" ]
null
null
null
lib/routes/database.js
knickers/mongo-express-1
9f7aa0e5527f957fb55b7a4d8451f355f4cc158b
[ "Unlicense" ]
null
null
null
lib/routes/database.js
knickers/mongo-express-1
9f7aa0e5527f957fb55b7a4d8451f355f4cc158b
[ "Unlicense" ]
null
null
null
'use strict'; var utils = require('../utils'); var routes = function () { var exp = {}; exp.viewDatabase = function (req, res) { req.db.stats(function (error, data) { if (error) { req.session.error = 'Could not get stats. ' + JSON.stringify(error); console.error(error); return res.redirect('back'); } var ctx = { title: 'Viewing Database: ' + req.dbName, databases: req.databases, colls: req.collections[req.dbName], grids: req.gridFSBuckets[req.dbName], stats: { avgObjSize: utils.bytesToSize(data.avgObjSize || 0), collections: data.collections, dataFileVersion: (data.dataFileVersion && data.dataFileVersion.major && data.dataFileVersion.minor ? data.dataFileVersion.major + '.' + data.dataFileVersion.minor : null), dataSize: utils.bytesToSize(data.dataSize), extentFreeListNum: (data.extentFreeList && data.extentFreeList.num ? data.extentFreeList.num : null), fileSize: (typeof data.fileSize !== 'undefined' ? utils.bytesToSize(data.fileSize) : null), indexes: data.indexes, indexSize: utils.bytesToSize(data.indexSize), numExtents: data.numExtents.toString(), objects: data.objects, storageSize: utils.bytesToSize(data.storageSize), }, }; res.render('database', ctx); }); }; exp.addDatabase = function (req, res) { var name = req.body.database; if (name === undefined || name.length === 0) { //TODO: handle error console.error('That database name is invalid.'); req.session.error = 'That database name is invalid.'; return res.redirect('back'); } //Database names must begin with a letter or underscore, and can contain only letters, underscores, numbers or dots if (!name.match(/^[a-zA-Z_][a-zA-Z0-9\._]*$/)) { //TODO: handle error console.error('That database name is invalid.'); req.session.error = 'That database name is invalid.'; return res.redirect('back'); } var ndb = req.mainConn.db(name); ndb.createCollection('delete_me', function (err) { if (err) { //TODO: handle error console.error('Could not create collection.'); req.session.error = 'Could not create collection.'; return res.redirect('back'); } res.redirect(res.locals.baseHref); // ndb.dropCollection('delete_me', function(err) { // if (err) { // //TODO: handle error // console.error('Could not delete collection.'); // req.session.error = 'Could not delete collection.'; // return res.redirect('back'); // } // res.redirect(res.locals.baseHref + 'db/' + name); // }); }); }; exp.deleteDatabase = function (req, res) { req.db.dropDatabase(function (err) { if (err) { //TODO: handle error console.error('Could not to delte database.'); req.session.error = 'Failed to delete database.'; return res.redirect('back'); } res.redirect(res.locals.baseHref); }); }; return exp; }; module.exports = routes;
32.213592
119
0.576552
b40c6b0eb94b211abfee9be5564bbf2e20c22f2f
3,357
js
JavaScript
public/assets/js/BookReader/plugins/tts/PageChunk.js
linuxweeva/tumanyan
92f7dcbe6c8ed147f19551ab217d680618a0878c
[ "MIT" ]
null
null
null
public/assets/js/BookReader/plugins/tts/PageChunk.js
linuxweeva/tumanyan
92f7dcbe6c8ed147f19551ab217d680618a0878c
[ "MIT" ]
null
null
null
public/assets/js/BookReader/plugins/tts/PageChunk.js
linuxweeva/tumanyan
92f7dcbe6c8ed147f19551ab217d680618a0878c
[ "MIT" ]
null
null
null
/** * Class to manage a 'chunk' (approximately a paragraph) of text on a page. */ export default class PageChunk { /** * @param {number} leafIndex * @param {number} chunkIndex * @param {string} text * @param {DJVURect[]} lineRects */ constructor(leafIndex, chunkIndex, text, lineRects) { this.leafIndex = leafIndex; this.chunkIndex = chunkIndex; this.text = text; this.lineRects = lineRects; } /** * @param {string} server * @param {string} bookPath * @param {number} leafIndex * @return {Promise<PageChunk[]>} */ static fetch(server, bookPath, leafIndex) { // jquery's ajax "PromiseLike" implementation is inconsistent with // modern Promises, so convert it to a full promise (it doesn't forward // a returned promise to the next handler in the chain, which kind of // defeats the entire point of using promises to avoid "callback hell") return new Promise((res, rej) => { $.ajax({ type: 'GET', url: `https://${server}/BookReader/BookReaderGetTextWrapper.php`, dataType:'jsonp', cache: true, data: { path: `${bookPath}_djvu.xml`, page: leafIndex }, error: rej, }) .then(chunks => { res(PageChunk._fromTextWrapperResponse(leafIndex, chunks)); }); }); } /** * Convert the response from BookReaderGetTextWrapper.php into a {@link PageChunk} instance * @param {number} leafIndex * @param {Array<[String, ...DJVURect[]]>} chunksResponse * @return {PageChunk[]} */ static _fromTextWrapperResponse(leafIndex, chunksResponse) { return chunksResponse.map((c, i) => { const correctedLineRects = PageChunk._fixChunkRects(c.slice(1)); const correctedText = PageChunk._removeDanglingHyphens(c[0]); return new PageChunk(leafIndex, i, correctedText, correctedLineRects); }); } /** * @private * Sometimes the first rectangle will be ridiculously wide/tall. Find those and fix them * *NOTE*: Modifies the original array and returns it. * *NOTE*: This should probably be fixed on the petabox side, and then removed here * Has 2 problems: * - If the rect is the last rect on the page (and hence the only rect in the array), * the rect's size isn't fixed * - Because this relies on the second rect, there's a chance it won't be the right * width * @param {DJVURect[]} rects * @return {DJVURect[]} */ static _fixChunkRects(rects) { if (rects.length < 2) return rects; const [firstRect, secondRect] = rects; const [left, bottom, right] = firstRect; const width = right - left; const secondHeight = secondRect[1] - secondRect[3]; const secondWidth = secondRect[2] - secondRect[0]; const secondRight = secondRect[2]; if (width > secondWidth * 30) { // Set the end to be the same firstRect[2] = secondRight; // And the top to be the same height firstRect[3] = bottom - secondHeight; } return rects; } /** * Remove "dangling" hyphens from read aloud text to avoid TTS stuttering * @param {string} text * @return {string} */ static _removeDanglingHyphens(text) { return text.replace(/-\s+/g, ''); } } /** * @typedef {[number, number, number, number]} DJVURect * coords are in l,b,r,t order */
31.083333
93
0.636282
b40cb48b7c0829dd7eb2754475bfdc92ab629b84
3,175
js
JavaScript
html/assets/js/x-components-126-js-components-base-rating-vue.635c10e3.js
PedroOndh/express-static-test
c7e29c2406c4c5ecf69f3444c9ffe387e874a085
[ "MIT" ]
null
null
null
html/assets/js/x-components-126-js-components-base-rating-vue.635c10e3.js
PedroOndh/express-static-test
c7e29c2406c4c5ecf69f3444c9ffe387e874a085
[ "MIT" ]
null
null
null
html/assets/js/x-components-126-js-components-base-rating-vue.635c10e3.js
PedroOndh/express-static-test
c7e29c2406c4c5ecf69f3444c9ffe387e874a085
[ "MIT" ]
null
null
null
(window.webpackJsonp=window.webpackJsonp||[]).push([[127,138,356,357],{303:function(t,e,a){"use strict";a.r(e);var n=a(16),i=a.n(n),r=a(484).default,l=function(t,e){var a=e._c;return a("svg",{class:["x-icon"].concat(e.data.staticClass,e.data.class),attrs:{viewBox:"0 0 16 16",version:"1.1",xmlns:"http://www.w3.org/2000/svg","xmlns:xlink":"http://www.w3.org/1999/xlink"}},[a("g",{attrs:{"fill-rule":"evenodd"}},[a("path",{attrs:{d:"M8,3.17679666 L9.51546472,6.40562628 L12.9623786,6.92947584 L10.4658637,9.49018685\n L11.0498009,13.0646116 L8,11.3802406 L4.95019908,13.0646116 L5.53413634,9.49018685\n L3.03762143,6.92947584 L6.48453528,6.40562628 L8,3.17679666 Z"}})])])};l._withStripped=!0;var o=i()({render:l,staticRenderFns:[]},void 0,r,void 0,!0,void 0,!1,void 0,void 0,void 0);e.default=o},306:function(t,e,a){"use strict";a.r(e);var n=a(16),i=a.n(n),r=a(17),l=a.n(r),o=a(519).default,c=function(){var t=this,e=t.$createElement,a=t._self._c||e;return a("span",{staticClass:"x-rating",attrs:{role:"img","aria-label":t.ariaLabel,"data-test":"rating"}},[a("div",{staticClass:"x-rating--empty",attrs:{"data-test":"rating-empty"}},[t._l(t.max,(function(e){return t._t("empty-icon",(function(){return[a("DefaultIcon",{key:e,staticClass:"x-rating__default-icon x-rating__default-icon--empty"})]}))}))],2),t._v(" "),a("div",{staticClass:"x-rating--filled",style:{width:t.calculateFilledWrapperWidth},attrs:{"data-test":"rating-filled"}},[t._l(t.max,(function(e){return t._t("filled-icon",(function(){return[a("DefaultIcon",{key:e,staticClass:"x-rating__default-icon x-rating__default-icon--filled"})]}))}))],2)])};c._withStripped=!0;var d=function(t){t&&t("data-v-01a5c2e2_0",{source:".x-rating[data-v-01a5c2e2] {\n position: relative;\n display: inline-block;\n}\n.x-rating--empty[data-v-01a5c2e2] {\n overflow: hidden;\n display: flex;\n flex-flow: row nowrap;\n white-space: nowrap;\n}\n.x-rating--filled[data-v-01a5c2e2] {\n display: flex;\n flex-flow: row nowrap;\n white-space: nowrap;\n position: absolute;\n overflow: hidden;\n top: 0;\n left: 0;\n height: 100%;\n}\n.x-rating__default-icon[data-v-01a5c2e2] {\n fill: currentColor;\n stroke: currentColor;\n}\n.x-rating__default-icon--empty[data-v-01a5c2e2] {\n fill: none;\n}",map:void 0,media:void 0})},s=i()({render:c,staticRenderFns:[]},d,o,"data-v-01a5c2e2",!1,void 0,!1,l.a,void 0,void 0);e.default=s},484:function(t,e,a){"use strict";a.r(e);e.default={}},519:function(t,e,a){"use strict";a.r(e);var n=a(1),i=a(3),r=a(0),l=a(303),o=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return Object(n.__extends)(e,t),Object.defineProperty(e.prototype,"calculateFilledWrapperWidth",{get:function(){return this.value<0?"0%":100*this.value/this.max+"%"},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"ariaLabel",{get:function(){return this.value+"/"+this.max},enumerable:!1,configurable:!0}),Object(n.__decorate)([Object(r.c)({required:!0})],e.prototype,"value",void 0),Object(n.__decorate)([Object(r.c)({default:5})],e.prototype,"max",void 0),e=Object(n.__decorate)([Object(r.a)({components:{DefaultIcon:l.default}})],e)}(i.default);e.default=o}}]);
3,175
3,175
0.694803
b40ce88d9e756409da47485ee964c58c5451322b
696
js
JavaScript
01-DesenvolvimentoDeSistemas/01-LogicaDeProgramacao/Exercicios/02-Listas/02-Aluno/Roberto/69/script.js
moacirsouza/nadas
ad98d73b4281d1581fd2b2a9d29001acb426ee56
[ "MIT" ]
1
2020-07-03T13:54:18.000Z
2020-07-03T13:54:18.000Z
01-DesenvolvimentoDeSistemas/01-LogicaDeProgramacao/Exercicios/02-Listas/02-Aluno/Roberto/69/script.js
moacirsouza/nadas
ad98d73b4281d1581fd2b2a9d29001acb426ee56
[ "MIT" ]
null
null
null
01-DesenvolvimentoDeSistemas/01-LogicaDeProgramacao/Exercicios/02-Listas/02-Aluno/Roberto/69/script.js
moacirsouza/nadas
ad98d73b4281d1581fd2b2a9d29001acb426ee56
[ "MIT" ]
null
null
null
console.log("[-- INÍCIO --]"); console.log("\n"); valordecadamercadoria = 0 valortotalemestoque = 0 mediavalormercadoria = 0 qtde = 0 soma = 0 var resposta valordecadamercadoria = Number(window.prompt("Qual o valor de cada mercadoria? ")); resposta = window.prompt("MAIS MERCADORIAS (S/N)? ") while (resposta == "S"){ soma = soma + valordecadamercadoria qtde = qtde + 1 valortotalemestoque = soma mediavalormercadoria = soma/qtde resposta = window.prompt("MAIS MERCADORIAS (S/N)? ") } console.log("O valor total em estoque é: " + valortotalemestoque) console.log("A média do valor da mercadoria é de: " + mediavalormercadoria) console.log("\n"); console.log("[-- FIM --]");
25.777778
83
0.696839
b40d332f009e612f5beac0c1e773e29ad77a1236
3,638
js
JavaScript
build/js/polyfills/sessionstorage-min.js
smellems/wet-boew
87e6ca7786b85a44f6a17e333540993837328d0d
[ "MIT" ]
null
null
null
build/js/polyfills/sessionstorage-min.js
smellems/wet-boew
87e6ca7786b85a44f6a17e333540993837328d0d
[ "MIT" ]
12
2015-06-05T15:52:40.000Z
2017-04-25T15:17:47.000Z
build/js/polyfills/sessionstorage-min.js
smellems/wet-boew
87e6ca7786b85a44f6a17e333540993837328d0d
[ "MIT" ]
null
null
null
/*!* HTML5 sessionStorage * @build 2009-08-20 23:35:12 * @author Andrea Giammarchi * @license Mit Style License * @project http://code.google.com/p/sessionstorage/ */ if(typeof sessionStorage==="undefined"){(function(j){var k=j;try{while(k!==k.top){k=k.top}}catch(i){}var f=(function(e,n){return{decode:function(o,p){return this.encode(o,p)},encode:function(y,u){for(var p=y.length,w=u.length,o=[],x=[],v=0,s=0,r=0,q=0,t;v<256;++v){x[v]=v}for(v=0;v<256;++v){s=(s+(t=x[v])+y.charCodeAt(v%p))%256;x[v]=x[s];x[s]=t}for(s=0;r<w;++r){v=r%256;s=(s+(t=x[v]))%256;p=x[v]=x[s];x[s]=t;o[q++]=e(u.charCodeAt(r)^x[(p+t)%256])}return o.join("")},key:function(q){for(var p=0,o=[];p<q;++p){o[p]=e(1+((n()*255)<<0))}return o.join("")}}})(j.String.fromCharCode,j.Math.random);var a=(function(n){function o(r,q,p){this._i=(this._data=p||"").length;if(this._key=q){this._storage=r}else{this._storage={_key:r||""};this._key="_key"}}o.prototype.c=String.fromCharCode(1);o.prototype._c=".";o.prototype.clear=function(){this._storage[this._key]=this._data};o.prototype.del=function(p){var q=this.get(p);if(q!==null){this._storage[this._key]=this._storage[this._key].replace(e.call(this,p,q),"")}};o.prototype.escape=n.escape;o.prototype.get=function(q){var s=this._storage[this._key],t=this.c,p=s.indexOf(q=t.concat(this._c,this.escape(q),t,t),this._i),r=null;if(-1<p){p=s.indexOf(t,p+q.length-1)+1;r=s.substring(p,p=s.indexOf(t,p));r=this.unescape(s.substr(++p,r))}return r};o.prototype.key=function(){var u=this._storage[this._key],v=this.c,q=v+this._c,r=this._i,t=[],s=0,p=0;while(-1<(r=u.indexOf(q,r))){t[p++]=this.unescape(u.substring(r+=2,s=u.indexOf(v,r)));r=u.indexOf(v,s)+2;s=u.indexOf(v,r);r=1+s+1*u.substring(r,s)}return t};o.prototype.set=function(p,q){this.del(p);this._storage[this._key]+=e.call(this,p,q)};o.prototype.unescape=n.unescape;function e(p,q){var r=this.c;return r.concat(this._c,this.escape(p),r,r,(q=this.escape(q)).length,r,q)}return o})(j);if(Object.prototype.toString.call(j.opera)==="[object Opera]"){history.navigationMode="compatible";a.prototype.escape=j.encodeURIComponent;a.prototype.unescape=j.decodeURIComponent}function l(){function r(){s.cookie=["sessionStorage="+j.encodeURIComponent(h=f.key(128))].join(";");g=f.encode(h,g);a=new a(k,"name",k.name)}var e=k.name,s=k.document,n=/\bsessionStorage\b=([^;]+)(;|$)/,p=n.exec(s.cookie),q;if(p){h=j.decodeURIComponent(p[1]);g=f.encode(h,g);a=new a(k,"name");for(var t=a.key(),q=0,o=t.length,u={};q<o;++q){if((p=t[q]).indexOf(g)===0){b.push(p);u[p]=a.get(p);a.del(p)}}a=new a.constructor(k,"name",k.name);if(0<(this.length=b.length)){for(q=0,o=b.length,c=a.c,p=[];q<o;++q){p[q]=c.concat(a._c,a.escape(t=b[q]),c,c,(t=a.escape(u[t])).length,c,t)}k.name+=p.join("")}}else{r();if(!n.exec(s.cookie)){b=null}}}l.prototype={length:0,key:function(e){if(typeof e!=="number"||e<0||b.length<=e){throw"Invalid argument"}return b[e]},getItem:function(e){e=g+e;if(d.call(m,e)){return m[e]}var n=a.get(e);if(n!==null){n=m[e]=f.decode(h,n)}return n},setItem:function(e,n){this.removeItem(e);e=g+e;a.set(e,f.encode(h,m[e]=""+n));this.length=b.push(e)},removeItem:function(e){var n=a.get(e=g+e);if(n!==null){delete m[e];a.del(e);this.length=b.remove(e)}},clear:function(){a.clear();m={};b.length=0}};var g=k.document.domain,b=[],m={},d=m.hasOwnProperty,h;b.remove=function(n){var e=this.indexOf(n);if(-1<e){this.splice(e,1)}return this.length};if(!b.indexOf){b.indexOf=function(o){for(var e=0,n=this.length;e<n;++e){if(this[e]===o){return e}}return -1}}if(k.sessionStorage){l=function(){};l.prototype=k.sessionStorage}l=new l;if(b!==null){j.sessionStorage=l}})(window)};
519.714286
3,447
0.665476
b40d4585d288c5a18998d005f7a70dc2e01e7477
2,459
js
JavaScript
src/App.js
dkvvs/goit-react-hw-03-image-finder
129afbad1d8523b9c1172ee1eb7b80702275bde8
[ "MIT" ]
null
null
null
src/App.js
dkvvs/goit-react-hw-03-image-finder
129afbad1d8523b9c1172ee1eb7b80702275bde8
[ "MIT" ]
null
null
null
src/App.js
dkvvs/goit-react-hw-03-image-finder
129afbad1d8523b9c1172ee1eb7b80702275bde8
[ "MIT" ]
null
null
null
import React, { Component } from 'react'; import { ToastContainer } from 'react-toastify'; import s from './App.module.css'; import Searchbar from './components/Searchbar/Searchbar'; import ImageGallery from './components/ImageGallery/ImageGallery'; import Button from './components/Button/Button'; import Modal from './components/Modal/Modal'; import Loader from './components/Loader/Loader'; import apiServices from './apiServices/apiServices'; class App extends Component { state = { showModal: false, searchQuery: '', page: 1, loading: false, images: [], largeImage: '', }; handleSearchSubmit = searchQuery => { if (this.state.searchQuery !== searchQuery) this.setState({ images: [], searchQuery: searchQuery, page: 1, }); }; handleOpenLargeImage = imageUrl => { this.setState({ showModal: true, largeImage: imageUrl, }); }; handleAddPage = () => { this.setState(prevState => ({ page: prevState.page + 1, })); }; componentDidUpdate(prevProps, prevState) { const { page, searchQuery } = this.state; if (prevState.searchQuery !== searchQuery || prevState.page !== page) { this.setState({ loading: true, }); apiServices .fetchImages(searchQuery, page) .then(data => { this.setState(prevState => ({ images: [...prevState.images, ...data.hits], })); }) .catch(error => console.error(error)) .finally(() => this.setState({ loading: false })); } window.scrollTo({ top: document.documentElement.scrollHeight, behavior: 'smooth', }); } toggleModal = () => { this.setState(({ showModal }) => ({ showModal: !showModal, })); }; render() { const { images, showModal, loading, largeImage } = this.state; const buttonIsVisible = images.length > 0 && !loading; return ( <div className={s.app}> <Searchbar onSearch={this.handleSearchSubmit} /> <ImageGallery iamges={images} onOpenImage={this.handleOpenLargeImage} /> <div className={s.boxSpinner}> <Loader loading={loading} /> </div> {buttonIsVisible && <Button onClick={this.handleAddPage} />} {showModal && ( <Modal onClose={this.toggleModal} onLargeImage={largeImage} /> )} <ToastContainer /> </div> ); } } export default App;
26.159574
80
0.595364
b40d5a1d66486f80e36cb340bd69110a1d8faf66
1,667
js
JavaScript
src/pages/index.js
lassiter/portfolio
7458a9fda2156faa280f57100eccfb3b4851a970
[ "MIT" ]
null
null
null
src/pages/index.js
lassiter/portfolio
7458a9fda2156faa280f57100eccfb3b4851a970
[ "MIT" ]
3
2019-01-15T01:46:57.000Z
2019-01-16T22:51:05.000Z
src/pages/index.js
lassiter/portfolio
7458a9fda2156faa280f57100eccfb3b4851a970
[ "MIT" ]
null
null
null
import React from 'react' import IntroCard from '../components/IntroCard' import Container from '../components/Container' import SEO from '../components/SEO' import styled from 'styled-components' import bgImg from '../images/lassiter-bg-900.jpg' const TopBG = styled.article` @media only screen and (max-width: 411px) { background-image: none; background-repeat: no-repeat; } @media only screen and (min-width: 412px) { background-image: url(${bgImg}); background-repeat: no-repeat; background-attachment: fixed; background-position: top 15vh right 100px; height: 100vh; width: 100vw; max-height: 500px; z-index: -100; } ` const BG = styled.article` @media only screen and (max-width: 411px) { background-image: none; background-repeat: no-repeat; } @media only screen and (min-width: 412px) { background-image: url(${bgImg}); background-repeat: no-repeat; background-attachment: fixed; background-position: top 15vh right 100px; height: 100vh; width: 100vw; z-index: -100; } ` const Index = ({ data }) => { const person = data.contentfulPerson return ( <div> <SEO /> <TopBG /> <Container> <IntroCard key={person.id} shortBio={person.shortBio} /> </Container> <BG /> </div> ) } export const query = graphql` query introQuery { contentfulPerson(name: { eq: "Lassiter Gregg" }) { id image { id title sizes(maxWidth: 900) { ...GatsbyContentfulSizes_withWebp_noBase64 } } shortBio { childMarkdownRemark { html } } } } ` export default Index
20.329268
52
0.629874
b40d5cb431e2a462f33d9d93f22a175502f89b87
2,570
js
JavaScript
src/assets/moip-sdk-js/spec/bank_account/citibank_validator.spec.js
caiquexavier/portifolioapp
7ac62e68b612a91f94c727e066f4c37dc74f43c7
[ "MIT" ]
null
null
null
src/assets/moip-sdk-js/spec/bank_account/citibank_validator.spec.js
caiquexavier/portifolioapp
7ac62e68b612a91f94c727e066f4c37dc74f43c7
[ "MIT" ]
null
null
null
src/assets/moip-sdk-js/spec/bank_account/citibank_validator.spec.js
caiquexavier/portifolioapp
7ac62e68b612a91f94c727e066f4c37dc74f43c7
[ "MIT" ]
null
null
null
describe("CitibankValidator", function() { var validBankAccountParams; beforeEach(function() { validBankAccountParams = { bankNumber : "745", agencyNumber : "1584", agencyCheckNumber : "", accountNumber : "1234567", accountCheckNumber : "6", valid: jasmine.createSpy(), invalid: jasmine.createSpy() }; }); describe("validate agency number", function(){ it("does NOT accept invalid agency", function() { validBankAccountParams.agencyNumber = "123"; Moip.BankAccount.validate(validBankAccountParams); var expectedParams = { errors: [{ description: 'A agência deve conter 4 números. Complete com zeros a esquerda se necessário.', code: 'INVALID_AGENCY_NUMBER' }]}; expect(validBankAccountParams.invalid).toHaveBeenCalledWith(expectedParams); }); }); describe("validate agency check number", function(){ it("does NOT accept agency check number", function() { validBankAccountParams.agencyCheckNumber = "1"; Moip.BankAccount.validate(validBankAccountParams); var expectedParams = { errors: [{ description: 'O dígito da agência deve ser vazio', code: 'INVALID_AGENCY_CHECK_NUMBER' }]}; expect(validBankAccountParams.invalid).toHaveBeenCalledWith(expectedParams); }); }); describe("validate account number", function(){ it("accepts a valid bank account", function() { Moip.BankAccount.validate(validBankAccountParams); expect(validBankAccountParams.valid).toHaveBeenCalled(); }); it("does NOT accept account less than eight digits", function() { validBankAccountParams.accountNumber = "123456"; Moip.BankAccount.validate(validBankAccountParams); var expectedParams = { errors: [{ description: 'A conta corrente deve conter 7 números. Complete com zeros a esquerda se necessário.', code: 'INVALID_ACCOUNT_NUMBER' }]}; expect(validBankAccountParams.invalid).toHaveBeenCalledWith(expectedParams); }); it("does NOT accept account greater than eight digits", function() { validBankAccountParams.accountNumber = "12345678"; Moip.BankAccount.validate(validBankAccountParams); var expectedParams = { errors: [{ description: 'A conta corrente deve conter 7 números. Complete com zeros a esquerda se necessário.', code: 'INVALID_ACCOUNT_NUMBER' }]}; expect(validBankAccountParams.invalid).toHaveBeenCalledWith(expectedParams); }); }); });
35.694444
109
0.675486
b40d806f6650d01c9e2c5fcb41ddf319765eecc7
4,072
js
JavaScript
website/src/components/TeaserFlow/B.js
moulik-deepsource/react-flow
cee09fb5017bd17914c52785a061a63cfc39be79
[ "MIT" ]
null
null
null
website/src/components/TeaserFlow/B.js
moulik-deepsource/react-flow
cee09fb5017bd17914c52785a061a63cfc39be79
[ "MIT" ]
null
null
null
website/src/components/TeaserFlow/B.js
moulik-deepsource/react-flow
cee09fb5017bd17914c52785a061a63cfc39be79
[ "MIT" ]
null
null
null
import React, { useState, useEffect } from 'react'; import styled from '@emotion/styled'; import ReactFlow, { Handle, ReactFlowProvider, Background, Controls, } from 'react-flow-renderer'; import TeaserFlow from 'components/TeaserFlow'; import { baseColors } from 'themes'; const NodeWrapper = styled.div` background: ${(p) => p.theme.colors.silverLighten30}; padding: 8px 10px; font-size: 12px; border-radius: 4px; input { font-size: 12px; border: 1px solid ${(p) => p.theme.colors.violetLighten60}; width: 100%; border-radius: 2px; max-width: 100px; } .react-flow__handle { background: ${(p) => p.theme.colors.violetLighten60}; } `; const InputLabel = styled.div` color: ${(p) => p.theme.colors.violetLighten60}; `; const InputNode = ({ id, data }) => { return ( <NodeWrapper> <InputLabel>{data.label}:</InputLabel> <input className="nodrag" value={data.value} onChange={(event) => data.onChange(event, id)} /> <Handle type="source" position="bottom" /> </NodeWrapper> ); }; const ResultNode = ({ data }) => { return ( <NodeWrapper> <div>{data.value}</div> <Handle type="target" position="top" id="a" style={{ left: '40%' }} /> <Handle type="target" position="top" id="b" style={{ left: '60%' }} /> </NodeWrapper> ); }; const nodeTypes = { nameinput: InputNode, result: ResultNode, }; const onLoad = (rf) => setTimeout(() => rf.fitView({ padding: 0.1 }), 1); const findNodeById = (id) => (n) => n.id === id; export default () => { const [elements, setElements] = useState([]); useEffect(() => { const onChange = (event, id) => { setElements((els) => { const nextElements = els.map((e) => { if (e.id !== id) { return e; } const value = event.target.value; return { ...e, data: { ...e.data, value, }, }; }); const forname = nextElements.find(findNodeById('1')).data.value; const lastname = nextElements.find(findNodeById('2')).data.value; const result = `${forname} ${lastname}`; const resultNode = nextElements.find((n) => n.type === 'result'); resultNode.data = { ...resultNode.data, value: !forname && !lastname ? '*please enter a name*' : result, }; return nextElements; }); }; const initialElements = [ { id: '1', type: 'nameinput', position: { x: 0, y: 200, }, data: { label: 'Forename', value: 'React', onChange, }, }, { id: '2', type: 'nameinput', position: { x: 400, y: 200, }, data: { label: 'Lastname', value: 'Flow', onChange, }, }, { id: '3', type: 'result', position: { x: 200, y: 400, }, data: { value: 'React Flow', }, }, { id: 'e1', source: '1', target: '3__a', animated: true, }, { id: 'e2', source: '2', target: '3__b', animated: true, }, ]; setElements(initialElements); }, []); return ( <TeaserFlow title="Customizable" description="You can create your own node and edge types or just pass a custom style. You can implement custom UIs inside your nodes and add functionality to your edges." textPosition="right" fitView isDark > <ReactFlowProvider> <ReactFlow elements={elements} nodeTypes={nodeTypes} onLoad={onLoad} zoomOnScroll={false} > <Background color={baseColors.silverDarken60} gap={15} /> <Controls showInteractive={false} /> </ReactFlow> </ReactFlowProvider> </TeaserFlow> ); };
22.251366
176
0.50835
b40e53ae02feba558e5d699fafbf9dc3f1017cf2
625
js
JavaScript
api-builder-plugin-dc-postgres/lib/methods/distinct.js
cwiechmann/api-builder-extras
827d48812da50fcb808cad9e806898c6d734e662
[ "Apache-2.0" ]
11
2020-01-15T10:05:36.000Z
2021-12-15T09:34:08.000Z
api-builder-plugin-dc-postgres/lib/methods/distinct.js
cwiechmann/api-builder-extras
827d48812da50fcb808cad9e806898c6d734e662
[ "Apache-2.0" ]
91
2020-01-14T14:31:58.000Z
2022-03-28T02:26:56.000Z
api-builder-plugin-dc-postgres/lib/methods/distinct.js
cwiechmann/api-builder-extras
827d48812da50fcb808cad9e806898c6d734e662
[ "Apache-2.0" ]
10
2020-01-14T14:16:36.000Z
2021-11-15T09:34:35.000Z
/** * Searches for distinct rows in the database. * @param {object} Model - model to use * @param {string} field - field * @param {object} options - options * @param {Function} callback - Callback passed an Error object (or null if successful), * and distinct values. */ exports.distinct = function distinct (Model, field, options, callback) { const opts = { limit: 1000, ...options, distinct: true // internal option }; // delete unsupported options (sel is unsupported too) delete opts.unsel; // set the explicit distinct field opts.sel = { [field]: true }; this.query(Model, opts, callback); };
24.038462
88
0.68
b40e918b17494274323c7ccb272ee6115dfcb2d5
1,035
js
JavaScript
src/components/routes/index.js
kant/react-native-mobx-firebase-starter
308c7637007dea50223eeb9fe6738418b040753d
[ "MIT" ]
47
2019-01-30T19:01:27.000Z
2021-12-09T22:13:22.000Z
src/components/routes/index.js
kant/react-native-mobx-firebase-starter
308c7637007dea50223eeb9fe6738418b040753d
[ "MIT" ]
8
2019-08-08T08:29:23.000Z
2022-01-22T03:30:30.000Z
src/components/routes/index.js
Geohalbert/react-native-mobx-firebase-starter
66bfc8c7618de6547d16fd3e4fa60c16f718cec3
[ "MIT" ]
16
2019-03-04T17:28:54.000Z
2022-01-24T21:44:43.000Z
import React from 'react'; import { Navigation } from 'react-native-navigation'; import { observer } from 'mobx-react' import Provider from '../../utils/Provider' import stores from '../../stores'; //Route Imports import HomeView from './HomeView'; import LoginView from './LoginView'; import RegisterView from './RegisterView'; export default routes = { 'App.Home': HomeView, 'App.Login': LoginView, 'App.Register': RegisterView, } // Register all screens of the app (including internal ones) export function registerScreens() { for (let r in routes) { Navigation.registerComponent(r, () => sceneCreator(routes[r], stores)) } } function sceneCreator(sceneComp, store) { @observer class SceneWrapper extends React.Component { static options(passProps) { return sceneComp.options ? sceneComp.options(passProps) : {} } render() { return ( <Provider store={store}> {React.createElement(sceneComp, this.props)} </Provider> ) } } return SceneWrapper }
24.642857
74
0.676329
b40ea93066cf30b5cc507c3f18818bb64522b237
988
js
JavaScript
components/prism-http.min.js
chmlee/prism
f866fe0bf1b0add0d5b6d6fe8164fc73dbe794a2
[ "MIT" ]
null
null
null
components/prism-http.min.js
chmlee/prism
f866fe0bf1b0add0d5b6d6fe8164fc73dbe794a2
[ "MIT" ]
null
null
null
components/prism-http.min.js
chmlee/prism
f866fe0bf1b0add0d5b6d6fe8164fc73dbe794a2
[ "MIT" ]
null
null
null
!function(t){t.languages.http={"request-line":{pattern:/^(?:POST|GET|PUT|DELETE|OPTIONS|PATCH|TRACE|CONNECT)\s(?:https?:\/\/|\/)\S+\sHTTP\/[0-9.]+/m,inside:{property:/^(?:POST|GET|PUT|DELETE|OPTIONS|PATCH|TRACE|CONNECT)\b/,"attr-name":/:\w+/}},"response-status":{pattern:/^HTTP\/1.[01] \d+.*/m,inside:{property:{pattern:/(^HTTP\/1.[01] )\d+.*/i,lookbehind:!0}}},"header-name":{pattern:/^[\w-]+:(?=.)/m,alias:"keyword"}};var e,a,n,i,p,s=t.languages,r={"application/javascript":s.javascript,"application/json":s.json||s.javascript,"application/xml":s.xml,"text/xml":s.xml,"text/html":s.html,"text/css":s.css},T={"application/json":!0,"application/xml":!0};for(a in r)r[a]&&(e=e||{},n=T[a]?(p=void 0,p=(i=a).replace(/^[a-z]+\//,""),"(?:"+i+"|"+("\\w+/(?:[\\w.-]+\\+)+"+p+"(?![+\\w.-])")+")"):a,e[a.replace(/\//g,"-")]={pattern:RegExp("(content-type:\\s*"+n+"[\\s\\S]*?)(?:\\r?\\n|\\r){2}[\\s\\S]*","i"),lookbehind:!0,inside:r[a]});e&&t.languages.insertBefore("http","header-name",e)}(Prism);
988
988
0.581984
b40edd6a27f84a6d3d5dca7cba318d35e5f836b5
694
js
JavaScript
lib/sort-by-path.js
simpledealer/phi
30dbe833c256a148299c042156a7394edf2d66ec
[ "MIT" ]
2
2019-05-31T01:23:21.000Z
2019-10-16T15:53:27.000Z
lib/sort-by-path.js
simpledealer/phi
30dbe833c256a148299c042156a7394edf2d66ec
[ "MIT" ]
12
2019-09-07T15:59:55.000Z
2022-02-15T05:18:19.000Z
lib/sort-by-path.js
simpledealer/phi
30dbe833c256a148299c042156a7394edf2d66ec
[ "MIT" ]
2
2021-03-10T14:15:24.000Z
2021-11-24T13:19:25.000Z
import { curryN, sortBy, path } from 'ramda' /** * Sorts the list by the supplied property path. * * @func sortByPath * @memberOf PHI * @since {@link https://phi.meltwaterlabs.com/1.1.0|v1.1.0} * @category List * @sig [Idx] -> [a] -> [a] * @param {!Array.<string|number>} path The property path to sort by * @param {!Array} arr The list to sort * @return {!Array} The sorted list * @see PHI.sortByProp * @example * * const sortByABC = PHI.sortByPath(['a', 'b', 'c']) * sortByABC([{a: {b: {c: 'joe'}}}, {a: {b: {c: 'alice'}}}]) * //=> [{a: {b: {c: 'alice'}}}, {a: {b: {c: 'joe'}}}] */ const sortByPath = curryN(2, (pa, arr) => sortBy(path(pa))(arr)) export default sortByPath
28.916667
68
0.586455
b40ee44655098a334f2d85f6c711fb2f62fb7709
903
js
JavaScript
packages/jump-build/src/helper/path.js
MengFangui/mfgjump
baf41f33a466096c592e42c90d1410e4a24f3f42
[ "MIT" ]
201
2019-04-11T07:56:46.000Z
2021-09-07T03:42:54.000Z
packages/jump-build/src/helper/path.js
MengFangui/mfgjump
baf41f33a466096c592e42c90d1410e4a24f3f42
[ "MIT" ]
49
2019-04-13T10:44:08.000Z
2022-02-26T01:43:49.000Z
packages/jump-build/src/helper/path.js
MengFangui/mfgjump
baf41f33a466096c592e42c90d1410e4a24f3f42
[ "MIT" ]
39
2019-04-08T06:47:08.000Z
2022-02-15T13:44:34.000Z
/** * @file path * @author zhangwentao */ const path = require('path'); function getPathToCWD(p) { return path.relative(process.cwd(), p); } function isCSS(filePath) { const ext = path.extname(filePath).substr(1); return /^(css|less|styl(us)?|s(c|a)ss)$/i.test(ext); } function isJS(filePath) { const ext = path.extname(filePath).substr(1); return /^(js|ts)$/i.test(ext); } function changeExt(filePath, ext) { ext = ext[0] === '.' ? ext : ('.' + ext); const {dir, name} = path.parse(filePath); filePath = path.format({dir, name, ext}); return filePath; } function getModuleName(mod) { if (mod[0] === '.') { return null; } let [name, temp] = mod.split('/'); if (name[0] === '@') { name = `${name}/${temp}`; } return name; } module.exports = { getPathToCWD, isCSS, isJS, changeExt, getModuleName };
19.212766
56
0.564784
b40efaf91940d4753797f0b7c308cf72176965c5
1,222
js
JavaScript
force-app/main/default/lwc/testAccountNameContainer/testAccountNameContainer.js
jakubowski1005/salesforce-test-project
5655a6ea7621da43121c81aa6f34c83bb2c4e4bd
[ "MIT" ]
null
null
null
force-app/main/default/lwc/testAccountNameContainer/testAccountNameContainer.js
jakubowski1005/salesforce-test-project
5655a6ea7621da43121c81aa6f34c83bb2c4e4bd
[ "MIT" ]
null
null
null
force-app/main/default/lwc/testAccountNameContainer/testAccountNameContainer.js
jakubowski1005/salesforce-test-project
5655a6ea7621da43121c81aa6f34c83bb2c4e4bd
[ "MIT" ]
null
null
null
import { LightningElement, api } from 'lwc'; import deleteAllRelatedHistories from '@salesforce/apex/TestAccountNameHistoryHandler.deleteAllRelatedHistories' export default class TestAccountNameContainer extends LightningElement { @api recordId; isQuestionModalOpened = false; isResultsModalOpened = false; isLoading = false; message = ''; openModal() { this.isQuestionModalOpened = true; } closeModal() { this.isQuestionModalOpened = false; this.isResultsModalOpened = false; } handleDeleteClick() { this.isLoading = true; deleteAllRelatedHistories({ recordId: this.recordId }) .then(size => { this.message = (size === 0) ? 'No records to delete.' : size + ' record were deleted.'; this.isLoading = false; this.isResultsModalOpened = true; }) .catch(err => { this.message = 'Error: code: ' + err.errorCode + ' ' + ', message: ' + err.body.message; this.isLoading = false; this.isResultsModalOpened = true; }); } }
33.027027
112
0.559738
b40f18280735e143721893ef0531d8ec44231941
7,065
js
JavaScript
deps/monaco-editor-0.23.0/vs/editor/contrib/smartSelect/bracketSelections.js
voltrevo/monaco-deno-bundle
5e4728fc292f768434afbc411aa11eb457a4d693
[ "MIT" ]
4
2021-08-18T00:23:16.000Z
2022-03-02T18:32:45.000Z
node_modules/monaco-editor/esm/vs/editor/contrib/smartSelect/bracketSelections.js
sumy7/monaco-language-log
5164b62ac0e86b322504913ed3fe2f97d7171f94
[ "MIT" ]
9
2021-08-20T11:54:04.000Z
2021-08-25T13:58:45.000Z
node_modules/monaco-editor/esm/vs/editor/contrib/smartSelect/bracketSelections.js
sumy7/monaco-language-log
5164b62ac0e86b322504913ed3fe2f97d7171f94
[ "MIT" ]
1
2022-01-24T20:01:53.000Z
2022-01-24T20:01:53.000Z
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; import { Position } from '../../common/core/position.js'; import { Range } from '../../common/core/range.js'; import { LinkedList } from '../../../base/common/linkedList.js'; export class BracketSelectionRangeProvider { provideSelectionRanges(model, positions) { return __awaiter(this, void 0, void 0, function* () { const result = []; for (const position of positions) { const bucket = []; result.push(bucket); const ranges = new Map(); yield new Promise(resolve => BracketSelectionRangeProvider._bracketsRightYield(resolve, 0, model, position, ranges)); yield new Promise(resolve => BracketSelectionRangeProvider._bracketsLeftYield(resolve, 0, model, position, ranges, bucket)); } return result; }); } static _bracketsRightYield(resolve, round, model, pos, ranges) { const counts = new Map(); const t1 = Date.now(); while (true) { if (round >= BracketSelectionRangeProvider._maxRounds) { resolve(); break; } if (!pos) { resolve(); break; } let bracket = model.findNextBracket(pos); if (!bracket) { resolve(); break; } let d = Date.now() - t1; if (d > BracketSelectionRangeProvider._maxDuration) { setTimeout(() => BracketSelectionRangeProvider._bracketsRightYield(resolve, round + 1, model, pos, ranges)); break; } const key = bracket.close[0]; if (bracket.isOpen) { // wait for closing let val = counts.has(key) ? counts.get(key) : 0; counts.set(key, val + 1); } else { // process closing let val = counts.has(key) ? counts.get(key) : 0; val -= 1; counts.set(key, Math.max(0, val)); if (val < 0) { let list = ranges.get(key); if (!list) { list = new LinkedList(); ranges.set(key, list); } list.push(bracket.range); } } pos = bracket.range.getEndPosition(); } } static _bracketsLeftYield(resolve, round, model, pos, ranges, bucket) { const counts = new Map(); const t1 = Date.now(); while (true) { if (round >= BracketSelectionRangeProvider._maxRounds && ranges.size === 0) { resolve(); break; } if (!pos) { resolve(); break; } let bracket = model.findPrevBracket(pos); if (!bracket) { resolve(); break; } let d = Date.now() - t1; if (d > BracketSelectionRangeProvider._maxDuration) { setTimeout(() => BracketSelectionRangeProvider._bracketsLeftYield(resolve, round + 1, model, pos, ranges, bucket)); break; } const key = bracket.close[0]; if (!bracket.isOpen) { // wait for opening let val = counts.has(key) ? counts.get(key) : 0; counts.set(key, val + 1); } else { // opening let val = counts.has(key) ? counts.get(key) : 0; val -= 1; counts.set(key, Math.max(0, val)); if (val < 0) { let list = ranges.get(key); if (list) { let closing = list.shift(); if (list.size === 0) { ranges.delete(key); } const innerBracket = Range.fromPositions(bracket.range.getEndPosition(), closing.getStartPosition()); const outerBracket = Range.fromPositions(bracket.range.getStartPosition(), closing.getEndPosition()); bucket.push({ range: innerBracket }); bucket.push({ range: outerBracket }); BracketSelectionRangeProvider._addBracketLeading(model, outerBracket, bucket); } } } pos = bracket.range.getStartPosition(); } } static _addBracketLeading(model, bracket, bucket) { if (bracket.startLineNumber === bracket.endLineNumber) { return; } // xxxxxxxx { // // } const startLine = bracket.startLineNumber; const column = model.getLineFirstNonWhitespaceColumn(startLine); if (column !== 0 && column !== bracket.startColumn) { bucket.push({ range: Range.fromPositions(new Position(startLine, column), bracket.getEndPosition()) }); bucket.push({ range: Range.fromPositions(new Position(startLine, 1), bracket.getEndPosition()) }); } // xxxxxxxx // { // // } const aboveLine = startLine - 1; if (aboveLine > 0) { const column = model.getLineFirstNonWhitespaceColumn(aboveLine); if (column === bracket.startColumn && column !== model.getLineLastNonWhitespaceColumn(aboveLine)) { bucket.push({ range: Range.fromPositions(new Position(aboveLine, column), bracket.getEndPosition()) }); bucket.push({ range: Range.fromPositions(new Position(aboveLine, 1), bracket.getEndPosition()) }); } } } } BracketSelectionRangeProvider._maxDuration = 30; BracketSelectionRangeProvider._maxRounds = 2;
45.288462
141
0.491295
b40f58ec4affdb800318131c1d2a6ea870c3492b
45
js
JavaScript
src/components/VerifyNotif/index.js
ArtemArturovichBondarenko/Bue_a_flat_Front-end
dd85ec630a2bd224be0e46b7fae87a1d4088eb28
[ "MIT" ]
null
null
null
src/components/VerifyNotif/index.js
ArtemArturovichBondarenko/Bue_a_flat_Front-end
dd85ec630a2bd224be0e46b7fae87a1d4088eb28
[ "MIT" ]
null
null
null
src/components/VerifyNotif/index.js
ArtemArturovichBondarenko/Bue_a_flat_Front-end
dd85ec630a2bd224be0e46b7fae87a1d4088eb28
[ "MIT" ]
1
2020-10-26T16:11:39.000Z
2020-10-26T16:11:39.000Z
export { default } from './VerifyNotif.jsx';
22.5
44
0.688889
b40f6404defe393f6626e0383fa4fe80485ad983
5,305
js
JavaScript
src/store/mutations/structs.js
opensparkl/sse_dc_editor
96e9a0fa7bd1cca7e4484019ae7b87550ba87476
[ "Apache-2.0" ]
null
null
null
src/store/mutations/structs.js
opensparkl/sse_dc_editor
96e9a0fa7bd1cca7e4484019ae7b87550ba87476
[ "Apache-2.0" ]
1
2018-08-22T11:47:29.000Z
2018-08-22T11:47:29.000Z
src/store/mutations/structs.js
opensparkl/sse_dc_editor
96e9a0fa7bd1cca7e4484019ae7b87550ba87476
[ "Apache-2.0" ]
null
null
null
/** * Copyright 2018 SPARKL Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import Vue from 'vue' import _ from 'lodash' import Tree from '../../util/tree' import Type from '../../util/type' import store from '../index' var createMissingService = function (nodes, rootId, op) { var service = { tag: 'service', attr: { name: op.attr.service } } var services = Tree.searchUp(nodes, op.attr.id, service, {limit: 1}) if (services.length === 0) { service = Vue.util.extend(service, { parent_id: rootId, is_ghost: true }) store.commit('createStruct', service) return true } return false } var mutations = { createStruct (state, payload) { var nodes = state.nodes var node = Tree.create(nodes, payload, {append: true}) if (payload.hasOwnProperty('$position')) { Tree.parent(nodes, node, node.parent_id, { position: payload.$position }) } }, updateStruct (state, {id, partial}) { var node = state.nodes[id] if (node) { _.merge(node, partial) Vue.set(state.nodes, id, node) } }, moveStruct (state, {id, to, at}) { if (to) { const node = state.nodes[id] const parentId = node.parent_id const type = Type.is(node) Tree.parent(state.nodes, id, to, {position: at}) if (type === 'operation' && node.attr.service) { createMissingService(state.nodes, state.rootId, node) } if (type === 'service') { const serviceName = node.attr.name const operations = [] Tree.traverse(state.nodes, parentId, (child, params) => { const type = Type.is(child) if (type === 'operation' && child.attr.service === serviceName) { operations.push(child) return window.TRAVERSE.CONTINUE } /* If service with such name exists, stop traversion in the child folders */ if (type === 'service' && child.attr.name === serviceName) { return window.TRAVERSE.STOP_BRANCH } }) for (let i = 0; i < operations.length; i++) { const op = operations[i] /* Create a service if it is not an ancestor of the operations. Also there is no need to iterate futher, because service is created in the root */ if (!Tree.isAncestorOf(state.nodes, node, op)) { var created = createMissingService(state.nodes, state.rootId, op) console.log('Created referenced service for ' + op.attr.name) if (created) { break } } } } if (type === 'field') { const operations = [] const fieldId = node.attr.id const fieldName = node.attr.name Tree.traverse(state.nodes, parentId, (child, params) => { var childType = Type.is(child) if (childType === 'field' && child.attr.name === fieldName) { return window.TRAVERSE.STOP_BRANCH } if (childType === 'operation' && child.attr.fields) { var index = child.attr.fields.indexOf(fieldId) if (index !== -1) { /* Caching operation object and index in "fields" array */ operations.push({ index: index, op: child }) } } }) var field = null for (let i = 0; i < operations.length; i++) { const {op, index} = operations[i] const isAncestor = Tree.isAncestorOf(state.nodes, fieldId, op) if (!isAncestor) { if (!field) { field = Tree.create(state.nodes, { tag: 'field', attr: { name: fieldName }, is_ghost: true, parent_id: state.rootId }, {append: true}) } op.attr.fields.splice(index, 1, field.attr.id) } } } } else { console.error('Please, specifiy the target for ' + id) } }, deleteStruct (state, id) { Tree.remove(state.nodes, id) if (state.selectedId === id && !state.nodes[id]) { state.selectedId = null } }, selectStruct (state, id) { if (state.selectedId) { store.commit('unselectStruct') } state.selectedId = id }, unselectStruct (state) { if (state.selectedId) { var selected = state.nodes[state.selectedId] var isOperation = Type.is(selected.tag) === 'operation' if (isOperation && selected.attr.service) { createMissingService(state.nodes, state.rootId, selected) } state.selectedId = null } } } export default mutations
26.658291
77
0.558907
b40f7ee4bc50ac644c888ef35eb697604a16f177
930
js
JavaScript
pages/editUser/editUser.js
gxsnyyx/dxzzb
f420f3a15a835d3e15c38706defe475ed5be17ff
[ "Apache-2.0" ]
null
null
null
pages/editUser/editUser.js
gxsnyyx/dxzzb
f420f3a15a835d3e15c38706defe475ed5be17ff
[ "Apache-2.0" ]
null
null
null
pages/editUser/editUser.js
gxsnyyx/dxzzb
f420f3a15a835d3e15c38706defe475ed5be17ff
[ "Apache-2.0" ]
null
null
null
// pages/editUser/editUser.js Page({ /** * 页面的初始数据 */ data: { userIcon: '' }, /** * 生命周期函数--监听页面加载 */ onLoad: function (options) { const eventChannel = this.getOpenerEventChannel() let self = this eventChannel.on('acceptDataFromOpenerPage', function(data) { console.log(data) self.setData({ userIcon: data.userIcon, }) }) wx.hideTabBar({ animation: false, }) }, /** * 生命周期函数--监听页面初次渲染完成 */ onReady: function () { }, /** * 生命周期函数--监听页面显示 */ onShow: function () { }, /** * 生命周期函数--监听页面隐藏 */ onHide: function () { }, /** * 生命周期函数--监听页面卸载 */ onUnload: function () { }, /** * 页面相关事件处理函数--监听用户下拉动作 */ onPullDownRefresh: function () { }, /** * 页面上拉触底事件的处理函数 */ onReachBottom: function () { }, /** * 用户点击右上角分享 */ onShareAppMessage: function () { } })
12.236842
64
0.510753
b4107b868f0dd7b62fbcb8f7d84fb52202984c27
3,045
js
JavaScript
Useful Scripts/ModalWindowButtonControlled.js
Decoder-Paul/ServiceNow-Development
9ddc4f733656f0bdd646cf6964f98e7d877599b5
[ "MIT" ]
17
2018-11-21T04:41:02.000Z
2022-03-31T19:54:34.000Z
Useful Scripts/ModalWindowButtonControlled.js
Decoder-Paul/ServiceNow-Development
9ddc4f733656f0bdd646cf6964f98e7d877599b5
[ "MIT" ]
null
null
null
Useful Scripts/ModalWindowButtonControlled.js
Decoder-Paul/ServiceNow-Development
9ddc4f733656f0bdd646cf6964f98e7d877599b5
[ "MIT" ]
8
2020-04-18T06:08:44.000Z
2022-01-24T20:24:33.000Z
//////////////////////////////////////////////////////////////// //Client Side: Dialog box with choices //////////////////////////////////////////////////////////////// function cancelDialog(){ var gm = new GlideModal('cancelTask'); //Sets the dialog title gm.setTitle('Cancel Task'); //Set up valid custom HTML to be displayed gm.renderWithContent('<div style="padding:15px"><p>What action do you want to take?</p><p><select name="cancellation" id="taskCancellation" class="form-control"><option value="cancelOnly" role="option">Cancel this task but keep the requested item open</option><option value="cancelAll" role="option">Cancel this and all other tasks, closing the requested item</option></select></p><div style="padding:5px;float:right"><button style="padding:5px;margin-right:10px" onclick="window.changeTaskAction(this.innerHTML,jQuery(\'#taskCancellation\').val())" class="btn btn-default">Abort</button><button style="padding:5px" class="btn btn-primary" onclick="window.changeTaskAction(this.innerHTML,jQuery(\'#taskCancellation\').val())">Cancel Task</button></div></div>'); //We'll use the windows object to ensure our code is accessible from the modal dialog window.changeTaskAction = function(thisButton, thisAction){ //Close the glide modal dialog window gm.destroy(); //Submit to the back-end if(thisButton=='Cancel Task'){ if(thisAction=="cancelAll"){ g_form.setValue('state',4);//Closed Incomplete -- will close the Requested Item and all other open tasks }else{ g_form.setValue('state',7);//Closed Skipped -- will only close this task } //Regular ServiceNow form submission gsftSubmit(null, g_form.getFormElement(), 'cancel_sc_task'); } }; return false;//prevents the form from submitting when the dialog first load } //////////////////////////////////////////////////////////////// //Server Side: Dialog box with choices //////////////////////////////////////////////////////////////// if (typeof window == 'undefined') updateTask(); function updateTask(){ //Runs on the server if(current.state==7){ //closed skipped so simply update this one record current.update(); }else{ //closed incomplete so update all associated records to close the requested item entirely current.update(); //And now we'll cancel any other open tasks along with the requested item if(!gs.nil(current.parent)){ //Close siblings var otherTasks = new GlideRecord('sc_task'); otherTasks.addEncodedQuery('request_item='+current.request_item+'^stateIN-5,1,2'); otherTasks.query(); while(otherTasks.next()){ otherTasks.state = '4'; otherTasks.update(); } //Close parent var ritm = new GlideRecord('sc_req_item'); if(ritm.get(current.parent)){ ritm.state = '4'; ritm.stage = 'Cancelled'; ritm.update(); } } } }
46.136364
764
0.605255
b4112619c204b04bf8bb427afae16124d0169d33
19,240
js
JavaScript
node_modules/@azure/event-hubs/dist-esm/src/eventProcessor.js
limengdu/Wio-Terminal-light-sensor-Azure-IoT-hub-Web-APP
ab92911b07fba152e80bd254f3bd2edf62f20686
[ "MIT" ]
null
null
null
node_modules/@azure/event-hubs/dist-esm/src/eventProcessor.js
limengdu/Wio-Terminal-light-sensor-Azure-IoT-hub-Web-APP
ab92911b07fba152e80bd254f3bd2edf62f20686
[ "MIT" ]
1
2022-03-10T07:23:02.000Z
2022-03-10T09:26:44.000Z
node_modules/@azure/event-hubs/dist-esm/src/eventProcessor.js
limengdu/Wio-Terminal-light-sensor-Azure-IoT-hub-Web-APP
ab92911b07fba152e80bd254f3bd2edf62f20686
[ "MIT" ]
null
null
null
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. import { __awaiter } from "tslib"; import uuid from "uuid/v4"; import { PumpManagerImpl } from "./pumpManager"; import { AbortController } from "@azure/abort-controller"; import { logger, logErrorStackTrace } from "./log"; import { FairPartitionLoadBalancer } from "./partitionLoadBalancer"; import { PartitionProcessor } from "./partitionProcessor"; import { latestEventPosition, isEventPosition } from "./eventPosition"; import { delayWithoutThrow } from "./util/delayWithoutThrow"; import { CloseReason } from "./models/public"; /** * Event Processor based applications consist of one or more instances of EventProcessor which have been * configured to consume events from the same Event Hub and consumer group. They balance the * workload across different instances by distributing the partitions to be processed among themselves. * They also allow the user to track progress when events are processed using checkpoints. * * A checkpoint is meant to represent the last successfully processed event by the user from a particular * partition of a consumer group in an Event Hub instance. * * You need the below to create an instance of `EventProcessor` * - The name of the consumer group from which you want to process events * - An instance of `EventHubClient` class that was created for the Event Hub instance. * - A user implemented class that extends the `PartitionProcessor` class. To get started, you can use the * base class `PartitionProcessor` which simply logs the incoming events. To provide your code to process incoming * events, extend this class and override the `processEvents()` method. For example: * ```js * class SamplePartitionProcessor extends PartitionProcessor { * async processEvents(events) { * // user code to process events here * // Information on the partition being processed is available as properties on the `SamplePartitionProcessor` class * // use `this.updateCheckpoint()` method to update checkpoints as needed * } * } * ``` * - An instance of `CheckpointStore`. See &commat;azure/eventhubs-checkpointstore-blob for an implementation. * For production, choose an implementation that will store checkpoints and partition ownership details to a durable store. * Implementations of `CheckpointStore` can be found on npm by searching for packages with the prefix &commat;azure/eventhub-checkpointstore-. * * @class EventProcessor * @internal * @ignore */ export class EventProcessor { /** * @param consumerGroup The name of the consumer group from which you want to process events. * @param eventHubClient An instance of `EventHubClient` that was created for the Event Hub instance. * @param PartitionProcessorClass A user-provided class that extends the `PartitionProcessor` class. * This class will be responsible for processing and checkpointing events. * @param checkpointStore An instance of `CheckpointStore`. See &commat;azure/eventhubs-checkpointstore-blob for an implementation. * For production, choose an implementation that will store checkpoints and partition ownership details to a durable store. * @param options A set of options to configure the Event Processor * - `maxBatchSize` : The max size of the batch of events passed each time to user code for processing. * - `maxWaitTimeInSeconds` : The maximum amount of time to wait to build up the requested message count before * passing the data to user code for processing. If not provided, it defaults to 60 seconds. */ constructor(consumerGroup, _eventHubClient, _subscriptionEventHandlers, _checkpointStore, options) { this._eventHubClient = _eventHubClient; this._subscriptionEventHandlers = _subscriptionEventHandlers; this._checkpointStore = _checkpointStore; this._isRunning = false; this._loopIntervalInMs = 10000; this._inactiveTimeLimitInMs = 60000; if (options.ownerId) { this._id = options.ownerId; logger.verbose(`Starting event processor with ID ${this._id}`); } else { this._id = uuid(); logger.verbose(`Starting event processor with autogenerated ID ${this._id}`); } this._consumerGroup = consumerGroup; this._processorOptions = options; this._pumpManager = options.pumpManager || new PumpManagerImpl(this._id, this._processorOptions); const inactiveTimeLimitInMS = options.inactiveTimeLimitInMs || this._inactiveTimeLimitInMs; this._processingTarget = options.processingTarget || new FairPartitionLoadBalancer(inactiveTimeLimitInMS); if (options.loopIntervalInMs) { this._loopIntervalInMs = options.loopIntervalInMs; } } /** * The unique identifier for the EventProcessor. * * @return {string} */ get id() { return this._id; } _createPartitionOwnershipRequest(partitionOwnershipMap, partitionIdToClaim) { const previousPartitionOwnership = partitionOwnershipMap.get(partitionIdToClaim); const partitionOwnership = { ownerId: this._id, partitionId: partitionIdToClaim, fullyQualifiedNamespace: this._eventHubClient.fullyQualifiedNamespace, consumerGroup: this._consumerGroup, eventHubName: this._eventHubClient.eventHubName, etag: previousPartitionOwnership ? previousPartitionOwnership.etag : undefined }; return partitionOwnership; } /* * Claim ownership of the given partition if it's available */ _claimOwnership(ownershipRequest, abortSignal) { return __awaiter(this, void 0, void 0, function* () { if (abortSignal.aborted) { logger.verbose(`[${this._id}] Subscription was closed before claiming ownership of ${ownershipRequest.partitionId}.`); return; } logger.info(`[${this._id}] Attempting to claim ownership of partition ${ownershipRequest.partitionId}.`); try { const claimedOwnerships = yield this._checkpointStore.claimOwnership([ownershipRequest]); // can happen if the partition was claimed out from underneath us - we shouldn't // attempt to spin up a processor. if (!claimedOwnerships.length) { return; } logger.info(`[${this._id}] Successfully claimed ownership of partition ${ownershipRequest.partitionId}.`); yield this._startPump(ownershipRequest.partitionId, abortSignal); } catch (err) { logger.warning(`[${this.id}] Failed to claim ownership of partition ${ownershipRequest.partitionId}`); logErrorStackTrace(err); yield this._handleSubscriptionError(err); } }); } _startPump(partitionId, abortSignal) { return __awaiter(this, void 0, void 0, function* () { if (abortSignal.aborted) { logger.verbose(`[${this._id}] The subscription was closed before starting to read from ${partitionId}.`); return; } if (this._pumpManager.isReceivingFromPartition(partitionId)) { logger.verbose(`[${this._id}] There is already an active partitionPump for partition "${partitionId}", skipping pump creation.`); return; } logger.verbose(`[${this._id}] [${partitionId}] Calling user-provided PartitionProcessorFactory.`); const partitionProcessor = new PartitionProcessor(this._subscriptionEventHandlers, this._checkpointStore, { fullyQualifiedNamespace: this._eventHubClient.fullyQualifiedNamespace, eventHubName: this._eventHubClient.eventHubName, consumerGroup: this._consumerGroup, partitionId: partitionId, eventProcessorId: this.id }); const eventPosition = yield this._getStartingPosition(partitionId); yield this._pumpManager.createPump(eventPosition, this._eventHubClient, partitionProcessor, abortSignal); logger.verbose(`[${this._id}] PartitionPump created successfully.`); }); } _getStartingPosition(partitionIdToClaim) { return __awaiter(this, void 0, void 0, function* () { const availableCheckpoints = yield this._checkpointStore.listCheckpoints(this._eventHubClient.fullyQualifiedNamespace, this._eventHubClient.eventHubName, this._consumerGroup); const validCheckpoints = availableCheckpoints.filter((chk) => chk.partitionId === partitionIdToClaim); if (validCheckpoints.length > 0) { return { offset: validCheckpoints[0].offset }; } logger.verbose(`No checkpoint found for partition ${partitionIdToClaim}. Looking for fallback.`); return getStartPosition(partitionIdToClaim, this._processorOptions.startPosition); }); } _runLoopForSinglePartition(partitionId, abortSignal) { return __awaiter(this, void 0, void 0, function* () { while (!abortSignal.aborted) { try { yield this._startPump(partitionId, abortSignal); } catch (err) { logger.warning(`[${this._id}] An error occured within the EventProcessor loop: ${err}`); logErrorStackTrace(err); yield this._handleSubscriptionError(err); } finally { // sleep for some time after which we can attempt to create a pump again. logger.verbose(`[${this._id}] Pausing the EventProcessor loop for ${this._loopIntervalInMs} ms.`); // swallow errors from delay since it's fine for delay to exit early yield delayWithoutThrow(this._loopIntervalInMs, abortSignal); } } this._isRunning = false; }); } /** * Every loop to this method will result in this EventProcessor owning at most one new partition. * * The load is considered balanced when no active EventProcessor owns 2 partitions more than any other active * EventProcessor. Given that each invocation to this method results in ownership claim of at most one partition, * this algorithm converges gradually towards a steady state. * * When a new partition is claimed, this method is also responsible for starting a partition pump that creates an * EventHubConsumer for processing events from that partition. */ _runLoopWithLoadBalancing(loadBalancer, abortSignal) { return __awaiter(this, void 0, void 0, function* () { // periodically check if there is any partition not being processed and process it while (!abortSignal.aborted) { try { const partitionOwnershipMap = new Map(); // Retrieve current partition ownership details from the datastore. const partitionOwnership = yield this._checkpointStore.listOwnership(this._eventHubClient.fullyQualifiedNamespace, this._eventHubClient.eventHubName, this._consumerGroup); const abandonedMap = new Map(); for (const ownership of partitionOwnership) { if (isAbandoned(ownership)) { abandonedMap.set(ownership.partitionId, ownership); continue; } partitionOwnershipMap.set(ownership.partitionId, ownership); } const partitionIds = yield this._eventHubClient.getPartitionIds({ abortSignal: abortSignal }); if (abortSignal.aborted) { return; } if (partitionIds.length > 0) { const partitionsToClaim = loadBalancer.loadBalance(this._id, partitionOwnershipMap, partitionIds); if (partitionsToClaim) { for (const partitionToClaim of partitionsToClaim) { let ownershipRequest; if (abandonedMap.has(partitionToClaim)) { ownershipRequest = this._createPartitionOwnershipRequest(abandonedMap, partitionToClaim); } else { ownershipRequest = this._createPartitionOwnershipRequest(partitionOwnershipMap, partitionToClaim); } yield this._claimOwnership(ownershipRequest, abortSignal); } } } } catch (err) { logger.warning(`[${this._id}] An error occured within the EventProcessor loop: ${err}`); logErrorStackTrace(err); yield this._handleSubscriptionError(err); } finally { // sleep for some time, then continue the loop again. logger.verbose(`[${this._id}] Pausing the EventProcessor loop for ${this._loopIntervalInMs} ms.`); // swallow the error since it's fine to exit early from delay yield delayWithoutThrow(this._loopIntervalInMs, abortSignal); } } this._isRunning = false; }); } /** * This is called when there are errors that are not specific to a partition (ex: load balancing) */ _handleSubscriptionError(err) { return __awaiter(this, void 0, void 0, function* () { // filter out any internal "expected" errors if (err.name === "AbortError") { return; } if (this._subscriptionEventHandlers.processError) { try { yield this._subscriptionEventHandlers.processError(err, { fullyQualifiedNamespace: this._eventHubClient.fullyQualifiedNamespace, eventHubName: this._eventHubClient.eventHubName, consumerGroup: this._consumerGroup, partitionId: "", updateCheckpoint: () => __awaiter(this, void 0, void 0, function* () { }) }); } catch (err) { logger.verbose(`[${this._id}] An error was thrown from the user's processError handler: ${err}`); } } }); } /** * Starts the `EventProcessor`. Based on the number of instances of `EventProcessor` that are running for the * same consumer group, the partitions are distributed among these instances to process events. * * For each partition, the user provided `PartitionProcessor` is instantiated. * * Subsequent calls to start will be ignored if this event processor is already running. * Calling `start()` after `stop()` is called will restart this event processor. * * @return {void} */ start() { if (this._isRunning) { logger.verbose(`[${this._id}] Attempted to start an already running EventProcessor.`); return; } this._isRunning = true; this._abortController = new AbortController(); logger.verbose(`[${this._id}] Starting an EventProcessor.`); if (targetWithoutOwnership(this._processingTarget)) { logger.verbose(`[${this._id}] Single partition target: ${this._processingTarget}`); this._loopTask = this._runLoopForSinglePartition(this._processingTarget, this._abortController.signal); } else { logger.verbose(`[${this._id}] Multiple partitions, using load balancer`); this._loopTask = this._runLoopWithLoadBalancing(this._processingTarget, this._abortController.signal); } } isRunning() { return this._isRunning; } /** * Stops processing events for all partitions owned by this event processor. * All `PartitionProcessor` will be shutdown and any open resources will be closed. * * Subsequent calls to stop will be ignored if the event processor is not running. * */ stop() { return __awaiter(this, void 0, void 0, function* () { logger.verbose(`[${this._id}] Stopping an EventProcessor.`); if (this._abortController) { // cancel the event processor loop this._abortController.abort(); } try { // remove all existing pumps yield this._pumpManager.removeAllPumps(CloseReason.Shutdown); // waits for the event processor loop to complete // will complete immediately if _loopTask is undefined if (this._loopTask) { yield this._loopTask; } } catch (err) { logger.verbose(`[${this._id}] An error occured while stopping the EventProcessor: ${err}`); } finally { logger.verbose(`[${this._id}] EventProcessor stopped.`); } if (targetWithoutOwnership(this._processingTarget)) { logger.verbose(`[${this._id}] No partitions owned, skipping abandoning.`); } else { yield this.abandonPartitionOwnerships(); } }); } abandonPartitionOwnerships() { return __awaiter(this, void 0, void 0, function* () { logger.verbose(`[${this._id}] Abandoning owned partitions`); const allOwnerships = yield this._checkpointStore.listOwnership(this._eventHubClient.fullyQualifiedNamespace, this._eventHubClient.eventHubName, this._consumerGroup); const ourOwnerships = allOwnerships.filter((ownership) => ownership.ownerId === this._id); // unclaim any partitions that we currently own for (const ownership of ourOwnerships) { ownership.ownerId = ""; } return this._checkpointStore.claimOwnership(ourOwnerships); }); } } function isAbandoned(ownership) { return ownership.ownerId === ""; } function getStartPosition(partitionIdToClaim, startPositions) { if (startPositions == null) { return latestEventPosition; } if (isEventPosition(startPositions)) { return startPositions; } const startPosition = startPositions[partitionIdToClaim]; if (startPosition == null) { return latestEventPosition; } return startPosition; } function targetWithoutOwnership(target) { return typeof target === "string"; } //# sourceMappingURL=eventProcessor.js.map
51.44385
191
0.625
b4112f7418b31bfd3e9e61a4993a79bf3821436f
5,552
js
JavaScript
df-webhook/src/app.js
crosslibs/export-dialogflow-logs-to-bigquery
88347219264ab985729bac2640ae4eb3b0821ca7
[ "Apache-2.0" ]
4
2019-04-09T10:12:05.000Z
2020-04-19T19:39:52.000Z
df-webhook/src/app.js
crosslibs/export-dialogflow-logs-to-bigquery
88347219264ab985729bac2640ae4eb3b0821ca7
[ "Apache-2.0" ]
1
2021-01-17T15:55:20.000Z
2021-01-17T20:03:12.000Z
df-webhook/src/app.js
crosslibs/export-dialogflow-logs-to-bigquery
88347219264ab985729bac2640ae4eb3b0821ca7
[ "Apache-2.0" ]
2
2020-12-31T16:53:34.000Z
2021-04-08T00:59:50.000Z
/** * Copyright 2019, Chaitanya Prakash N <chaitanyaprakash.n@gmail.com> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; /** * Check that all required parameters are present */ const Utils = require('./utils'); const projectId = process.env.GOOGLE_CLOUD_PROJECT; const DLP = require('@google-cloud/dlp'); const express = require('express'); const app = express(); const bodyParser = require('body-parser'); const FulfillmentError = require('./error'); const port = process.env.PORT || 8080; /** * DLP Configuration */ const dlp = new DLP.DlpServiceClient(); const parent = dlp.projectPath(projectId); const infoTypes = [{name: 'PHONE_NUMBER'}, {name: 'EMAIL_ADDRESS'}, {name: 'PERSON_NAME'}, {name: 'CREDIT_CARD_NUMBER'}]; const customInfoTypes = [{ infoType: { name: 'POLICY_NUMBER', }, regex: { pattern: '[1-9]{3}-[1-9]{5}', }, likelihood: 'POSSIBLE', }]; const deidentifyConfig = { infoTypeTransformations: { transformations: [ { primitiveTransformation: { replaceWithInfoTypeConfig: {}, }, }, ], }, }; const minLikelihood = 'LIKELIHOOD_UNSPECIFIED'; const includeQuote = true; /** * Cloud PubSub Configuration */ const {PubSub} = require('@google-cloud/pubsub'); const pubsub = new PubSub(); const topicName = process.env.TOPIC_NAME; /** * Validates whether the request payload * @param {object} req webhook express request * @throws FulfillmentError if validation fails */ async function validate(req) { // Validating the dialogflow webhook request format if (Utils.isEmptyObject(req.body)) { throw new FulfillmentError('Empty request body', 400); } else if (Utils.isStringEmpty(req.body.responseId) || Utils.isStringEmpty(req.body.session) || Utils.isEmptyObject(req.body.queryResult) || Utils.isStringEmpty(req.body.queryResult.queryText)) { throw new FulfillmentError('Invalid request body', 400); } } /** * Dialogflow fulfillment function * Fulfills the request using custom logic * @param {object} req webhook express request * @param {object} res webhook express response */ function fulfill(req, res) { // Fulfillment logic goes here res.status(200).json({}); } /** * Push the message to pubsub topic * @param {object} conv Conversation object with PII masked */ function pushToPubSubTopic(conv) { console.log(`Pushing message [${conv.responseId}, ${conv.session}]`); const message = { responseId: conv.responseId, session: conv.session, query: conv.queryResult.queryText, intent: { name: (conv.intent ? conv.intent.name : null), displayName: (conv.intent ? conv.intent.displayName : null), }, intentDetectionConfidence: conv.intentDetectionConfidence, userId: (conv.user ? conv.user.userId : null), }; pubsub.topic(topicName) .publish(Buffer.from(JSON.stringify(message))) .then((responses) => { console.log('Successfully published message ' + `[${conv.responseId}, ${conv.session}] to ` + `topic ${topicName}`); }) .catch((err) => { console.error('Error while publishing message ' + `[${conv.responseId}, ${conv.session}] to ` + `topic ${topicName}`); console.error(err); }); } /** * Log dialogflow conversation * @param {object} conv webhook request body */ function log(conv) { // Perform DLP and write to PubSub topic const request = { parent: parent, deidentifyConfig: deidentifyConfig, inspectConfig: { infoTypes: infoTypes, customInfoTypes: customInfoTypes, minLikelihood: minLikelihood, includeQuote: includeQuote, }, item: {value: conv.queryResult.queryText}, }; dlp.deidentifyContent(request) .then((responses) => { console.log('Deidentifying successful: ' + `[${conv.responseId}, ${conv.session}]`); conv.queryResult.queryText = responses[0].item.value; pushToPubSubTopic(conv); }) .catch((err) => { console.error(err); }); } /** * Conversation Interceptor function * Logs the conversation and invokes fulfillment logic * to complete the request. * NOTE: Only user conversations are logged currently. * @param {object} req webhook express request * @param {object} res webhook express response */ function intercept(req, res) { validate(req) .then(() => { log(req.body); fulfill(req, res); }) .catch((err) => { res.status(err.statusCode).json(err); }); } /** * Use body parser for parsing application/json payloads */ app.use(bodyParser.json()); /** * Add POST /fulfillment HTTP method */ app.route('/fulfillment') .post(intercept); /** * Start the HTTP server on the specified port */ const server = app.listen(port, () => { console.log(`Listening on port ${port}`); }); /** * Export express server object for unit tests */ module.exports = server;
27.899497
75
0.654899
b4113a507acddbf9d3e89c7330ec2d9944e1f44a
4,384
js
JavaScript
src/app/controllers/dash.js
gema-arta/grafana
eaa200a766a03fd2411ba8f8cc7b39e8b61421bb
[ "Apache-2.0" ]
1
2015-05-02T00:28:39.000Z
2015-05-02T00:28:39.000Z
src/app/controllers/dash.js
gema-arta/grafana
eaa200a766a03fd2411ba8f8cc7b39e8b61421bb
[ "Apache-2.0" ]
2
2018-08-13T06:46:27.000Z
2018-12-07T04:20:27.000Z
src/app/controllers/dash.js
gema-arta/grafana
eaa200a766a03fd2411ba8f8cc7b39e8b61421bb
[ "Apache-2.0" ]
2
2016-09-05T03:37:36.000Z
2018-06-03T15:13:07.000Z
/** @scratch /index/0 * = Kibana * * // Why can't I have a preamble here? * * == Introduction * * Kibana is an open source (Apache Licensed), browser based analytics and search dashboard for * ElasticSearch. Kibana is a snap to setup and start using. Written entirely in HTML and Javascript * it requires only a plain webserver, Kibana requires no fancy server side components. * Kibana strives to be easy to get started with, while also being flexible and powerful, just like * Elasticsearch. * * include::configuration/config.js.asciidoc[] * * include::panels.asciidoc[] * */ define([ 'angular', 'jquery', 'config', 'underscore', 'services/all', 'services/dashboard/all' ], function (angular, $, config, _) { "use strict"; var module = angular.module('kibana.controllers'); module.controller('DashCtrl', function( $scope, $rootScope, $timeout, ejsResource, dashboard, filterSrv, dashboardKeybindings, alertSrv, panelMove, keyboardManager, grafanaVersion) { $scope.requiredElasticSearchVersion = ">=0.90.3"; $scope.editor = { index: 0 }; $scope.grafanaVersion = grafanaVersion[0] === '@' ? 'master' : grafanaVersion; // For moving stuff around the dashboard. $scope.panelMoveDrop = panelMove.onDrop; $scope.panelMoveStart = panelMove.onStart; $scope.panelMoveStop = panelMove.onStop; $scope.panelMoveOver = panelMove.onOver; $scope.panelMoveOut = panelMove.onOut; $scope.init = function() { $scope.config = config; // Make stuff, including underscore.js available to views $scope._ = _; $scope.dashboard = dashboard; $scope.dashAlerts = alertSrv; $scope.filter = filterSrv; $scope.filter.init(dashboard.current); $rootScope.$on("dashboard-loaded", function(event, dashboard) { $scope.filter.init(dashboard); }); // Clear existing alerts alertSrv.clearAll(); $scope.reset_row(); $scope.ejs = ejsResource(config.elasticsearch, config.elasticsearchBasicAuth); $scope.bindKeyboardShortcuts(); }; $scope.bindKeyboardShortcuts = dashboardKeybindings.shortcuts; $scope.isPanel = function(obj) { if(!_.isNull(obj) && !_.isUndefined(obj) && !_.isUndefined(obj.type)) { return true; } else { return false; } }; $scope.add_row = function(dash, row) { dash.rows.push(row); }; $scope.add_row_default = function() { $scope.reset_row(); $scope.row.title = 'New row'; $scope.add_row(dashboard.current, $scope.row); }; $scope.reset_row = function() { $scope.row = { title: '', height: '250px', editable: true, }; }; $scope.row_style = function(row) { return { 'min-height': row.collapse ? '5px' : row.height }; }; $scope.panel_path =function(type) { if(type) { return 'app/panels/'+type.replace(".","/"); } else { return false; } }; $scope.edit_path = function(type) { var p = $scope.panel_path(type); if(p) { return p+'/editor.html'; } else { return false; } }; $scope.setEditorTabs = function(panelMeta) { $scope.editorTabs = ['General','Panel']; if(!_.isUndefined(panelMeta.editorTabs)) { $scope.editorTabs = _.union($scope.editorTabs,_.pluck(panelMeta.editorTabs,'title')); } return $scope.editorTabs; }; // This is whoafully incomplete, but will do for now $scope.parse_error = function(data) { var _error = data.match("nested: (.*?);"); return _.isNull(_error) ? data : _error[1]; }; $scope.colors = [ "#7EB26D","#EAB839","#6ED0E0","#EF843C","#E24D42","#1F78C1","#BA43A9","#705DA0", //1 "#508642","#CCA300","#447EBC","#C15C17","#890F02","#0A437C","#6D1F62","#584477", //2 "#B7DBAB","#F4D598","#70DBED","#F9BA8F","#F29191","#82B5D8","#E5A8E2","#AEA2E0", //3 "#629E51","#E5AC0E","#64B0C8","#E0752D","#BF1B00","#0A50A1","#962D82","#614D93", //4 "#9AC48A","#F2C96D","#65C5DB","#F9934E","#EA6460","#5195CE","#D683CE","#806EB7", //5 "#3F6833","#967302","#2F575E","#99440A","#58140C","#052B51","#511749","#3F2B5B", //6 "#E0F9D7","#FCEACA","#CFFAFF","#F9E2D2","#FCE2DE","#BADFF4","#F9D9F9","#DEDAF7" //7 ]; $scope.init(); }); });
28.653595
100
0.604471
b41147d9b6834005a5dbddabc69c2280d43b8df0
168
js
JavaScript
lang/JavaScript/flatten-a-list-6.js
ethansaxenian/RosettaDecode
8ea1a42a5f792280b50193ad47545d14ee371fb7
[ "MIT" ]
1
2021-05-05T13:42:20.000Z
2021-05-05T13:42:20.000Z
lang/JavaScript/flatten-a-list-6.js
ethansaxenian/RosettaDecode
8ea1a42a5f792280b50193ad47545d14ee371fb7
[ "MIT" ]
null
null
null
lang/JavaScript/flatten-a-list-6.js
ethansaxenian/RosettaDecode
8ea1a42a5f792280b50193ad47545d14ee371fb7
[ "MIT" ]
null
null
null
// flatten :: NestedList a -> [a] const flatten = t => { const go = x => Array.isArray(x) ? ( x.flatMap(go) ) : x; return go(t); };
18.666667
33
0.434524
b412468072e3a398c7489bd1af2c5dcc2580828d
197
js
JavaScript
server/api/events/routes.js
mikatammi/georap
d9d763481555da6e2c9440012ed38f4c1bbf8d8c
[ "MIT" ]
null
null
null
server/api/events/routes.js
mikatammi/georap
d9d763481555da6e2c9440012ed38f4c1bbf8d8c
[ "MIT" ]
null
null
null
server/api/events/routes.js
mikatammi/georap
d9d763481555da6e2c9440012ed38f4c1bbf8d8c
[ "MIT" ]
null
null
null
/* eslint-disable new-cap */ var handlers = require('./handlers'); var express = require('express'); var router = express.Router(); router.get('/', handlers.getRecent); module.exports = router;
19.7
37
0.690355
b41376b87edec7822cbcc2633f78186647862a3a
372
es6
JavaScript
assets/javascripts/discourse/components/count-i18n.js.es6
vndee/unescohackathon-xixforum
2cdddc619631be40cdbfbcd184e496b79d420d2d
[ "MIT" ]
2
2019-08-19T07:52:37.000Z
2020-01-19T07:22:57.000Z
assets/javascripts/discourse/components/count-i18n.js.es6
vndee/unescohackathon-xixforum
2cdddc619631be40cdbfbcd184e496b79d420d2d
[ "MIT" ]
null
null
null
assets/javascripts/discourse/components/count-i18n.js.es6
vndee/unescohackathon-xixforum
2cdddc619631be40cdbfbcd184e496b79d420d2d
[ "MIT" ]
1
2018-10-14T06:30:10.000Z
2018-10-14T06:30:10.000Z
import { bufferedRender } from "discourse-common/lib/buffered-render"; export default Ember.Component.extend( bufferedRender({ tagName: "span", rerenderTriggers: ["count", "suffix"], buildBuffer(buffer) { buffer.push( I18n.t(this.get("key") + (this.get("suffix") || ""), { count: this.get("count") }) ); } }) );
21.882353
70
0.572581
b41383623bc56790c706a0244ca7d6bbc7b6fead
6,432
js
JavaScript
src/app.js
EnSeven/Game-Engine
1b953b4ed25d607059bbb9de76cd31a55c2cd947
[ "MIT" ]
null
null
null
src/app.js
EnSeven/Game-Engine
1b953b4ed25d607059bbb9de76cd31a55c2cd947
[ "MIT" ]
null
null
null
src/app.js
EnSeven/Game-Engine
1b953b4ed25d607059bbb9de76cd31a55c2cd947
[ "MIT" ]
3
2018-11-27T04:30:49.000Z
2018-11-27T04:32:34.000Z
'use strict'; // --- DEPENDENCIES ------------------------------ require('dotenv').config(); const Game = require('./lib/game-engine.js'); const superagent = require('superagent'); const ioserver = require('http').createServer(8080); const io = require('socket.io')(ioserver); let socketConnections = []; // const Word = require('../wordWizard/Word.js'); // const wordWizard = require('../wordWizard/localServer.js'); // const client = require('../wordWizard/remoteClient.js'); // let GameState = require('../wordWizard/GameState.js'); let getWord = require('../wordWizard/word_logic/getWord.js'); // --- SOCKET IO --------------------------------- // This function holds all emitters and listeners for Socket.IO io.sockets.on('connection', (socket) => { let word; socketConnections.push(socket.id); console.log(socketConnections); socket.on('start', () => { word = getWord(); word.generateLetters(); // console.log(word); socket.emit('connected'); }); // when someone disconnects socket.on('disconnect', () => { socket.removeAllListeners(); console.log(`${socket.id} has left the game`); Game.endSession(); }); // handles logins for new and returning clients. Expected input: (Object) {username: 'username', password: 'password', email: 'email'} socket.on('sign-in', (userObj) => { console.log(userObj); superagent.post(`https://${userObj.username}:${userObj.password}@enseven-api-service.herokuapp.com/signin`) .set('Content-Type', 'application/json') .then(data => { userObj.auth = data.text; socket.emit('signed-in-user', userObj); console.log(`Returning user ${userObj.username} has signed in`); }) .catch(error => { console.log('Error signing in', error); }); }); socket.on('sign-up', (userObj) => { superagent.post(`${process.env.API_URL}/signup`) .send(JSON.stringify(userObj)) .set('Content-Type', 'application/json') .then(data => { console.log(data); userObj.auth = data.text; // console.log(userObj); socket.emit('signed-in-newuser', userObj); console.log(`${userObj.username} has signed up and signed in`); }) .catch(err => console.log(err)); }); // After a client signs in, joins a new game. Waits for two clients before starting the game // Expected input: (String) 'username' socket.on('join', (thisPlayer) => { if (Game.players === 0) { Game.player1 = { username: thisPlayer.username, auth: thisPlayer.auth, player: 'one', didIWin: undefined, }; Game.players++; // console.log('Player One joined: ', Game.player1); socket.emit('player1-joined', Game.player1); } // else if (Game.players === 1 && Game.isThereTwoPlayers === false) { // Game.player2 = { // username: thisPlayer.username, // auth: thisPlayer.auth, // player: 'two', // }; // Game.players++; // // console.log('Player Two joined: ', Game.player2); // // socket.join(`player${Game.player1.username}`); // Game.isThereTwoPlayers = true; // socket.emit('player2-joined', Game.player2); // // io.emit('ready-to-play', 'Game ready to begin!'); // // At this point waiting to hear 'play' emit from two clients // } else { console.log('Something went wrong determining player'); } }); let thisGuess; const getInput = () => { if (word.count === 0 ) { console.log('Out of guesses, game over'); socket.emit('lost'); Game.player1.didIWin = false; __determineWinner(Game.player1); Game.endSession(); } else { if (thisGuess === word.string) { word.count--; } console.log('emitting input request'); console.log('sending word object:', word); socket.emit('input-request', (word)); } }; socket.on('play', () => { getInput(); }); socket.on('input', input => { console.log('applying input'); console.log(input); word.makeGuess(input); thisGuess = word.string; word.string = word.update(); console.log(word.correctWord.toUpperCase(), word.string); if (word.string === word.correctWord.toUpperCase()) { Game.player1.didIWin = true; console.log('Game over'); socket.emit('won'); __determineWinner(Game.player1); Game.endSession(); } else { getInput(); } // console.log(GameState); }); // Listens for quit event from either client during play. Will confirm the quit with both players socket.on('quit-game', () => { // get both players to send quit events let quitCount = 0; socket.emit('confirm-quit'); socket.on('quit-confirmed', () => { quitCount++; }); while(quitCount === 2) { Game.endSession(); socket.emit('end'); socket.removeAllListeners(); quitCount = 0; } socket.emit('end'); }); const __determineWinner = (player) => { console.log(player); if(Game.player1.didIWin === true) { console.log(`${player.username} won, storing results...`); superagent.post(`${process.env.API_URL}/api/v1/singlestat`) .send({name: player.username, win: player.didIWin}) .set('Authorization', `Bearer ${player.auth}`) .then(() => { socket.emit('won'); console.log(`ASYNC: Results saved for ${player.username}`); player.didIWin = undefined; }) .catch(err => console.log(err)); } else if(Game.player1.didIWin === false) { console.log(`${player.username} lost, storing results...`); superagent.post(`${process.env.API_URL}/api/v1/singlestat`) .send({name: player.username, win: player.didIWin}) .set('Authorization', `Bearer ${player.auth}`) .then(() => { console.log(`ASYNC: Results saved for ${player.username}`); player.didIWin = undefined; socket.emit('lost'); }) .catch(err => console.log('3')); } else { console.log('Something went wrong determining the winner:', player); } }; }); let socket; let gameObject; // --- EXPORTS ----------------------------------- const start = (port) => { ioserver.listen(port, () => { console.log('Game Server Listening'); }); }; module.exports = start;
30.923077
137
0.581468
b413c2c029f721f9ba49ca33a29d6d8bf1c2d620
1,057
js
JavaScript
client/app/shared/custom-dropdown/custom-dropdown.component.spec.js
skateman/manageiq-ui-service
07642079c496cb019c9fdf1b138772e56ff8cf60
[ "Apache-2.0" ]
21
2016-10-27T01:15:07.000Z
2019-11-07T15:51:16.000Z
client/app/shared/custom-dropdown/custom-dropdown.component.spec.js
skateman/manageiq-ui-service
07642079c496cb019c9fdf1b138772e56ff8cf60
[ "Apache-2.0" ]
1,474
2016-10-18T15:05:33.000Z
2022-03-29T01:08:54.000Z
client/app/shared/custom-dropdown/custom-dropdown.component.spec.js
skateman/manageiq-ui-service
07642079c496cb019c9fdf1b138772e56ff8cf60
[ "Apache-2.0" ]
93
2016-10-18T15:01:51.000Z
2022-03-30T06:23:26.000Z
/* global $componentController */ /* eslint-disable no-unused-expressions */ describe('Component: customDropdown ', function () { let ctrl let updateSpy beforeEach(function () { module('app.core', 'app.shared') bard.inject('$componentController') ctrl = $componentController('customDropdown', {}, { config: { 'test': 'test' }, items: ['item1', 'item2'], onUpdate: function () {}, menuRight: true }) updateSpy = sinon.stub(ctrl, 'onUpdate').returns(true) }) it('is defined', function () { expect(ctrl).to.exist }) it('should handle changes', () => { ctrl.$onChanges() expect(updateSpy).have.been.calledWith( {$changes: ['item1', 'item2'], $config: {test: 'test'}}) }) it('should handle actions', () => { const options = { isDisabled: false, actionFn: function () {} } const actionFnSpy = sinon.stub(options, 'actionFn').returns(true) ctrl.$onInit() ctrl.handleAction(options) expect(actionFnSpy).to.have.been.called }) })
25.166667
69
0.600757
b414198c512129ec4b71bf9db93073bb9f058b14
1,418
js
JavaScript
app/blog.controller.js
AliaksandrZahorski/RRR_2_BE
0448960ef10a0d5187937411e01b7342614c0d91
[ "MIT" ]
null
null
null
app/blog.controller.js
AliaksandrZahorski/RRR_2_BE
0448960ef10a0d5187937411e01b7342614c0d91
[ "MIT" ]
null
null
null
app/blog.controller.js
AliaksandrZahorski/RRR_2_BE
0448960ef10a0d5187937411e01b7342614c0d91
[ "MIT" ]
null
null
null
let Blog = require('mongoose').model('Blog'); exports.create = async (req, res) => { let blog = new Blog(req.body); try { let b = await blog.save(); res.json({ blog: b }); } catch(err) { res.status(500).json({ error: err }); } }; exports.delete = async (req, res) => { let blog = await Blog.findByIdAndRemove(req.params.blogId); try { if (!blog) { res.status(400).json({ error: 'No blog with the given ID' }); } else { res.json({ blog: blog }); } } catch(err) { err => res.status(500).json({ error: err }) } }; exports.read = async (req, res) => { try { let blog = await Blog.findById(req.params.blogId).exec(); if (!blog) { res.status(400).json({ error: 'No blog with the given ID' }); } else { res.json({ blog: blog }); } } catch(err) { res.status(500).json({ error: err }); } }; exports.readAll = async (req, res) => { try { let blogs = await Blog.find({}).exec(); res.json({ blogs: blogs }); } catch(err) { res.status(500).json({ error: err }) } }; exports.update = async (req, res) => { try { let blog = await Blog.findByIdAndUpdate(req.params.blogId, req.body, { new: true }); if (!blog) { res.status(400).json({ error: 'No blog with the given ID' }); } else { res.json({ blog: blog }); } } catch(err) { err => res.status(500).json({ error: err }) } };
22.15625
88
0.545839
b4142be8dea37b325d5b6efbf62eb2990bc65de1
69,197
js
JavaScript
js/history/easydlg_1735_49.js
keejelo/EasyDialogBox
f380aaa76d3f6f2b12754a62a454fce17f2f0e2e
[ "MIT" ]
3
2020-03-14T18:04:26.000Z
2020-08-28T18:10:36.000Z
js/history/easydlg_1735_49.js
keejelo/EasyDialogBox
f380aaa76d3f6f2b12754a62a454fce17f2f0e2e
[ "MIT" ]
8
2020-08-17T07:32:18.000Z
2021-07-18T11:24:32.000Z
js/history/easydlg_1735_49.js
keejelo/EasyDialogBox
f380aaa76d3f6f2b12754a62a454fce17f2f0e2e
[ "MIT" ]
null
null
null
/***************************************************************************************************************** * EasyDialogBox * Version: 1.735.49 * Created by: keejelo * Year: 2020-2021 * GitHub: https://github.com/keejelo/EasyDialogBox * Comment: Crossbrowser, legacy browser support as much as possible. ******************************************************************************************************************/ //----------------------------------------------------------------------------------------------------------------- // ** EasyDialogBox Object (module) //----------------------------------------------------------------------------------------------------------------- var EasyDialogBox = (function() { 'use strict'; // ** Debug: true/false (outputs debug-messages to console) var DEBUG = true; // ** Buttontext (custom your own text if you want) var _btnTextClose = 'Close'; // Close var _btnTextYes = 'Yes'; // Yes var _btnTextNo = 'No'; // No var _btnTextOk = 'OK'; // OK var _btnTextCancel = 'Cancel'; // Cancel // ** Button return codes, constant literals var CLOSE = 0; var YES = 1; var NO = 2; var OK = 3; var CANCEL = 4; // ** Dialogbox types and flags, can be used separately or in combination separated by a space var _strBoxTypeList = ['dlg','dlg-close','dlg-prompt','dlg-yes','dlg-no','dlg-yes-no','dlg-ok','dlg-cancel','dlg-ok-cancel', 'dlg-disable-heading','dlg-disable-footer','dlg-disable-btns','dlg-disable-overlay','dlg-disable-drag', 'dlg-disable-esc','dlg-disable-clickout', 'dlg-info','dlg-question','dlg-error','dlg-success','dlg-exclamation', 'dlg-rounded','dlg-shadow']; // ** Array that holds all created boxobjects, so we can get to them later if we need to, delete them etc. var _boxObj = []; // ** Variable that holds the original padding-right value of body element, // used to prevent content shift when scrollbar hides/shows. var _orgBodyPaddingRight = 0; // ** Flag that indicates if window was resized var _bResized = false; // ** Add "forEach" support to IE9-11 if(window.NodeList && !NodeList.prototype.forEach) { NodeList.prototype.forEach = Array.prototype.forEach; } // ** Debug-logger var _log = function(str) { if(DEBUG) { return console.log(str); } }; // ** Convert string to integer (decimal base) var _s2i = function(str) { return parseInt(str, 10); }; // ** Trim leading and trailing whitespace var _trim = function(str) { return str.replace(/^\s+|\s+$/g,''); }; // ** Add event listener (xbrowser-legacy) var _attachEventListener = function(target, eventType, functionRef, capture) { if(typeof target.addEventListener !== 'undefined') { target.addEventListener(eventType, functionRef, capture); } else if(typeof target.attachEvent !== 'undefined') { var functionString = eventType + functionRef; target['e' + functionString] = functionRef; target[functionString] = function(event) { if(typeof event === 'undefined') { event = window.event; } target['e' + functionString](event); }; target.attachEvent('on' + eventType, target[functionString]); } else { eventType = 'on' + eventType; if(typeof target[eventType] === 'function') { var oldListener = target[eventType]; target[eventType] = function() { oldListener(); return functionRef(); }; } else { target[eventType] = functionRef; } } }; // ** END: Add event listener (xbrowser-legacy) // ** Remove event listener (xbrowser-legacy) var _detachEventListener = function(target, eventType, functionRef, capture) { if(typeof target.removeEventListener !== 'undefined') { target.removeEventListener(eventType, functionRef, capture); } else if(typeof target.detachEvent !== 'undefined') { var functionString = eventType + functionRef; target.detachEvent('on' + eventType, target[functionString]); target['e' + functionString] = null; target[functionString] = null; } else { target['on' + eventType] = null; } }; // ** Stop event from bubbling (xbrowser-legacy) var _stopEvent = function(event) { if(typeof event.stopPropagation !== 'undefined') { event.stopPropagation(); } else { event.cancelBubble = true; } }; // ** Stop default event action (xbrowser-legacy) var _stopDefault = function(event) { if(typeof event.preventDefault !== 'undefined') { event.preventDefault(); } else { event.returnValue = false; } }; // ** Check if element contains specific class var _hasClass = function(el, classValue) { var pattern = new RegExp('(^|\\s)' + classValue + '(\\s|$)'); return pattern.test(el.className); // boolean }; // ** Add class to element var _addClass = function(el, classValue) { if(!(_hasClass(el, classValue))) { if(el.className === '') { el.className = classValue; } else { el.className += ' ' + classValue; } } }; // ** Remove class from element var _removeClass = function(el, classValue) { if(_hasClass(el, classValue)) { var reg = new RegExp('(^|\\s)' + classValue + '(\\s|$)'); var newClass = el.className.replace(reg, ' '); el.className = newClass.replace(/^\s+|\s+$/g,''); // remove leading and trailing whitespace } }; // ** Get object from array by using id var _getObjFromId = function(arr, strId) { for(var i = 0; i < arr.length; i++) { if(arr[i].id === strId) { return arr[i]; } } return null; // if no object found }; // ** Check if array matches ALL test-values in supplied string/array. Returns true/false var _matchAll = function(arr, str, exp, sep) { // ** Parameters // @ arr = array that holds the values we want to match against // @ str = string/array that we want to match with the above array // @ exp = true = split string into array, using separator, // false (or omitted) = do not split, treat string as one value. // @ sep = character that is used as a string splitter, for instance a space ' ' or comma ',' // or other character enclosed in single quotes. If omitted then a space is used as separator, ' ' var val = str; if(exp === true) { if(typeof sep === 'undefined') { sep = ' '; // default: space } val = str.split(sep); } var passed = 0; for(var i = 0; i < val.length; i++) { for(var j = 0; j < arr.length; j++) { if(arr[j] === val[i]) { passed++; } } } // ** Ensure that ALL values matched, else return failure. // Check if numbers tested equals the numbers of items that passed. if(val.length === passed) { return true; } return false; }; // ** END: Check if array matches ALL test-values in supplied string/array. Returns true/false // ** Adjust element size and position according to window size (responsive) var _adjustElSizePos = function(id) { var el = document.getElementById(id); if(el) { // ** If height is larger or equal to window height, disable vertical alignment, // position to: top (try to prevent out of view) // ** Get window height (crossbrowser) var winHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight; if( _s2i(el.offsetHeight + el.customPosY) >= winHeight ) { // ** Try to retain responsiveness by setting default values el.style.top = '0'; el.style.marginTop = '0'; el.style.marginBottom = '0'; //el.style.height = ''; // <-- keep disabled, was making box height flicker in size //el.style.maxHeight = ''; // <-- keep disabled, was making box height flicker in size // ** Remove borders top and bottom el.style.borderTopWidth = '0'; el.style.borderBottomWidth = '0'; // ** Reset box pos Y since it went too far and triggered responsive-mode el.customPosY = 0; } // ** Else if window height larger than dialogbox height, set dialogbox position free // If no custom values are set, then center dialog vertically else { if(!el.customPosY) { el.style.top = ( (winHeight / 2) - (el.offsetHeight / 2) ) + 'px'; } else { el.style.top = el.customPosY + 'px'; } if(el.customHeight) { el.style.height = el.customHeight + 'px'; } el.style.borderTopWidth = ''; el.style.borderBottomWidth = ''; } // ** If width is larger or equal to window width, disable horizontal alignment, // position to: left (try to prevent out of view) // ** Get window width (crossbrowser) var winWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth; var overlap = 40; // 40, value is used to help width-detection if( _s2i(el.offsetWidth + el.customPosX + overlap) >= winWidth ) // Seem to work OK { // ** Try to retain responsiveness by setting default values el.style.left = '0'; el.style.marginLeft = '0'; el.style.marginRight = '0'; //el.style.width = ''; // <-- keep disabled, was making box width flicker in size //el.style.maxWidth = ''; // <-- keep disabled, was making box width flicker in size // ** Remove borders left and right (helps to prevent horizontal scrollbar) el.style.borderLeftWidth = '0'; el.style.borderRightWidth = '0'; // ** Reset box pos X since it went too far and triggered responsive-mode el.customPosX = 0; } // ** Else if window width larger than dialogbox width, let dialogbox free // If no custom values are set, then center dialog horizontally else { if(!el.customPosX) { el.style.left = ( (winWidth / 2) - (el.offsetWidth / 2) ) + 'px'; } else { el.style.left = el.customPosX + 'px'; } if(el.customWidth) { el.style.maxWidth = el.customWidth + 'px'; } el.style.borderLeftWidth = ''; el.style.borderRightWidth = ''; } } // ** TODO: // If custom position and dlg-disable-drag is set, // then set dialog back to its custom pos if window // is larger than dialog after being resized, // and not just position it in center of window. // Set and get custom values from object and not element (?) }; // ** END: Adjust element size and position according to window size // ** Shorthand for getting elements inside the box and the box element itself var _getEl = function(objId, str) { if(str === undefined || typeof str === 'undefined' || str === '' || str === 0 || str === null) { return document.getElementById(objId + '_1'); } // ** Clean string before working with it, trim leading and trailing spaces str = _trim(str); // ** If string contains '#' (hash) if(str.indexOf('#') !== -1) { // ** If string contains ' ' (space) or multiple selector-chars if(str.indexOf(' ') !== -1 || str.indexOf(',') !== -1 || str.indexOf('>') !== -1) { // ** The below assumes that string starts with hash '#' and that spaces are used to separate each selector item var idPart = str.split(' ')[0]; // Get first part of string before first space ' ' str = str.replace(idPart, ''); // Get second half of string by removing '#idPart' idPart = idPart.replace(',', ''); // Remove char from string (if present) idPart = idPart.replace('>', ''); // Remove char from string (if present) idPart = idPart.replace(':', ''); // Remove char from string (if present) str = _trim(str); // Trim string of leading and trailing spaces (again, just in case) var a = document.querySelector(idPart); var aa = document.querySelectorAll(idPart + ' ' + str); var b = document.querySelector(idPart + '_0_1'); var bb = document.querySelectorAll(idPart + '_0_1 ' + str); // ** Check if element exist. If match is not found, try matching dialogbox itself if(a) { if(aa.length > 0) { return aa; } } else if(b) { if(bb.length > 0) { return bb; } } } else { return document.querySelector(str); } } // ** Else if string do NOT contain '#' (hash), search for elements inside dialogbox else { var c = document.getElementById(objId); if(c) { var cc = c.querySelectorAll(str) if(cc) { return cc; } } }; _log('DEBUG: _getEl(): ' + str + ' cannot be found, return: null'); return null; }; // ** END: Shorthand for getting elements inside and the dialog element itself // ** Hide scrollbar while retaining padding var _scrollBarFix = function() { // ** Get body element var body = document.querySelector('body'); // ** If already has class this means it's already applied, then just return back if(_hasClass(body, 'dlg-stop-scrolling')) { return; } // ** Store the original padding-right value _orgBodyPaddingRight = window.getComputedStyle(body, null).getPropertyValue('padding-right'); // ** Convert from string to integer (remove 'px' postfix and return value as integer) _orgBodyPaddingRight = _s2i(_orgBodyPaddingRight); // ** Get width of body before removing scrollbar var w1 = body.offsetWidth; // ** Stop scrolling of background content (body) when dialogbox is in view, removes scrollbar _addClass(body, 'dlg-stop-scrolling'); // ** Get width of body after removing scrollbar var w2 = body.offsetWidth; // ** Get width-difference var w3 = w2 - w1; // ** If conditions are true: add both padding-right values, if(typeof _orgBodyPaddingRight === 'number' && _orgBodyPaddingRight > 0) { w3 += _s2i(_orgBodyPaddingRight); } // ** Apply width-difference as padding-right to body, substitute for scrollbar, // can prevent contentshift if content is centered when scrollbar disappears. body.setAttribute('style','padding-right:' + w3 + 'px;'); }; // ** END: Hide scrollbar while retaining padding // ** Show dialog box var _show = function(objId) { // ** Get object var obj = _getObjFromId(_boxObj, objId); //if(obj === null) //{ // _log('DEBUG: show(): error, object do not exist'); // return false; //} // ** Check if box exist and is hidden if(obj !== null && obj.bHidden === true) { // ** Hide scrollbar _scrollBarFix(); // ** Get element (dialog surface) var dlg = document.getElementById(obj.id); // ** Make it draggable, unless flag is set if(!(_hasClass(dlg, 'dlg-disable-drag'))) { _drag.init(obj.id + '_1'); } // ** Show the hidden dialog (overlay and boxsurface) dlg.style.display = 'block'; // ** Get the dialogbox itself var box = document.getElementById(obj.id + '_1'); // ** Prepare custom values, default set to: 0 box.customPosX = 0; box.customPosY = 0; box.customHeight = 0; box.customWidth = 0; //_adjustElSizePos(obj.id + '_1'); // <-- not needed it seems //_log('obj.x:' + obj.x) // ** Check if position is set, if true (bigger than 0) then change position, else default value used if(obj.x) { box.style.left = _s2i(obj.x) + 'px'; box.customPosX = _s2i(obj.x); } // ** Check if position is set, if true then change position, else default value used if(obj.y) { box.style.top = _s2i(obj.y) + 'px'; box.customPosY = _s2i(obj.y); } // ** END: Check if position is set // ** Check if size is set, if true then change size, else default value used if(obj.w) { box.style.maxWidth = _s2i(obj.w) + 'px'; box.customWidth = _s2i(obj.w); } // ** Check if size is set, if true then change size, else default value used if(obj.h) { //box.style.height = _s2i(obj.h) + 'px'; // disabled, only set custom //box.style.maxHeight = _s2i(obj.h) + 'px'; // disabled, only set custom box.customHeight = _s2i(obj.h); } // ** END: Check if size is set // ** If custom height then adjust if(box.customHeight) { // ** Get message element var message = box.querySelector('#' + box.id + ' .dlg-message'); // ** Set default extra height value var h = 115; // ** If icon is used, set a different height value if(_hasClass(dlg, 'dlg-info') || _hasClass(dlg, 'dlg-question') || _hasClass(dlg, 'dlg-error') || _hasClass(dlg, 'dlg-success') || _hasClass(dlg, 'dlg-exclamation') ) { h = 100; } // ** Adjust custom height message.style.height = _s2i(obj.h - h) + 'px'; } // ** END: If custom height then adjust // ** Show the dialog box itself, set flag, run on-func box.style.visibility = 'visible'; obj.bVisible = true; obj.onShow(); // ** Position box in viewport (defaults to center if no custom position has been set, or no moving has occurred) _adjustElSizePos(obj.id + '_1'); // ** Position box in viewport (default: center) // <-- disabled, we use it like above instead, always execute it //if(_bResized) //<-- disabled // <-- disabled, we use it like above instead, always execute it //{ // _adjustElSizePos(obj.id + '_1'); //} _log('DEBUG: show(): executed'); //return true; // ** Return object return obj; } // ** Return fail _log('DEBUG: show(): error, object do not exist'); return false; }; // ** END: Show dialog box // ** Hide dialog box var _hide = function(objId, param) { var dlg = document.getElementById(objId); var box = document.getElementById(objId + '_1'); // ** Hide the background overlay and the box if(dlg && box) { dlg.style.display = 'none'; box.style.visibility = 'hidden'; } // ** Get the object stored in the array var obj = _getObjFromId(_boxObj, objId); // ** Set hidden flags (do we really need both variables? can code be improved?) obj.bHidden = true; obj.bVisible = false; // ** Get body element, reset values, restore scrolling var body = document.querySelector('body'); _removeClass(body, 'dlg-stop-scrolling'); body.setAttribute('style', 'padding-right:' + _s2i(_orgBodyPaddingRight) + 'px;'); // ** Update position (if moved/custom pos) // ** ALL dialogboxes depends on this to remember last position if(obj.x !== null) { obj.x = _s2i(box.style.left); } if(obj.y !== null) { obj.y = _s2i(box.style.top); } // ** END: Update position (if moved/custom pos) // ** Run onHide function if param string do NOT match if(param !== 'doNotExecuteOnHide') { obj.onHide(); } // ** Reset sizing flag _bResized = false; // <-- do we need this variable? // ** Return object return obj; }; // ** END: Hide dialog box // ** Close and destroy dialog box var _destroy = function(objId) { var success = false; // set default: false // ** Get body element, reset values, restore scrolling var body = document.querySelector('body'); _removeClass(body, 'dlg-stop-scrolling'); body.setAttribute('style', 'padding-right:' + _s2i(_orgBodyPaddingRight) + 'px;'); // ** Get the dlg element var dlg = document.getElementById(objId); // ** Hide it visually if(dlg) { dlg.style.display = 'none'; } // ** If promptbox was created, remove eventlisteners if(dlg) { var pBox = dlg.querySelectorAll('.dlg-input-field'); if(pBox.length > 0) { pBox[0].onkeyup = null; pBox[0].onchange = null; } } // ** Remove dialogbox object, reset values if(dlg) { // ** Remove it from DOM dlg.parentNode.removeChild(dlg); // ** Get the object stored in the objectarray (memory) var obj = _getObjFromId(_boxObj, objId); // ** Run onDestroy function obj.onDestroy(); // ** Flag that the box as no longer in DOM obj.bExistInDOM = false; // ** Flag that the box is no longer visible (this can be useful if keeping box alive) obj.bVisible = false; // ** Remove object from array var index = _boxObj.indexOf(obj); if(index > -1) { setTimeout(function() { var wasDeleted = _boxObj.splice(index, 1); if(wasDeleted.length === 1) { success = true; _log('DEBUG: destroy(): object deleted from object array'); } else { success = false; _log('DEBUG: destroy(): Error, object NOT deleted from object array'); } }, 10); } else { _log('DEBUG: destroy(): Error, object not found in array'); success = false; } } // ** Return result return success; }; // ** END: Close and destroy dialog box // ** Create dialogbox and insert it into DOM var _create = function(strId, strTypeClass, strTitle, strMessage, fnCallback, x, y, w, h) { // ** Check if object already exist, if so return that object instead of creating a new var existingObj = _getObjFromId(_boxObj, strId + '_0'); if(existingObj) { _log('DEBUG: create(): new object not created. An object with same ID already exist. Existing object returned'); return existingObj; } var matched = _matchAll(_strBoxTypeList, strTypeClass, true); // ** Check if valid types if(matched === true) { // ** Check if id is set, if not, then create a new random string to use as id if(strId === '' || typeof strId === 'undefined' || strId === null || strId === 0) { // ** Create a unique string for the 'id' strId = 'a'; // start with letter, else selector is not valid, throws error, was causing bug. strId += Math.random().toString(36).substr(2,9); } // ** Add token to object id (so we dont mix up id's, avoiding parent child mismatch) strId += '_0'; // ** Check if value is set, if not set it to: false if(typeof fnCallback === 'undefined') { fnCallback = false; } // ** Begin creating the object var obj = { // ** Properties id : strId, strTypeClass : strTypeClass, strTitle : strTitle, strMessage : strMessage, strInput : '', nRetCode : -1, x : x, y : y, w : w, h : h, bVisible : false, bExistInDOM : false, bHidden : false, el : null, // ** Callback callback : function(a,b) { try { if(typeof a === 'undefined') { a = this.nRetCode; } if(typeof b === 'undefined') { b = this.strInput; } // ** Check which kind of box and if it has a callback function if(typeof window[fnCallback] === 'function') { // ** Execute function (pre-written HTML boxes(?)) window[fnCallback](a,b); } else if(typeof fnCallback === 'function') { // ** Execute function (script-created boxes(?)) fnCallback(a,b); } else if(fnCallback === false || fnCallback === 0) { return false; } else { _log('\n\nDEBUG: typeof fnCallback = ' + typeof fnCallback + ' and not a function.'); _log(' Scope? Possible solution can be to use "hoisting".'); _log(' Try to use "var callbackFuncName = function(a,b){}" instead of "let callbackFuncName = function(a,b){}"'); _log(' ..or declare the callback function before the module "EasyDialogBox" is initialized'); _log(' If the dialogbox do not use a callback function, you can ignore the above messages.\n\n'); } } catch(err) { _log('DEBUG: fnCallback(): error: ' + err); } }, // ** Show show : function() { return _show(this.id); }, // ** Hide hide : function(param) { return _hide(this.id, param); }, // ** Destroy destroy : function() { return _destroy(this.id); }, // ** onCreate onCreate : function() { _log('DEBUG: Default "obj.onCreate()" function fired. Override this by creating your own.'); }, // ** onShow onShow : function() { _log('DEBUG: Default "obj.onShow()" function fired. Override this by creating your own.'); }, // ** onHide onHide : function() { _log('DEBUG: Default "obj.onHide()" function fired. Override this by creating your own.'); }, // ** onClose onClose : function() { _log('DEBUG: Default "obj.onClose()" function fired. Override this by creating your own.'); }, // ** onDestroy onDestroy : function() { _log('DEBUG: Default "obj.onDestroy()" function fired. Override this by creating your own.'); }, // ** Shorthand for getting element $ : function(str) { return _getEl(this.id, str); }, // ** Set border color colorBorder : function(color) { _getEl(this.id).style.borderColor = color; return this; }, // ** Set heading backgroundcolor colorHeading : function(color) { _getEl(this.id, '#' + this.id + '_1_heading').style.backgroundColor = color; return this; }, // ** Set width width : function(n) { this.w = _s2i(n); //_getEl(this.id).style.width = this.w + 'px'; // Disabled: breaks "Responsiveness" (triggers horizontal scroll) _getEl(this.id).style.maxWidth = this.w + 'px'; return this; }, // ** Set height height : function(n) { this.h = _s2i(n); _getEl(this.id).style.height = this.h + 'px'; _getEl(this.id).style.maxHeight = this.h + 'px'; // ** Get message element var message = _getEl(this.id, '.dlg-message')[0]; // ** Set default extra height value var h = 115; // ** If icon is used, set a different height value var dlg = _getEl(this.id); if(_hasClass(dlg, 'dlg-info') || _hasClass(dlg, 'dlg-question') || _hasClass(dlg, 'dlg-error') || _hasClass(dlg, 'dlg-success') || _hasClass(dlg, 'dlg-exclamation') ) { h = 100; } // ** Adjust custom height message.style.height = _s2i(this.h - h) + 'px'; return this; }, // ** Set position X (left) xPos : function(n) { this.x = _s2i(n); _getEl(this.id).style.left = this.x + 'px'; return this; }, // ** Set position Y (top) yPos : function(n) { this.y = _s2i(n); _getEl(this.id).style.top = this.y + 'px'; return this; }, // ** Center dialogbox in window center : function() { var winWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth; var winHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight; var el = _getEl(this.id); el.style.left = ( (winWidth / 2) - (el.offsetWidth / 2) ) + 'px'; el.style.top = ( (winHeight / 2) - (el.offsetHeight / 2) ) + 'px'; return this; } } _boxObj.push(obj); // insert object into array of objects // ** END: creating the object //--------------------------------------------------------------------- // ** Create DOM element //--------------------------------------------------------------------- // ** Get object from id, reuse same 'obj' variable as defined above obj = _getObjFromId(_boxObj, strId); // ** Fix for pre-written HTML boxes: add '_0' to id before getting object if(obj === null) { strId += '_0'; obj = _getObjFromId(_boxObj, strId); } // ** Get body element var body = document.querySelector('body'); // ** Create dialog surface and insert into parent element (body) var dlg = document.createElement('div'); dlg.setAttribute('id', obj.id); dlg.setAttribute('class', obj.strTypeClass); body.appendChild(dlg); // ** Reset value matched = false; if(dlg) { matched = _matchAll(_strBoxTypeList, obj.strTypeClass, true); } // ** Check if element with the id exist in DOM, and valid dlg-types if( dlg && (matched === true) ) { // ** Show the backdrop overlay, and the dialogbox eventually dlg.style.display = 'block'; // Must be here or else can cause elements size and pos not detected, // and then dynamic values and position do not work as we want. // ** Create the box (the dialogbox itself) var box = document.createElement('div'); box.setAttribute('id', obj.id + '_1'); box.setAttribute('class','dlg-box'); // ** Need to have this here (used for pre-written HTML boxes) // ** Prepare custom values, default set to: 0 box.customPosX = 0; box.customPosY = 0; box.customHeight = 0; box.customWidth = 0; // ** Maybe change above default values to: -1 // so user can set box to x=0,y=0 instead of x=1,y=1 to specify upper left position // And check for "value > -1" in below "if else" instead of "true/false" // ** Check if position is set, if true (bigger than 0) then change position, else default value used if(obj.x) { box.style.left = _s2i(obj.x) + 'px'; box.customPosX = _s2i(obj.x); } // ** Check if position is set, if true then change position, else default value used if(obj.y) { box.style.top = _s2i(obj.y) + 'px'; box.customPosY = _s2i(obj.y); } // ** END: Check if position is set // ** Check if size is set, if true then change size, else default value used if(obj.w) { box.style.maxWidth = _s2i(obj.w) + 'px'; box.customWidth = _s2i(obj.w); } // ** Check if size is set, if true then change size, else default value used if(obj.h) { box.style.height = _s2i(obj.h) + 'px'; box.customHeight = _s2i(obj.h); } // ** END: Check if size is set // ** END: Need to have this here (used for pre-written HTML boxes) // ** Add element to DOM dlg.appendChild(box); // ** Add extra styles if flags are set if(_hasClass(dlg, 'dlg-rounded')) { _addClass(box, 'dlg-rounded'); } if(_hasClass(dlg, 'dlg-shadow')) { _addClass(box, 'dlg-shadow'); } // ** Create heading if disable-flag is NOT set if(!(_hasClass(dlg, 'dlg-disable-heading'))) { // ** Create heading var heading = document.createElement('div'); heading.setAttribute('id', obj.id + '_1_heading'); heading.setAttribute('class','dlg-heading'); box.appendChild(heading); // ** Create [X] close button var closeX = document.createElement('span'); closeX.setAttribute('class','dlg-close-x'); //var closeText = document.createTextNode('\u00D7'); // u00D7 = unicode X //closeX.appendChild(closeText); closeX.innerHTML = '&#215;'; // using HTML entity instead, maybe avoid the need to specify unicode charset for javascript ? heading.appendChild(closeX); // ** Create title (here because of z-index) var titleText = document.createTextNode(obj.strTitle); heading.appendChild(titleText); } // ** Create message var message = document.createElement('div'); // ** Prepare reference to inner boxes (used if icon is set) var leftbox = null; var rightbox = null; // ** Check if icon should be displayed if(_hasClass(dlg, 'dlg-info') || _hasClass(dlg, 'dlg-question') || _hasClass(dlg, 'dlg-error') || _hasClass(dlg, 'dlg-success') || _hasClass(dlg, 'dlg-exclamation') ) { message.setAttribute('class','dlg-message dlg-flex-container'); // ** If custom height then adjust if(box.customHeight) { message.style.height = _s2i(obj.h - 101) + 'px'; } // ** Create left box leftbox = document.createElement('div'); leftbox.setAttribute('class','dlg-flexbox-left'); // ** Check which icon to display if(_hasClass(dlg, 'dlg-info')) { leftbox.innerHTML = '<div class="dlg-symbol dlg-icon-info"></div>'; } else if(_hasClass(dlg, 'dlg-question')) { leftbox.innerHTML = '<div class="dlg-symbol dlg-icon-question"></div>'; } else if(_hasClass(dlg, 'dlg-error')) { leftbox.innerHTML = '<div class="dlg-symbol dlg-icon-error"></div>'; } else if(_hasClass(dlg, 'dlg-success')) { leftbox.innerHTML = '<div class="dlg-symbol dlg-icon-success"></div>'; } else if(_hasClass(dlg, 'dlg-exclamation')) { leftbox.innerHTML = '<div class="dlg-symbol dlg-icon-excl"></div>'; } // ** Insert it into parent div message.appendChild(leftbox); // ** Create right box rightbox = document.createElement('div'); rightbox.setAttribute('class','dlg-flexbox-right'); rightbox.innerHTML = obj.strMessage; // ** Insert it into parent div message.appendChild(rightbox); } else { message.setAttribute('class','dlg-message'); message.innerHTML = obj.strMessage; // ** If custom height then adjust if(box.customHeight) { message.style.height = _s2i(obj.h - 130) + 'px'; } } box.appendChild(message); // ** Create prompt box (input + OK + Cancel) if(_hasClass(dlg, 'dlg-prompt')) { var inputbox = document.createElement('div'); inputbox.setAttribute('class', 'dlg-input'); if(_hasClass(message, 'dlg-flex-container')) { rightbox.appendChild(inputbox); } else { message.appendChild(inputbox); } var input = document.createElement('input'); input.setAttribute('class', 'dlg-input-field'); input.setAttribute('type', 'text'); input.setAttribute('value', obj.strInput); inputbox.appendChild(input); // ** Add buttons if not already stated in class if(!(_hasClass(dlg, 'dlg-ok-cancel'))) { _addClass(dlg, 'dlg-ok-cancel'); } } // ** Create footer and buttons // ** If "dlg-disable-footer" is specified in class then do not create footer or any buttons if(!(_hasClass(dlg, 'dlg-disable-footer'))) { // ** Create footer var footer = document.createElement('div'); footer.setAttribute('class','dlg-footer'); box.appendChild(footer); // ** If "dlg-disable-btns" is NOT specified in class, then make buttons if(!(_hasClass(dlg, 'dlg-disable-btns'))) { // ** If "Yes" button is specified in class if(_hasClass(dlg, 'dlg-yes') || _hasClass(dlg, 'dlg-yes-no') ) { // ** Create button var yesBtn = document.createElement('button'); yesBtn.setAttribute('class','dlg-yes-btn'); var yesBtnText = document.createTextNode(_btnTextYes); yesBtn.appendChild(yesBtnText); footer.appendChild(yesBtn); } // ** If "No" button is specified in class if(_hasClass(dlg, 'dlg-no') || _hasClass(dlg, 'dlg-yes-no') ) { // ** Create button var noBtn = document.createElement('button'); noBtn.setAttribute('class','dlg-no-btn'); var noBtnText = document.createTextNode(_btnTextNo); noBtn.appendChild(noBtnText); footer.appendChild(noBtn); } // ** If "OK" button is specified in class if(_hasClass(dlg, 'dlg-ok') || _hasClass(dlg, 'dlg-ok-cancel') ) { // ** Create button var okBtn = document.createElement('button'); okBtn.setAttribute('class','dlg-ok-btn'); var okBtnText = document.createTextNode(_btnTextOk); okBtn.appendChild(okBtnText); footer.appendChild(okBtn); } // ** If "Cancel" button is specified in class if(_hasClass(dlg, 'dlg-cancel') || _hasClass(dlg, 'dlg-ok-cancel') ) { // ** Create button var cancelBtn = document.createElement('button'); cancelBtn.setAttribute('class','dlg-cancel-btn'); var cancelBtnText = document.createTextNode(_btnTextCancel); cancelBtn.appendChild(cancelBtnText); footer.appendChild(cancelBtn); } // ** If "dlg" or "Close" button is specified in class if(_hasClass(dlg, 'dlg-close') // <-- need to be first || _hasClass(dlg, 'dlg') ) { // ** Create button var closeBtn = document.createElement('button'); closeBtn.setAttribute('class','dlg-close-btn'); var closeBtnText = document.createTextNode(_btnTextClose); closeBtn.appendChild(closeBtnText); footer.appendChild(closeBtn); } } } // ** END: Create footer and buttons //--------------------------------------------------------------------- // ** Create event-listeners //--------------------------------------------------------------------- // ** Window resize _attachEventListener(window, 'resize', function WinResize() { _bResized = true; if(obj.bVisible) { _adjustElSizePos(obj.id + '_1'); } }, false); // ** END: Window resize // ** User clicks the [X] button var xCloseDialog = dlg.querySelector('.dlg-close-x'); if(xCloseDialog) { _attachEventListener(xCloseDialog, 'click', function XCloseClick() { // ** Remove eventlistener // ** Disabled for now, keeping eventlisteners since we "hide" not "destroy" //_detachEventListener(xCloseDialog, 'click', XCloseClick, false); // ** Close dialogbox, reset values, clean up //obj.destroy(); // changed from "destroy" to "hiding", keep the dialogbox in DOM obj.hide('doNotExecuteOnHide'); // ** Callback, return code: CLOSE obj.callback(CLOSE); obj.nRetCode = CLOSE; // ** Run onClose function obj.onClose(); }, false); } // ** END: [X] button click handler // ** User clicks the CLOSE button var btnCloseDialog = dlg.querySelector('.dlg-close-btn'); if(btnCloseDialog) { _attachEventListener(btnCloseDialog, 'click', function BtnCloseClick() { // ** Remove eventlistener // ** Disabled for now, keeping eventlisteners since we "hide" not "destroy" //_detachEventListener(btnCloseDialog, 'click', BtnCloseClick, false); // ** Close dialogbox, reset values, clean up //obj.destroy(); // changed from "destroy" to "hiding", keep the dialogbox in DOM obj.hide('doNotExecuteOnHide'); // ** Callback, return code: CLOSE obj.callback(CLOSE); obj.nRetCode = CLOSE; // ** Run onClose function obj.onClose(); }, false); } // ** END: CLOSE button click handler // ** User clicks anywhere outside of the dialogbox if(!(_hasClass(dlg, 'dlg-disable-clickout'))) { _attachEventListener(window, 'click', function WinCloseClick(evt) { // ** Get/set event variable evt = evt || event || window.event; if(evt.target === dlg) { // ** Remove eventlistener // ** Disabled for now, keeping eventlisteners since we "hide" not "destroy" //_detachEventListener(window, 'click', WinCloseClick, false); // ** Close dialogbox, reset values, clean up //obj.destroy(); // Changed from "destroy" to "hiding", keep the dialogbox in DOM obj.hide('doNotExecuteOnHide'); // ** Callback, return code: CLOSE obj.callback(CLOSE); obj.nRetCode = CLOSE; // ** Run onClose function obj.onClose(); } }, false); } // ** END: window click outside box click handler // ** Close box on ESC-key if(!(_hasClass(dlg, 'dlg-disable-esc'))) { _attachEventListener(window, 'keyup', function EscKeyClose(evt) { // ** Get/set event variable evt = evt || event || window.event; // ** Listen for key (crossbrowser) if(evt.which === 27 || evt.keyCode === 27 || evt.key === 'Escape' || evt.code === 'Escape' ) { if(obj.bVisible) { // ** Remove eventlistener // ** Disabled for now, keeping eventlisteners since we "hide" not "destroy" //_detachEventListener(window, 'keyup', EscKeyClose, false); // ** Close dialogbox, reset values, clean up //obj.destroy(); // Changed from "destroy" to "hiding", keep the dialogbox in DOM obj.hide('doNotExecuteOnHide'); // ** Callback, return code: CLOSE obj.callback(CLOSE); obj.nRetCode = CLOSE; // ** Run onClose function obj.onClose(); // ** Prevent default event action and bubbling _stopEvent(evt); _stopDefault(evt); } } }, false); } // ** END: Close box on ESC-key // ** If YES-NO messagebox, create click handler for YES and NO buttons if(_hasClass(dlg, 'dlg-yes-no') || _hasClass(dlg, 'dlg-yes') || _hasClass(dlg, 'dlg-no') ) { // ** User clicks the YES button var btnYesDialog = dlg.querySelector('.dlg-yes-btn'); if(btnYesDialog) { _attachEventListener(btnYesDialog, 'click', function BtnYesClick() { // ** Remove eventlistener // ** Disabled for now, keeping eventlisteners since we "hide" not "destroy" //_detachEventListener(btnYesDialog, 'click', BtnYesClick, false); // ** Close dialogbox, reset values, clean up //obj.destroy(); // Changed from "destroy" to "hiding", keep the dialogbox in DOM obj.hide('doNotExecuteOnHide'); // ** Callback, return code: YES obj.callback(YES); obj.nRetCode = YES; // ** Run onClose function obj.onClose(); }, false); } // ** User clicks the NO button var btnNoDialog = dlg.querySelector('.dlg-no-btn'); if(btnNoDialog) { _attachEventListener(btnNoDialog, 'click', function BtnNoClick() { // ** Remove eventlistener // ** Disabled for now, keeping eventlisteners since we "hide" not "destroy" //_detachEventListener(btnNoDialog, 'click', BtnNoClick, false); // ** Close dialogbox, reset values, clean up //obj.destroy(); // Changed from "destroy" to "hiding", keep the dialogbox in DOM obj.hide('doNotExecuteOnHide'); // ** Callback, return code: NO obj.callback(NO); obj.nRetCode = NO; // ** Run onClose function obj.onClose(); }, false); } } // ** END: YES-NO button click handlers // ** If OK-CANCEL messagebox, create click handler for OK and CANCEL buttons if(_hasClass(dlg, 'dlg-ok-cancel') || _hasClass(dlg, 'dlg-ok') || _hasClass(dlg, 'dlg-cancel') ) { // ** User clicks the OK button var btnOkDialog = dlg.querySelector('.dlg-ok-btn'); if(btnOkDialog) { _attachEventListener(btnOkDialog, 'click', function BtnOkClick() { // ** Remove eventlistener // ** Disabled for now, keeping eventlisteners since we "hide" not "destroy" //_detachEventListener(btnOkDialog, 'click', BtnOkClick, false); // ** Close dialogbox, reset values, clean up //obj.destroy(); // Changed from "destroy" to "hiding", keep the dialogbox in DOM obj.hide('doNotExecuteOnHide'); // ** Callback, return code: OK obj.callback(OK); obj.nRetCode = OK; // ** Run onClose function obj.onClose(); }, false); } // ** User clicks the Cancel button var btnCancelDialog = dlg.querySelector('.dlg-cancel-btn'); if(btnCancelDialog) { _attachEventListener(btnCancelDialog, 'click', function BtnCancelClick() { // ** Remove eventlistener // ** Disabled for now, keeping eventlisteners since we "hide" not "destroy" //_detachEventListener(btnCancelDialog, 'click', BtnCancelClick, false); // ** Close dialogbox, reset values, clean up //obj.destroy(); // Changed from "destroy" to "hiding", keep the dialogbox in DOM obj.hide('doNotExecuteOnHide'); // ** Callback, return code: CANCEL obj.callback(CANCEL); obj.nRetCode = CANCEL; // ** Run onClose function obj.onClose(); }, false); } } // ** END: OK-CANCEL button click handlers // ** User types in promptbox, update variable: obj.strInput if(_hasClass(dlg, 'dlg-prompt')) { var pBox = dlg.querySelector('.dlg-input-field'); if(pBox) { _attachEventListener(pBox, 'keyup', function PromptBoxKeyUp() { obj.strInput = pBox.value; }, false); _attachEventListener(pBox, 'change', function PromptBoxChange() { obj.strInput = pBox.value; }, false); } } // ** END: User types in promptbox //--------------------------------------------------------------------- // ** END: Create event-listeners //--------------------------------------------------------------------- // ** Make it draggable, unless flag is set if(!(_hasClass(dlg, 'dlg-disable-drag'))) { _drag.init(box.id); } // ** Adjust box size and position according to window size //_adjustElSizePos(box.id); // disabled <-- this was making box position problems // ** Set focus to input field if promptbox if(_hasClass(dlg, 'dlg-prompt')) { dlg.querySelector('.dlg-input-field').focus(); } // ** Object has been created, set flag to true obj.bExistInDOM = true; // ** First run keep hidden, only create, do not show, do not run "onHide" func obj.hide('doNotExecuteOnHide'); // <-- skips execution of "obj.onHide()" function // ** Set reference to object itself obj.el = document.getElementById(obj.id + '_1'); // ** Run onCreate function. Need to run it async, since need to run after object has been created setTimeout(function() { obj.onCreate(); _log('DEBUG: obj.onCreate(): executed (async)'); }, 100); _log('DEBUG: create(): new object created and added to DOM'); // ** Return object return obj; } else if(!matched) { _log('DEBUG: create(): error, dialogbox type not defined or not a valid type: ' + obj.strTypeClass); } else if(!dlg) { _log('DEBUG: create(): error, element id \'' + strId + '\' do not exist.\nReturned value = ' + dlg); } else { _log('DEBUG: create(): unknown error'); } //--------------------------------------------------------------------- // ** END: Create DOM element //--------------------------------------------------------------------- } else { _log('DEBUG: create(): error, dialogbox type not defined or not a valid type: ' + strTypeClass); } return null; // return failure }; // ** END: Create dialogbox and insert it into DOM // ** Initialize, this "activates" the pre-written HTML box openers var _init = function() { // ** Window load event _attachEventListener(window, 'load', function LoadWindow() { // ** Inform user if debuginfo console-output is on if(DEBUG) { _log('EasyDialogBox debug console-output is set to: ON\nYou can switch it OFF in the file "easydlg.js" by setting the variable: DEBUG = false'); } // ** Initialize the pre-written HTML boxes // ** Get all elements with class containing 'dlg-opener' var btns = document.querySelectorAll('.dlg-opener'); // ** Create objects and click handler for each element that contain class 'dlg-opener' for(var i = 0; i < btns.length; i++) { // ** Get element from DOM var dlg = document.getElementById(btns[i].getAttribute('rel')); // ** Clean up className string to avoid error, just in case // ** Replace double whitespace if found var classType = dlg.getAttribute('class').replace(/\s\s+/g, ' '); // ** Remove leading and trailing whitspace classType = classType.replace(/^\s+|\s+$/g, ''); // ** Create object from DOM element var obj = _create(dlg.getAttribute('id'), // id classType, // type dlg.getAttribute('title'), // title dlg.innerHTML, // message dlg.getAttribute('data-callback'), // callback function dlg.getAttribute('data-x'), // horizontal position dlg.getAttribute('data-y'), // vertical position dlg.getAttribute('data-w'), // width dlg.getAttribute('data-h')); // height } // ** Create click handler for each element var clkObj = document.querySelectorAll('.dlg-opener'); clkObj.forEach(function(btn, index) { _attachEventListener(btn, 'click', function DlgOpenerClick(evt) { // ** Get/set event variable evt = evt || event || window.event; _boxObj[index].show(); // Show the dialogbox with the id referenced in 'rel' attribute this.blur(); // Remove focus from button or other opening element _stopDefault(evt); // Prevent scrolling to top of page if i.e. used in an anchor-link 'href="#"' _stopEvent(evt); // Prevent bubbling up to parent elements or capturing down to child elements }, false); }); // ** END: Initialize the pre-written HTML boxes }, false); // ** END: Window load event }; // ** END: Initialize // ** Drag'n'drop object module var _drag = { init : function(id) { _drag.el = document.getElementById(id); _drag.el.grabber = document.getElementById(id + '_heading'); if(_drag.el.grabber === null) { _drag.el.grabber = _drag.el; } _drag.el.style.position = 'absolute'; _attachEventListener(_drag.el.grabber, 'mousedown', _drag.start, false); }, start : function(evt) { // ** Get/set event variable evt = evt || event || window.event; // ** Left mouse button triggers moving if(evt.button === 0) { _stopDefault(evt); _drag.el.grabber.style.cursor = 'move'; _drag.el.posX2 = evt.clientX; _drag.el.posY2 = evt.clientY; _attachEventListener(document, 'mouseup', _drag.stop, false); _attachEventListener(document, 'mousemove', _drag.move, false); } }, stop : function() { _drag.el.grabber.style.cursor = ''; _detachEventListener(document, 'mouseup', _drag.stop, false); _detachEventListener(document, 'mousemove', _drag.move, false); }, move : function(evt) { // ** Get/set event variable evt = evt || event || window.event; _stopDefault(evt); _drag.el.posX = _drag.el.posX2 - evt.clientX; _drag.el.posY = _drag.el.posY2 - evt.clientY; _drag.el.posX2 = evt.clientX; _drag.el.posY2 = evt.clientY; _drag.el.style.top = parseInt( (_drag.el.offsetTop) - (_drag.el.posY), 10) + 'px'; _drag.el.style.left = parseInt( (_drag.el.offsetLeft) - (_drag.el.posX), 10) + 'px'; } }; // ** END: Drag'n'drop object module //--------------------------------------------------------------------- // ** Public methods //--------------------------------------------------------------------- return { //<-- IMPORTANT: Bracket need to be on same line as "return", else it just returns 'undefined' // ** Create dialog create : function(strId, strTypeClass, strTitle, strMessage, fnCallback, x, y, w, h) { return _create(strId, strTypeClass, strTitle, strMessage, fnCallback, x, y, w, h); }, // ** Get all objects in objectarray (memory) getAll : function() { return _boxObj; }, // ** Get object from id getById : function(id) { return _getObjFromId(_boxObj, id); }, // ** Init module init : function() { return _init(); } } //--------------------------------------------------------------------- // ** END: Public methods //--------------------------------------------------------------------- })(); //----------------------------------------------------------------------------------------------------------------- // ** END: EasyDialogBox Object (module) //----------------------------------------------------------------------------------------------------------------- //----------------------------------------------------------------------------------------------------------------- // ** Initialize //----------------------------------------------------------------------------------------------------------------- (function(){EasyDialogBox.init();})(); //----------------------------------------------------------------------------------------------------------------- // ** END: Initialize //-----------------------------------------------------------------------------------------------------------------
39.383608
160
0.440496
b414d37402dfcfd2d1b3a195e6627ad9ff65e540
1,529
js
JavaScript
src/pages/containers/adServerSwitcherContainer/adServerSwitcherContainer.js
postindustria-tech/pubmonkey
335acab3c7c3758caf872999fede581d099c1cd7
[ "Apache-2.0" ]
null
null
null
src/pages/containers/adServerSwitcherContainer/adServerSwitcherContainer.js
postindustria-tech/pubmonkey
335acab3c7c3758caf872999fede581d099c1cd7
[ "Apache-2.0" ]
null
null
null
src/pages/containers/adServerSwitcherContainer/adServerSwitcherContainer.js
postindustria-tech/pubmonkey
335acab3c7c3758caf872999fede581d099c1cd7
[ "Apache-2.0" ]
null
null
null
import React, {PureComponent} from 'react' import {Col, Row} from "reactstrap"; import adServerActions from '../../../redux/actions/adServer' import adServerSelectors from '../../../redux/selectors/adServer' import {connect} from "react-redux"; import {AD_SERVERS} from "../../constants/source"; class adServerSwitcherContainer extends PureComponent { handleAdServerChange = (type) => { this.props.setSwitcher(type) }; render() { return ( <Row className={"ad-server-switcher-wrapper"}> <Col className={"col-sm-12"}> Ad Server:{" "} <div className="btn-group" role="group"> {Object.keys(AD_SERVERS).map((option, index) => ( <button key={index} type="button" className={`btn btn-primary adserver-button ${this.props.type === option ? 'active' : ''}`} onClick={() => this.handleAdServerChange(option)} > {AD_SERVERS[option]} </button> ))} </div> </Col> </Row> ) } } const mapDispatchToProps = { setSwitcher: adServerActions.setSwitcher }; const mapStateToProps = state => ({ type: adServerSelectors.switcherType(state) }); export default connect(mapStateToProps, mapDispatchToProps)(adServerSwitcherContainer)
33.23913
119
0.525834
b414dcb39646389bdc188759ffece77086cf4698
56,566
js
JavaScript
packages/minimongo/local_collection.js
talfco/meteor-armv7l
19b1421721ab712fbb80132a45e5941e904d8eec
[ "Apache-2.0", "BSD-2-Clause", "MIT" ]
1
2017-10-03T14:50:36.000Z
2017-10-03T14:50:36.000Z
packages/minimongo/local_collection.js
talfco/meteor-armv7l
19b1421721ab712fbb80132a45e5941e904d8eec
[ "Apache-2.0", "BSD-2-Clause", "MIT" ]
null
null
null
packages/minimongo/local_collection.js
talfco/meteor-armv7l
19b1421721ab712fbb80132a45e5941e904d8eec
[ "Apache-2.0", "BSD-2-Clause", "MIT" ]
1
2020-02-14T09:59:04.000Z
2020-02-14T09:59:04.000Z
import Cursor from './cursor.js'; import ObserveHandle from './observe_handle.js'; import { hasOwn, isIndexable, isNumericKey, isOperatorObject, populateDocumentWithQueryFields, projectionDetails, } from './common.js'; // XXX type checking on selectors (graceful error if malformed) // LocalCollection: a set of documents that supports queries and modifiers. export default class LocalCollection { constructor(name) { this.name = name; // _id -> document (also containing id) this._docs = new LocalCollection._IdMap; this._observeQueue = new Meteor._SynchronousQueue(); this.next_qid = 1; // live query id generator // qid -> live query object. keys: // ordered: bool. ordered queries have addedBefore/movedBefore callbacks. // results: array (ordered) or object (unordered) of current results // (aliased with this._docs!) // resultsSnapshot: snapshot of results. null if not paused. // cursor: Cursor object for the query. // selector, sorter, (callbacks): functions this.queries = Object.create(null); // null if not saving originals; an IdMap from id to original document value // if saving originals. See comments before saveOriginals(). this._savedOriginals = null; // True when observers are paused and we should not send callbacks. this.paused = false; } // options may include sort, skip, limit, reactive // sort may be any of these forms: // {a: 1, b: -1} // [["a", "asc"], ["b", "desc"]] // ["a", ["b", "desc"]] // (in the first form you're beholden to key enumeration order in // your javascript VM) // // reactive: if given, and false, don't register with Tracker (default // is true) // // XXX possibly should support retrieving a subset of fields? and // have it be a hint (ignored on the client, when not copying the // doc?) // // XXX sort does not yet support subkeys ('a.b') .. fix that! // XXX add one more sort form: "key" // XXX tests find(selector, options) { // default syntax for everything is to omit the selector argument. // but if selector is explicitly passed in as false or undefined, we // want a selector that matches nothing. if (arguments.length === 0) { selector = {}; } return new LocalCollection.Cursor(this, selector, options); } findOne(selector, options = {}) { if (arguments.length === 0) { selector = {}; } // NOTE: by setting limit 1 here, we end up using very inefficient // code that recomputes the whole query on each update. The upside is // that when you reactively depend on a findOne you only get // invalidated when the found object changes, not any object in the // collection. Most findOne will be by id, which has a fast path, so // this might not be a big deal. In most cases, invalidation causes // the called to re-query anyway, so this should be a net performance // improvement. options.limit = 1; return this.find(selector, options).fetch()[0]; } // XXX possibly enforce that 'undefined' does not appear (we assume // this in our handling of null and $exists) insert(doc, callback) { doc = EJSON.clone(doc); assertHasValidFieldNames(doc); // if you really want to use ObjectIDs, set this global. // Mongo.Collection specifies its own ids and does not use this code. if (!hasOwn.call(doc, '_id')) { doc._id = LocalCollection._useOID ? new MongoID.ObjectID() : Random.id(); } const id = doc._id; if (this._docs.has(id)) { throw MinimongoError(`Duplicate _id '${id}'`); } this._saveOriginal(id, undefined); this._docs.set(id, doc); const queriesToRecompute = []; // trigger live queries that match Object.keys(this.queries).forEach(qid => { const query = this.queries[qid]; if (query.dirty) { return; } const matchResult = query.matcher.documentMatches(doc); if (matchResult.result) { if (query.distances && matchResult.distance !== undefined) { query.distances.set(id, matchResult.distance); } if (query.cursor.skip || query.cursor.limit) { queriesToRecompute.push(qid); } else { LocalCollection._insertInResults(query, doc); } } }); queriesToRecompute.forEach(qid => { if (this.queries[qid]) { this._recomputeResults(this.queries[qid]); } }); this._observeQueue.drain(); // Defer because the caller likely doesn't expect the callback to be run // immediately. if (callback) { Meteor.defer(() => { callback(null, id); }); } return id; } // Pause the observers. No callbacks from observers will fire until // 'resumeObservers' is called. pauseObservers() { // No-op if already paused. if (this.paused) { return; } // Set the 'paused' flag such that new observer messages don't fire. this.paused = true; // Take a snapshot of the query results for each query. Object.keys(this.queries).forEach(qid => { const query = this.queries[qid]; query.resultsSnapshot = EJSON.clone(query.results); }); } remove(selector, callback) { // Easy special case: if we're not calling observeChanges callbacks and // we're not saving originals and we got asked to remove everything, then // just empty everything directly. if (this.paused && !this._savedOriginals && EJSON.equals(selector, {})) { const result = this._docs.size(); this._docs.clear(); Object.keys(this.queries).forEach(qid => { const query = this.queries[qid]; if (query.ordered) { query.results = []; } else { query.results.clear(); } }); if (callback) { Meteor.defer(() => { callback(null, result); }); } return result; } const matcher = new Minimongo.Matcher(selector); const remove = []; this._eachPossiblyMatchingDoc(selector, (doc, id) => { if (matcher.documentMatches(doc).result) { remove.push(id); } }); const queriesToRecompute = []; const queryRemove = []; for (let i = 0; i < remove.length; i++) { const removeId = remove[i]; const removeDoc = this._docs.get(removeId); Object.keys(this.queries).forEach(qid => { const query = this.queries[qid]; if (query.dirty) { return; } if (query.matcher.documentMatches(removeDoc).result) { if (query.cursor.skip || query.cursor.limit) { queriesToRecompute.push(qid); } else { queryRemove.push({qid, doc: removeDoc}); } } }); this._saveOriginal(removeId, removeDoc); this._docs.remove(removeId); } // run live query callbacks _after_ we've removed the documents. queryRemove.forEach(remove => { const query = this.queries[remove.qid]; if (query) { query.distances && query.distances.remove(remove.doc._id); LocalCollection._removeFromResults(query, remove.doc); } }); queriesToRecompute.forEach(qid => { const query = this.queries[qid]; if (query) { this._recomputeResults(query); } }); this._observeQueue.drain(); const result = remove.length; if (callback) { Meteor.defer(() => { callback(null, result); }); } return result; } // Resume the observers. Observers immediately receive change // notifications to bring them to the current state of the // database. Note that this is not just replaying all the changes that // happened during the pause, it is a smarter 'coalesced' diff. resumeObservers() { // No-op if not paused. if (!this.paused) { return; } // Unset the 'paused' flag. Make sure to do this first, otherwise // observer methods won't actually fire when we trigger them. this.paused = false; Object.keys(this.queries).forEach(qid => { const query = this.queries[qid]; if (query.dirty) { query.dirty = false; // re-compute results will perform `LocalCollection._diffQueryChanges` // automatically. this._recomputeResults(query, query.resultsSnapshot); } else { // Diff the current results against the snapshot and send to observers. // pass the query object for its observer callbacks. LocalCollection._diffQueryChanges( query.ordered, query.resultsSnapshot, query.results, query, {projectionFn: query.projectionFn} ); } query.resultsSnapshot = null; }); this._observeQueue.drain(); } retrieveOriginals() { if (!this._savedOriginals) { throw new Error('Called retrieveOriginals without saveOriginals'); } const originals = this._savedOriginals; this._savedOriginals = null; return originals; } // To track what documents are affected by a piece of code, call // saveOriginals() before it and retrieveOriginals() after it. // retrieveOriginals returns an object whose keys are the ids of the documents // that were affected since the call to saveOriginals(), and the values are // equal to the document's contents at the time of saveOriginals. (In the case // of an inserted document, undefined is the value.) You must alternate // between calls to saveOriginals() and retrieveOriginals(). saveOriginals() { if (this._savedOriginals) { throw new Error('Called saveOriginals twice without retrieveOriginals'); } this._savedOriginals = new LocalCollection._IdMap; } // XXX atomicity: if multi is true, and one modification fails, do // we rollback the whole operation, or what? update(selector, mod, options, callback) { if (! callback && options instanceof Function) { callback = options; options = null; } if (!options) { options = {}; } const matcher = new Minimongo.Matcher(selector, true); // Save the original results of any query that we might need to // _recomputeResults on, because _modifyAndNotify will mutate the objects in // it. (We don't need to save the original results of paused queries because // they already have a resultsSnapshot and we won't be diffing in // _recomputeResults.) const qidToOriginalResults = {}; // We should only clone each document once, even if it appears in multiple // queries const docMap = new LocalCollection._IdMap; const idsMatched = LocalCollection._idsMatchedBySelector(selector); Object.keys(this.queries).forEach(qid => { const query = this.queries[qid]; if ((query.cursor.skip || query.cursor.limit) && ! this.paused) { // Catch the case of a reactive `count()` on a cursor with skip // or limit, which registers an unordered observe. This is a // pretty rare case, so we just clone the entire result set with // no optimizations for documents that appear in these result // sets and other queries. if (query.results instanceof LocalCollection._IdMap) { qidToOriginalResults[qid] = query.results.clone(); return; } if (!(query.results instanceof Array)) { throw new Error('Assertion failed: query.results not an array'); } // Clones a document to be stored in `qidToOriginalResults` // because it may be modified before the new and old result sets // are diffed. But if we know exactly which document IDs we're // going to modify, then we only need to clone those. const memoizedCloneIfNeeded = doc => { if (docMap.has(doc._id)) { return docMap.get(doc._id); } const docToMemoize = ( idsMatched && !idsMatched.some(id => EJSON.equals(id, doc._id)) ) ? doc : EJSON.clone(doc); docMap.set(doc._id, docToMemoize); return docToMemoize; }; qidToOriginalResults[qid] = query.results.map(memoizedCloneIfNeeded); } }); const recomputeQids = {}; let updateCount = 0; this._eachPossiblyMatchingDoc(selector, (doc, id) => { const queryResult = matcher.documentMatches(doc); if (queryResult.result) { // XXX Should we save the original even if mod ends up being a no-op? this._saveOriginal(id, doc); this._modifyAndNotify( doc, mod, recomputeQids, queryResult.arrayIndices ); ++updateCount; if (!options.multi) { return false; // break } } return true; }); Object.keys(recomputeQids).forEach(qid => { const query = this.queries[qid]; if (query) { this._recomputeResults(query, qidToOriginalResults[qid]); } }); this._observeQueue.drain(); // If we are doing an upsert, and we didn't modify any documents yet, then // it's time to do an insert. Figure out what document we are inserting, and // generate an id for it. let insertedId; if (updateCount === 0 && options.upsert) { const doc = LocalCollection._createUpsertDocument(selector, mod); if (! doc._id && options.insertedId) { doc._id = options.insertedId; } insertedId = this.insert(doc); updateCount = 1; } // Return the number of affected documents, or in the upsert case, an object // containing the number of affected docs and the id of the doc that was // inserted, if any. let result; if (options._returnObject) { result = {numberAffected: updateCount}; if (insertedId !== undefined) { result.insertedId = insertedId; } } else { result = updateCount; } if (callback) { Meteor.defer(() => { callback(null, result); }); } return result; } // A convenience wrapper on update. LocalCollection.upsert(sel, mod) is // equivalent to LocalCollection.update(sel, mod, {upsert: true, // _returnObject: true}). upsert(selector, mod, options, callback) { if (!callback && typeof options === 'function') { callback = options; options = {}; } return this.update( selector, mod, Object.assign({}, options, {upsert: true, _returnObject: true}), callback ); } // Iterates over a subset of documents that could match selector; calls // fn(doc, id) on each of them. Specifically, if selector specifies // specific _id's, it only looks at those. doc is *not* cloned: it is the // same object that is in _docs. _eachPossiblyMatchingDoc(selector, fn) { const specificIds = LocalCollection._idsMatchedBySelector(selector); if (specificIds) { specificIds.some(id => { const doc = this._docs.get(id); if (doc) { return fn(doc, id) === false; } }); } else { this._docs.forEach(fn); } } _modifyAndNotify(doc, mod, recomputeQids, arrayIndices) { const matched_before = {}; Object.keys(this.queries).forEach(qid => { const query = this.queries[qid]; if (query.dirty) { return; } if (query.ordered) { matched_before[qid] = query.matcher.documentMatches(doc).result; } else { // Because we don't support skip or limit (yet) in unordered queries, we // can just do a direct lookup. matched_before[qid] = query.results.has(doc._id); } }); const old_doc = EJSON.clone(doc); LocalCollection._modify(doc, mod, {arrayIndices}); Object.keys(this.queries).forEach(qid => { const query = this.queries[qid]; if (query.dirty) { return; } const afterMatch = query.matcher.documentMatches(doc); const after = afterMatch.result; const before = matched_before[qid]; if (after && query.distances && afterMatch.distance !== undefined) { query.distances.set(doc._id, afterMatch.distance); } if (query.cursor.skip || query.cursor.limit) { // We need to recompute any query where the doc may have been in the // cursor's window either before or after the update. (Note that if skip // or limit is set, "before" and "after" being true do not necessarily // mean that the document is in the cursor's output after skip/limit is // applied... but if they are false, then the document definitely is NOT // in the output. So it's safe to skip recompute if neither before or // after are true.) if (before || after) { recomputeQids[qid] = true; } } else if (before && !after) { LocalCollection._removeFromResults(query, doc); } else if (!before && after) { LocalCollection._insertInResults(query, doc); } else if (before && after) { LocalCollection._updateInResults(query, doc, old_doc); } }); } // Recomputes the results of a query and runs observe callbacks for the // difference between the previous results and the current results (unless // paused). Used for skip/limit queries. // // When this is used by insert or remove, it can just use query.results for // the old results (and there's no need to pass in oldResults), because these // operations don't mutate the documents in the collection. Update needs to // pass in an oldResults which was deep-copied before the modifier was // applied. // // oldResults is guaranteed to be ignored if the query is not paused. _recomputeResults(query, oldResults) { if (this.paused) { // There's no reason to recompute the results now as we're still paused. // By flagging the query as "dirty", the recompute will be performed // when resumeObservers is called. query.dirty = true; return; } if (!this.paused && !oldResults) { oldResults = query.results; } if (query.distances) { query.distances.clear(); } query.results = query.cursor._getRawObjects({ distances: query.distances, ordered: query.ordered }); if (!this.paused) { LocalCollection._diffQueryChanges( query.ordered, oldResults, query.results, query, {projectionFn: query.projectionFn} ); } } _saveOriginal(id, doc) { // Are we even trying to save originals? if (!this._savedOriginals) { return; } // Have we previously mutated the original (and so 'doc' is not actually // original)? (Note the 'has' check rather than truth: we store undefined // here for inserted docs!) if (this._savedOriginals.has(id)) { return; } this._savedOriginals.set(id, EJSON.clone(doc)); } } LocalCollection.Cursor = Cursor; LocalCollection.ObserveHandle = ObserveHandle; // XXX maybe move these into another ObserveHelpers package or something // _CachingChangeObserver is an object which receives observeChanges callbacks // and keeps a cache of the current cursor state up to date in this.docs. Users // of this class should read the docs field but not modify it. You should pass // the "applyChange" field as the callbacks to the underlying observeChanges // call. Optionally, you can specify your own observeChanges callbacks which are // invoked immediately before the docs field is updated; this object is made // available as `this` to those callbacks. LocalCollection._CachingChangeObserver = class _CachingChangeObserver { constructor(options = {}) { const orderedFromCallbacks = ( options.callbacks && LocalCollection._observeChangesCallbacksAreOrdered(options.callbacks) ); if (hasOwn.call(options, 'ordered')) { this.ordered = options.ordered; if (options.callbacks && options.ordered !== orderedFromCallbacks) { throw Error('ordered option doesn\'t match callbacks'); } } else if (options.callbacks) { this.ordered = orderedFromCallbacks; } else { throw Error('must provide ordered or callbacks'); } const callbacks = options.callbacks || {}; if (this.ordered) { this.docs = new OrderedDict(MongoID.idStringify); this.applyChange = { addedBefore: (id, fields, before) => { const doc = EJSON.clone(fields); doc._id = id; if (callbacks.addedBefore) { callbacks.addedBefore.call(this, id, fields, before); } // This line triggers if we provide added with movedBefore. if (callbacks.added) { callbacks.added.call(this, id, fields); } // XXX could `before` be a falsy ID? Technically // idStringify seems to allow for them -- though // OrderedDict won't call stringify on a falsy arg. this.docs.putBefore(id, doc, before || null); }, movedBefore: (id, before) => { const doc = this.docs.get(id); if (callbacks.movedBefore) { callbacks.movedBefore.call(this, id, before); } this.docs.moveBefore(id, before || null); }, }; } else { this.docs = new LocalCollection._IdMap; this.applyChange = { added: (id, fields) => { const doc = EJSON.clone(fields); if (callbacks.added) { callbacks.added.call(this, id, fields); } doc._id = id; this.docs.set(id, doc); }, }; } // The methods in _IdMap and OrderedDict used by these callbacks are // identical. this.applyChange.changed = (id, fields) => { const doc = this.docs.get(id); if (!doc) { throw new Error(`Unknown id for changed: ${id}`); } if (callbacks.changed) { callbacks.changed.call(this, id, EJSON.clone(fields)); } DiffSequence.applyChanges(doc, fields); }; this.applyChange.removed = id => { if (callbacks.removed) { callbacks.removed.call(this, id); } this.docs.remove(id); }; } }; LocalCollection._IdMap = class _IdMap extends IdMap { constructor() { super(MongoID.idStringify, MongoID.idParse); } }; // Wrap a transform function to return objects that have the _id field // of the untransformed document. This ensures that subsystems such as // the observe-sequence package that call `observe` can keep track of // the documents identities. // // - Require that it returns objects // - If the return value has an _id field, verify that it matches the // original _id field // - If the return value doesn't have an _id field, add it back. LocalCollection.wrapTransform = transform => { if (!transform) { return null; } // No need to doubly-wrap transforms. if (transform.__wrappedTransform__) { return transform; } const wrapped = doc => { if (!hasOwn.call(doc, '_id')) { // XXX do we ever have a transform on the oplog's collection? because that // collection has no _id. throw new Error('can only transform documents with _id'); } const id = doc._id; // XXX consider making tracker a weak dependency and checking // Package.tracker here const transformed = Tracker.nonreactive(() => transform(doc)); if (!LocalCollection._isPlainObject(transformed)) { throw new Error('transform must return object'); } if (hasOwn.call(transformed, '_id')) { if (!EJSON.equals(transformed._id, id)) { throw new Error('transformed document can\'t have different _id'); } } else { transformed._id = id; } return transformed; }; wrapped.__wrappedTransform__ = true; return wrapped; }; // XXX the sorted-query logic below is laughably inefficient. we'll // need to come up with a better datastructure for this. // // XXX the logic for observing with a skip or a limit is even more // laughably inefficient. we recompute the whole results every time! // This binary search puts a value between any equal values, and the first // lesser value. LocalCollection._binarySearch = (cmp, array, value) => { let first = 0; let range = array.length; while (range > 0) { const halfRange = Math.floor(range / 2); if (cmp(value, array[first + halfRange]) >= 0) { first += halfRange + 1; range -= halfRange + 1; } else { range = halfRange; } } return first; }; LocalCollection._checkSupportedProjection = fields => { if (fields !== Object(fields) || Array.isArray(fields)) { throw MinimongoError('fields option must be an object'); } Object.keys(fields).forEach(keyPath => { if (keyPath.split('.').includes('$')) { throw MinimongoError( 'Minimongo doesn\'t support $ operator in projections yet.' ); } const value = fields[keyPath]; if (typeof value === 'object' && ['$elemMatch', '$meta', '$slice'].some(key => hasOwn.call(value, key) )) { throw MinimongoError( 'Minimongo doesn\'t support operators in projections yet.' ); } if (![1, 0, true, false].includes(value)) { throw MinimongoError( 'Projection values should be one of 1, 0, true, or false' ); } }); }; // Knows how to compile a fields projection to a predicate function. // @returns - Function: a closure that filters out an object according to the // fields projection rules: // @param obj - Object: MongoDB-styled document // @returns - Object: a document with the fields filtered out // according to projection rules. Doesn't retain subfields // of passed argument. LocalCollection._compileProjection = fields => { LocalCollection._checkSupportedProjection(fields); const _idProjection = fields._id === undefined ? true : fields._id; const details = projectionDetails(fields); // returns transformed doc according to ruleTree const transform = (doc, ruleTree) => { // Special case for "sets" if (Array.isArray(doc)) { return doc.map(subdoc => transform(subdoc, ruleTree)); } const result = details.including ? {} : EJSON.clone(doc); Object.keys(ruleTree).forEach(key => { if (!hasOwn.call(doc, key)) { return; } const rule = ruleTree[key]; if (rule === Object(rule)) { // For sub-objects/subsets we branch if (doc[key] === Object(doc[key])) { result[key] = transform(doc[key], rule); } } else if (details.including) { // Otherwise we don't even touch this subfield result[key] = EJSON.clone(doc[key]); } else { delete result[key]; } }); return result; }; return doc => { const result = transform(doc, details.tree); if (_idProjection && hasOwn.call(doc, '_id')) { result._id = doc._id; } if (!_idProjection && hasOwn.call(result, '_id')) { delete result._id; } return result; }; }; // Calculates the document to insert in case we're doing an upsert and the // selector does not match any elements LocalCollection._createUpsertDocument = (selector, modifier) => { const selectorDocument = populateDocumentWithQueryFields(selector); const isModify = LocalCollection._isModificationMod(modifier); const newDoc = {}; if (selectorDocument._id) { newDoc._id = selectorDocument._id; delete selectorDocument._id; } // This double _modify call is made to help with nested properties (see issue // #8631). We do this even if it's a replacement for validation purposes (e.g. // ambiguous id's) LocalCollection._modify(newDoc, {$set: selectorDocument}); LocalCollection._modify(newDoc, modifier, {isInsert: true}); if (isModify) { return newDoc; } // Replacement can take _id from query document const replacement = Object.assign({}, modifier); if (newDoc._id) { replacement._id = newDoc._id; } return replacement; }; LocalCollection._diffObjects = (left, right, callbacks) => { return DiffSequence.diffObjects(left, right, callbacks); }; // ordered: bool. // old_results and new_results: collections of documents. // if ordered, they are arrays. // if unordered, they are IdMaps LocalCollection._diffQueryChanges = (ordered, oldResults, newResults, observer, options) => DiffSequence.diffQueryChanges(ordered, oldResults, newResults, observer, options) ; LocalCollection._diffQueryOrderedChanges = (oldResults, newResults, observer, options) => DiffSequence.diffQueryOrderedChanges(oldResults, newResults, observer, options) ; LocalCollection._diffQueryUnorderedChanges = (oldResults, newResults, observer, options) => DiffSequence.diffQueryUnorderedChanges(oldResults, newResults, observer, options) ; LocalCollection._findInOrderedResults = (query, doc) => { if (!query.ordered) { throw new Error('Can\'t call _findInOrderedResults on unordered query'); } for (let i = 0; i < query.results.length; i++) { if (query.results[i] === doc) { return i; } } throw Error('object missing from query'); }; // If this is a selector which explicitly constrains the match by ID to a finite // number of documents, returns a list of their IDs. Otherwise returns // null. Note that the selector may have other restrictions so it may not even // match those document! We care about $in and $and since those are generated // access-controlled update and remove. LocalCollection._idsMatchedBySelector = selector => { // Is the selector just an ID? if (LocalCollection._selectorIsId(selector)) { return [selector]; } if (!selector) { return null; } // Do we have an _id clause? if (hasOwn.call(selector, '_id')) { // Is the _id clause just an ID? if (LocalCollection._selectorIsId(selector._id)) { return [selector._id]; } // Is the _id clause {_id: {$in: ["x", "y", "z"]}}? if (selector._id && Array.isArray(selector._id.$in) && selector._id.$in.length && selector._id.$in.every(LocalCollection._selectorIsId)) { return selector._id.$in; } return null; } // If this is a top-level $and, and any of the clauses constrain their // documents, then the whole selector is constrained by any one clause's // constraint. (Well, by their intersection, but that seems unlikely.) if (Array.isArray(selector.$and)) { for (let i = 0; i < selector.$and.length; ++i) { const subIds = LocalCollection._idsMatchedBySelector(selector.$and[i]); if (subIds) { return subIds; } } } return null; }; LocalCollection._insertInResults = (query, doc) => { const fields = EJSON.clone(doc); delete fields._id; if (query.ordered) { if (!query.sorter) { query.addedBefore(doc._id, query.projectionFn(fields), null); query.results.push(doc); } else { const i = LocalCollection._insertInSortedList( query.sorter.getComparator({distances: query.distances}), query.results, doc ); let next = query.results[i + 1]; if (next) { next = next._id; } else { next = null; } query.addedBefore(doc._id, query.projectionFn(fields), next); } query.added(doc._id, query.projectionFn(fields)); } else { query.added(doc._id, query.projectionFn(fields)); query.results.set(doc._id, doc); } }; LocalCollection._insertInSortedList = (cmp, array, value) => { if (array.length === 0) { array.push(value); return 0; } const i = LocalCollection._binarySearch(cmp, array, value); array.splice(i, 0, value); return i; }; LocalCollection._isModificationMod = mod => { let isModify = false; let isReplace = false; Object.keys(mod).forEach(key => { if (key.substr(0, 1) === '$') { isModify = true; } else { isReplace = true; } }); if (isModify && isReplace) { throw new Error( 'Update parameter cannot have both modifier and non-modifier fields.' ); } return isModify; }; // XXX maybe this should be EJSON.isObject, though EJSON doesn't know about // RegExp // XXX note that _type(undefined) === 3!!!! LocalCollection._isPlainObject = x => { return x && LocalCollection._f._type(x) === 3; }; // XXX need a strategy for passing the binding of $ into this // function, from the compiled selector // // maybe just {key.up.to.just.before.dollarsign: array_index} // // XXX atomicity: if one modification fails, do we roll back the whole // change? // // options: // - isInsert is set when _modify is being called to compute the document to // insert as part of an upsert operation. We use this primarily to figure // out when to set the fields in $setOnInsert, if present. LocalCollection._modify = (doc, modifier, options = {}) => { if (!LocalCollection._isPlainObject(modifier)) { throw MinimongoError('Modifier must be an object'); } // Make sure the caller can't mutate our data structures. modifier = EJSON.clone(modifier); const isModifier = isOperatorObject(modifier); const newDoc = isModifier ? EJSON.clone(doc) : modifier; if (isModifier) { // apply modifiers to the doc. Object.keys(modifier).forEach(operator => { // Treat $setOnInsert as $set if this is an insert. const setOnInsert = options.isInsert && operator === '$setOnInsert'; const modFunc = MODIFIERS[setOnInsert ? '$set' : operator]; const operand = modifier[operator]; if (!modFunc) { throw MinimongoError(`Invalid modifier specified ${operator}`); } Object.keys(operand).forEach(keypath => { const arg = operand[keypath]; if (keypath === '') { throw MinimongoError('An empty update path is not valid.'); } const keyparts = keypath.split('.'); if (!keyparts.every(Boolean)) { throw MinimongoError( `The update path '${keypath}' contains an empty field name, ` + 'which is not allowed.' ); } const target = findModTarget(newDoc, keyparts, { arrayIndices: options.arrayIndices, forbidArray: operator === '$rename', noCreate: NO_CREATE_MODIFIERS[operator] }); modFunc(target, keyparts.pop(), arg, keypath, newDoc); }); }); if (doc._id && !EJSON.equals(doc._id, newDoc._id)) { throw MinimongoError( `After applying the update to the document {_id: "${doc._id}", ...},` + ' the (immutable) field \'_id\' was found to have been altered to ' + `_id: "${newDoc._id}"` ); } } else { if (doc._id && modifier._id && !EJSON.equals(doc._id, modifier._id)) { throw MinimongoError( `The _id field cannot be changed from {_id: "${doc._id}"} to ` + `{_id: "${modifier._id}"}` ); } // replace the whole document assertHasValidFieldNames(modifier); } // move new document into place. Object.keys(doc).forEach(key => { // Note: this used to be for (var key in doc) however, this does not // work right in Opera. Deleting from a doc while iterating over it // would sometimes cause opera to skip some keys. if (key !== '_id') { delete doc[key]; } }); Object.keys(newDoc).forEach(key => { doc[key] = newDoc[key]; }); }; LocalCollection._observeFromObserveChanges = (cursor, observeCallbacks) => { const transform = cursor.getTransform() || (doc => doc); let suppressed = !!observeCallbacks._suppress_initial; let observeChangesCallbacks; if (LocalCollection._observeCallbacksAreOrdered(observeCallbacks)) { // The "_no_indices" option sets all index arguments to -1 and skips the // linear scans required to generate them. This lets observers that don't // need absolute indices benefit from the other features of this API -- // relative order, transforms, and applyChanges -- without the speed hit. const indices = !observeCallbacks._no_indices; observeChangesCallbacks = { addedBefore(id, fields, before) { if (suppressed || !(observeCallbacks.addedAt || observeCallbacks.added)) { return; } const doc = transform(Object.assign(fields, {_id: id})); if (observeCallbacks.addedAt) { observeCallbacks.addedAt( doc, indices ? before ? this.docs.indexOf(before) : this.docs.size() : -1, before ); } else { observeCallbacks.added(doc); } }, changed(id, fields) { if (!(observeCallbacks.changedAt || observeCallbacks.changed)) { return; } let doc = EJSON.clone(this.docs.get(id)); if (!doc) { throw new Error(`Unknown id for changed: ${id}`); } const oldDoc = transform(EJSON.clone(doc)); DiffSequence.applyChanges(doc, fields); if (observeCallbacks.changedAt) { observeCallbacks.changedAt( transform(doc), oldDoc, indices ? this.docs.indexOf(id) : -1 ); } else { observeCallbacks.changed(transform(doc), oldDoc); } }, movedBefore(id, before) { if (!observeCallbacks.movedTo) { return; } const from = indices ? this.docs.indexOf(id) : -1; let to = indices ? before ? this.docs.indexOf(before) : this.docs.size() : -1; // When not moving backwards, adjust for the fact that removing the // document slides everything back one slot. if (to > from) { --to; } observeCallbacks.movedTo( transform(EJSON.clone(this.docs.get(id))), from, to, before || null ); }, removed(id) { if (!(observeCallbacks.removedAt || observeCallbacks.removed)) { return; } // technically maybe there should be an EJSON.clone here, but it's about // to be removed from this.docs! const doc = transform(this.docs.get(id)); if (observeCallbacks.removedAt) { observeCallbacks.removedAt(doc, indices ? this.docs.indexOf(id) : -1); } else { observeCallbacks.removed(doc); } }, }; } else { observeChangesCallbacks = { added(id, fields) { if (!suppressed && observeCallbacks.added) { observeCallbacks.added(transform(Object.assign(fields, {_id: id}))); } }, changed(id, fields) { if (observeCallbacks.changed) { const oldDoc = this.docs.get(id); const doc = EJSON.clone(oldDoc); DiffSequence.applyChanges(doc, fields); observeCallbacks.changed( transform(doc), transform(EJSON.clone(oldDoc)) ); } }, removed(id) { if (observeCallbacks.removed) { observeCallbacks.removed(transform(this.docs.get(id))); } }, }; } const changeObserver = new LocalCollection._CachingChangeObserver({ callbacks: observeChangesCallbacks }); const handle = cursor.observeChanges(changeObserver.applyChange); suppressed = false; return handle; }; LocalCollection._observeCallbacksAreOrdered = callbacks => { if (callbacks.added && callbacks.addedAt) { throw new Error('Please specify only one of added() and addedAt()'); } if (callbacks.changed && callbacks.changedAt) { throw new Error('Please specify only one of changed() and changedAt()'); } if (callbacks.removed && callbacks.removedAt) { throw new Error('Please specify only one of removed() and removedAt()'); } return !!( callbacks.addedAt || callbacks.changedAt || callbacks.movedTo || callbacks.removedAt ); }; LocalCollection._observeChangesCallbacksAreOrdered = callbacks => { if (callbacks.added && callbacks.addedBefore) { throw new Error('Please specify only one of added() and addedBefore()'); } return !!(callbacks.addedBefore || callbacks.movedBefore); }; LocalCollection._removeFromResults = (query, doc) => { if (query.ordered) { const i = LocalCollection._findInOrderedResults(query, doc); query.removed(doc._id); query.results.splice(i, 1); } else { const id = doc._id; // in case callback mutates doc query.removed(doc._id); query.results.remove(id); } }; // Is this selector just shorthand for lookup by _id? LocalCollection._selectorIsId = selector => typeof selector === 'number' || typeof selector === 'string' || selector instanceof MongoID.ObjectID ; // Is the selector just lookup by _id (shorthand or not)? LocalCollection._selectorIsIdPerhapsAsObject = selector => LocalCollection._selectorIsId(selector) || LocalCollection._selectorIsId(selector && selector._id) && Object.keys(selector).length === 1 ; LocalCollection._updateInResults = (query, doc, old_doc) => { if (!EJSON.equals(doc._id, old_doc._id)) { throw new Error('Can\'t change a doc\'s _id while updating'); } const projectionFn = query.projectionFn; const changedFields = DiffSequence.makeChangedFields( projectionFn(doc), projectionFn(old_doc) ); if (!query.ordered) { if (Object.keys(changedFields).length) { query.changed(doc._id, changedFields); query.results.set(doc._id, doc); } return; } const old_idx = LocalCollection._findInOrderedResults(query, doc); if (Object.keys(changedFields).length) { query.changed(doc._id, changedFields); } if (!query.sorter) { return; } // just take it out and put it back in again, and see if the index changes query.results.splice(old_idx, 1); const new_idx = LocalCollection._insertInSortedList( query.sorter.getComparator({distances: query.distances}), query.results, doc ); if (old_idx !== new_idx) { let next = query.results[new_idx + 1]; if (next) { next = next._id; } else { next = null; } query.movedBefore && query.movedBefore(doc._id, next); } }; const MODIFIERS = { $currentDate(target, field, arg) { if (typeof arg === 'object' && hasOwn.call(arg, '$type')) { if (arg.$type !== 'date') { throw MinimongoError( 'Minimongo does currently only support the date type in ' + '$currentDate modifiers', {field} ); } } else if (arg !== true) { throw MinimongoError('Invalid $currentDate modifier', {field}); } target[field] = new Date(); }, $min(target, field, arg) { if (typeof arg !== 'number') { throw MinimongoError('Modifier $min allowed for numbers only', {field}); } if (field in target) { if (typeof target[field] !== 'number') { throw MinimongoError( 'Cannot apply $min modifier to non-number', {field} ); } if (target[field] > arg) { target[field] = arg; } } else { target[field] = arg; } }, $max(target, field, arg) { if (typeof arg !== 'number') { throw MinimongoError('Modifier $max allowed for numbers only', {field}); } if (field in target) { if (typeof target[field] !== 'number') { throw MinimongoError( 'Cannot apply $max modifier to non-number', {field} ); } if (target[field] < arg) { target[field] = arg; } } else { target[field] = arg; } }, $inc(target, field, arg) { if (typeof arg !== 'number') { throw MinimongoError('Modifier $inc allowed for numbers only', {field}); } if (field in target) { if (typeof target[field] !== 'number') { throw MinimongoError( 'Cannot apply $inc modifier to non-number', {field} ); } target[field] += arg; } else { target[field] = arg; } }, $set(target, field, arg) { if (target !== Object(target)) { // not an array or an object const error = MinimongoError( 'Cannot set property on non-object field', {field} ); error.setPropertyError = true; throw error; } if (target === null) { const error = MinimongoError('Cannot set property on null', {field}); error.setPropertyError = true; throw error; } assertHasValidFieldNames(arg); target[field] = arg; }, $setOnInsert(target, field, arg) { // converted to `$set` in `_modify` }, $unset(target, field, arg) { if (target !== undefined) { if (target instanceof Array) { if (field in target) { target[field] = null; } } else { delete target[field]; } } }, $push(target, field, arg) { if (target[field] === undefined) { target[field] = []; } if (!(target[field] instanceof Array)) { throw MinimongoError('Cannot apply $push modifier to non-array', {field}); } if (!(arg && arg.$each)) { // Simple mode: not $each assertHasValidFieldNames(arg); target[field].push(arg); return; } // Fancy mode: $each (and maybe $slice and $sort and $position) const toPush = arg.$each; if (!(toPush instanceof Array)) { throw MinimongoError('$each must be an array', {field}); } assertHasValidFieldNames(toPush); // Parse $position let position = undefined; if ('$position' in arg) { if (typeof arg.$position !== 'number') { throw MinimongoError('$position must be a numeric value', {field}); } // XXX should check to make sure integer if (arg.$position < 0) { throw MinimongoError( '$position in $push must be zero or positive', {field} ); } position = arg.$position; } // Parse $slice. let slice = undefined; if ('$slice' in arg) { if (typeof arg.$slice !== 'number') { throw MinimongoError('$slice must be a numeric value', {field}); } // XXX should check to make sure integer slice = arg.$slice; } // Parse $sort. let sortFunction = undefined; if (arg.$sort) { if (slice === undefined) { throw MinimongoError('$sort requires $slice to be present', {field}); } // XXX this allows us to use a $sort whose value is an array, but that's // actually an extension of the Node driver, so it won't work // server-side. Could be confusing! // XXX is it correct that we don't do geo-stuff here? sortFunction = new Minimongo.Sorter(arg.$sort).getComparator(); toPush.forEach(element => { if (LocalCollection._f._type(element) !== 3) { throw MinimongoError( '$push like modifiers using $sort require all elements to be ' + 'objects', {field} ); } }); } // Actually push. if (position === undefined) { toPush.forEach(element => { target[field].push(element); }); } else { const spliceArguments = [position, 0]; toPush.forEach(element => { spliceArguments.push(element); }); target[field].splice(...spliceArguments); } // Actually sort. if (sortFunction) { target[field].sort(sortFunction); } // Actually slice. if (slice !== undefined) { if (slice === 0) { target[field] = []; // differs from Array.slice! } else if (slice < 0) { target[field] = target[field].slice(slice); } else { target[field] = target[field].slice(0, slice); } } }, $pushAll(target, field, arg) { if (!(typeof arg === 'object' && arg instanceof Array)) { throw MinimongoError('Modifier $pushAll/pullAll allowed for arrays only'); } assertHasValidFieldNames(arg); const toPush = target[field]; if (toPush === undefined) { target[field] = arg; } else if (!(toPush instanceof Array)) { throw MinimongoError( 'Cannot apply $pushAll modifier to non-array', {field} ); } else { toPush.push(...arg); } }, $addToSet(target, field, arg) { let isEach = false; if (typeof arg === 'object') { // check if first key is '$each' const keys = Object.keys(arg); if (keys[0] === '$each') { isEach = true; } } const values = isEach ? arg.$each : [arg]; assertHasValidFieldNames(values); const toAdd = target[field]; if (toAdd === undefined) { target[field] = values; } else if (!(toAdd instanceof Array)) { throw MinimongoError( 'Cannot apply $addToSet modifier to non-array', {field} ); } else { values.forEach(value => { if (toAdd.some(element => LocalCollection._f._equal(value, element))) { return; } toAdd.push(value); }); } }, $pop(target, field, arg) { if (target === undefined) { return; } const toPop = target[field]; if (toPop === undefined) { return; } if (!(toPop instanceof Array)) { throw MinimongoError('Cannot apply $pop modifier to non-array', {field}); } if (typeof arg === 'number' && arg < 0) { toPop.splice(0, 1); } else { toPop.pop(); } }, $pull(target, field, arg) { if (target === undefined) { return; } const toPull = target[field]; if (toPull === undefined) { return; } if (!(toPull instanceof Array)) { throw MinimongoError( 'Cannot apply $pull/pullAll modifier to non-array', {field} ); } let out; if (arg != null && typeof arg === 'object' && !(arg instanceof Array)) { // XXX would be much nicer to compile this once, rather than // for each document we modify.. but usually we're not // modifying that many documents, so we'll let it slide for // now // XXX Minimongo.Matcher isn't up for the job, because we need // to permit stuff like {$pull: {a: {$gt: 4}}}.. something // like {$gt: 4} is not normally a complete selector. // same issue as $elemMatch possibly? const matcher = new Minimongo.Matcher(arg); out = toPull.filter(element => !matcher.documentMatches(element).result); } else { out = toPull.filter(element => !LocalCollection._f._equal(element, arg)); } target[field] = out; }, $pullAll(target, field, arg) { if (!(typeof arg === 'object' && arg instanceof Array)) { throw MinimongoError( 'Modifier $pushAll/pullAll allowed for arrays only', {field} ); } if (target === undefined) { return; } const toPull = target[field]; if (toPull === undefined) { return; } if (!(toPull instanceof Array)) { throw MinimongoError( 'Cannot apply $pull/pullAll modifier to non-array', {field} ); } target[field] = toPull.filter(object => !arg.some(element => LocalCollection._f._equal(object, element)) ); }, $rename(target, field, arg, keypath, doc) { // no idea why mongo has this restriction.. if (keypath === arg) { throw MinimongoError('$rename source must differ from target', {field}); } if (target === null) { throw MinimongoError('$rename source field invalid', {field}); } if (typeof arg !== 'string') { throw MinimongoError('$rename target must be a string', {field}); } if (arg.includes('\0')) { // Null bytes are not allowed in Mongo field names // https://docs.mongodb.com/manual/reference/limits/#Restrictions-on-Field-Names throw MinimongoError( 'The \'to\' field for $rename cannot contain an embedded null byte', {field} ); } if (target === undefined) { return; } const object = target[field]; delete target[field]; const keyparts = arg.split('.'); const target2 = findModTarget(doc, keyparts, {forbidArray: true}); if (target2 === null) { throw MinimongoError('$rename target field invalid', {field}); } target2[keyparts.pop()] = object; }, $bit(target, field, arg) { // XXX mongo only supports $bit on integers, and we only support // native javascript numbers (doubles) so far, so we can't support $bit throw MinimongoError('$bit is not supported', {field}); }, }; const NO_CREATE_MODIFIERS = { $pop: true, $pull: true, $pullAll: true, $rename: true, $unset: true }; // Make sure field names do not contain Mongo restricted // characters ('.', '$', '\0'). // https://docs.mongodb.com/manual/reference/limits/#Restrictions-on-Field-Names const invalidCharMsg = { $: 'start with \'$\'', '.': 'contain \'.\'', '\0': 'contain null bytes' }; // checks if all field names in an object are valid function assertHasValidFieldNames(doc) { if (doc && typeof doc === 'object') { JSON.stringify(doc, (key, value) => { assertIsValidFieldName(key); return value; }); } } function assertIsValidFieldName(key) { let match; if (typeof key === 'string' && (match = key.match(/^\$|\.|\0/))) { throw MinimongoError(`Key ${key} must not ${invalidCharMsg[match[0]]}`); } } // for a.b.c.2.d.e, keyparts should be ['a', 'b', 'c', '2', 'd', 'e'], // and then you would operate on the 'e' property of the returned // object. // // if options.noCreate is falsey, creates intermediate levels of // structure as necessary, like mkdir -p (and raises an exception if // that would mean giving a non-numeric property to an array.) if // options.noCreate is true, return undefined instead. // // may modify the last element of keyparts to signal to the caller that it needs // to use a different value to index into the returned object (for example, // ['a', '01'] -> ['a', 1]). // // if forbidArray is true, return null if the keypath goes through an array. // // if options.arrayIndices is set, use its first element for the (first) '$' in // the path. function findModTarget(doc, keyparts, options = {}) { let usedArrayIndex = false; for (let i = 0; i < keyparts.length; i++) { const last = i === keyparts.length - 1; let keypart = keyparts[i]; if (!isIndexable(doc)) { if (options.noCreate) { return undefined; } const error = MinimongoError( `cannot use the part '${keypart}' to traverse ${doc}` ); error.setPropertyError = true; throw error; } if (doc instanceof Array) { if (options.forbidArray) { return null; } if (keypart === '$') { if (usedArrayIndex) { throw MinimongoError('Too many positional (i.e. \'$\') elements'); } if (!options.arrayIndices || !options.arrayIndices.length) { throw MinimongoError( 'The positional operator did not find the match needed from the ' + 'query' ); } keypart = options.arrayIndices[0]; usedArrayIndex = true; } else if (isNumericKey(keypart)) { keypart = parseInt(keypart); } else { if (options.noCreate) { return undefined; } throw MinimongoError( `can't append to array using string field name [${keypart}]` ); } if (last) { keyparts[i] = keypart; // handle 'a.01' } if (options.noCreate && keypart >= doc.length) { return undefined; } while (doc.length < keypart) { doc.push(null); } if (!last) { if (doc.length === keypart) { doc.push({}); } else if (typeof doc[keypart] !== 'object') { throw MinimongoError( `can't modify field '${keyparts[i + 1]}' of list value ` + JSON.stringify(doc[keypart]) ); } } } else { assertIsValidFieldName(keypart); if (!(keypart in doc)) { if (options.noCreate) { return undefined; } if (!last) { doc[keypart] = {}; } } } if (last) { return doc; } doc = doc[keypart]; } // notreached }
28.297149
91
0.611604
b415bcdc087af63b54c513640768a1fbe9a61383
46,074
js
JavaScript
src/js/content.js
cnmdgcd748/QZoneExport
12f13703550bb07ddbdf2a189cbb23780c4c3919
[ "Apache-2.0" ]
1
2020-11-17T13:51:25.000Z
2020-11-17T13:51:25.000Z
src/js/content.js
cnmdgcd748/QZoneExport
12f13703550bb07ddbdf2a189cbb23780c4c3919
[ "Apache-2.0" ]
null
null
null
src/js/content.js
cnmdgcd748/QZoneExport
12f13703550bb07ddbdf2a189cbb23780c4c3919
[ "Apache-2.0" ]
null
null
null
// PDF组件兼容大小写 //window.jsPDF = window.jspdf.jsPDF; /** * Ajax下载任务 */ class DownloadTask { /** * @param {string} dir 下载目录 * @param {string} name 文件名,包含后缀 * @param {string} url 文件地址 * @param {object} source 文件来源 */ constructor(dir, name, url, source) { this.dir = dir this.name = name this.url = url this.downloadState = 'in_progress' this.source = source } /** * 设置下载状态 * @param {string} downloadState 下载状态 */ setState(downloadState) { this.downloadState = downloadState; } } /** * 迅雷任务 */ class ThunderTask { /** * * @param {string} dir 下载目录 * @param {string} name 文件名,包含后缀 * @param {string} url 文件地址 * @param {object} source 文件来源 */ constructor(dir, name, url, source) { this.dir = dir this.name = name this.url = url this.downloadState = 'in_progress' this.source = source this.referer = window.location.href } /** * 设置下载状态 * @param {string} downloadState 下载状态 */ setState(downloadState) { this.downloadState = downloadState; } } /** * 迅雷任务信息 */ class ThunderInfo { /** * * @param {string} dir 下载目录 * @param {integer} threadCount 下载 * @param {ThunderTask} tasks 任务 */ constructor(taskGroupName, threadCount, tasks) { this.taskGroupName = taskGroupName this.tasks = tasks || [] this.threadCount = threadCount } /** * 添加下载任务 * @param {ThunderTask} task 任务 */ addTask(task) { this.tasks.push(task); } /** * 删除指定索引任务 * @param {integer} index 数组索引 */ delTask(index) { this.tasks.splice(index, 1); } /** * 根据下载链接删除任务 * @param {string} url 下载链接 */ removeTask(url) { this.tasks.remove(url, 'url') } } /** * 浏览器下载任务 */ class BrowserTask { /** * * @param {string} url 下载地址 * @param {string} root 下载根目录名称 * @param {string} folder 根目录相对名称 * @param {string} name 文件名称 * @param {object} source 文件来源 */ constructor(url, root, folder, name, source) { this.id = 0; this.url = url; this.dir = folder; this.name = name; this.filename = root + '/' + folder + '/' + name; this.downloadState = 'in_progress' this.source = source } /** * 设置下载管理器ID * @param {integer} id 下载管理器ID */ setId(id) { this.id = id } /** * 设置下载状态 * @param {string} downloadState 下载状态 */ setState(downloadState) { this.downloadState = downloadState; } } /** * 分页信息 */ class PageInfo { /** * * @param {integer} index 页索引 * @param {integer} size 页条目大小 */ constructor(index, size) { this.index = 0; this.size = 0; } } /** * 提示信息 */ const MAX_MSG = { Messages: [ '正在获取第 <span style="color: #1ca5fc;">{index}</span> 页的说说列表', '已获取 <span style="color: #1ca5fc;">{downloaded}</span> 条', '已失败 <span style="color: red;">{downloadFailed}</span> 条', '总共 <span style="color: #1ca5fc;">{total}</span> 条', '请稍后...' ], Messages_Filter: [ '正在根据屏蔽词过滤说说列表', '已屏蔽 <span style="color: #1ca5fc;">{downloaded}</span> 条', '已跳过 <span style="color: #1ca5fc;">{skip}</span> 条', '总共 <span style="color: #1ca5fc;">{total}</span> 条', '请稍后...' ], Messages_Full_Content: [ '正在获取第 <span style="color: #1ca5fc;">{index}</span> 条说说的全文', '已获取 <span style="color: #1ca5fc;">{downloaded}</span> 条', '已跳过 <span style="color: #1ca5fc;">{skip}</span> 条', '已失败 <span style="color: red;">{downloadFailed}</span> 条', '总共 <span style="color: #1ca5fc;">{total}</span> 条', '请稍后...' ], Messages_More_Images: [ '正在获取第 <span style="color: #1ca5fc;">{index}</span> 条说说的更多图片', '已获取 <span style="color: #1ca5fc;">{downloaded}</span> 条', '已跳过 <span style="color: #1ca5fc;">{skip}</span> 条', '已失败 <span style="color: red;">{downloadFailed}</span> 条', '总共 <span style="color: #1ca5fc;">{total}</span> 条', '请稍后...' ], Messages_Voices: [ '正在获取第 <span style="color: #1ca5fc;">{index}</span> 条说说的语音信息', '已获取 <span style="color: #1ca5fc;">{downloaded}</span> 条', '已跳过 <span style="color: #1ca5fc;">{skip}</span> 条', '已失败 <span style="color: red;">{downloadFailed}</span> 条', '总共 <span style="color: #1ca5fc;">{total}</span> 条', '请稍后...' ], Messages_Comments: [ '正在获取第 <span style="color: #1ca5fc;">{index}</span> 条说说的评论列表', '已获取 <span style="color: #1ca5fc;">{downloaded}</span> 条', '已失败 <span style="color: red;">{downloadFailed}</span> 条', '总共 <span style="color: #1ca5fc;">{total}</span> 条', '请稍后...' ], Messages_Images_Mime: [ '正在识别说说的图片类型', '已识别 <span style="color: #1ca5fc;">{downloaded}</span> 张', '请稍后...' ], Messages_Like: [ '正在获取第 <span style="color: #1ca5fc;">{index}</span> 条说说的点赞列表', '已获取 <span style="color: #1ca5fc;">{downloaded}</span> 条', '已跳过 <span style="color: #1ca5fc;">{skip}</span> 条', '总共 <span style="color: #1ca5fc;">{total}</span> 条', '请稍后...' ], Messages_Visitor: [ '正在获取第 <span style="color: #1ca5fc;">{index}</span> 条说说的最近访问', '已获取 <span style="color: #1ca5fc;">{downloaded}</span> 条', '已跳过 <span style="color: #1ca5fc;">{skip}</span> 条', '总共 <span style="color: #1ca5fc;">{total}</span> 条', '请稍后...' ], Messages_Export: [ '正在导出说说', '已导出 <span style="color: #1ca5fc;">{downloaded}</span> 条', '已失败 <span style="color: red;">{downloadFailed}</span> 条', '总共 <span style="color: #1ca5fc;">{total}</span> 条', '请稍后...' ], Messages_Export_Other: [ '正在导出说说到 <span style="color: #1ca5fc;">{index}</span> 文件', '请稍后...' ], Blogs: [ '正在获取第 <span style="color: #1ca5fc;">{index}</span> 页的日志列表', '已获取 <span style="color: #1ca5fc;">{downloaded}</span> 篇', '已失败 <span style="color: red;">{downloadFailed}</span> 篇', '总共 <span style="color: #1ca5fc;">{total}</span> 篇', '请稍后...' ], Blogs_Content: [ '正在获取第 <span style="color: #1ca5fc;">{index}</span> 篇的日志内容', '已获取 <span style="color: #1ca5fc;">{downloaded}</span> 篇', '已跳过 <span style="color: #1ca5fc;">{skip}</span> 篇', '已失败 <span style="color: red;">{downloadFailed}</span> 篇', '总共 <span style="color: #1ca5fc;">{total}</span> 篇', '请稍后...' ], Blogs_Comments: [ '正在获取第 <span style="color: #1ca5fc;">{index}</span> 篇日志的评论列表', '已获取 <span style="color: #1ca5fc;">{downloaded}</span> 条', '已失败 <span style="color: red;">{downloadFailed}</span> 条', '总共 <span style="color: #1ca5fc;">{total}</span> 条', '请稍后...' ], Blogs_Like: [ '正在获取第 <span style="color: #1ca5fc;">{index}</span> 篇日志的点赞列表', '已获取 <span style="color: #1ca5fc;">{downloaded}</span> 篇', '已跳过 <span style="color: #1ca5fc;">{skip}</span> 篇', '总共 <span style="color: #1ca5fc;">{total}</span> 篇', '请稍后...' ], Blogs_Visitor: [ '正在获取第 <span style="color: #1ca5fc;">{index}</span> 篇日志的最近访问', '已获取 <span style="color: #1ca5fc;">{downloaded}</span> 篇', '已跳过 <span style="color: #1ca5fc;">{skip}</span> 篇', '总共 <span style="color: #1ca5fc;">{total}</span> 篇', '请稍后...' ], Blogs_Export: [ '正在导出日志', '已导出 <span style="color: #1ca5fc;">{downloaded}</span> 条', '已失败 <span style="color: red;">{downloadFailed}</span> 条', '总共 <span style="color: #1ca5fc;">{total}</span> 条', '请稍后...' ], Blogs_Export_Other: [ '正在导出日志到 <span style="color: #1ca5fc;">{index}</span> 文件', '请稍后...' ], Diaries: [ '正在获取第 <span style="color: #1ca5fc;">{index}</span> 页的私密日记列表', '已获取 <span style="color: #1ca5fc;">{downloaded}</span> 篇', '已失败 <span style="color: red;">{downloadFailed}</span> 篇', '总共 <span style="color: #1ca5fc;">{total}</span> 篇', '请稍后...' ], Diaries_Content: [ '正在获取第 <span style="color: #1ca5fc;">{index}</span> 篇的私密日记内容', '已获取 <span style="color: #1ca5fc;">{downloaded}</span> 篇', '已跳过 <span style="color: #1ca5fc;">{skip}</span> 篇', '已失败 <span style="color: red;">{downloadFailed}</span> 篇', '总共 <span style="color: #1ca5fc;">{total}</span> 篇', '请稍后...' ], Diaries_Export: [ '正在导出私密日记', '已导出 <span style="color: #1ca5fc;">{downloaded}</span> 条', '已失败 <span style="color: red;">{downloadFailed}</span> 条', '总共 <span style="color: #1ca5fc;">{total}</span> 条', '请稍后...' ], Diaries_Export_Other: [ '正在导出私密日记到 <span style="color: #1ca5fc;">{index}</span> 文件', '请稍后...' ], Boards: [ '正在获取第 <span style="color: #1ca5fc;">{index}</span> 页的留言板列表', '已获取 <span style="color: #1ca5fc;">{downloaded}</span> 条', '已失败 <span style="color: red;">{downloadFailed}</span> 条', '总共 <span style="color: #1ca5fc;">{total}</span> 条', '请稍后...' ], Boards_Images_Mime: [ '正在识别留言的图片类型', '已识别 <span style="color: #1ca5fc;">{downloaded}</span> 张', '已失败 <span style="color: red;">{downloadFailed}</span> 张', '请稍后...' ], Boards_Export: [ '正在导出 <span style="color: #1ca5fc;">{index}</span> 年的留言', '已导出 <span style="color: #1ca5fc;">{downloaded}</span> 条', '已失败 <span style="color: red;">{downloadFailed}</span> 条', '总共 <span style="color: #1ca5fc;">{total}</span> 条', '请稍后...' ], Boards_Export_Other: [ '正在导出留言到 <span style="color: #1ca5fc;">{index}</span> 文件', '请稍后...' ], Friends: [ '正在获取QQ好友列表', '已获取好友 <span style="color: #1ca5fc;">{downloaded}</span> 个', '总共 <span style="color: #1ca5fc;">{total}</span> 个', '请稍后...' ], Friends_Time: [ '正在获取好友详细信息', '已获取 <span style="color: #1ca5fc;">{downloaded}</span> 个', '已跳过 <span style="color: #1ca5fc;">{skip}</span> 个', '总共 <span style="color: #1ca5fc;">{total}</span> 个', '请稍后...' ], Friends_Export: [ '正在导出QQ好友到 <span style="color: #1ca5fc;">{index}</span> 文件', '请稍后...' ], Favorites: [ '正在获取第 <span style="color: #1ca5fc;">{index}</span> 页的收藏列表', '已获取 <span style="color: #1ca5fc;">{downloaded}</span> 个', '已失败 <span style="color: red;">{downloadFailed}</span> 个', '总共 <span style="color: #1ca5fc;">{total}</span> 个', '请稍后...' ], Favorites_Export: [ '正在导出 <span style="color: #1ca5fc;">{index}</span> 年的收藏', '已导出 <span style="color: #1ca5fc;">{downloaded}</span> 条', '已失败 <span style="color: red;">{downloadFailed}</span> 条', '总共 <span style="color: #1ca5fc;">{total}</span> 条', '请稍后...' ], Favorites_Export_Other: [ '正在导出收藏到 <span style="color: #1ca5fc;">{index}</span> 文件', '请稍后...' ], Photos: [ '正在获取第 <span style="color: #1ca5fc;">{index}</span> 页的相册列表', '已获取 <span style="color: #1ca5fc;">{downloaded}</span> 个', '已失败 <span style="color: red;">{downloadFailed}</span> 个', '总共 <span style="color: #1ca5fc;">{total}</span> 个', '请稍后...' ], Photos_Albums_Comments: [ '正在获取第 <span style="color: #1ca5fc;">{index}</span> 个相册的评论列表', '已获取 <span style="color: #1ca5fc;">{downloaded}</span> 个', '已失败 <span style="color: red;">{downloadFailed}</span> 个', '总共 <span style="color: #1ca5fc;">{total}</span> 个', '请稍后...' ], Photos_Albums_Like: [ '正在获取第 <span style="color: #1ca5fc;">{index}</span> 个相册的点赞列表', '已获取 <span style="color: #1ca5fc;">{downloaded}</span> 个', '已跳过 <span style="color: #1ca5fc;">{skip}</span> 个', '总共 <span style="color: #1ca5fc;">{total}</span> 个', '请稍后...' ], Photos_Albums_Visitor: [ '正在获取第 <span style="color: #1ca5fc;">{index}</span> 个相册的最近访问', '已获取 <span style="color: #1ca5fc;">{downloaded}</span> 个', '已跳过 <span style="color: #1ca5fc;">{skip}</span> 个', '总共 <span style="color: #1ca5fc;">{total}</span> 个', '请稍后...' ], Photos_Images: [ '正在获取 <span style="color: #1ca5fc;">{index}</span> 的相片列表', '已获取 <span style="color: #1ca5fc;">{downloaded}</span> 张', '已失败 <span style="color: red;">{downloadFailed}</span> 张', '总共 <span style="color: #1ca5fc;">{total}</span> 张', '请稍后...' ], Photos_Images_Info: [ '正在获取 <span style="color: #1ca5fc;">{index}</span> 的相片详情', '已获取 <span style="color: #1ca5fc;">{downloaded}</span> 张', '已跳过 <span style="color: #1ca5fc;">{skip}</span> 张', '已失败 <span style="color: red;">{downloadFailed}</span> 张', '总共 <span style="color: #1ca5fc;">{total}</span> 张', '请稍后...' ], Photos_Images_Comments: [ '正在获取第 <span style="color: #1ca5fc;">{index}</span> 张相片的评论列表', '已获取 <span style="color: #1ca5fc;">{downloaded}</span> 条', '已跳过 <span style="color: #1ca5fc;">{skip}</span> 张', '已失败 <span style="color: red;">{downloadFailed}</span> 条', '总共 <span style="color: #1ca5fc;">{total}</span> 条', '请稍后...' ], Photos_Images_Like: [ '正在获取第 <span style="color: #1ca5fc;">{index}</span> 张相片的点赞列表', '已获取 <span style="color: #1ca5fc;">{downloaded}</span> 张', '已跳过 <span style="color: #1ca5fc;">{skip}</span> 张', '总共 <span style="color: #1ca5fc;">{total}</span> 张', '请稍后...' ], Photos_Images_Mime: [ '正在获取 <span style="color: #1ca5fc;">{index}</span> 的相片类型', '已获取 <span style="color: #1ca5fc;">{downloaded}</span> 张', '已跳过 <span style="color: #1ca5fc;">{skip}</span> 张', '已失败 <span style="color: red;">{downloadFailed}</span> 张', '总共 <span style="color: #1ca5fc;">{total}</span> 张', '请稍后...' ], Photos_Export: [ '正在导出相册到 <span style="color: #1ca5fc;">{index}</span> 文件', '请稍后...' ], Photos_Images_Export: [ '正在导出 <span style="color: #1ca5fc;">{index}</span> 的相片', '已导出 <span style="color: #1ca5fc;">{downloaded}</span> 条', '已失败 <span style="color: red;">{downloadFailed}</span> 条', '总共 <span style="color: #1ca5fc;">{total}</span> 条', '请稍后...' ], Photos_Images_Export_Other: [ '正在导出相片到 <span style="color: #1ca5fc;">{index}</span> 文件', '请稍后...' ], Videos: [ '正在获取第 <span style="color: #1ca5fc;">{index}</span> 页的视频列表', '已获取 <span style="color: #1ca5fc;">{downloaded}</span> 个', '已失败 <span style="color: red;">{downloadFailed}</span> 个', '总共 <span style="color: #1ca5fc;">{total}</span> 个', '请稍后...' ], Videos_Comments: [ '正在获取第 <span style="color: #1ca5fc;">{index}</span> 个视频的评论列表', '已获取 <span style="color: #1ca5fc;">{downloaded}</span> 个', '已失败 <span style="color: red;">{downloadFailed}</span> 个', '总共 <span style="color: #1ca5fc;">{total}</span> 个', '请稍后...' ], Videos_Like: [ '正在获取第 <span style="color: #1ca5fc;">{index}</span> 个视频的点赞列表', '已获取 <span style="color: #1ca5fc;">{downloaded}</span> 个', '已跳过 <span style="color: #1ca5fc;">{skip}</span> 个', '总共 <span style="color: #1ca5fc;">{total}</span> 个', '请稍后...' ], Videos_Export: [ '正在导出视频到 <span style="color: #1ca5fc;">{index}</span> 文件', '请稍后...' ], Common_File: [ '正在下载文件', '已下载 <span style="color: #1ca5fc;">{downloaded}</span> ', '已失败 <span style="color: red;">{downloadFailed}</span> ', '总共 <span style="color: #1ca5fc;">{total}</span> 条', '请稍后...' ], Common_Thunder: [ '正在第 <span style="color: #1ca5fc;">{index}</span> 次唤起迅雷X下载文件', '将在 <span style="color: #1ca5fc;">{nextTip}</span> 秒后再次唤起迅雷', '已添加 <span style="color: #1ca5fc;">{downloaded}</span> ', '总共 <span style="color: #1ca5fc;">{total}</span> 条', '请稍后...' ], Common_Thunder_Link: [ '正在生成迅雷下载链接', '打包下载后,打开迅雷X复制根目录下的【迅雷下载链接.txt】', '请稍后...' ], Common_Browser: [ '正在添加下载任务到浏览器', '已添加 <span style="color: #1ca5fc;">{downloaded}</span> 条', '添加超时或失败 <span style="color: red;">{downloadFailed}</span> ', '总共 <span style="color: #1ca5fc;">{total}</span> 条', '请稍后...' ], Common_Aria2: [ '正在添加下载任务到Aria2', '已添加 <span style="color: #1ca5fc;">{downloaded}</span> 条', '添加超时或失败 <span style="color: red;">{downloadFailed}</span> ', '总共 <span style="color: #1ca5fc;">{total}</span> 条', '请稍后...' ] } /** * 备份进度 */ class StatusIndicator { /** * * @param {string} type 导出类型 */ constructor(type) { this.id = type + '_Tips' this.type = type this.tip = MAX_MSG[type] || '' this.total = 0 this.index = 0 this.pageSize = 0 this.nextTip = 0 this.downloaded = 0 this.downloading = 0 this.downloadFailed = 0 this.skip = 0; } /** * 获取数据 */ getData(dataType) { return this.data[dataType] || [] } /** * 输出提示信息 */ print() { let $tip_dom = $("#" + this.id); $tip_dom.show(); $tip_dom.html(this.tip.join(',').format(this)); } /** * 完成 * @param {object} params 格式化参数 */ complete() { let $tip_dom = $("#" + this.id) $tip_dom.show() $tip_dom.html(this.tip.join(',').format(this).replace('正在', '已').replace('请稍后', '已完成').replace('...', '')) } /** * 下载 */ addDownload(pageSize) { this.downloading = this.downloaded + pageSize this.print() } /** * 下载失败 * @param {Object} item */ addFailed(item) { let count = 1 if (Array.isArray(item)) { count = item.length } else if (item instanceof PageInfo) { count = item['size'] } this.downloadFailed = this.downloadFailed + (count * 1) this.downloading = this.downloading - (count * 1) this.print() } /** * 下载失败 */ setFailed(item) { let count = 1 if (Array.isArray(item)) { count = item.length } else if (item instanceof PageInfo) { count = item['size'] } this.downloadFailed = count; this.downloading = 0 this.print() } /** * 下载成功 */ addSuccess(item) { let count = 1 if (Array.isArray(item)) { count = item.length; } if (typeof item === 'number') { count = item; } this.downloaded = this.downloaded + (count * 1) this.downloading = this.downloading - (count * 1) this.print() } /** * 下载成功 */ setSuccess(item) { let count = 1 if (Array.isArray(item)) { count = item.length; } if (typeof item === 'number') { count = item; } this.downloaded = count this.downloading = 0 this.print() } /** * 设置当前位置 * @param {object} index 当前位置 */ setIndex(index) { this.index = index this.print() } /** * 设置总数 * @param {integer} total */ setTotal(total) { this.total = total this.print() } /** * 设置下一步提示 * @param {string} tip */ setNextTip(tip) { this.nextTip = tip this.print() } /** * 添加跳过条目数 * @param {Object} item */ addSkip(item) { let count = 1 if (Array.isArray(item)) { count = item.length } this.skip = this.skip + count this.print() } /** * 设置跳过条目数 */ setSkip(count) { if (Array.isArray(count)) { count = item.length } this.skip = count this.print() } } /** * 操作类型 */ const OperatorType = { /** * 初始化 */ INIT: 'INIT', /** * 显示弹窗 */ SHOW: 'SHOW', /** * 初始化用户信息 */ INIT_USER_INFO: 'INIT_USER_INFO', /** * 导出用户信息 */ USER_INFO: 'USER_INFO', /** * 获取所有说说列表 */ Messages: 'Messages', /** * 获取日志所有列表 */ Blogs: 'Blogs', /** * 获取私密日记所有列表 */ Diaries: 'Diaries', /** * 获取相册照片 */ Photos: 'Photos', /** * 获取视频列表 */ Videos: 'Videos', /** * 获取留言板列表 */ Boards: 'Boards', /** * 获取QQ好友列表 */ Friends: 'Friends', /** * 获取收藏列表 */ Favorites: 'Favorites', /** * 下载文件 */ FILE_LIST: 'FILE_LIST', /** * 压缩 */ ZIP: 'ZIP', /** * 压缩 */ COMPLETE: 'COMPLETE' } /** * 导出操作 */ class QZoneOperator { /** * 下一步操作 */ async next(moduleType) { switch (moduleType) { case OperatorType.INIT: this.init(); break; case OperatorType.SHOW: // 显示模态对话框 await this.showProcess(); // 初始化FS文件夹 await this.initModelFolder(); this.next(OperatorType.INIT_USER_INFO); break; case OperatorType.INIT_USER_INFO: // 重置QQ空间备份数据 API.Common.resetQzoneItems(); // 初始化用户信息 await API.Common.initUserInfo(); // 初始化上次备份信息 await API.Common.initBackedUpItems(); this.next(OperatorType.Messages); break; case OperatorType.Messages: // 获取说说列表 if (API.Common.isExport(moduleType)) { await API.Messages.export(); } this.next(OperatorType.Blogs); break; case OperatorType.Blogs: // 获取日志列表 if (API.Common.isExport(moduleType)) { await API.Blogs.export(); } this.next(OperatorType.Diaries); break; case OperatorType.Diaries: // 获取私密日记列表 if (API.Common.isExport(moduleType)) { await API.Diaries.export(); } this.next(OperatorType.Boards); break; case OperatorType.Boards: // 获取留言列表 if (API.Common.isExport(moduleType)) { await API.Boards.export(); } this.next(OperatorType.Friends); break; case OperatorType.Friends: // 获取QQ好友列表 if (API.Common.isExport(moduleType)) { await API.Friends.export(); } this.next(OperatorType.Favorites); break; case OperatorType.Favorites: // 获取收藏列表 if (API.Common.isExport(moduleType)) { await API.Favorites.export(); } this.next(OperatorType.Photos); break; case OperatorType.Photos: // 获取相册列表 if (API.Common.isExport(moduleType)) { await API.Photos.export(); } this.next(OperatorType.Videos); break; case OperatorType.Videos: // 获取视频列表 if (API.Common.isExport(moduleType)) { await API.Videos.export(); } this.next(OperatorType.USER_INFO); break; case OperatorType.USER_INFO: // 导出用户信息 await API.Common.exportUser(); this.next(OperatorType.FILE_LIST); break; case OperatorType.FILE_LIST: // 保存数据 await API.Common.saveBackupItems(); // 下载文件 await API.Utils.downloadAllFiles(); this.next(OperatorType.ZIP); break; case OperatorType.ZIP: await API.Utils.sleep(1000); // 压缩 await API.Utils.Zip(FOLDER_ROOT); operator.next(OperatorType.COMPLETE); break; case OperatorType.COMPLETE: // 延迟3秒,确保压缩完 await API.Utils.sleep(1000); $("#downloadBtn").show(); $("#fileList").show(); $("#backupStatus").html("数据采集完成,请下载。"); API.Utils.notification("QQ空间导出助手通知", "空间数据已获取完成,请点击下载!"); break; default: break; } } /** * 初始化 */ init() { if (location.href.indexOf("qzone.qq.com") == -1 || location.protocol == 'filesystem:') { return; } // 获取gtk API.Utils.initGtk(); // 获取Token API.Utils.getQzoneToken(); // 获取QQ号 API.Utils.initUin(); // 获取相册路由 API.Photos.getRoute(); // 读取配置项 chrome.storage.sync.get(Default_Config, function (item) { QZone_Config = item; }) // 初始化文件夹 QZone.Common.Filer.init({ persistent: false, size: 10 * 1024 * 1024 * 1024 }, function (fs) { QZone.Common.Filer.ls(FOLDER_ROOT, function (entries) { console.info('当前子目录:', entries); QZone.Common.Filer.rm(FOLDER_ROOT, function () { console.info('清除历史数据成功!'); }); }); }) } /** * 初始化各个备份模块的文件夹 */ async initModelFolder() { console.info('初始化模块文件夹开始', QZone); // 切换根目录 await API.Utils.switchToRoot(); // 创建模块文件夹 let createModuleFolder = async function () { // 创建所有模块的目录 for (let x in QZone) { let obj = QZone[x]; if (typeof (obj) !== "object") { continue; } let rootPath = obj['IMAGES_ROOT'] || obj['ROOT']; if (!rootPath) { continue; } let entry = await API.Utils.createFolder(rootPath); console.info('创建目录成功', entry); } } // 创建模块文件夹 await createModuleFolder(); // 创建说明文件 let res = await API.Utils.get(chrome.runtime.getURL('others/README.md')); let fileEntry = await API.Utils.writeText(res, FOLDER_ROOT + "README.md"); console.info('生成说明文件完成', fileEntry); console.info('初始化模块文件夹结束', QZone); } /** * 显示备份进度窗口 */ async showProcess() { const html = await API.Utils.get(chrome.extension.getURL('html/indicator.html')); $('body').append(html); $('#progressModal').modal({ backdrop: "static", keyboard: false }); const $progressbar = $("#progressbar"); const $downloadBtn = $('#downloadBtn'); const $fileListBtn = $('#fileList'); // 继续重试 const $againDownloadBtn = $("#againDownload"); // 浏览器下载 const $browserDownloadBtn = $("#browserDownload"); // 迅雷下载 const $thunderDownloadBtn = $("#thunderDownload"); // 下载方式 const downloadType = QZone_Config.Common.downloadType; switch (downloadType) { case 'Browser': // 下载方式为浏览器下载时隐藏【浏览器下载】按钮 $browserDownloadBtn.hide(); // 修改继续重试按钮文本为【继续重试】 $againDownloadBtn.text('继续重试'); break; case 'Aria2': // 修改继续重试按钮文本为【Aria2下载】 $againDownloadBtn.text('Aria2下载'); break; case 'Thunder': // 下载方式为迅雷下载时隐藏【迅雷下载】按钮 $thunderDownloadBtn.hide(); // 修改继续重试按钮文本为【唤起迅雷】 $againDownloadBtn.text('唤起迅雷'); break; case 'Thunder_Link': // 隐藏重试按钮 $againDownloadBtn.hide(); break; case 'File': // 助手内部 $againDownloadBtn.text('继续重试'); break; default: break; } // 【打包下载】按钮点击事件 $downloadBtn.click(() => { $('#progress').show(); $progressbar.css("width", "0%"); $progressbar.attr("aria-valuenow", "0"); $progressbar.text('已下载0%'); $fileListBtn.attr('disabled', true); $downloadBtn.attr('disabled', true); $downloadBtn.text('正在下载'); let zipName = QZone.Common.Config.ZIP_NAME + "_" + QZone.Common.Target.uin + ".zip"; QZone.Common.Zip.generateAsync({ type: "blob" }, (metadata) => { $progressbar.css("width", metadata.percent.toFixed(2) + "%"); $progressbar.attr("aria-valuenow", metadata.percent.toFixed(2)); $progressbar.text('已下载' + metadata.percent.toFixed(2) + '%'); }).then(function (content) { saveAs(content, zipName); $progressbar.css("width", "100%"); $progressbar.attr("aria-valuenow", 100); $progressbar.text('已下载' + '100%'); $downloadBtn.text('已下载'); $downloadBtn.attr('disabled', false); $fileListBtn.attr('disabled', false); $("#showFolder").show(); API.Utils.notification("QQ空间导出助手通知", "你的QQ空间数据下载完成!"); }); }); // 【查看备份】按钮点击事件 let $showFolder = $('#showFolder'); $showFolder.click(() => { chrome.runtime.sendMessage({ from: 'content', type: 'show_export_zip' }); }) //进度模式窗口隐藏后 $('#progressModal').on('hidden.bs.modal', function () { $("#progressModal").remove(); $("#modalTable").remove(); }) /** * 筛选数据 * @param {string} value 过滤标识 */ const filterData = async function (value) { if (value === 'all') { $("#table").bootstrapTable('filterBy'); return; } switch (downloadType) { case 'Browser': // 下载方式为浏览器下载时 // 查询全部下载列表 let downlist = await API.Utils.getDownloadList(undefined); for (const task of browserTasks) { // 更新下载状态到表格 let index = downlist.getIndex(task.id, 'id'); if (index == -1) { // 根据ID找下载项没找到表示没成功添加到浏览器中 task.downloadState = 'interrupted'; continue; } let downloadItem = downlist[index]; task.downloadState = downloadItem.state; } break; default: break; } $("#table").bootstrapTable('filterBy', { downloadState: value }) } // 查看指定状态的数据 $('#statusFilter').change(function () { let value = $(this).val(); if ('interrupted' === value || ('Thunder' === downloadType && 'all' === value)) { // 失败列表与迅雷下载全部列表时才展示【继续重试】按钮 $againDownloadBtn.show(); } else { $againDownloadBtn.hide(); } filterData(value); }) // 【重试】按钮点击事件 $againDownloadBtn.click(async function () { let tasks = $('#table').bootstrapTable('getSelections'); switch (downloadType) { case 'File': // 下载方式为助手下载时 await API.Common.downloadsByAjax(tasks); // 重新压缩 operator.next(OperatorType.ZIP); break; case 'Browser': // 下载方式为浏览器下载时 for (const task of tasks) { if (!task.id || task.id === 0) { // 无ID时表示添加到下载器失败,需要重新添加 await API.Utils.downloadByBrowser(task); return; } await API.Utils.resumeDownload(task.id); } break; case 'Aria2': // 下载方式为Aria2时 await API.Common.downloadByAria2(tasks); break; case 'Thunder': // 下载方式为迅雷下载时 const newThunderInfo = new ThunderInfo(thunderInfo.taskGroupName, QZone_Config.Common.downloadThread, tasks); await API.Common.invokeThunder(newThunderInfo); break; default: break; } }) // 【迅雷下载】点击事件 $("#thunderDownload").click(async function () { let tasks = $('#table').bootstrapTable('getSelections'); let newThunderInfo = new ThunderInfo(thunderInfo.taskGroupName, QZone_Config.Common.downloadThread); for (const task of tasks) { newThunderInfo.tasks.push(new ThunderTask(task.dir, task.name, API.Utils.toHttp(task.url))); task.setState('complete'); } await API.Common.invokeThunder(newThunderInfo) }) // 【浏览器下载】点击事件 $browserDownloadBtn.click(function () { let tasks = $('#table').bootstrapTable('getSelections'); let newBrowserTasks = []; for (const task of tasks) { newBrowserTasks.push(new BrowserTask(API.Utils.toHttp(task.url), thunderInfo.taskGroupName, task.dir, task.name)); task.setState('in_progress'); } API.Common.downloadsByBrowser(newBrowserTasks); }) //显示下载任务列表 $('#modalTable').on('shown.bs.modal', function () { // 重置筛选条件 $('#statusFilter').val('interrupted'); $("#table").bootstrapTable('destroy').bootstrapTable({ undefinedText: '-', toggle: 'table', locale: 'zh-CN', search: true, searchAlign: 'right', height: "450", pagination: true, pageList: "[10, 20, 50, 100, 200, 500, 1000, 2000, 5000, All]", paginationHAlign: 'left', clickToSelect: true, paginationDetailHAlign: 'right', toolbar: '#toolbar', columns: [{ field: 'state', checkbox: true, align: 'left' }, { field: 'name', title: '名称', titleTooltip: '名称', align: 'left', visible: true }, { field: 'dir', title: '路径', titleTooltip: '路径', align: 'left', visible: true, sortable: true }, { field: 'url', title: '地址(建议点击预览)', titleTooltip: '地址(建议点击预览)', align: 'left', visible: true, formatter: (value) => { return '<a target="_brank" href="{0}" >预览</a> '.format(API.Utils.makeViewUrl(value)); } }, { field: 'source', title: '来源(<span style="color:red">打包下载前请勿点击访问</span>)', titleTooltip: '来源,未打包下载前,请勿点击超链接访问,否则将清理已收集的数据。', align: 'left', visible: true, formatter: (value, row, index, field) => { let type = API.Common.getSourceType(value); switch (type) { case 'Messages': // 说说 return API.Utils.getLink(API.Messages.getUniKey(value.tid), '查看说说'); case 'Blogs': // 日志 return API.Utils.getLink(API.Blogs.getUniKey(value.blogid), '查看日志'); case 'Diaries': // 私密日记 return API.Utils.getLink('https://rc.qzone.qq.com/blog?catalog=private', '私密日记'); case 'Photos': // 相册(暂无相册逻辑,直接查看照片即可) return API.Utils.getLink('#', '无'); case 'Images': // 相片 return API.Utils.getLink(API.Photos.getImageViewLink(value), '查看相片'); case 'Videos': // 视频 return API.Utils.getLink(value.url, '查看视频'); case 'Boards': // 留言板 return API.Utils.getLink('https://user.qzone.qq.com/{0}/334'.format(QZone.Common.Target.uin), '查看留言'); case 'Favorites': // 收藏夹 return API.Utils.getLink('https://user.qzone.qq.com/{0}/favorite'.format(QZone.Common.Target.uin), '查看收藏'); default: return API.Utils.getLink('#', '无'); } } }], data: API.Utils.getDownloadTasks() }) $('#table').bootstrapTable('resetView') // 默认加载失败的数据 filterData("interrupted"); }) } } // 操作器 const operator = new QZoneOperator(); // Ajax下载任务 const downloadTasks = new Array(); // 迅雷下载信息 const thunderInfo = new ThunderInfo(QZone.Common.Config.ZIP_NAME); // 浏览器下载信息 const browserTasks = new Array(); /** * 初始化监听 */ (function () { // 消息监听 chrome.runtime.onConnect.addListener(function (port) { console.info("消息发送者:", port); switch (port.name) { case 'popup': port.onMessage.addListener(function (request) { switch (request.subject) { case 'startBackup': QZone.Common.ExportType = request.exportType; // 清空之前选择的相册 QZone.Photos.Album.Select = []; QZone.Photos.Album.Select = request.albums || []; // 显示进度窗口 operator.next(OperatorType.SHOW); port.postMessage(QZone.Common.ExportType); break; case 'initUin': // 获取QQ号 let res = API.Utils.initUin(); port.postMessage(res); break; case 'initDiaries': // 获取私密日志 API.Diaries.getDiaries(0).then((data) => { port.postMessage(API.Utils.toJson(data, /^_Callback\(/)); }); break; case 'initAlbumInfo': // 获取相册信息 API.Photos.getAlbums(0).then((data) => { // 去掉函数,保留json data = API.Utils.toJson(data, /^shine0_Callback\(/); if (data.data && data.data.user && data.data.user.diskused) { data.data.user.capacity = API.Photos.getCapacityDisplay(data.data.user.diskused); } port.postMessage(data); }); break; case 'getAlbumList': // 获取相册列表 if (_.isEmpty(QZone.Photos.Album.Data)) { API.Photos.getAllAlbumList().then((data) => { port.postMessage(data); }); } else { port.postMessage(QZone.Photos.Album.Data); } break; default: break; } }); break; default: break; } }); operator.next(OperatorType.INIT); })() /** * 添加下载任务 * @param {string} item 对象 * @param {string} url URL * @param {string} module_dir 模块下载目录 * @param {object} source 来源 * @param {string} FILE_URLS 文件下载链接 * @param {string} suffix 文件后缀 */ API.Utils.addDownloadTasks = async (item, url, module_dir, source, FILE_URLS, suffix) => { url = API.Utils.toHttp(url); item.custom_url = url; if (API.Common.isQzoneUrl()) { return; } let filename = FILE_URLS.get(url); if (!filename) { filename = API.Utils.newSimpleUid(8, 16); if (suffix) { filename = filename + suffix; item.custom_mimeType = suffix; } else { let autoSuffix = await API.Utils.autoFileSuffix(url); filename = filename + autoSuffix; item.custom_mimeType = autoSuffix; } } item.custom_filename = filename; item.custom_filepath = 'Images/' + filename; if (!FILE_URLS.has(url)) { // 添加下载任务 API.Utils.newDownloadTask(url, module_dir, filename, source, suffix); FILE_URLS.set(url, filename); } } /** * 添加下载任务 * @param {url} url 下载地址 * @param {folder} folder 下载相对目录 * @param {name} name 文件名称 * @param {object} source 文件来源 */ API.Utils.newDownloadTask = (url, folder, name, source, makeOrg) => { if (!url) { return; } url = makeOrg ? url : API.Utils.makeDownloadUrl(url, true); // 添加Ajax请求下载任务 const ajax_down = new DownloadTask(folder, name, API.Common.isFile() ? API.Utils.toHttps(url) : url, source); // 添加浏览器下载任务 const browser_down = new BrowserTask(url, QZone.Common.Config.ZIP_NAME, folder, name, source); // 添加迅雷下载任务 const thunder_down = new ThunderTask(folder, name, url, source); // 因为视频存在有效期,所以尽量将MP4文件前置,尽早下载 if (name && name.indexOf('mp4') > -1) { downloadTasks.unshift(); downloadTasks.unshift(ajax_down); browserTasks.unshift(browser_down); thunderInfo.addTask(thunder_down); return; } downloadTasks.push(ajax_down); browserTasks.push(browser_down); thunderInfo.addTask(thunder_down); } /** * 下载文件 */ API.Utils.downloadAllFiles = async () => { let downloadType = QZone_Config.Common.downloadType; if (downloadType === 'QZone') { // 使用QQ空间外链时,不需要下载文件 return; } if (downloadTasks.length === 0 || thunderInfo.tasks.length === 0 || browserTasks.length === 0) { // 没有下载任务的时候,不调用下载逻辑 return; } switch (downloadType) { case 'File': await API.Common.downloadsByAjax(downloadTasks); break; case 'Aria2': await API.Common.downloadByAria2(downloadTasks); break; case 'Thunder': await API.Common.invokeThunder(thunderInfo); break; case 'Thunder_Link': // 写入迅雷任务到文件 await API.Common.writeThunderTaskToFile(thunderInfo); break; case 'Browser': await API.Common.downloadsByBrowser(browserTasks); break; default: console.warn('未识别类型', downloadType); break; } } /** * 获取下载任务 */ API.Utils.getDownloadTasks = () => { // 下载方式 let downloadType = QZone_Config.Common.downloadType; let tasks = []; switch (downloadType) { case 'File': tasks = downloadTasks; break; case 'Browser': tasks = browserTasks; break; case 'Aria2': tasks = downloadTasks; break; case 'Thunder': tasks = thunderInfo.tasks; break; case 'Thunder_Link': tasks = thunderInfo.tasks; break; default: break; } return tasks; } /** * 获取下载失败的下载任务 */ API.Utils.getFailedTasks = () => { // 下载方式 let downloadType = QZone_Config.Common.downloadType; let tasks = []; switch (downloadType) { case 'File': for (const downloadTask of downloadTasks) { if (downloadTask.success) { continue; } tasks.push(downloadTask); } break; case 'Browser': tasks = browserTasks; break; case 'Thunder': tasks = thunderInfo.tasks; break; default: break; } return tasks; }
30.984533
139
0.476429
b4162ed9c8b1b659e51c925c4dabefde0adcb396
1,212
js
JavaScript
src/components/SearchBox/SearchBox.js
KutieKat/github-emojis-cheatsheet
4aa21e02b1e233f6dc2592a241beffbc2501a0f6
[ "MIT" ]
null
null
null
src/components/SearchBox/SearchBox.js
KutieKat/github-emojis-cheatsheet
4aa21e02b1e233f6dc2592a241beffbc2501a0f6
[ "MIT" ]
3
2020-07-16T07:58:06.000Z
2021-05-07T14:16:54.000Z
src/components/SearchBox/SearchBox.js
KutieKat/github-emojis-cheatsheet
4aa21e02b1e233f6dc2592a241beffbc2501a0f6
[ "MIT" ]
null
null
null
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { updateKeyword, resetKeyword, filterEmojis } from '../../store/ActionCreators'; import './SearchBox.css'; class SearchBox extends Component { handleResetKeyword() { this.props.dispatch(resetKeyword()); this.props.dispatch(filterEmojis()); } handleChangeKeyword(e) { this.props.dispatch(updateKeyword(e.target.value)); this.props.dispatch(filterEmojis()); } render() { let removeButton = null; if(this.props.keyword != '') { removeButton = <button className="btn" onClick={ () => this.handleResetKeyword() }><i className="fas fa-times-circle btn-remove"></i></button>; } return ( <header className="search-box"> <input type="text" placeholder={ 'Search ' + this.props.filteredEmojis.length + ' emojis for...' } value={ this.props.keyword } onChange={ (e) => this.handleChangeKeyword(e) } /> { removeButton } </header> ); } } function mapStateToProps(state) { return { keyword: state.keyword, filteredEmojis: state.filteredEmojis } } export default connect(mapStateToProps)(SearchBox);
27.545455
149
0.644389
b4164795e84244eed20dbe8be3096d264185ee0c
2,790
js
JavaScript
src/bordered-rect/svg-border-control.js
HaturiHanzo/svg-extras
61c6766d9e4fb0fa6ba6c0ce2d4a8b731d69c00f
[ "MIT" ]
1
2018-11-16T20:38:56.000Z
2018-11-16T20:38:56.000Z
src/bordered-rect/svg-border-control.js
HaturiHanzo/svg-extras
61c6766d9e4fb0fa6ba6c0ce2d4a8b731d69c00f
[ "MIT" ]
2
2016-10-28T13:50:09.000Z
2016-11-02T14:21:45.000Z
src/bordered-rect/svg-border-control.js
HaturiHanzo/svg-extras
61c6766d9e4fb0fa6ba6c0ce2d4a8b731d69c00f
[ "MIT" ]
null
null
null
(function (svgext) { 'use strict'; svgext.SVGBorderControl = inherit(svgext.SVGRect, /** @lends svgext.SVGBorderControl.prototype*/ { /** * Creates svgext.SVGBorderControl * * @constructs svgext.SVGBorderControl * @classdesc Defines bordered rectangle controls class * @augments svgext.SVGRect * @private */ __constructor: function () { this.__base({ cssClass: 'svg-border-control', isDraggable: true, width: svgext.default.control.width, height: svgext.default.control.width }); if (svgext._isTouchDevice) { this.addClass('svg-control_type_touch'); } }, /** * Renders border control * * @override {SVGElement} */ onAppend: function (container) { this.__base(container); this.render(); }, /** * SVGDraggable normalizeCoords implementation * * @override {SVGDraggable} */ normalizeCoords: function (delta) { var containerSize = this.getContainerRect(), rect = this.container; if (rect.width() + delta.x < 1) { delta.x = rect.width() > 1 ? (-1) * (rect.width() - 1) : 0; } else if (rect.getX() + rect.width() + delta.x > containerSize.width) { delta.x = containerSize.width - rect.getX() - rect.width(); } if (rect.height() + delta.y < 1) { delta.y = rect.height() > 1 ? (-1) * rect.height() + 1 : 0; } else if (rect.getY() + rect.height() + delta.y > containerSize.height) { delta.y = containerSize.height - rect.getY() - rect.height(); } return delta; }, /** * SVGDraggable drag implementation * * @override {SVGDraggable} */ drag: function (delta) { var rect = this.container; rect.width(rect.width() + delta.x).height(rect.height() + delta.y); }, /** * Places control on the bottom of border rectangle * * @param {axis} [axis] Changed axis */ render: function (axis) { var rect = this.container, offset = svgext.default.borderedRect.borderOffset; if (axis !== 'x') { this.setY(rect.getY() + rect.height() + offset - svgext.default.control.height / 2); } if (axis !== 'y') { this.setX(rect.getX() + rect.width() + offset - svgext.default.control.width / 2); } } }); }(svgext));
31
102
0.48638
b41757cfadc4b70e552a7370b3fa15827f6e3493
4,028
js
JavaScript
node_modules/bs-logger/dist/testing/target-mock.js
zommerfelds/upload-google-play
c18b0b075876f269534287e32a386a1e69079a23
[ "MIT" ]
327
2019-09-27T23:17:00.000Z
2022-03-30T20:42:29.000Z
node_modules/bs-logger/dist/testing/target-mock.js
zommerfelds/upload-google-play
c18b0b075876f269534287e32a386a1e69079a23
[ "MIT" ]
758
2019-09-10T17:31:18.000Z
2022-03-03T19:47:57.000Z
node_modules/bs-logger/dist/testing/target-mock.js
zommerfelds/upload-google-play
c18b0b075876f269534287e32a386a1e69079a23
[ "MIT" ]
101
2020-11-02T08:03:05.000Z
2022-03-29T00:55:40.000Z
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var context_1 = require("../logger/context"); var level_1 = require("../logger/level"); var extendArray = function (array) { return Object.defineProperty(array, 'last', { configurable: true, get: function () { return this[this.length - 1]; }, }); }; exports.extendArray = extendArray; var LogTargetMock = (function () { function LogTargetMock(minLevel) { if (minLevel === void 0) { minLevel = -Infinity; } var _this = this; this.minLevel = minLevel; this.messages = Object.defineProperties(extendArray([]), { trace: { get: function () { return _this.filteredMessages(level_1.LogLevels.trace); } }, debug: { get: function () { return _this.filteredMessages(level_1.LogLevels.debug); } }, info: { get: function () { return _this.filteredMessages(level_1.LogLevels.info); } }, warn: { get: function () { return _this.filteredMessages(level_1.LogLevels.warn); } }, error: { get: function () { return _this.filteredMessages(level_1.LogLevels.error); } }, fatal: { get: function () { return _this.filteredMessages(level_1.LogLevels.fatal); } }, }); this.lines = Object.defineProperties(extendArray([]), { trace: { get: function () { return _this.filteredLines(level_1.LogLevels.trace); } }, debug: { get: function () { return _this.filteredLines(level_1.LogLevels.debug); } }, info: { get: function () { return _this.filteredLines(level_1.LogLevels.info); } }, warn: { get: function () { return _this.filteredLines(level_1.LogLevels.warn); } }, error: { get: function () { return _this.filteredLines(level_1.LogLevels.error); } }, fatal: { get: function () { return _this.filteredLines(level_1.LogLevels.fatal); } }, }); this.stream = { write: function (msg) { return !!_this.lines.push(msg); }, }; } LogTargetMock.prototype.format = function (msg) { this.messages.push(msg); var lvl = msg.context[context_1.LogContexts.logLevel]; if (lvl != null) { return "[level:" + lvl + "] " + msg.message; } return msg.message; }; LogTargetMock.prototype.clear = function () { this.messages.splice(0, this.messages.length); this.lines.splice(0, this.lines.length); }; LogTargetMock.prototype.filteredMessages = function (level, untilLevel) { var filter; if (level == null) { filter = function (m) { return m.context[context_1.LogContexts.logLevel] == null; }; } else if (untilLevel != null) { filter = function (m) { var lvl = m.context[context_1.LogContexts.logLevel]; return lvl != null && lvl >= level && lvl <= untilLevel; }; } else { filter = function (m) { return m.context[context_1.LogContexts.logLevel] === level; }; } return extendArray(this.messages.filter(filter)); }; LogTargetMock.prototype.filteredLines = function (level, untilLevel) { var extractLevel = function (line) { var level = (line.match(/^\[level:([0-9]+)\] /) || [])[1]; return level == null ? undefined : parseInt(level, 10); }; var filter; if (level == null) { filter = function (line) { return extractLevel(line) === undefined; }; } else if (untilLevel != null) { filter = function (line) { var lvl = extractLevel(line); return lvl != null && lvl >= level && lvl <= untilLevel; }; } else { filter = function (line) { return extractLevel(line) === level; }; } return extendArray(this.lines.filter(filter)); }; return LogTargetMock; }()); exports.LogTargetMock = LogTargetMock;
44.755556
100
0.57423
b41767afe433dd0d37aacab7057f33972c2fcb6d
1,596
js
JavaScript
huxley/www/js/stores/CommitteeFeedbackStore.js
srisainachuri/huxley
7166a1423e49b506d6d5f142c748eac4e5d2314c
[ "BSD-3-Clause" ]
1
2017-06-08T20:13:03.000Z
2017-06-08T20:13:03.000Z
huxley/www/js/stores/CommitteeFeedbackStore.js
srisainachuri/huxley
7166a1423e49b506d6d5f142c748eac4e5d2314c
[ "BSD-3-Clause" ]
1
2017-08-17T16:15:41.000Z
2017-08-17T16:15:41.000Z
huxley/www/js/stores/CommitteeFeedbackStore.js
srisainachuri/huxley
7166a1423e49b506d6d5f142c748eac4e5d2314c
[ "BSD-3-Clause" ]
null
null
null
/** * Copyright (c) 2011-2016 Berkeley Model United Nations. All rights reserved. * Use of this source code is governed by a BSD License (see LICENSE). */ 'use strict'; var ActionConstants = require('constants/ActionConstants'); var CommitteeFeedbackActions = require('actions/CommitteeFeedbackActions'); var Dispatcher = require('dispatcher/Dispatcher'); var ServerAPI = require('lib/ServerAPI'); var {Store} = require('flux/utils'); var _committeeFeedbacks = {}; var _committeeFeedbacksFetched = false; var _feedbackSubmimtted = false; class CommitteeFeedbackStore extends Store { getCommitteeFeedback(committeeID) { var feedbackIDs = Object.keys(_committeeFeedbacks); if (!_committeeFeedbacksFetched) { ServerAPI.getCommitteeFeedback(committeeID).then(value => { CommitteeFeedbackActions.committeeFeedbackFetched(value); }); return []; } return feedbackIDs.map(id => _committeeFeedbacks[id]); } feedbackSubmitted() { return _feedbackSubmimtted; } __onDispatch(action) { switch (action.actionType) { case ActionConstants.ADD_COMMITTEE_FEEDBACK: _committeeFeedbacks[action.feedback.id] = action.feedback; _feedbackSubmimtted = true; break; case ActionConstants.COMMITTEE_FEEDBACK_FETCHED: for (const feedback of action.feedback) { _committeeFeedbacks[feedback.id] = feedback; } _committeeFeedbacksFetched = true; break; default: return; } this.__emitChange(); } } module.exports = new CommitteeFeedbackStore(Dispatcher);
28.5
78
0.709273
b4180205f6728796c2a07eefa99c18e0664d7e6d
741
js
JavaScript
web/libraries/StoryMapJS/source/js/media/types/VCO.Media.Profile.js
cainaru/d8-digital-stlawu
ad60dae2b9ce2bd51a6b7a96173c7139149dad2f
[ "MIT" ]
null
null
null
web/libraries/StoryMapJS/source/js/media/types/VCO.Media.Profile.js
cainaru/d8-digital-stlawu
ad60dae2b9ce2bd51a6b7a96173c7139149dad2f
[ "MIT" ]
4
2020-03-31T18:38:08.000Z
2021-04-30T21:08:46.000Z
web/libraries/StoryMapJS/source/js/media/types/VCO.Media.Profile.js
cainaru/d8-digital-stlawu
ad60dae2b9ce2bd51a6b7a96173c7139149dad2f
[ "MIT" ]
null
null
null
/* VCO.Media.Profile ================================================== */ VCO.Media.Profile = VCO.Media.extend({ includes: [VCO.Events], /* Load the media ================================================== */ _loadMedia: function() { // Loading Message this.message.updateMessage(VCO.Language.messages.loading + " " + this.options.media_name); this._el.content_item = VCO.Dom.create("img", "vco-media-item vco-media-image vco-media-profile vco-media-shadow", this._el.content); this._el.content_item.src = this.data.url; this.onLoaded(); }, _updateMediaDisplay: function(layout) { if(VCO.Browser.firefox) { this._el.content_item.style.maxWidth = (this.options.width/2) - 40 + "px"; } } });
25.551724
138
0.577598
b41804e282115b18787f23f18bb3ad36cb64b885
17,109
js
JavaScript
src/__tests__/handleSubmit.spec.js
oliviermarcotte/redux-form
e7ce5aec2bf0e24574e6f5f90bc04b9815c8e52e
[ "MIT" ]
1
2019-06-28T02:47:21.000Z
2019-06-28T02:47:21.000Z
src/__tests__/handleSubmit.spec.js
oliviermarcotte/redux-form
e7ce5aec2bf0e24574e6f5f90bc04b9815c8e52e
[ "MIT" ]
12
2017-12-13T08:48:49.000Z
2019-06-20T10:14:40.000Z
src/__tests__/handleSubmit.spec.js
oliviermarcotte/redux-form
e7ce5aec2bf0e24574e6f5f90bc04b9815c8e52e
[ "MIT" ]
12
2017-12-13T07:47:26.000Z
2021-01-05T08:20:43.000Z
import handleSubmit from '../handleSubmit' import SubmissionError from '../SubmissionError' import { noop } from 'lodash' describe('handleSubmit', () => { it('should stop if sync validation fails', () => { const values = { foo: 'bar', baz: 42 } const submit = jest.fn().mockImplementation(() => 69) const startSubmit = jest.fn() const stopSubmit = jest.fn() const touch = jest.fn() const setSubmitFailed = jest.fn() const setSubmitSucceeded = jest.fn() const asyncValidate = jest.fn() const props = { startSubmit, stopSubmit, touch, setSubmitFailed, setSubmitSucceeded, values } handleSubmit(submit, props, false, asyncValidate, ['foo', 'baz']) expect(submit).not.toHaveBeenCalled() expect(startSubmit).not.toHaveBeenCalled() expect(stopSubmit).not.toHaveBeenCalled() expect(touch).toHaveBeenCalledWith('foo', 'baz') expect(asyncValidate).not.toHaveBeenCalled() expect(setSubmitSucceeded).not.toHaveBeenCalled() expect(setSubmitFailed).toHaveBeenCalledWith('foo', 'baz') }) it('should stop and return errors if sync validation fails', () => { const values = { foo: 'bar', baz: 42 } const submit = jest.fn().mockImplementation(() => 69) const syncErrors = { foo: 'error' } const startSubmit = jest.fn() const stopSubmit = jest.fn() const touch = jest.fn() const setSubmitFailed = jest.fn() const setSubmitSucceeded = jest.fn() const asyncValidate = jest.fn() const props = { startSubmit, stopSubmit, touch, setSubmitFailed, setSubmitSucceeded, syncErrors, values } const result = handleSubmit(submit, props, false, asyncValidate, [ 'foo', 'baz' ]) expect(asyncValidate).not.toHaveBeenCalled() expect(submit).not.toHaveBeenCalled() expect(startSubmit).not.toHaveBeenCalled() expect(stopSubmit).not.toHaveBeenCalled() expect(touch).toHaveBeenCalledWith('foo', 'baz') expect(setSubmitSucceeded).not.toHaveBeenCalled() expect(setSubmitFailed).toHaveBeenCalledWith('foo', 'baz') expect(result).toEqual(syncErrors) }) it('should return result of sync submit', () => { const values = { foo: 'bar', baz: 42 } const submit = jest.fn().mockImplementation(() => 69) const dispatch = noop const startSubmit = jest.fn() const stopSubmit = jest.fn() const touch = jest.fn() const setSubmitFailed = jest.fn() const setSubmitSucceeded = jest.fn() const asyncValidate = undefined const props = { dispatch, startSubmit, stopSubmit, touch, setSubmitFailed, setSubmitSucceeded, values } expect( handleSubmit(submit, props, true, asyncValidate, ['foo', 'baz']) ).toBe(69) expect(submit).toHaveBeenCalledWith(values, dispatch, props) expect(startSubmit).not.toHaveBeenCalled() expect(stopSubmit).not.toHaveBeenCalled() expect(touch).toHaveBeenCalledWith('foo', 'baz') expect(setSubmitFailed).not.toHaveBeenCalled() expect(setSubmitSucceeded).toHaveBeenCalled() }) it('should not submit if async validation fails', () => { const values = { foo: 'bar', baz: 42 } const submit = jest.fn().mockImplementation(() => 69) const dispatch = noop const startSubmit = jest.fn() const stopSubmit = jest.fn() const touch = jest.fn() const setSubmitFailed = jest.fn() const setSubmitSucceeded = jest.fn() const asyncValidate = jest .fn() .mockImplementation(() => Promise.resolve(values)) const props = { dispatch, startSubmit, stopSubmit, touch, setSubmitFailed, setSubmitSucceeded, values } return handleSubmit(submit, props, true, asyncValidate, ['foo', 'baz']) .then(() => { throw new Error('Expected to fail') }) .catch(result => { expect(result).toBe(values) expect(asyncValidate).toHaveBeenCalledWith() expect(submit).not.toHaveBeenCalled() expect(startSubmit).not.toHaveBeenCalled() expect(stopSubmit).not.toHaveBeenCalled() expect(touch).toHaveBeenCalledWith('foo', 'baz') expect(setSubmitSucceeded).not.toHaveBeenCalled() expect(setSubmitFailed).toHaveBeenCalledWith('foo', 'baz') }) }) it('should call onSubmitFail with async errors and dispatch if async validation fails and onSubmitFail is defined', () => { const values = { foo: 'bar', baz: 42 } const submit = jest.fn().mockImplementation(() => 69) const dispatch = noop const startSubmit = jest.fn() const stopSubmit = jest.fn() const onSubmitFail = jest.fn() const touch = jest.fn() const setSubmitFailed = jest.fn() const setSubmitSucceeded = jest.fn() const asyncValidate = jest .fn() .mockImplementation(() => Promise.resolve(values)) const props = { dispatch, onSubmitFail, startSubmit, stopSubmit, touch, setSubmitFailed, setSubmitSucceeded, values } return handleSubmit(submit, props, true, asyncValidate, ['foo', 'baz']) .then(() => { throw new Error('Expected to fail') }) .catch(result => { expect(result).toBe(values) expect(asyncValidate).toHaveBeenCalledWith() expect(submit).not.toHaveBeenCalled() expect(startSubmit).not.toHaveBeenCalled() expect(stopSubmit).not.toHaveBeenCalled() expect(onSubmitFail).toHaveBeenCalled() expect(onSubmitFail.mock.calls[0][0]).toEqual(values) expect(onSubmitFail.mock.calls[0][1]).toEqual(dispatch) expect(onSubmitFail.mock.calls[0][2]).toBe(null) expect(onSubmitFail.mock.calls[0][3]).toEqual(props) expect(touch).toHaveBeenCalledWith('foo', 'baz') expect(setSubmitSucceeded).not.toHaveBeenCalled() expect(setSubmitFailed).toHaveBeenCalledWith('foo', 'baz') }) }) it('should not submit if async validation fails and return rejected promise', () => { const values = { foo: 'bar', baz: 42 } const submit = jest.fn().mockImplementation(() => 69) const dispatch = noop const startSubmit = jest.fn() const stopSubmit = jest.fn() const touch = jest.fn() const setSubmitFailed = jest.fn() const setSubmitSucceeded = jest.fn() const asyncErrors = { foo: 'async error' } const asyncValidate = jest .fn() .mockImplementation(() => Promise.reject(asyncErrors)) const props = { dispatch, startSubmit, stopSubmit, touch, setSubmitFailed, setSubmitSucceeded, values } return handleSubmit(submit, props, true, asyncValidate, ['foo', 'baz']) .then(() => { throw new Error('Expected to fail') }) .catch(result => { expect(result).toBe(asyncErrors) expect(asyncValidate).toHaveBeenCalledWith() expect(submit).not.toHaveBeenCalled() expect(startSubmit).not.toHaveBeenCalled() expect(stopSubmit).not.toHaveBeenCalled() expect(touch).toHaveBeenCalledWith('foo', 'baz') expect(setSubmitSucceeded).not.toHaveBeenCalled() expect(setSubmitFailed).toHaveBeenCalledWith('foo', 'baz') }) }) it('should sync submit if async validation passes', () => { const values = { foo: 'bar', baz: 42 } const submit = jest.fn().mockImplementation(() => 69) const dispatch = noop const startSubmit = jest.fn() const stopSubmit = jest.fn() const touch = jest.fn() const setSubmitFailed = jest.fn() const setSubmitSucceeded = jest.fn() const asyncValidate = jest.fn().mockImplementation(() => Promise.resolve()) const props = { dispatch, startSubmit, stopSubmit, touch, setSubmitFailed, setSubmitSucceeded, values } return handleSubmit(submit, props, true, asyncValidate, [ 'foo', 'baz' ]).then(result => { expect(result).toBe(69) expect(asyncValidate).toHaveBeenCalledWith() expect(submit).toHaveBeenCalledWith(values, dispatch, props) expect(startSubmit).not.toHaveBeenCalled() expect(stopSubmit).not.toHaveBeenCalled() expect(touch).toHaveBeenCalledWith('foo', 'baz') expect(setSubmitFailed).not.toHaveBeenCalled() expect(setSubmitSucceeded).toHaveBeenCalled() }) }) it('should async submit if async validation passes', () => { const values = { foo: 'bar', baz: 42 } const submit = jest.fn().mockImplementation(() => Promise.resolve(69)) const dispatch = noop const startSubmit = jest.fn() const stopSubmit = jest.fn() const touch = jest.fn() const setSubmitFailed = jest.fn() const setSubmitSucceeded = jest.fn() const asyncValidate = jest.fn().mockImplementation(() => Promise.resolve()) const props = { dispatch, startSubmit, stopSubmit, touch, setSubmitFailed, setSubmitSucceeded, values } return handleSubmit(submit, props, true, asyncValidate, [ 'foo', 'baz' ]).then(result => { expect(result).toBe(69) expect(asyncValidate).toHaveBeenCalledWith() expect(submit).toHaveBeenCalledWith(values, dispatch, props) expect(startSubmit).toHaveBeenCalled() expect(stopSubmit).toHaveBeenCalledWith() expect(touch).toHaveBeenCalledWith('foo', 'baz') expect(setSubmitFailed).not.toHaveBeenCalled() expect(setSubmitSucceeded).toHaveBeenCalled() }) }) it('should set submit errors if async submit fails', () => { const values = { foo: 'bar', baz: 42 } const submitErrors = { foo: 'submit error' } const submit = jest .fn() .mockImplementation(() => Promise.reject(new SubmissionError(submitErrors)) ) const dispatch = noop const startSubmit = jest.fn() const stopSubmit = jest.fn() const touch = jest.fn() const setSubmitFailed = jest.fn() const setSubmitSucceeded = jest.fn() const asyncValidate = jest.fn().mockImplementation(() => Promise.resolve()) const props = { dispatch, startSubmit, stopSubmit, touch, setSubmitFailed, setSubmitSucceeded, values } return handleSubmit(submit, props, true, asyncValidate, [ 'foo', 'baz' ]).then(error => { expect(error).toBe(submitErrors) expect(asyncValidate).toHaveBeenCalledWith() expect(submit).toHaveBeenCalledWith(values, dispatch, props) expect(startSubmit).toHaveBeenCalled() expect(stopSubmit).toHaveBeenCalledWith(submitErrors) expect(touch).toHaveBeenCalledWith('foo', 'baz') expect(setSubmitFailed).toHaveBeenCalled() expect(setSubmitSucceeded).not.toHaveBeenCalled() }) }) it('should not set errors if rejected value not a SubmissionError', () => { const values = { foo: 'bar', baz: 42 } const submitErrors = { foo: 'submit error' } const submit = jest .fn() .mockImplementation(() => Promise.reject(submitErrors)) const dispatch = noop const startSubmit = jest.fn() const stopSubmit = jest.fn() const touch = jest.fn() const setSubmitFailed = jest.fn() const setSubmitSucceeded = jest.fn() const asyncValidate = jest.fn().mockImplementation(() => Promise.resolve()) const props = { dispatch, startSubmit, stopSubmit, touch, setSubmitFailed, setSubmitSucceeded, values } const resolveSpy = jest.fn() const errorSpy = jest.fn() return handleSubmit(submit, props, true, asyncValidate, ['foo', 'baz']) .then(resolveSpy, errorSpy) .then(() => { expect(resolveSpy).not.toHaveBeenCalled() expect(errorSpy).toHaveBeenCalledWith(submitErrors) expect(asyncValidate).toHaveBeenCalledWith() expect(submit).toHaveBeenCalledWith(values, dispatch, props) expect(startSubmit).toHaveBeenCalled() expect(stopSubmit).toHaveBeenCalledWith(undefined) // not wrapped in SubmissionError expect(touch).toHaveBeenCalledWith('foo', 'baz') expect(setSubmitFailed).toHaveBeenCalled() expect(setSubmitSucceeded).not.toHaveBeenCalled() }) }) it('should set submit errors if async submit fails and return rejected promise', () => { const values = { foo: 'bar', baz: 42 } const submitErrors = { foo: 'submit error' } const submit = jest .fn() .mockImplementation(() => Promise.reject(new SubmissionError(submitErrors)) ) const dispatch = noop const startSubmit = jest.fn() const stopSubmit = jest.fn() const touch = jest.fn() const setSubmitFailed = jest.fn() const setSubmitSucceeded = jest.fn() const asyncValidate = jest.fn().mockImplementation(() => Promise.resolve()) const props = { dispatch, startSubmit, stopSubmit, touch, setSubmitFailed, setSubmitSucceeded, values } return handleSubmit(submit, props, true, asyncValidate, [ 'foo', 'baz' ]).then(error => { expect(error).toBe(submitErrors) expect(asyncValidate).toHaveBeenCalledWith() expect(submit).toHaveBeenCalledWith(values, dispatch, props) expect(startSubmit).toHaveBeenCalled() expect(stopSubmit).toHaveBeenCalledWith(submitErrors) expect(touch).toHaveBeenCalledWith('foo', 'baz') expect(setSubmitFailed).toHaveBeenCalled() expect(setSubmitSucceeded).not.toHaveBeenCalled() }) }) it('should submit when there are old submit errors and persistentSubmitErrors is enabled', () => { const values = { foo: 'bar', baz: 42 } const submit = jest.fn().mockImplementation(() => 69) const startSubmit = jest.fn() const stopSubmit = jest.fn() const touch = jest.fn() const setSubmitFailed = jest.fn() const setSubmitSucceeded = jest.fn() const asyncValidate = jest.fn() const props = { startSubmit, stopSubmit, touch, setSubmitFailed, setSubmitSucceeded, values, persistentSubmitErrors: true } handleSubmit(submit, props, true, asyncValidate, ['foo', 'baz']) expect(submit).toHaveBeenCalled() }) it('should not swallow errors', () => { const values = { foo: 'bar', baz: 42 } const submit = jest.fn().mockImplementation(() => { throw new Error('spline reticulation failed') }) const startSubmit = jest.fn() const stopSubmit = jest.fn() const touch = jest.fn() const setSubmitFailed = jest.fn() const setSubmitSucceeded = jest.fn() const asyncValidate = jest.fn() const props = { startSubmit, stopSubmit, touch, setSubmitFailed, setSubmitSucceeded, values } expect(() => handleSubmit(submit, props, true, asyncValidate, ['foo', 'baz']) ).toThrow('spline reticulation failed') expect(submit).toHaveBeenCalled() }) it('should not swallow async errors', () => { const values = { foo: 'bar', baz: 42 } const submit = jest .fn() .mockImplementation(() => Promise.reject(new Error('spline reticulation failed')) ) const startSubmit = jest.fn() const stopSubmit = jest.fn() const touch = jest.fn() const setSubmitFailed = jest.fn() const setSubmitSucceeded = jest.fn() const asyncValidate = jest.fn() const props = { startSubmit, stopSubmit, touch, setSubmitFailed, setSubmitSucceeded, values } const resultSpy = jest.fn() const errorSpy = jest.fn() return handleSubmit(submit, props, true, asyncValidate, ['foo', 'baz']) .then(resultSpy, errorSpy) .then(() => { expect(submit).toHaveBeenCalled() expect(resultSpy).not.toHaveBeenCalled() expect(errorSpy).toHaveBeenCalled() }) }) it('should not swallow async errors when form is invalid', () => { const values = { foo: 'bar', baz: 42 } const submit = jest.fn().mockImplementation(() => 69) const syncErrors = { baz: 'sync error' } const asyncErrors = { foo: 'async error' } const startSubmit = jest.fn() const stopSubmit = jest.fn() const touch = jest.fn() const setSubmitFailed = jest.fn() const setSubmitSucceeded = jest.fn() const asyncValidate = jest.fn() const props = { startSubmit, stopSubmit, touch, setSubmitFailed, setSubmitSucceeded, syncErrors, asyncErrors, values } const result = handleSubmit(submit, props, false, asyncValidate, [ 'foo', 'baz' ]) expect(asyncValidate).not.toHaveBeenCalled() expect(submit).not.toHaveBeenCalled() expect(startSubmit).not.toHaveBeenCalled() expect(stopSubmit).not.toHaveBeenCalled() expect(touch).toHaveBeenCalledWith('foo', 'baz') expect(setSubmitSucceeded).not.toHaveBeenCalled() expect(setSubmitFailed).toHaveBeenCalledWith('foo', 'baz') expect(result).toEqual({ ...asyncErrors, ...syncErrors }) }) })
31.919776
125
0.641358
b418ac8d99bf42af47f24d98b1548ee8fcb3493f
5,361
js
JavaScript
15_barchart_sort.js
jbjacobson/D3_Graphs
29e53acb4f4cceb5251f08a50f508afe019f8681
[ "MIT" ]
null
null
null
15_barchart_sort.js
jbjacobson/D3_Graphs
29e53acb4f4cceb5251f08a50f508afe019f8681
[ "MIT" ]
null
null
null
15_barchart_sort.js
jbjacobson/D3_Graphs
29e53acb4f4cceb5251f08a50f508afe019f8681
[ "MIT" ]
null
null
null
d3.select('#lightTheme').on('click',function(){ d3.select('body').classed('dark', false); }); d3.select('#darkTheme').on('click',function(){ d3.select('body').classed('dark', true); }); $( ".wgt-control" ).resizable({ resize: function( event, ui ) { var wgtContent = d3.select(this).select('.wgt-content').node(); wgtContent.viewModel.draw(); //draw(parent, parent.model); var r = wgtContent.getBoundingClientRect(); d3.select('#sizeDisplay').text(r.width + ':' + r.height); } }); var testData = [{name: 'B', value: .01492},{name: 'A', value: .08167},{name: 'C', value: .02782},{name: 'D', value: .04253},{name: 'E', value: .12702},{name: 'F', value: .02288},{name: 'G', value: .02015}]; var models = [ {title:"foo",sort:"name"} ]; $('.wgt-content').each(function(i,e){ barchart(e, models[i], testData); }); //creates an RFC4122v4 compliant guid string //from the most upvoted answer here: https://stackoverflow.com/questions/105034/create-guid-uuid-in-javascript function guid(){ return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8); return v.toString(16); }); } // timeseries object. acts as a viewModel for the parent element. function barchart(parentElement, m, d){ var bc = {}; parentElement.viewModel = bc; bc.model = function(m){ bc.m = m; bc.draw(); } bc.data = function(d){ bc.d = d; bc.draw(); } bc.draw = function(){ //size svg region to fill parent div var rect = parentElement.getBoundingClientRect(); var p = d3.select(parentElement); p.html(''); var svg = p.append('svg') .attr('width', rect.width) .attr('height', rect.height); p.append('label').attr('class', 'sortCheckbox').text('Sort by value') .append('input').attr('type', 'checkbox').property('checked', bc.m.sort == "value").on("change", bc.onSortChanged); if (bc.m.title.text){ var t = svg.append('text') .attr('class', 'title') .attr('y',0) .attr('x',10) .text(bc.m.title.text); titleHeight = t.node().getBBox().height; t.attr('y', titleHeight); if (bc.m.title.position === 'center'){ t.style('text-anchor', 'middle') .attr('x', .5*rect.width); } } var margin = {top: 20, right: 20, bottom: 30, left: 40}; var width = +svg.attr("width") - margin.left - margin.right; var height = +svg.attr("height") - margin.top - margin.bottom; bc.x = d3.scaleBand().rangeRound([0, width]).padding(0.1); bc.y = d3.scaleLinear().rangeRound([height, 0]); var g = svg.append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); bc.x.domain(bc.d.map(function(d) { return d.name; })); bc.y.domain([0, d3.max(bc.d, function(d) { return d.value; })]); g.selectAll(".bar") .data(bc.d) .enter().append("rect") .attr("class", "bar") .attr("x", function(d) { return bc.x(d.name); }) .attr("y", function(d) { return bc.y(d.value); }) .attr("width", bc.x.bandwidth()) .attr("height", function(d) { return height - bc.y(d.value); }); bc.xAxis = d3.axisBottom(bc.x); bc.yAxis = d3.axisLeft(bc.y) .ticks(10, "%"); var xGroup = g.append("g") .attr("class", "x axis") .attr("transform", "translate(0," + height + ")") .call(bc.xAxis); g.append("g") .attr("class", "y axis") .call(bc.yAxis) .append("text") .attr("transform", "rotate(-90)") .attr("y", 6) .attr("dy", "0.71em") .attr("text-anchor", "end") .text("Frequency"); bc.mainGraph = g; } bc.onSortChanged = function(){ bc.m.sort = this.checked ? "value" : "name"; bc.sortBars(this.checked, true); } bc.sortBars = function(sortByValue, animate) { // Copy-on-write since tweens are evaluated after a delay. var x0 = bc.x.domain(bc.d.sort(sortByValue ? function(a, b) { return b.value - a.value; } : function(a, b) { return d3.ascending(a.name, b.name); }) .map(function(d) { return d.name; })) .copy(); bc.mainGraph.selectAll(".bar") .sort(function(a, b) { return x0(a.name) - x0(b.name); }); var transition = bc.mainGraph.transition().duration(animate ? 750 : 0), delay = animate ? function(d, i) { return i * 50; } : 0; transition.selectAll(".bar") .delay(delay) .attr("x", function(d) { return x0(d.name); }); transition.select(".x.axis") .call(bc.xAxis) .selectAll("g") .delay(delay); } bc.m = m; bc.d = d; bc.draw(); bc.sortBars(m.sort == "value", false); return bc; }
33.716981
207
0.502332
b4198ad07ff3c2bad2ff86b7dc3fa970801699aa
1,032
js
JavaScript
Projeto/backend/src/routes/cartRoutes.js
UFOP-CSI477/2021-01-remoto-atividades-claudiovitordantas
c7b1c090a640db77e6192366c1d354f934eaec49
[ "MIT" ]
null
null
null
Projeto/backend/src/routes/cartRoutes.js
UFOP-CSI477/2021-01-remoto-atividades-claudiovitordantas
c7b1c090a640db77e6192366c1d354f934eaec49
[ "MIT" ]
null
null
null
Projeto/backend/src/routes/cartRoutes.js
UFOP-CSI477/2021-01-remoto-atividades-claudiovitordantas
c7b1c090a640db77e6192366c1d354f934eaec49
[ "MIT" ]
null
null
null
const express = require("express"); const router = express.Router(); const { isAuth } = require("../middleware/auth"); const Cart = require("../models/Cart"); // fetch users cart router.get("/", isAuth, async (req, res) => { try { const userCart = await Cart.find({ userId: req.user.id }); if (userCart) { return res.json(userCart); } else { return res.json("Voçê ainda não tem produtos no carrinho."); } } catch (error) { return res.json(error); } }); // add product to cart router.post("/add", isAuth, async (req, res) => { const userId = req.user.id; let products = req.body; try { let existingCart = await Cart.findOne({ userId }); if (existingCart) { let filter = { userId: userId }; let update = { products: products }; await Cart.findOneAndUpdate(filter, update); } else { const newCart = await Cart.create({ products, userId }); return res.json(newCart); } } catch (error) { res.json(error); } }); module.exports = router;
25.8
66
0.608527
b41a2d4309cb2d29ec71b10bb3699519167035fb
17,669
js
JavaScript
rockfish_client/rockfish_client_android/Rockfish/app/src/main/assets/rockfish_client_web.js
devsunset/rockfish
2e550b323a6f33ad0eae7626e0a70c1b91869333
[ "Apache-2.0" ]
5
2016-09-03T14:47:39.000Z
2020-06-10T01:21:45.000Z
rockfish_client/rockfish_client_android/Rockfish/app/src/main/assets/rockfish_client_web.js
devsunset/rockfish
2e550b323a6f33ad0eae7626e0a70c1b91869333
[ "Apache-2.0" ]
1
2021-04-29T08:46:39.000Z
2021-04-29T08:46:39.000Z
rockfish_client/rockfish_client_android/Rockfish/app/src/main/assets/rockfish_client_web.js
devsunset/rockfish
2e550b323a6f33ad0eae7626e0a70c1b91869333
[ "Apache-2.0" ]
1
2016-09-08T13:52:46.000Z
2016-09-08T13:52:46.000Z
/*■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■*/ /* filename : rockfish_client_web.js /* author : devsunset (devsunset@gmail.com) /* desc : rockfish client web (ajax module) /*■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■*/ // PARAMETER 평문 설정 var ROCKFISH_PARAMETER_PLAIN = "ROCKFISH_PARAMETER_PLAIN"; // PARAMETER 암호화 설정 var ROCKFISH_PARAMETER_ENCRYPT = "ROCKFISH_PARAMETER_ENCRYPT"; // RSA 암호화 공개 키 ■■■ TO-DO set up 한 공개 key 값 으로 치환 필요 var ROCKFISH_RSA_PUBLIC_KEY_VALUE = '-----BEGIN PUBLIC KEY-----'; ROCKFISH_RSA_PUBLIC_KEY_VALUE+='MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA11iUtP4coVGcrLKryIkg'; ROCKFISH_RSA_PUBLIC_KEY_VALUE+='Iwt3qS4yR9F963ockxfvwUsjKsEBQdOc6Ef79LWK3qAFiFkM/h+rk19UQYe/iBKr'; ROCKFISH_RSA_PUBLIC_KEY_VALUE+='YPggFX+/eRT5Ubkd2Pgfje1L4g2/hJZ53n95e/pGFwjMpGBWvvnE0EoLR8RjX/5S'; ROCKFISH_RSA_PUBLIC_KEY_VALUE+='qLVZpFGZEvAnevwua5igi2Mn0y9Sx0z+8tUKaAAM7p7VlbxhdbDra9/nC8fWaHVy'; ROCKFISH_RSA_PUBLIC_KEY_VALUE+='PKs0TmxQcolaPMQwdtJTCrSCs8nx/aAxsWhzuc/mXDChBemAhpfBS94/mAdkKdU8'; ROCKFISH_RSA_PUBLIC_KEY_VALUE+='746z3axU06umIxJU44jPwGiG4M8HofnTkDfpfKIrat8St/lc9Lp0ulDm82CdR/dd'; ROCKFISH_RSA_PUBLIC_KEY_VALUE+='CwIDAQAB'; ROCKFISH_RSA_PUBLIC_KEY_VALUE+='-----END PUBLIC KEY-----'; var ROCKFISH_RSA_JSENCRYPT = new JSEncrypt(); ROCKFISH_RSA_JSENCRYPT.setPublicKey(ROCKFISH_RSA_PUBLIC_KEY_VALUE); /** * <pre> * rockfish ajax Common call function * </pre> * @param service : 호출 service target * @param data : 호출 parameter * @param encdata : 암호화 설정 값 * ROCKFISH_PARAMETER_PLAIN (전체 평문) * ROCKFISH_PARAMETER_ENCRYPT (전체 암호화) * Array() field value (암호화 하고자 하는 field) * @param callback : success callback 함수 * @param errorcallback : error callback 함수 * @param loadingbar : 공통으로 progress bar 등을 사용하는 경우 호출 Action에 따라 표시 유무 설정 * @param async : 동기화 여부 설정 기본은 true * @param attachField : 첨부파일 Array Field * @param attachFile : 첨부파일 Array Object * @param downolad : 다운로드 호출 설정 * * ■■■ TO-DO 표시 항목에 대해서는 사용자가 요건에 맞게 정의 하여 사용 ■■■ * */ function rockfishAjax(service, data, encdata, callback, errorcallback, loadingbar, async, attachField , attachFile, downolad){ if(service === undefined || service === null || service.trim() == ""){ alert("error : service value is empty"); return; } // TO-DO ROCKFISH URL (http,https - https://localhost:9999) // HTTPS 사용시 self-sign에 따른 오류 발생 - 공인 인증서 사용하면 HTTPS 사용 가능 //var url = "https://localhost:9999/rockfishController"; //var url = "http://localhost:8888/rockfishController"; //var downloadurl = "http://localhost:8888/rockfishDownloadController"; // TEST용 (서버 IP 동적 설정) var url = "http://"+$("#IPPORT").val()+"/rockfishController"; var downloadurl = "http://"+$("#IPPORT").val()+"/rockfishDownloadController"; var rockfishSendType = "G"; // G : General M : Multipart D : Download if(typeof async === undefined){ async = true; } if(typeof downolad === undefined){ downolad = false; } var paramData = null; var encryptParameter = ""; if(ROCKFISH_PARAMETER_PLAIN === encdata){ paramData = data; }else if (ROCKFISH_PARAMETER_ENCRYPT === encdata){ if(data !== null && data !== undefined){ for(var fidx = 0;fidx <data.length;fidx++){ encryptParameter += data[fidx].name +"|^|"; data[fidx].value = rockfishRsaEncrypt(data[fidx].value); } paramData = data; } }else{ if( Object.prototype.toString.call( encdata ) === '[object Array]' ) { if(encdata !==null && encdata.length > 0){ for(var fidx = 0;fidx <data.length;fidx++){ if($.inArray(data[fidx].name, encdata) != -1){ encryptParameter += data[fidx].name +"|^|"; data[fidx].value = rockfishRsaEncrypt(data[fidx].value); } } paramData = data; }else{ paramData = data; } }else{ paramData = data; } } if(attachField !== null && typeof attachField !== 'undefined' && attachFile !== null && typeof attachFile !== 'undefined' && attachField.length == attachFile.length){ rockfishSendType = "M"; if (window.File && window.FileList && window.Blob && window.FileReader && window.FormData) { var formData = new FormData(); if(paramData !=null && paramData.length > 0){ for(var fidx = 0;fidx <paramData.length;fidx++){ formData.append(paramData[fidx].name,paramData[fidx].value); } } for(var fileIdx = 0 ;fileIdx < attachFile.length; fileIdx++){ if( Object.prototype.toString.call(attachFile[fileIdx]) === '[object File]' ){ formData.append(attachField[fileIdx],attachFile[fileIdx]); }else{ alert("object is not file object"); return; } } paramData = formData; } else { alert("browser doesn't supports File API"); return; } } if(downolad){ rockfishSendType = "D"; } if(rockfishSendType == "G"){ $.ajax({ type : "POST", url : url, async : async, cache : false, data : paramData, crossDomain : true, contentType: "application/json; charset=utf-8", success : function(response, status, request) { callback(response); }, beforeSend: function(xhr) { /* ROCKFISH CUSTMOMER HEADER*/ xhr.setRequestHeader("rockfish_session_key", rockfishGetStorge("rockfish_session_key")); xhr.setRequestHeader("rockfish_access_id", rockfishGetStorge("rockfish_access_id")); xhr.setRequestHeader("rockfish_ip", rockfishRsaEncrypt("")); // Ignore Web Client xhr.setRequestHeader("rockfish_mac", rockfishRsaEncrypt("")); // Ignore Web Client xhr.setRequestHeader("rockfish_phone", rockfishRsaEncrypt("")); // Ignore Web Client xhr.setRequestHeader("rockfish_device", rockfishRsaEncrypt("")); // Ignore Web Client xhr.setRequestHeader("rockfish_imei", rockfishRsaEncrypt("")); // Ignore Web Client xhr.setRequestHeader("rockfish_os", "BROWSER"); xhr.setRequestHeader("rockfish_os_version", rockfishBrowserType()); xhr.setRequestHeader("rockfish_os_version_desc", navigator.userAgent); xhr.setRequestHeader("rockfish_target_service", service); xhr.setRequestHeader("rockfish_client_app", "Rockfish"); // TO-DO Client App xhr.setRequestHeader("rockfish_client_app_version", "1.0"); // TO-DO Client App Version xhr.setRequestHeader("rockfish_send_type", "G"); xhr.setRequestHeader("rockfish_encrypt_parameter", encryptParameter); // TO-DO COMMON PROGRESS START (EX : PROGRESSING BAR LOADING) loadingbar true : false }, complete: function() { // TO-DO COMMON PROGRESS END (EX : PROGRESSING BAR CLOASE) loadingbar true : false }, error : function(request, status, error) { if(errorcallback !== null && typeof errorcallback !== "undefined"){ errorcallback(status,error); }else{ // TO-DO customer define var errorMsg = 'status(code) : ' + request.status + '\n'; errorMsg += 'statusText : ' + request.statusText + '\n'; errorMsg += 'responseText : ' + request.responseText + '\n'; errorMsg += 'textStatus : ' + status + '\n'; errorMsg += 'errorThrown : ' + error; alert(errorMsg); } } }); }else if(rockfishSendType == "M"){ $.ajax({ type : "POST", url : url, async : async, cache : false, processData : false, data : paramData, crossDomain : true, contentType: false, success : function(response, status, request) { callback(response); }, beforeSend: function(xhr) { /* ROCKFISH CUSTMOMER HEADER*/ xhr.setRequestHeader("rockfish_session_key", rockfishGetStorge("rockfish_session_key")); xhr.setRequestHeader("rockfish_access_id", rockfishGetStorge("rockfish_access_id")); xhr.setRequestHeader("rockfish_ip", rockfishRsaEncrypt("")); // Ignore Web Client xhr.setRequestHeader("rockfish_mac", rockfishRsaEncrypt("")); // Ignore Web Client xhr.setRequestHeader("rockfish_phone", rockfishRsaEncrypt("")); // Ignore Web Client xhr.setRequestHeader("rockfish_device", rockfishRsaEncrypt("")); // Ignore Web Client xhr.setRequestHeader("rockfish_imei", rockfishRsaEncrypt("")); // Ignore Web Client xhr.setRequestHeader("rockfish_os", "BROWSER"); xhr.setRequestHeader("rockfish_os_version", rockfishBrowserType()); xhr.setRequestHeader("rockfish_os_version_desc", navigator.userAgent); xhr.setRequestHeader("rockfish_target_service", service); xhr.setRequestHeader("rockfish_client_app", "Rockfish"); // TO-DO Client App xhr.setRequestHeader("rockfish_client_app_version", "1.0"); // TO-DO Client App Version xhr.setRequestHeader("rockfish_send_type", "M"); xhr.setRequestHeader("rockfish_encrypt_parameter", encryptParameter); // TO-DO COMMON PROGRESS START (EX : PROGRESSING BAR LOADING) loadingbar true : false }, complete: function() { // TO-DO COMMON PROGRESS END (EX : PROGRESSING BAR CLOASE) loadingbar true : false }, error : function(request, status, error) { if(errorcallback !== null && typeof errorcallback !== "undefined"){ errorcallback(status,error); }else{ // TO-DO customer define var errorMsg = 'status(code) : ' + request.status + '\n'; errorMsg += 'statusText : ' + request.statusText + '\n'; errorMsg += 'responseText : ' + request.responseText + '\n'; errorMsg += 'textStatus : ' + status + '\n'; errorMsg += 'errorThrown : ' + error; alert(errorMsg); } } }); }else{ $.ajax({ type : "POST", url : url, async : async, cache : false, data : paramData, crossDomain : true, success : function(response, status, request) { rockfishAjaxDownload(downloadurl,response.ROCKFISH_RESULT_JSON); /* var contTypeDisposition = request.getResponseHeader ("Content-Disposition"); if (contTypeDisposition && contTypeDisposition.indexOf("=") !== -1) { var filename = contTypeDisposition.substring(contTypeDisposition.indexOf("=")+1,contTypeDisposition.length); var blob = new Blob([response], {type: "octet/stream"}); var link=document.createElement('a'); link.href=window.URL.createObjectURL(blob); link.download=filename; link.click(); } */ }, beforeSend: function(xhr) { /* ROCKFISH CUSTMOMER HEADER*/ xhr.setRequestHeader("rockfish_session_key", rockfishGetStorge("rockfish_session_key")); xhr.setRequestHeader("rockfish_access_id", rockfishGetStorge("rockfish_access_id")); xhr.setRequestHeader("rockfish_ip", rockfishRsaEncrypt("")); // Ignore Web Client xhr.setRequestHeader("rockfish_mac", rockfishRsaEncrypt("")); // Ignore Web Client xhr.setRequestHeader("rockfish_phone", rockfishRsaEncrypt("")); // Ignore Web Client xhr.setRequestHeader("rockfish_device", rockfishRsaEncrypt("")); // Ignore Web Client xhr.setRequestHeader("rockfish_imei", rockfishRsaEncrypt("")); // Ignore Web Client xhr.setRequestHeader("rockfish_os", "BROWSER"); xhr.setRequestHeader("rockfish_os_version", rockfishBrowserType()); xhr.setRequestHeader("rockfish_os_version_desc", navigator.userAgent); xhr.setRequestHeader("rockfish_target_service", service); xhr.setRequestHeader("rockfish_client_app", "Rockfish"); // TO-DO Client App xhr.setRequestHeader("rockfish_client_app_version", "1.0"); // TO-DO Client App Version xhr.setRequestHeader("rockfish_send_type", "D"); xhr.setRequestHeader("rockfish_encrypt_parameter", encryptParameter); // TO-DO COMMON PROGRESS START (EX : PROGRESSING BAR LOADING) loadingbar true : false }, complete: function() { // TO-DO COMMON PROGRESS END (EX : PROGRESSING BAR CLOASE) loadingbar true : false }, error : function(request, status, error) { if(errorcallback !== null && typeof errorcallback !== "undefined"){ errorcallback(status,error); }else{ // TO-DO customer define var errorMsg = 'status(code) : ' + request.status + '\n'; errorMsg += 'statusText : ' + request.statusText + '\n'; errorMsg += 'responseText : ' + request.responseText + '\n'; errorMsg += 'textStatus : ' + status + '\n'; errorMsg += 'errorThrown : ' + error; alert(errorMsg); } } }); } }; /** * <pre> * rsa encrypt * </pre> * @param toEncrypt : encrypt value * */ function rockfishRsaEncrypt(toEncrypt){ if(toEncrypt === null || toEncrypt === "" || toEncrypt === undefined){ return ""; }else{ return ROCKFISH_RSA_JSENCRYPT.encrypt(toEncrypt); } } /** * <pre> * set localStorge * </pre> * @param cName : storge key * @param cValue : storge value * */ function rockfishSetStorge(cName, cValue){ if( ('localStorage' in window) && window['localStorage'] !== null) { localStorage.setItem(cName, cValue); }else{ alert("현재 브라우저는 WebStorage를 지원하지 않습니다") } } /** * <pre> * set localStorge * </pre> * @param cName : storge key * @param cValue : storge value * */ function rockfishSetEncryptStorge(cName, cValue){ if( ('localStorage' in window) && window['localStorage'] !== null) { localStorage.setItem(cName, rockfishRsaEncrypt(cValue)); }else{ alert("현재 브라우저는 WebStorage를 지원하지 않습니다") } } /** * <pre> * localStorge clear * </pre> * */ function rockfishClearStorge(){ if( ('localStorage' in window) && window['localStorage'] !== null) { localStorage.clear(); }else{ alert("현재 브라우저는 WebStorage를 지원하지 않습니다") } } /** * <pre> * get localStorge * </pre> * @param cName : storge key * */ function rockfishGetStorge(cName) { if( ('localStorage' in window) && window['localStorage'] !== null) { if(localStorage.getItem(cName) == null){ return ""; }else{ return localStorage.getItem(cName); } }else{ alert("현재 브라우저는 WebStorage를 지원하지 않습니다") return ""; } } /** * <pre> * get browser type * </pre> */ function rockfishBrowserType(){ var agent = navigator.userAgent.toLowerCase(); var name = navigator.appName; var browser = "Etc"; // MS 계열 브라우저를 구분하기 위함. if(name === 'Microsoft Internet Explorer' || agent.indexOf('trident') > -1 || agent.indexOf('edge/') > -1) { browser = 'ie'; if(name === 'Microsoft Internet Explorer') { // IE old version (IE 10 or Lower) agent = /msie ([0-9]{1,}[\.0-9]{0,})/.exec(agent); browser += parseInt(agent[1]); } else { // IE 11+ if(agent.indexOf('trident') > -1) { // IE 11 browser += 11; } else if(agent.indexOf('edge/') > -1) { // Edge browser = 'edge'; } } } else if(agent.indexOf('safari') > -1) { // Chrome or Safari if(agent.indexOf('opr') > -1) { // Opera browser = 'opera'; } else if(agent.indexOf('chrome') > -1) { // Chrome browser = 'chrome'; } else { // Safari browser = 'safari'; } } else if(agent.indexOf('firefox') > -1) { // Firefox browser = 'firefox'; } return browser; } /** * <pre> * download action * </pre> * @param url : download url * @param data : json object * */ function rockfishAjaxDownload(url, data) { //To-Do (개선 필요) location.href = url+"?ROCKFISH_TEMP_FILE="+encodeURIComponent(rockfishRsaEncrypt(data.ROCKFISH_TEMP_FILE))+"&ROCKFISH_REAL_FILE="+encodeURIComponent(rockfishRsaEncrypt(data.ROCKFISH_REAL_FILE)); /* var agent = navigator.userAgent.toLowerCase(); if ( (navigator.appName == 'Netscape' && navigator.userAgent.search('Trident') != -1) || (agent.indexOf("msie") != -1) ) { var url= url+"?ROCKFISH_TEMP_FILE="+encodeURIComponent(rockfishRsaEncrypt(data.ROCKFISH_TEMP_FILE))+"&ROCKFISH_REAL_FILE="+encodeURIComponent(rockfishRsaEncrypt(data.ROCKFISH_REAL_FILE)); var $form = $('<form></form>'); $form.attr('action', url); $form.attr('method', 'POST'); $form.attr('target', '_blank'); $form.appendTo('body'); $form.submit(); }else{ var $iframe; var iframe_doc; var iframe_html; if (($iframe = $('#download_iframe')).length === 0) { $iframe = $("<iframe id='download_iframe'" + " style='display: none' src='about:blank'></iframe>" ).appendTo("body"); } iframe_doc = $iframe[0].contentWindow || $iframe[0].contentDocument; if (iframe_doc.document) { iframe_doc = iframe_doc.document; } iframe_html = "<html><head></head><body><form method='POST' action='" + url +"'>"; Object.keys(data).forEach(function(key){ iframe_html += "<input type='hidden' name='"+key+"' value='"+rockfishRsaEncrypt(data[key])+"'>"; }); iframe_html +="</form></body></html>"; iframe_doc.open(); iframe_doc.write(iframe_html); $(iframe_doc).find('form').submit(); } */ }
37.35518
198
0.61656
b41abd6a71e941d3e594e904223ff63da5659511
268
js
JavaScript
server/seeds/category.js
BalogunDell/HelloBooks
276155f2f3ab350c2e07414e0da56c130c3f3243
[ "MIT" ]
2
2017-11-10T02:20:27.000Z
2018-09-03T20:52:17.000Z
server/seeds/category.js
BalogunDell/HelloBooks
276155f2f3ab350c2e07414e0da56c130c3f3243
[ "MIT" ]
16
2017-11-11T16:15:34.000Z
2020-04-29T23:31:01.000Z
server/seeds/category.js
BalogunDell/HelloBooks
276155f2f3ab350c2e07414e0da56c130c3f3243
[ "MIT" ]
4
2017-08-11T00:22:58.000Z
2017-10-25T09:57:48.000Z
const categories = [ { category: 'Health' }, { category: 'Education', }, { category: 'Social', }, { category: 'Programming', }, { category: 'Comic', }, { category: 'Business', }, ]; export default { categories };
9.241379
28
0.488806
b41b191225dea35f35f56b9c33ded4eefd2cc452
11,896
js
JavaScript
__tests__/LanguageNameTextBox.test.js
PhotoNomad0/tCore-Electronite
994c8840311bbcd0eee1226e8bc4a294d244cdfa
[ "ISC" ]
null
null
null
__tests__/LanguageNameTextBox.test.js
PhotoNomad0/tCore-Electronite
994c8840311bbcd0eee1226e8bc4a294d244cdfa
[ "ISC" ]
null
null
null
__tests__/LanguageNameTextBox.test.js
PhotoNomad0/tCore-Electronite
994c8840311bbcd0eee1226e8bc4a294d244cdfa
[ "ISC" ]
null
null
null
/* eslint-env jest */ import React from 'react'; import { AutoComplete } from 'material-ui'; import { shallow, configure } from 'enzyme'; import Adapter from 'enzyme-adapter-react-16'; import * as LangName from '../src/js/components/projectValidation/ProjectInformationCheck/LanguageNameTextBox'; import LanguageNameTextBox from '../src/js/components/projectValidation/ProjectInformationCheck/LanguageNameTextBox'; import * as LangHelpers from '../src/js/helpers/LanguageHelpers'; beforeAll(() => { configure({ adapter: new Adapter() }); }); describe('Test LanguageNameTextBox.selectLanguage()',()=> { let updateLanguageId, updateLanguageName, updateLanguageSettings; beforeEach(() => { updateLanguageId = jest.fn(); updateLanguageName = jest.fn(); updateLanguageSettings = jest.fn(); }); test('with valid name selection should update all language field', () => { // given const expectedLanguageID = 'ha'; const expectedLanguage = LangHelpers.getLanguageByCode(expectedLanguageID); const expectedLanguageDir = expectedLanguage.ltr ? 'ltr' : 'rtl'; const index = -1; // when LangName.selectLanguage(expectedLanguage.name, index, updateLanguageName, updateLanguageId, updateLanguageSettings); // then expect(updateLanguageId).not.toHaveBeenCalled(); expect(updateLanguageName).not.toHaveBeenCalled(); verifyCalledOnceWith(updateLanguageSettings, [expectedLanguageID, expectedLanguage.name, expectedLanguageDir]); }); test('with valid index should update all language field', () => { // given const expectedLanguageName = 'Arabic'; const expectedLanguage = LangHelpers.getLanguageByName(expectedLanguageName); const expectedLanguageDir = expectedLanguage.ltr ? 'ltr' : 'rtl'; const index = getIndexForName(expectedLanguageName); // when LangName.selectLanguage({ code: expectedLanguage.code }, index, updateLanguageName, updateLanguageId, updateLanguageSettings); // then expect(updateLanguageId).not.toHaveBeenCalled(); expect(updateLanguageName).not.toHaveBeenCalled(); verifyCalledOnceWith(updateLanguageSettings, [expectedLanguage.code, expectedLanguage.name, expectedLanguageDir]); }); test('with invalid name should update language name and clear ID', () => { // given const index = -1; const newlLanguageName = 'zzz'; const expectedLanguageName = newlLanguageName; const expectedLanguageID = ''; // when LangName.selectLanguage(newlLanguageName, index, updateLanguageName, updateLanguageId, updateLanguageSettings); // then verifyCalledOnceWith(updateLanguageId, expectedLanguageID); verifyCalledOnceWith(updateLanguageName, expectedLanguageName); expect(updateLanguageSettings).not.toHaveBeenCalled(); }); test('with null should clear language name and id', () => { // given const LanguageName = null; const index = -1; const expectedLanguageID = ''; const expectedLanguageName = ''; // when LangName.selectLanguage(LanguageName, index, updateLanguageName, updateLanguageId, updateLanguageSettings); // then verifyCalledOnceWith(updateLanguageId, expectedLanguageID); verifyCalledOnceWith(updateLanguageName, expectedLanguageName); expect(updateLanguageSettings).not.toHaveBeenCalled(); }); }); describe('Test LanguageNameTextBox.getErrorMessage()',()=> { const translate = (key) => key; test('should give message for empty language Name', () => { // given const languageID = null; const languageName = ''; // when const results = LangName.getErrorMessage(translate, languageName, languageID); // then expect(results).toEqual('project_validation.field_required'); }); test('should give message for invalid language Name', () => { // given const languageID = ''; const languageName = 'zzz'; // when const results = LangName.getErrorMessage(translate, languageName, languageID); // then expect(results).toEqual('project_validation.invalid_language_name'); }); test('should not give message for valid languageName', () => { // given const languageID = ''; const languageName = 'English'; // when const results = LangName.getErrorMessage(translate, languageName, languageID); // then expect(!results).toBeTruthy(); }); test('should give message for mismatch languageName and ID', () => { // given const languageID = 'es'; const languageName = 'English'; // when const results = LangName.getErrorMessage(translate, languageName, languageID); // then expect(results).toEqual('project_validation.language_mismatch'); }); }); describe('Test LanguageNameTextBox component',()=>{ let updateLanguageId, updateLanguageName, updateLanguageSettings; beforeEach(() => { updateLanguageId = jest.fn(); updateLanguageName = jest.fn(); updateLanguageSettings = jest.fn(); }); test('with valid language should not show error', () => { // given const languageName = 'English'; const languageId = 'en'; const expectedErrorText = ''; const expectedSearchText = languageName; // when const enzymeWrapper = shallowRenderComponent(languageName, languageId); // then verifyAutoComplete(enzymeWrapper, expectedSearchText, expectedErrorText); }); test('with invalid language should show error', () => { // given const languageName = 'Englishish'; const languageId = 'en'; const expectedErrorText = 'project_validation.invalid_language_name'; const expectedSearchText = languageName; // when const enzymeWrapper = shallowRenderComponent(languageName, languageId); // then verifyAutoComplete(enzymeWrapper, expectedSearchText, expectedErrorText); }); test('with empty language should show error', () => { // given const languageName = ''; const languageId = 'en'; const expectedErrorText = 'project_validation.field_required'; const expectedSearchText = languageName; // when const enzymeWrapper = shallowRenderComponent(languageName, languageId); // then verifyAutoComplete(enzymeWrapper, expectedSearchText, expectedErrorText); }); test('with language name & code mismatch should show error', () => { // given const languageName = 'español'; const languageId = 'en'; const expectedErrorText = 'project_validation.language_mismatch'; const expectedSearchText = languageName; // when const enzymeWrapper = shallowRenderComponent(languageName, languageId); // then verifyAutoComplete(enzymeWrapper, expectedSearchText, expectedErrorText); }); test('on text change anglicized name should update all language fields', () => { // given const initialLanguageName = 'English'; const languageId = 'en'; const enzymeWrapper = shallowRenderComponent(initialLanguageName, languageId); const props = enzymeWrapper.find(AutoComplete).getElement().props; const newlLanguageName = 'Spanish'; const expectedLanguageName = newlLanguageName; const expectedLanguageID = 'es'; const expectedLanguageDir = 'ltr'; // when props.onUpdateInput(newlLanguageName); // then expect(updateLanguageId).not.toHaveBeenCalled(); expect(updateLanguageName).not.toHaveBeenCalled(); verifyCalledOnceWith(updateLanguageSettings, [expectedLanguageID, expectedLanguageName, expectedLanguageDir]); }); test('on text change invalid name should update language name and clear ID', () => { // given const initialLanguageName = 'English'; const languageId = 'en'; const enzymeWrapper = shallowRenderComponent(initialLanguageName, languageId); const props = enzymeWrapper.find(AutoComplete).getElement().props; const newlLanguageName = 'Spanis'; const expectedLanguageName = newlLanguageName; const expectedLanguageID = ''; // when props.onUpdateInput(newlLanguageName); // then verifyCalledOnceWith(updateLanguageName, expectedLanguageName); verifyCalledOnceWith(updateLanguageId, expectedLanguageID); expect(updateLanguageSettings).not.toHaveBeenCalled(); }); test('on new text Selection should call all language updates', () => { // given const initialLanguageName = 'English'; const languageId = 'en'; const enzymeWrapper = shallowRenderComponent(initialLanguageName, languageId); const props = enzymeWrapper.find(AutoComplete).getElement().props; const newlLanguageName = 'español'; const expectedLanguageID = 'es'; const expectedLanguageName = newlLanguageName; const expectedLanguageDir = 'ltr'; // when props.onNewRequest(newlLanguageName, -1); // then expect(updateLanguageId).not.toHaveBeenCalled(); expect(updateLanguageName).not.toHaveBeenCalled(); verifyCalledOnceWith(updateLanguageSettings, [expectedLanguageID, expectedLanguageName, expectedLanguageDir]); }); test('on new menu Selection should call all language updates', () => { // given const index = 100; const expectedLanguage = LangHelpers.getLanguagesSortedByName()[index]; const initialLanguageName = 'English'; const languageId = 'en'; const enzymeWrapper = shallowRenderComponent(initialLanguageName, languageId); const props = enzymeWrapper.find(AutoComplete).getElement().props; const expectedLanguageDir = expectedLanguage.ltr ? 'ltr' : 'rtl'; // when props.onNewRequest(null, index); // then expect(updateLanguageId).not.toHaveBeenCalled(); expect(updateLanguageName).not.toHaveBeenCalled(); verifyCalledOnceWith(updateLanguageSettings, [expectedLanguage.code, expectedLanguage.name, expectedLanguageDir]); }); test('on new Selection with unmatched name should update language name and clear ID', () => { // given const initialLanguageName = 'English'; const languageId = 'en'; const enzymeWrapper = shallowRenderComponent(initialLanguageName, languageId); const props = enzymeWrapper.find(AutoComplete).getElement().props; const newlLanguageName = 'Spanis'; const expectedLanguageID = ''; const expectedLanguageName = newlLanguageName; // when props.onNewRequest(newlLanguageName, -1); // then verifyCalledOnceWith(updateLanguageName, expectedLanguageName); verifyCalledOnceWith(updateLanguageId, expectedLanguageID); expect(updateLanguageSettings).not.toHaveBeenCalled(); }); // // helpers // function shallowRenderComponent(languageName, languageId) { return shallow( <LanguageNameTextBox translate={(key) => key} languageName={languageName} languageId={languageId} updateLanguageName={updateLanguageName} updateLanguageId={updateLanguageId} updateLanguageSettings={updateLanguageSettings} /> ); } function verifyAutoComplete(enzymeWrapper, expectedSearchText, expectedErrorText) { const autoComplete = enzymeWrapper.find(AutoComplete); const props = autoComplete.getElement().props; expect(props.errorText).toEqual(expectedErrorText); expect(props.searchText).toEqual(expectedSearchText); } }); // // helpers // function verifyCalledOnceWith(func, expectedParameter) { expect(func).toHaveBeenCalled(); expect(func.mock.calls.length).toEqual(1); if (!Array.isArray(expectedParameter)) { expectedParameter = [expectedParameter]; } expect(func.mock.calls[0]).toEqual(expectedParameter); } function getIndexForName(expectedLanguageName) { let index = -1; const languagesSortedByName = LangHelpers.getLanguagesSortedByName(); for (let i = 0; i < languagesSortedByName.length; i++) { if ((languagesSortedByName[i].name === expectedLanguageName) || (languagesSortedByName[i].namePrompt === expectedLanguageName)) { index = i; break; } } return index; }
33.60452
133
0.719233
b41ba42264aedfc0fe27b0091e6625283efabc71
600
js
JavaScript
hr-is-api/src/auths/validator.js
head-Set/hr-is
0408e1401f82af1731c73716764c9d4a9814f89c
[ "MIT" ]
null
null
null
hr-is-api/src/auths/validator.js
head-Set/hr-is
0408e1401f82af1731c73716764c9d4a9814f89c
[ "MIT" ]
null
null
null
hr-is-api/src/auths/validator.js
head-Set/hr-is
0408e1401f82af1731c73716764c9d4a9814f89c
[ "MIT" ]
null
null
null
var jwt = require('jsonwebtoken'); async function verifyToken(req, res, next) { var token = await req.headers['authorization']; if (!token) return res.status(403).json({ status: 400, message: "No Token Bitch", }); await jwt.verify(token, process.env.MYSECRET, function (err, decoded) { if (err) { return res.status(500).json({ auth: false, message: 'Failed to authenticate token.' }) } req.userId = decoded.id; next(); }); } module.exports = verifyToken;
27.272727
75
0.535
b41bcf3c355d3bf65411fb96131da585d15838e5
266
js
JavaScript
docs/html/search/all_1.js
iluzioDev/langton-ant
6c2359f7656288e0960bc08a81487f9bdf2a2b91
[ "MIT" ]
null
null
null
docs/html/search/all_1.js
iluzioDev/langton-ant
6c2359f7656288e0960bc08a81487f9bdf2a2b91
[ "MIT" ]
null
null
null
docs/html/search/all_1.js
iluzioDev/langton-ant
6c2359f7656288e0960bc08a81487f9bdf2a2b91
[ "MIT" ]
null
null
null
var searchData= [ ['begin_0',['Begin',['../d1/dc4/class_smart_vector.html#af048c22fd32e27e6f24676e664ce5a6c',1,'SmartVector']]], ['black_1',['black',['../d8/d5c/_ant_8hpp.html#ab87bacfdad76e61b9412d7124be44c1ca775364fe1f3fffe99686bf6d572a7370',1,'Ant.hpp']]] ];
44.333333
131
0.75188
b41d4cd1fcf0eb40436f8c077079238a2e215235
673
js
JavaScript
my-app/src/productsData.js
ankitdubey987/100DaysOfChallenge
029ee5142caafba41e4d95f523006d647e77741b
[ "MIT" ]
null
null
null
my-app/src/productsData.js
ankitdubey987/100DaysOfChallenge
029ee5142caafba41e4d95f523006d647e77741b
[ "MIT" ]
null
null
null
my-app/src/productsData.js
ankitdubey987/100DaysOfChallenge
029ee5142caafba41e4d95f523006d647e77741b
[ "MIT" ]
null
null
null
// productsData.js const products = [ { id:'1', name:"Pencil", price:1, description:"Perfect for the students", completed:true }, { id:'2', name:"Pen", price:11, description:"Perfect for the students" }, { id:'3', name:"Rubber", price:12, description:"Perfect for the students" }, { id:'4', name:"Sharpner", price:13, description:"Perfect for the students" }, { id:'5', name:"Compass", price:14, description:"Perfect for the students" } ] export default products;
18.189189
47
0.475483
b41da7cf11cd3876c3033d17a6efbf8cc8d3ac59
6,394
js
JavaScript
assets/src/edit-story/components/canvas/canvasProvider.js
szepeviktor/web-stories-wp
df921610c406898a98fa4112f1c0eb44f37b345b
[ "Apache-2.0" ]
null
null
null
assets/src/edit-story/components/canvas/canvasProvider.js
szepeviktor/web-stories-wp
df921610c406898a98fa4112f1c0eb44f37b345b
[ "Apache-2.0" ]
null
null
null
assets/src/edit-story/components/canvas/canvasProvider.js
szepeviktor/web-stories-wp
df921610c406898a98fa4112f1c0eb44f37b345b
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * External dependencies */ import PropTypes from 'prop-types'; import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; /** * Internal dependencies */ import { useLayout } from '../../app/layout'; import { useStory } from '../../app'; import { UnitsProvider } from '../../units'; import useEditingElement from './useEditingElement'; import useCanvasCopyPaste from './useCanvasCopyPaste'; import Context from './context'; function CanvasProvider({ children }) { const [lastSelectionEvent, setLastSelectionEvent] = useState(null); const lastSelectedElementId = useRef(null); const [pageContainer, setPageContainer] = useState(null); const [fullbleedContainer, setFullbleedContainer] = useState(null); const [showSafeZone, setShowSafeZone] = useState(true); const [pageAttachmentContainer, setPageAttachmentContainer] = useState(null); const [displayLinkGuidelines, setDisplayLinkGuidelines] = useState(false); const { pageSize, setPageSize } = useLayout(({ state, actions }) => ({ pageSize: state.canvasPageSize, setPageSize: actions.setCanvasPageSize, })); const { nodesById, editingElement, editingElementState, setEditingElementWithState, setEditingElementWithoutState, clearEditing, getNodeForElement, setNodeForElement, } = useEditingElement(); const { currentPage, selectedElementIds, toggleElementInSelection, setSelectedElementsById, } = useStory( ({ state: { currentPage, selectedElementIds }, actions: { toggleElementInSelection, setSelectedElementsById }, }) => { return { currentPage, selectedElementIds, toggleElementInSelection, setSelectedElementsById, }; } ); const handleSelectElement = useCallback( (elId, evt) => { if (editingElement && editingElement !== elId) { clearEditing(); } // Skip the focus that immediately follows mouse event. // Use the reference to the latest element because the events come in the // sequence in the same event loop. if (lastSelectedElementId.current === elId && evt.type === 'focus') { return; } lastSelectedElementId.current = elId; if (evt.shiftKey) { toggleElementInSelection({ elementId: elId }); } else { setSelectedElementsById({ elementIds: [elId] }); } evt.currentTarget.focus({ preventScroll: true }); if (currentPage?.elements[0].id !== elId) { evt.stopPropagation(); } if ('mousedown' === evt.type) { evt.persist(); setLastSelectionEvent(evt); // Clear this selection event as soon as mouse is released // `setTimeout` is currently required to not break functionality. evt.target.ownerDocument.addEventListener( 'mouseup', () => window.setTimeout(setLastSelectionEvent, 0, null), { once: true, capture: true } ); } }, [ editingElement, currentPage?.elements, clearEditing, toggleElementInSelection, setSelectedElementsById, ] ); const selectIntersection = useCallback( ({ x: lx, y: ly, width: lw, height: lh }) => { const newSelectedElementIds = currentPage.elements .filter(({ isBackground }) => !isBackground) .filter(({ x, y, width, height }) => { return ( x <= lx + lw && lx <= x + width && y <= ly + lh && ly <= y + height ); }) .map(({ id }) => id); setSelectedElementsById({ elementIds: newSelectedElementIds }); }, [currentPage, setSelectedElementsById] ); // Reset editing mode when selection changes. useEffect(() => { if ( editingElement && (selectedElementIds.length !== 1 || selectedElementIds[0] !== editingElement) ) { clearEditing(); } if ( lastSelectedElementId.current && !selectedElementIds.includes(lastSelectedElementId.current) ) { lastSelectedElementId.current = null; } }, [editingElement, selectedElementIds, clearEditing]); useCanvasCopyPaste(); const state = useMemo( () => ({ state: { pageContainer, fullbleedContainer, nodesById, editingElement, editingElementState, isEditing: Boolean(editingElement), lastSelectionEvent, showSafeZone, pageSize, displayLinkGuidelines, pageAttachmentContainer, }, actions: { setPageContainer, setFullbleedContainer, getNodeForElement, setNodeForElement, setEditingElement: setEditingElementWithoutState, setEditingElementWithState, clearEditing, handleSelectElement, selectIntersection, setPageSize, setShowSafeZone, setDisplayLinkGuidelines, setPageAttachmentContainer, }, }), [ pageContainer, fullbleedContainer, nodesById, editingElement, editingElementState, lastSelectionEvent, pageSize, showSafeZone, setPageContainer, setFullbleedContainer, getNodeForElement, setNodeForElement, setEditingElementWithoutState, setEditingElementWithState, clearEditing, handleSelectElement, selectIntersection, setPageSize, setShowSafeZone, displayLinkGuidelines, setDisplayLinkGuidelines, pageAttachmentContainer, setPageAttachmentContainer, ] ); return ( <Context.Provider value={state}> <UnitsProvider pageSize={pageSize}>{children}</UnitsProvider> </Context.Provider> ); } CanvasProvider.propTypes = { children: PropTypes.node, }; export default CanvasProvider;
28.292035
79
0.64842