language
stringclasses
6 values
original_string
stringlengths
25
887k
text
stringlengths
25
887k
JavaScript
function monthsButton(firstMonth, secondMonth, monthOne, monthTwo) { return ( <View style={styles.monthButtonView}> {monthButton(monthOne, firstMonth)} {monthButton(monthTwo, secondMonth)} </View> ); }
function monthsButton(firstMonth, secondMonth, monthOne, monthTwo) { return ( <View style={styles.monthButtonView}> {monthButton(monthOne, firstMonth)} {monthButton(monthTwo, secondMonth)} </View> ); }
JavaScript
function yearButton() { return ( <View style={styles.yearButtonView}> <TouchableOpacity style={styles.yearButton} onPress={() => goBack()}> <Text style={styles.yearButtonText}>{route.params.dates[0].substring(24, 28)}</Text> </TouchableOpacity> </View> ); }
function yearButton() { return ( <View style={styles.yearButtonView}> <TouchableOpacity style={styles.yearButton} onPress={() => goBack()}> <Text style={styles.yearButtonText}>{route.params.dates[0].substring(24, 28)}</Text> </TouchableOpacity> </View> ); }
JavaScript
function monthMenu() { var butJan = false; var butFeb = false; var butMar = false; var butApr = false; var butMay = false; var butJun = false; var butJul = false; var butAug = false; var butSep = false; var butOct = false; var butNov = false; var butDec = false; var monthArray = route.params.dates; for (var index = 0; index < monthArray.length; index++) { switch (monthArray[index].substring(4, 7)) { case 'Jan': butJan = true; break; case 'Feb': butFeb = true; break; case 'Mar': butMar = true; break; case 'Apr': butApr = true; break; case 'May': butMay = true; break; case 'Jun': butJun = true; break; case 'Jul': butJul = true; break; case 'Aug': butAug = true; break; case 'Sep': butSep = true; break; case 'Oct': butOct = true; break; case 'Nov': butNov = true; break; case 'Dec': butDec = true; break; default: break; } }; return ( <ScrollView style={styles.scrollContainer}> { monthsButton('Jan', 'Feb', butJan, butFeb)} { monthsButton('Mar', 'Apr', butMar, butApr)} { monthsButton('May', 'Jun', butMay, butJun)} { monthsButton('Jul', 'Aug', butJul, butAug)} { monthsButton('Sep', 'Oct', butSep, butOct)} { monthsButton('Nov', 'Dec', butNov, butDec)} </ScrollView> ); }
function monthMenu() { var butJan = false; var butFeb = false; var butMar = false; var butApr = false; var butMay = false; var butJun = false; var butJul = false; var butAug = false; var butSep = false; var butOct = false; var butNov = false; var butDec = false; var monthArray = route.params.dates; for (var index = 0; index < monthArray.length; index++) { switch (monthArray[index].substring(4, 7)) { case 'Jan': butJan = true; break; case 'Feb': butFeb = true; break; case 'Mar': butMar = true; break; case 'Apr': butApr = true; break; case 'May': butMay = true; break; case 'Jun': butJun = true; break; case 'Jul': butJul = true; break; case 'Aug': butAug = true; break; case 'Sep': butSep = true; break; case 'Oct': butOct = true; break; case 'Nov': butNov = true; break; case 'Dec': butDec = true; break; default: break; } }; return ( <ScrollView style={styles.scrollContainer}> { monthsButton('Jan', 'Feb', butJan, butFeb)} { monthsButton('Mar', 'Apr', butMar, butApr)} { monthsButton('May', 'Jun', butMay, butJun)} { monthsButton('Jul', 'Aug', butJul, butAug)} { monthsButton('Sep', 'Oct', butSep, butOct)} { monthsButton('Nov', 'Dec', butNov, butDec)} </ScrollView> ); }
JavaScript
function startWorkout() { if (contextObject.workoutList.length != 0) { for (var index = 0; index < contextObject.workoutList.length; index++) { contextObject.workout.push({ "exerciseID": contextObject.workoutList[index].exerciseID, "exerciseName": contextObject.workoutList[index].title, "description": contextObject.workoutList[index].description, "picture": contextObject.workoutList[index].picture, "reps": [], "weight": [] }); } contextObject.workoutStarted = true; } }
function startWorkout() { if (contextObject.workoutList.length != 0) { for (var index = 0; index < contextObject.workoutList.length; index++) { contextObject.workout.push({ "exerciseID": contextObject.workoutList[index].exerciseID, "exerciseName": contextObject.workoutList[index].title, "description": contextObject.workoutList[index].description, "picture": contextObject.workoutList[index].picture, "reps": [], "weight": [] }); } contextObject.workoutStarted = true; } }
JavaScript
function addNoteButton() { if (note === '') { return ( <TouchableOpacity style={styles.addNoteButton} disabled={true} > <Text style={styles.notesButtonText}>+</Text> </TouchableOpacity> ); } else { return ( <TouchableOpacity style={styles.addNoteButton} onPress={() => addNote()}> <Text style={styles.notesButtonText}>+</Text> </TouchableOpacity> ); } }
function addNoteButton() { if (note === '') { return ( <TouchableOpacity style={styles.addNoteButton} disabled={true} > <Text style={styles.notesButtonText}>+</Text> </TouchableOpacity> ); } else { return ( <TouchableOpacity style={styles.addNoteButton} onPress={() => addNote()}> <Text style={styles.notesButtonText}>+</Text> </TouchableOpacity> ); } }
JavaScript
function createBranch() { if (route.params.parentID == 'root') { axios.post('http://68.172.33.6:9083/exercises/addExerciseBranch', { branchName: branchName, childrenType: "", children: [], nodeType: "root", parentNode: "" }, { headers: { "Authorization": `Bearer ${contextObject.jwt}` } }).catch(e => console.log(e)); } else { var objectID = 'ObjectId(' + route.params.parentID + ')'; axios.post('http://68.172.33.6:9083/exercises/addExerciseBranch', { branchName: branchName, childrenType: "", children: [], nodeType: "child", parentNode: objectID }, { headers: { "Authorization": `Bearer ${contextObject.jwt}` } }).catch(e => console.log(e)); } axios.get('http://68.172.33.6:9083/exercises/allRoots', { headers: { "Authorization": `Bearer ${contextObject.jwt}` } }) .then(response => navigation.navigate('Home', { branches: response.data, childrenType: 'branch', })).catch(e => console.log(e)); }
function createBranch() { if (route.params.parentID == 'root') { axios.post('http://68.172.33.6:9083/exercises/addExerciseBranch', { branchName: branchName, childrenType: "", children: [], nodeType: "root", parentNode: "" }, { headers: { "Authorization": `Bearer ${contextObject.jwt}` } }).catch(e => console.log(e)); } else { var objectID = 'ObjectId(' + route.params.parentID + ')'; axios.post('http://68.172.33.6:9083/exercises/addExerciseBranch', { branchName: branchName, childrenType: "", children: [], nodeType: "child", parentNode: objectID }, { headers: { "Authorization": `Bearer ${contextObject.jwt}` } }).catch(e => console.log(e)); } axios.get('http://68.172.33.6:9083/exercises/allRoots', { headers: { "Authorization": `Bearer ${contextObject.jwt}` } }) .then(response => navigation.navigate('Home', { branches: response.data, childrenType: 'branch', })).catch(e => console.log(e)); }
JavaScript
isBadWeave(weave, maxWeaves) { if (weave.leadingGcdEvent.ability) { const weaveCount = weave.weaves.filter( event => !this.invuln.isUntargetable('all', event.timestamp), ).length //allow a single weave of the OGCD exceptions if (weaveCount === 1 && OGCD_EXCEPTIONS.includes(weave.weaves[0].ability.guid)) { return false } //allow first eno to be ignored because it's a neccessary weave. 10s for that to happen because of O5s Eno delay. if (weaveCount === 1) { const ogcdTime = weave.weaves[0].timestamp - this.parser.fight.start_time if (ogcdTime < OPENER_ENO_TIME_THRESHHOLD && weave.weaves[0].ability.guid === ACTIONS.ENOCHIAN.id) { return false } } //allow single weave under fast B3/F3 if ((weave.leadingGcdEvent.ability.guid === ACTIONS.FIRE_III.id && this._lastF3FastCast) || (weave.leadingGcdEvent.ability.guid === ACTIONS.BLIZZARD_III.id && this._lastB3FastCast) ) { if (weaveCount === 1) { return false } } } return super.isBadWeave(weave, maxWeaves) }
isBadWeave(weave, maxWeaves) { if (weave.leadingGcdEvent.ability) { const weaveCount = weave.weaves.filter( event => !this.invuln.isUntargetable('all', event.timestamp), ).length //allow a single weave of the OGCD exceptions if (weaveCount === 1 && OGCD_EXCEPTIONS.includes(weave.weaves[0].ability.guid)) { return false } //allow first eno to be ignored because it's a neccessary weave. 10s for that to happen because of O5s Eno delay. if (weaveCount === 1) { const ogcdTime = weave.weaves[0].timestamp - this.parser.fight.start_time if (ogcdTime < OPENER_ENO_TIME_THRESHHOLD && weave.weaves[0].ability.guid === ACTIONS.ENOCHIAN.id) { return false } } //allow single weave under fast B3/F3 if ((weave.leadingGcdEvent.ability.guid === ACTIONS.FIRE_III.id && this._lastF3FastCast) || (weave.leadingGcdEvent.ability.guid === ACTIONS.BLIZZARD_III.id && this._lastB3FastCast) ) { if (weaveCount === 1) { return false } } } return super.isBadWeave(weave, maxWeaves) }
JavaScript
_onCast(event) { const action = getDataBy(ACTIONS, 'id', event.ability.guid) if (!action) { return } const lastGcdActionId = this._lastGcd ? this._lastGcd.ability.guid : undefined if (!action.onGcd) { this._lastOgcd = event this._ogcdUsed = true return } // Calc the time in the GCD that the boss can't be targeted - R2ing before an invuln to prevent an R3 cancel is good const invulnTime = this.invuln.getUntargetableUptime( 'all', event.timestamp, event.timestamp + this.gcd.getEstimate(), ) if ( action.onGcd && lastGcdActionId === ACTIONS.SMN_RUIN_II.id && invulnTime === 0 ) { if (this._ogcdUsed) { // This was at least used for a weave, even though you should have enough other instants to not need R2s in general. this._weaved.push(this._lastGcd) } else if (this.movedSinceLastGcd()) { // Separate count if they at least moved this._moveOnly.push(this._lastGcd) } else { this._worthless.push(this._lastGcd) } } // If this cast is on the gcd, store it for comparison this._lastGcd = event this._pos = this.combatants.selected.resources // If this is an R2 cast, track it if (action.id === ACTIONS.SMN_RUIN_II.id) { // Explicitly setting the ogcd tracker to true while bahamut is out, // we don't want to fault people for using R2 for WWs during bahamut. this._ogcdUsed = (this.pets.getCurrentPet() === PETS.DEMI_BAHAMUT.id) } }
_onCast(event) { const action = getDataBy(ACTIONS, 'id', event.ability.guid) if (!action) { return } const lastGcdActionId = this._lastGcd ? this._lastGcd.ability.guid : undefined if (!action.onGcd) { this._lastOgcd = event this._ogcdUsed = true return } // Calc the time in the GCD that the boss can't be targeted - R2ing before an invuln to prevent an R3 cancel is good const invulnTime = this.invuln.getUntargetableUptime( 'all', event.timestamp, event.timestamp + this.gcd.getEstimate(), ) if ( action.onGcd && lastGcdActionId === ACTIONS.SMN_RUIN_II.id && invulnTime === 0 ) { if (this._ogcdUsed) { // This was at least used for a weave, even though you should have enough other instants to not need R2s in general. this._weaved.push(this._lastGcd) } else if (this.movedSinceLastGcd()) { // Separate count if they at least moved this._moveOnly.push(this._lastGcd) } else { this._worthless.push(this._lastGcd) } } // If this cast is on the gcd, store it for comparison this._lastGcd = event this._pos = this.combatants.selected.resources // If this is an R2 cast, track it if (action.id === ACTIONS.SMN_RUIN_II.id) { // Explicitly setting the ogcd tracker to true while bahamut is out, // we don't want to fault people for using R2 for WWs during bahamut. this._ogcdUsed = (this.pets.getCurrentPet() === PETS.DEMI_BAHAMUT.id) } }
JavaScript
render() { distribute(this.events, this.canvas).forEach(event => { event.create() this.canvas.add(event) }) return this }
render() { distribute(this.events, this.canvas).forEach(event => { event.create() this.canvas.add(event) }) return this }
JavaScript
function registerClass(rule, className) { // Skip falsy values if (!className) return true // Support array of class names `{composes: ['foo', 'bar']}` if (Array.isArray(className)) { for (let index = 0; index < className.length; index++) { const isSetted = registerClass(rule, className[index]) if (!isSetted) return false } return true } // Support space separated class names `{composes: 'foo bar'}` if (className.indexOf(' ') > -1) { return registerClass(rule, className.split(' ')) } const {parent} = rule.options // It is a ref to a local rule. if (className[0] === '$') { const refRule = parent.getRule(className.substr(1)) if (!refRule) { warning(false, `[JSS] Referenced rule is not defined. \n${rule.toString()}`) return false } if (refRule === rule) { warning(false, `[JSS] Cyclic composition detected. \n${rule.toString()}`) return false } parent.classes[rule.key] += ` ${parent.classes[refRule.key]}` return true } parent.classes[rule.key] += ` ${className}` return true }
function registerClass(rule, className) { // Skip falsy values if (!className) return true // Support array of class names `{composes: ['foo', 'bar']}` if (Array.isArray(className)) { for (let index = 0; index < className.length; index++) { const isSetted = registerClass(rule, className[index]) if (!isSetted) return false } return true } // Support space separated class names `{composes: 'foo bar'}` if (className.indexOf(' ') > -1) { return registerClass(rule, className.split(' ')) } const {parent} = rule.options // It is a ref to a local rule. if (className[0] === '$') { const refRule = parent.getRule(className.substr(1)) if (!refRule) { warning(false, `[JSS] Referenced rule is not defined. \n${rule.toString()}`) return false } if (refRule === rule) { warning(false, `[JSS] Cyclic composition detected. \n${rule.toString()}`) return false } parent.classes[rule.key] += ` ${parent.classes[refRule.key]}` return true } parent.classes[rule.key] += ` ${className}` return true }
JavaScript
function jssCompose() { function onProcessStyle(style, rule) { if (!('composes' in style)) return style registerClass(rule, style.composes) // Remove composes property to prevent infinite loop. delete style.composes return style } return {onProcessStyle} }
function jssCompose() { function onProcessStyle(style, rule) { if (!('composes' in style)) return style registerClass(rule, style.composes) // Remove composes property to prevent infinite loop. delete style.composes return style } return {onProcessStyle} }
JavaScript
function createGroups(events) { const groups = [] const eventGroupMap = {} events.forEach(event => { let group = eventGroupMap[event.id] if (!group) { group = eventGroupMap[event.id] group = [event] groups.push(group) } events.forEach(_event => { if (_event === event) return if (collide(event, _event)) { if (!eventGroupMap[_event.id]) { eventGroupMap[_event.id] = group group.push(_event) } } }) }) return groups }
function createGroups(events) { const groups = [] const eventGroupMap = {} events.forEach(event => { let group = eventGroupMap[event.id] if (!group) { group = eventGroupMap[event.id] group = [event] groups.push(group) } events.forEach(_event => { if (_event === event) return if (collide(event, _event)) { if (!eventGroupMap[_event.id]) { eventGroupMap[_event.id] = group group.push(_event) } } }) }) return groups }
JavaScript
function distribute(events, canvas) { function setStyle(column, nr, columns) { const width = canvas.getContentWidth() / columns.length column.forEach(event => { const top = utils.minToY(event.start) const height = utils.minToY(event.end) - top event.setStyle({ width: `${width}px`, height: `${height}px`, top: `${top}px`, left: `${nr * width}px` }) }) } createGroups(events).forEach(group => { createColumns(group).forEach(setStyle) }) return events }
function distribute(events, canvas) { function setStyle(column, nr, columns) { const width = canvas.getContentWidth() / columns.length column.forEach(event => { const top = utils.minToY(event.start) const height = utils.minToY(event.end) - top event.setStyle({ width: `${width}px`, height: `${height}px`, top: `${top}px`, left: `${nr * width}px` }) }) } createGroups(events).forEach(group => { createColumns(group).forEach(setStyle) }) return events }
JavaScript
function processArray(value, prop, scheme, rule) { if (scheme[prop] == null) return value if (value.length === 0) return [] if (Array.isArray(value[0])) return processArray(value[0], prop, scheme, rule) if (typeof value[0] === 'object') { return mapValuesByProp(value, prop, rule) } return [value] }
function processArray(value, prop, scheme, rule) { if (scheme[prop] == null) return value if (value.length === 0) return [] if (Array.isArray(value[0])) return processArray(value[0], prop, scheme, rule) if (typeof value[0] === 'object') { return mapValuesByProp(value, prop, rule) } return [value] }
JavaScript
function customPropsToStyle(value, rule, customProps, isFallback) { for (const prop in customProps) { const propName = customProps[prop] // If current property doesn't exist already in rule - add new one if (typeof value[prop] !== 'undefined' && (isFallback || !rule.prop(propName))) { const appendedValue = styleDetector( { [propName]: value[prop] }, rule )[propName] // Add style directly in rule if (isFallback) rule.style.fallbacks[propName] = appendedValue else rule.style[propName] = appendedValue } // Delete converted property to avoid double converting delete value[prop] } return value }
function customPropsToStyle(value, rule, customProps, isFallback) { for (const prop in customProps) { const propName = customProps[prop] // If current property doesn't exist already in rule - add new one if (typeof value[prop] !== 'undefined' && (isFallback || !rule.prop(propName))) { const appendedValue = styleDetector( { [propName]: value[prop] }, rule )[propName] // Add style directly in rule if (isFallback) rule.style.fallbacks[propName] = appendedValue else rule.style[propName] = appendedValue } // Delete converted property to avoid double converting delete value[prop] } return value }
JavaScript
function styleDetector(style, rule, isFallback) { for (const prop in style) { const value = style[prop] if (Array.isArray(value)) { // Check double arrays to avoid recursion. if (!Array.isArray(value[0])) { if (prop === 'fallbacks') { for (let index = 0; index < style.fallbacks.length; index++) { style.fallbacks[index] = styleDetector(style.fallbacks[index], rule, true) } continue } style[prop] = processArray(value, prop, propArray, rule) // Avoid creating properties with empty values if (!style[prop].length) delete style[prop] } } else if (typeof value === 'object') { if (prop === 'fallbacks') { style.fallbacks = styleDetector(style.fallbacks, rule, true) continue } style[prop] = objectToArray(value, prop, rule, isFallback) // Avoid creating properties with empty values if (!style[prop].length) delete style[prop] } // Maybe a computed value resulting in an empty string else if (style[prop] === '') delete style[prop] } return style }
function styleDetector(style, rule, isFallback) { for (const prop in style) { const value = style[prop] if (Array.isArray(value)) { // Check double arrays to avoid recursion. if (!Array.isArray(value[0])) { if (prop === 'fallbacks') { for (let index = 0; index < style.fallbacks.length; index++) { style.fallbacks[index] = styleDetector(style.fallbacks[index], rule, true) } continue } style[prop] = processArray(value, prop, propArray, rule) // Avoid creating properties with empty values if (!style[prop].length) delete style[prop] } } else if (typeof value === 'object') { if (prop === 'fallbacks') { style.fallbacks = styleDetector(style.fallbacks, rule, true) continue } style[prop] = objectToArray(value, prop, rule, isFallback) // Avoid creating properties with empty values if (!style[prop].length) delete style[prop] } // Maybe a computed value resulting in an empty string else if (style[prop] === '') delete style[prop] } return style }
JavaScript
function jssExpand() { function onProcessStyle(style, rule) { if (!style || rule.type !== 'style') return style if (Array.isArray(style)) { // Pass rules one by one and reformat them for (let index = 0; index < style.length; index++) { style[index] = styleDetector(style[index], rule) } return style } return styleDetector(style, rule) } return {onProcessStyle} }
function jssExpand() { function onProcessStyle(style, rule) { if (!style || rule.type !== 'style') return style if (Array.isArray(style)) { // Pass rules one by one and reformat them for (let index = 0; index < style.length; index++) { style[index] = styleDetector(style[index], rule) } return style } return styleDetector(style, rule) } return {onProcessStyle} }
JavaScript
function createItems(items, location, depth, maxDepth, activeHash, isDesktop) { return ( items && items.map((item, index) => { const isActive = isDesktop && item.url === `#${activeHash}` return ( <li data-testid={item.url || ``} sx={{ [mediaQueries.xl]: { fontSize: 1 } }} key={location.pathname + (item.url || depth + `-` + index)} > {item.url && ( <Link sx={{ "&&": { color: isActive ? `link.color` : `textMuted`, border: 0, borderBottom: t => isActive ? `1px solid ${t.colors.link.hoverBorder}` : `none`, transition: t => `all ${t.transition.speed.fast} ${t.transition.curve.default}`, ":hover": { color: `link.color`, borderBottom: t => `1px solid ${t.colors.link.hoverBorder}`, }, }, }} to={location.pathname + item.url} > {item.title} </Link> )} {item.items && isUnderDepthLimit(depth, maxDepth) && ( <ul sx={{ color: `textMuted`, listStyle: `none`, ml: 5 }}> {createItems( item.items, location, depth + 1, maxDepth, activeHash, isDesktop )} </ul> )} </li> ) }) ) }
function createItems(items, location, depth, maxDepth, activeHash, isDesktop) { return ( items && items.map((item, index) => { const isActive = isDesktop && item.url === `#${activeHash}` return ( <li data-testid={item.url || ``} sx={{ [mediaQueries.xl]: { fontSize: 1 } }} key={location.pathname + (item.url || depth + `-` + index)} > {item.url && ( <Link sx={{ "&&": { color: isActive ? `link.color` : `textMuted`, border: 0, borderBottom: t => isActive ? `1px solid ${t.colors.link.hoverBorder}` : `none`, transition: t => `all ${t.transition.speed.fast} ${t.transition.curve.default}`, ":hover": { color: `link.color`, borderBottom: t => `1px solid ${t.colors.link.hoverBorder}`, }, }, }} to={location.pathname + item.url} > {item.title} </Link> )} {item.items && isUnderDepthLimit(depth, maxDepth) && ( <ul sx={{ color: `textMuted`, listStyle: `none`, ml: 5 }}> {createItems( item.items, location, depth + 1, maxDepth, activeHash, isDesktop )} </ul> )} </li> ) }) ) }
JavaScript
function autocompleteSelected(e) { e.stopPropagation() // Use an anchor tag to parse the absolute url (from autocomplete.js) into a relative url const a = document.createElement(`a`) a.href = e._args[0].url searchInput.current.blur() // Compare hash and slug and remove hash if both are same const paths = a.pathname.split(`/`).filter(el => el !== ``) const slug = paths[paths.length - 1] const path = `#${slug}` === a.hash ? `${a.pathname}` : `${a.pathname}${a.hash}` navigate(path) }
function autocompleteSelected(e) { e.stopPropagation() // Use an anchor tag to parse the absolute url (from autocomplete.js) into a relative url const a = document.createElement(`a`) a.href = e._args[0].url searchInput.current.blur() // Compare hash and slug and remove hash if both are same const paths = a.pathname.split(`/`).filter(el => el !== ``) const slug = paths[paths.length - 1] const path = `#${slug}` === a.hash ? `${a.pathname}` : `${a.pathname}${a.hash}` navigate(path) }
JavaScript
function resolvePlugin(pluginName, rootDir) { // Only find plugins when we're not given an absolute path if (!existsSync(pluginName)) { // Find the plugin in the local plugins folder const resolvedPath = slash(path.resolve(`./plugins/${pluginName}`)) if (existsSync(resolvedPath)) { if (existsSync(`${resolvedPath}/package.json`)) { const packageJSON = JSON.parse( fs.readFileSync(`${resolvedPath}/package.json`, `utf-8`) ) const name = packageJSON.name || pluginName warnOnIncompatiblePeerDependency(name, packageJSON) return { resolve: resolvedPath, name, id: createPluginId(name), version: packageJSON.version || createFileContentHash(resolvedPath, `**`), } } else { // Make package.json a requirement for local plugins too throw new Error(`Plugin ${pluginName} requires a package.json file`) } } } /** * Here we have an absolute path to an internal plugin, or a name of a module * which should be located in node_modules. */ try { const requireSource = rootDir !== null ? createRequireFromPath(`${rootDir}/:internal:`) : require // If the path is absolute, resolve the directory of the internal plugin, // otherwise resolve the directory containing the package.json const resolvedPath = slash( path.dirname( requireSource.resolve( path.isAbsolute(pluginName) ? pluginName : `${pluginName}/package.json` ) ) ) const packageJSON = JSON.parse( fs.readFileSync(`${resolvedPath}/package.json`, `utf-8`) ) warnOnIncompatiblePeerDependency(packageJSON.name, packageJSON) return { resolve: resolvedPath, id: createPluginId(packageJSON.name), name: packageJSON.name, version: packageJSON.version, } } catch (err) { throw new Error( `Unable to find plugin "${pluginName}". Perhaps you need to install its package?` ) } }
function resolvePlugin(pluginName, rootDir) { // Only find plugins when we're not given an absolute path if (!existsSync(pluginName)) { // Find the plugin in the local plugins folder const resolvedPath = slash(path.resolve(`./plugins/${pluginName}`)) if (existsSync(resolvedPath)) { if (existsSync(`${resolvedPath}/package.json`)) { const packageJSON = JSON.parse( fs.readFileSync(`${resolvedPath}/package.json`, `utf-8`) ) const name = packageJSON.name || pluginName warnOnIncompatiblePeerDependency(name, packageJSON) return { resolve: resolvedPath, name, id: createPluginId(name), version: packageJSON.version || createFileContentHash(resolvedPath, `**`), } } else { // Make package.json a requirement for local plugins too throw new Error(`Plugin ${pluginName} requires a package.json file`) } } } /** * Here we have an absolute path to an internal plugin, or a name of a module * which should be located in node_modules. */ try { const requireSource = rootDir !== null ? createRequireFromPath(`${rootDir}/:internal:`) : require // If the path is absolute, resolve the directory of the internal plugin, // otherwise resolve the directory containing the package.json const resolvedPath = slash( path.dirname( requireSource.resolve( path.isAbsolute(pluginName) ? pluginName : `${pluginName}/package.json` ) ) ) const packageJSON = JSON.parse( fs.readFileSync(`${resolvedPath}/package.json`, `utf-8`) ) warnOnIncompatiblePeerDependency(packageJSON.name, packageJSON) return { resolve: resolvedPath, id: createPluginId(packageJSON.name), name: packageJSON.name, version: packageJSON.version, } } catch (err) { throw new Error( `Unable to find plugin "${pluginName}". Perhaps you need to install its package?` ) } }
JavaScript
async function processRemoteNode({ url, cache, createNode, parentNodeId, auth = {}, httpHeaders = {}, createNodeId, ext, name, }) { const pluginCacheDir = cache.directory // See if there's response headers for this url // from a previous request. const cachedHeaders = await cache.get(cacheId(url)) const headers = { ...httpHeaders } if (cachedHeaders && cachedHeaders.etag) { headers[`If-None-Match`] = cachedHeaders.etag } // Add htaccess authentication if passed in. This isn't particularly // extensible. We should define a proper API that we validate. const httpOpts = {} if (auth && (auth.htaccess_pass || auth.htaccess_user)) { httpOpts.auth = `${auth.htaccess_user}:${auth.htaccess_pass}` } // Create the temp and permanent file names for the url. const digest = createContentDigest(url) if (!name) { name = getRemoteFileName(url) } if (!ext) { ext = getRemoteFileExtension(url) } const tmpFilename = createFilePath(pluginCacheDir, `tmp-${digest}`, ext) // Fetch the file. const response = await requestRemoteNode(url, headers, tmpFilename, httpOpts) if (response.statusCode == 200) { // Save the response headers for future requests. await cache.set(cacheId(url), response.headers) } // If the user did not provide an extension and we couldn't get one from remote file, try and guess one if (ext === ``) { const buffer = readChunk.sync(tmpFilename, 0, fileType.minimumBytes) const filetype = fileType(buffer) if (filetype) { ext = `.${filetype.ext}` } } const filename = createFilePath(path.join(pluginCacheDir, digest), name, ext) // If the status code is 200, move the piped temp file to the real name. if (response.statusCode === 200) { await fs.move(tmpFilename, filename, { overwrite: true }) // Else if 304, remove the empty response. } else { await fs.remove(tmpFilename) } // Create the file node. const fileNode = await createFileNode(filename, createNodeId, {}) fileNode.internal.description = `File "${url}"` fileNode.url = url fileNode.parent = parentNodeId // Override the default plugin as gatsby-source-filesystem needs to // be the owner of File nodes or there'll be conflicts if any other // File nodes are created through normal usages of // gatsby-source-filesystem. await createNode(fileNode, { name: `gatsby-source-filesystem` }) return fileNode }
async function processRemoteNode({ url, cache, createNode, parentNodeId, auth = {}, httpHeaders = {}, createNodeId, ext, name, }) { const pluginCacheDir = cache.directory // See if there's response headers for this url // from a previous request. const cachedHeaders = await cache.get(cacheId(url)) const headers = { ...httpHeaders } if (cachedHeaders && cachedHeaders.etag) { headers[`If-None-Match`] = cachedHeaders.etag } // Add htaccess authentication if passed in. This isn't particularly // extensible. We should define a proper API that we validate. const httpOpts = {} if (auth && (auth.htaccess_pass || auth.htaccess_user)) { httpOpts.auth = `${auth.htaccess_user}:${auth.htaccess_pass}` } // Create the temp and permanent file names for the url. const digest = createContentDigest(url) if (!name) { name = getRemoteFileName(url) } if (!ext) { ext = getRemoteFileExtension(url) } const tmpFilename = createFilePath(pluginCacheDir, `tmp-${digest}`, ext) // Fetch the file. const response = await requestRemoteNode(url, headers, tmpFilename, httpOpts) if (response.statusCode == 200) { // Save the response headers for future requests. await cache.set(cacheId(url), response.headers) } // If the user did not provide an extension and we couldn't get one from remote file, try and guess one if (ext === ``) { const buffer = readChunk.sync(tmpFilename, 0, fileType.minimumBytes) const filetype = fileType(buffer) if (filetype) { ext = `.${filetype.ext}` } } const filename = createFilePath(path.join(pluginCacheDir, digest), name, ext) // If the status code is 200, move the piped temp file to the real name. if (response.statusCode === 200) { await fs.move(tmpFilename, filename, { overwrite: true }) // Else if 304, remove the empty response. } else { await fs.remove(tmpFilename) } // Create the file node. const fileNode = await createFileNode(filename, createNodeId, {}) fileNode.internal.description = `File "${url}"` fileNode.url = url fileNode.parent = parentNodeId // Override the default plugin as gatsby-source-filesystem needs to // be the owner of File nodes or there'll be conflicts if any other // File nodes are created through normal usages of // gatsby-source-filesystem. await createNode(fileNode, { name: `gatsby-source-filesystem` }) return fileNode }
JavaScript
function Pane(props) { return React.createElement( "div", { className: props.className, id: props.id, role: "tabpanel", "aria-labelledby": props.tag }, React.createElement( "p", null, props.text.map(function (text, index) { return typeof text == "string" ? React.createElement( "span", { key: index }, text ) : React.createElement( "a", { key: index, href: text.link }, text.label ); }) ), React.createElement("img", { src: props.plot, className: "rounded mx-auto d-block", alt: "...", style: { maxHeight: "50vh", width: "auto" } }) ); }
function Pane(props) { return React.createElement( "div", { className: props.className, id: props.id, role: "tabpanel", "aria-labelledby": props.tag }, React.createElement( "p", null, props.text.map(function (text, index) { return typeof text == "string" ? React.createElement( "span", { key: index }, text ) : React.createElement( "a", { key: index, href: text.link }, text.label ); }) ), React.createElement("img", { src: props.plot, className: "rounded mx-auto d-block", alt: "...", style: { maxHeight: "50vh", width: "auto" } }) ); }
JavaScript
function PaneMultiImage(props) { return React.createElement( "div", { className: props.className, id: props.id, role: "tabpanel", "aria-labelledby": props.tag }, React.createElement( "p", null, props.text.map(function (text, index) { return typeof text == "string" ? React.createElement( "span", { key: index }, text ) : React.createElement( "a", { key: index, href: text.link }, text.label ); }) ), props.plot_list.map(function (item) { return React.createElement("img", { src: item, key: item, className: "rounded mx-auto d-block", alt: "...", style: { height: "auto", width: "auto" } }); }) ); }
function PaneMultiImage(props) { return React.createElement( "div", { className: props.className, id: props.id, role: "tabpanel", "aria-labelledby": props.tag }, React.createElement( "p", null, props.text.map(function (text, index) { return typeof text == "string" ? React.createElement( "span", { key: index }, text ) : React.createElement( "a", { key: index, href: text.link }, text.label ); }) ), props.plot_list.map(function (item) { return React.createElement("img", { src: item, key: item, className: "rounded mx-auto d-block", alt: "...", style: { height: "auto", width: "auto" } }); }) ); }
JavaScript
function StatsPane(props) { var sample_stat = props.sample_stats[props.sample_id]; var stats_list = ["Total Reads", "Total merged peaks", "Median reads per cell", "Median per cell FRIP", "Median per cell FRIT", "Median Duplication rate"]; var safe_name = "hp" + props.sample_id.replace(/[.]/g, "-"); return React.createElement( "div", { className: "tab-pane fade", id: "nav" + safe_name + "-stats", role: "tabpanel", "aria-labelledby": "nav" + safe_name + "-stats-tab" }, React.createElement( "table", { className: "table table-hover" }, React.createElement( "thead", null, React.createElement( "tr", null, React.createElement("th", { scope: "col" }), stats_list.map(function (item, index) { return React.createElement(TitleRow, { key: index, samp: item }); }) ) ), React.createElement( "tbody", null, React.createElement( "tr", null, React.createElement( "th", { scope: "row" }, props.sample_id ), React.createElement(RegRow, { val: sample_stat.Total_reads }), React.createElement(RegRow, { val: sample_stat.Total_merged_peaks }), React.createElement(RegRow, { val: sample_stat.Median_reads_per_cell }), React.createElement(RegRow, { val: sample_stat.Median_per_cell_frip }), React.createElement(RegRow, { val: sample_stat.Median_per_cell_frit }), React.createElement(RegRow, { val: sample_stat.Median_duplication_rate }) ) ) ) ); }
function StatsPane(props) { var sample_stat = props.sample_stats[props.sample_id]; var stats_list = ["Total Reads", "Total merged peaks", "Median reads per cell", "Median per cell FRIP", "Median per cell FRIT", "Median Duplication rate"]; var safe_name = "hp" + props.sample_id.replace(/[.]/g, "-"); return React.createElement( "div", { className: "tab-pane fade", id: "nav" + safe_name + "-stats", role: "tabpanel", "aria-labelledby": "nav" + safe_name + "-stats-tab" }, React.createElement( "table", { className: "table table-hover" }, React.createElement( "thead", null, React.createElement( "tr", null, React.createElement("th", { scope: "col" }), stats_list.map(function (item, index) { return React.createElement(TitleRow, { key: index, samp: item }); }) ) ), React.createElement( "tbody", null, React.createElement( "tr", null, React.createElement( "th", { scope: "row" }, props.sample_id ), React.createElement(RegRow, { val: sample_stat.Total_reads }), React.createElement(RegRow, { val: sample_stat.Total_merged_peaks }), React.createElement(RegRow, { val: sample_stat.Median_reads_per_cell }), React.createElement(RegRow, { val: sample_stat.Median_per_cell_frip }), React.createElement(RegRow, { val: sample_stat.Median_per_cell_frit }), React.createElement(RegRow, { val: sample_stat.Median_duplication_rate }) ) ) ) ); }
JavaScript
function render() { var data = this.props.data; var currentSort = this.state.currentSort; return React.createElement( "div", { className: "tab-pane fade show active", id: "summary", role: "tabpanel" }, React.createElement( "div", { className: "d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom" }, React.createElement( "h1", { className: "h3", id: "lig-name" }, "Summary Table" ) ), data.length > 0 && React.createElement( "table", { className: "table table-hover table-responsive summary-table" }, React.createElement( "thead", null, React.createElement( "tr", null, React.createElement( "th", null, "Sample", React.createElement( "button", { onClick: this.onSortSample, className: "sort_button" }, React.createElement("i", { className: "fas fa-sort" }) ) ), React.createElement( "th", null, "Total reads", React.createElement( "button", { onClick: this.onSortTotalReads, className: "sort_button" }, React.createElement("i", { className: "fas fa-sort" }) ) ), React.createElement( "th", null, "Total merged peaks", React.createElement( "button", { onClick: this.onSortTotalPeaks, className: "sort_button" }, React.createElement("i", { className: "fas fa-sort" }) ) ), React.createElement( "th", null, "Median reads per cell", React.createElement( "button", { onClick: this.onSortMedianReads, className: "sort_button" }, React.createElement("i", { className: "fas fa-sort" }) ) ), React.createElement( "th", null, "Median per cell FRIP", React.createElement( "button", { onClick: this.onSortMedianFrip, className: "sort_button" }, React.createElement("i", { className: "fas fa-sort" }) ) ), React.createElement( "th", null, "Median per cell FRIT", React.createElement( "button", { onClick: this.onSortMedianFrit, className: "sort_button" }, React.createElement("i", { className: "fas fa-sort" }) ) ), React.createElement( "th", null, "Median duplication rate", React.createElement( "button", { onClick: this.onSortMedianDuplication, className: "sort_button" }, React.createElement("i", { className: "fas fa-sort" }) ) ) ) ), React.createElement( "tbody", null, [].concat(_toConsumableArray(data)).sort(sortTypes[currentSort].fn).map(function (p, index) { return React.createElement( "tr", { key: index }, React.createElement( "td", null, p.Sample ), React.createElement( "td", null, p.Total_reads ), React.createElement( "td", null, p.Total_merged_peaks ), React.createElement( "td", null, p.Median_reads_per_cell ), React.createElement( "td", null, p.Median_per_cell_frip ), React.createElement( "td", null, p.Median_per_cell_frit ), React.createElement( "td", null, p.Median_duplication_rate ) ); }) ) ) ); }
function render() { var data = this.props.data; var currentSort = this.state.currentSort; return React.createElement( "div", { className: "tab-pane fade show active", id: "summary", role: "tabpanel" }, React.createElement( "div", { className: "d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom" }, React.createElement( "h1", { className: "h3", id: "lig-name" }, "Summary Table" ) ), data.length > 0 && React.createElement( "table", { className: "table table-hover table-responsive summary-table" }, React.createElement( "thead", null, React.createElement( "tr", null, React.createElement( "th", null, "Sample", React.createElement( "button", { onClick: this.onSortSample, className: "sort_button" }, React.createElement("i", { className: "fas fa-sort" }) ) ), React.createElement( "th", null, "Total reads", React.createElement( "button", { onClick: this.onSortTotalReads, className: "sort_button" }, React.createElement("i", { className: "fas fa-sort" }) ) ), React.createElement( "th", null, "Total merged peaks", React.createElement( "button", { onClick: this.onSortTotalPeaks, className: "sort_button" }, React.createElement("i", { className: "fas fa-sort" }) ) ), React.createElement( "th", null, "Median reads per cell", React.createElement( "button", { onClick: this.onSortMedianReads, className: "sort_button" }, React.createElement("i", { className: "fas fa-sort" }) ) ), React.createElement( "th", null, "Median per cell FRIP", React.createElement( "button", { onClick: this.onSortMedianFrip, className: "sort_button" }, React.createElement("i", { className: "fas fa-sort" }) ) ), React.createElement( "th", null, "Median per cell FRIT", React.createElement( "button", { onClick: this.onSortMedianFrit, className: "sort_button" }, React.createElement("i", { className: "fas fa-sort" }) ) ), React.createElement( "th", null, "Median duplication rate", React.createElement( "button", { onClick: this.onSortMedianDuplication, className: "sort_button" }, React.createElement("i", { className: "fas fa-sort" }) ) ) ) ), React.createElement( "tbody", null, [].concat(_toConsumableArray(data)).sort(sortTypes[currentSort].fn).map(function (p, index) { return React.createElement( "tr", { key: index }, React.createElement( "td", null, p.Sample ), React.createElement( "td", null, p.Total_reads ), React.createElement( "td", null, p.Total_merged_peaks ), React.createElement( "td", null, p.Median_reads_per_cell ), React.createElement( "td", null, p.Median_per_cell_frip ), React.createElement( "td", null, p.Median_per_cell_frit ), React.createElement( "td", null, p.Median_duplication_rate ) ); }) ) ) ); }
JavaScript
function buttonHandler (submitEvent) { //prevent refresh submitEvent.preventDefault(); //Get the id of the button that was clicked let choice = submitEvent.target.getAttribute("id"); //If choice === SubmitJournal submit the new journal if (choice === 'submitJournal') { sumbitJournal(); } // If choice === refreshJournals // call showAllJournals else if (choice === 'refreshFrontPage' || 'navbarImg') { changePage(1); } // if choice === commentGiphyBtn // start add giphy process else if(choice === 'commentGiphyBtn') { let targetName = submitEvent.target.name; let journalId = ""+targetName; journalId = journalId.replace("commentGiphyBtn",""); try { let searchBar = document.getElementById(journalId+"cmtGiphySearch"); let searchTerm = searchBar.value; if(searchTerm === "" || !searchTerm) { alert("Invalid search term - did you add anything in?"); } else { addGiphytoComment(journalId,searchTerm); } } catch { alert("Couldn't get giphy search bar input"); } } // if choice === submitJournalComment // Call addCommentToJournal else if(choice === 'submitJournalComment') { let targetJournal = submitEvent.target.name; console.log("Taget Journal: " + targetJournal) addCommentToJournal(targetJournal); } else if(choice === 'giphybtnsearch') { let searchBar = document.getElementById("giphytextsearch"); let searchTerm = searchBar.value; if(searchTerm === "" || !searchTerm) { alert("Invalid search term - did you add anything in the search box?"); } else { addGiphyToNewJournal(searchTerm); } } //If choice is none of these // throw debug error alert else { alert("Don't know what clicked, target is: " +submitEvent.target.getAttribute("id")); } }
function buttonHandler (submitEvent) { //prevent refresh submitEvent.preventDefault(); //Get the id of the button that was clicked let choice = submitEvent.target.getAttribute("id"); //If choice === SubmitJournal submit the new journal if (choice === 'submitJournal') { sumbitJournal(); } // If choice === refreshJournals // call showAllJournals else if (choice === 'refreshFrontPage' || 'navbarImg') { changePage(1); } // if choice === commentGiphyBtn // start add giphy process else if(choice === 'commentGiphyBtn') { let targetName = submitEvent.target.name; let journalId = ""+targetName; journalId = journalId.replace("commentGiphyBtn",""); try { let searchBar = document.getElementById(journalId+"cmtGiphySearch"); let searchTerm = searchBar.value; if(searchTerm === "" || !searchTerm) { alert("Invalid search term - did you add anything in?"); } else { addGiphytoComment(journalId,searchTerm); } } catch { alert("Couldn't get giphy search bar input"); } } // if choice === submitJournalComment // Call addCommentToJournal else if(choice === 'submitJournalComment') { let targetJournal = submitEvent.target.name; console.log("Taget Journal: " + targetJournal) addCommentToJournal(targetJournal); } else if(choice === 'giphybtnsearch') { let searchBar = document.getElementById("giphytextsearch"); let searchTerm = searchBar.value; if(searchTerm === "" || !searchTerm) { alert("Invalid search term - did you add anything in the search box?"); } else { addGiphyToNewJournal(searchTerm); } } //If choice is none of these // throw debug error alert else { alert("Don't know what clicked, target is: " +submitEvent.target.getAttribute("id")); } }
JavaScript
async function refreshPage () { current_page = 1; //Create variables containing both sets of data, by calling functions which return journals and comments let journalData = await getJournals(); let commentData = await getComments(); //We're doing a general refresh, so no targetting. let journaTargetted = false; displayData(journalData, commentData, journaTargetted); }
async function refreshPage () { current_page = 1; //Create variables containing both sets of data, by calling functions which return journals and comments let journalData = await getJournals(); let commentData = await getComments(); //We're doing a general refresh, so no targetting. let journaTargetted = false; displayData(journalData, commentData, journaTargetted); }
JavaScript
async function displayTargetJournal(targetJournalId) { //get all data let journalData = await getJournals(); let commentData = await getComments(); let journalTargetted = true; //variables for our data to pass let journalToPass = []; let commentsToPass = []; //loop through our journals, get the one we want and save it as our data to pass journalData.forEach((jrnl) => { if(parseInt(jrnl.id) === parseInt(targetJournalId)) { journalToPass.push(jrnl); }; }); //loop through comments, get the one we want and save it as our data to pass commentData.forEach((cmt) => { if(parseInt(cmt.journalId) === parseInt(targetJournalId)) { commentsToPass.push(cmt); }; }); //Send them to display displayData(journalToPass,commentsToPass, journalTargetted); }
async function displayTargetJournal(targetJournalId) { //get all data let journalData = await getJournals(); let commentData = await getComments(); let journalTargetted = true; //variables for our data to pass let journalToPass = []; let commentsToPass = []; //loop through our journals, get the one we want and save it as our data to pass journalData.forEach((jrnl) => { if(parseInt(jrnl.id) === parseInt(targetJournalId)) { journalToPass.push(jrnl); }; }); //loop through comments, get the one we want and save it as our data to pass commentData.forEach((cmt) => { if(parseInt(cmt.journalId) === parseInt(targetJournalId)) { commentsToPass.push(cmt); }; }); //Send them to display displayData(journalToPass,commentsToPass, journalTargetted); }
JavaScript
function sumbitJournal() { //get text input into the box let contentInput = document.getElementById("contentInputBox").value; let giphyUrl = ""; if(contentInput.length > 349) { alert("Too many characters for new journal - max is 350.") } else if(contentInput === "" || !contentInput) { alert("Invalid input for new journal - is the input box empty?") } else { try{ giphyUrl = document.getElementById("jrnlGiphyImage").src; } catch (err) { console.log("giphy url blank - may be error: " +err) } //POST the journal fetch("https://nojudgies.herokuapp.com/newJournal", { method: "POST", headers: { 'Content-Type' : 'application/Json'}, body: JSON.stringify({ //details to send - id is irrelevant, our backend resolves. "id": 99999, "content": contentInput, "reactions" : [0,0,0], "giphy": giphyUrl }) }) .then(changePage(1)) //Throw an error if it didn't work. .catch ((error) => alert ("Couldn't post, reason: " +error)); } }
function sumbitJournal() { //get text input into the box let contentInput = document.getElementById("contentInputBox").value; let giphyUrl = ""; if(contentInput.length > 349) { alert("Too many characters for new journal - max is 350.") } else if(contentInput === "" || !contentInput) { alert("Invalid input for new journal - is the input box empty?") } else { try{ giphyUrl = document.getElementById("jrnlGiphyImage").src; } catch (err) { console.log("giphy url blank - may be error: " +err) } //POST the journal fetch("https://nojudgies.herokuapp.com/newJournal", { method: "POST", headers: { 'Content-Type' : 'application/Json'}, body: JSON.stringify({ //details to send - id is irrelevant, our backend resolves. "id": 99999, "content": contentInput, "reactions" : [0,0,0], "giphy": giphyUrl }) }) .then(changePage(1)) //Throw an error if it didn't work. .catch ((error) => alert ("Couldn't post, reason: " +error)); } }
JavaScript
static saveJournals() { //get the data we want to save const dataToSave = JSON.stringify(journalData); // use fs.writeFile, specify directory, what to save, and error handling. fs.writeFile('./data/journalJSONData.txt', dataToSave, err => { if (err) { console.log("Couldn't save journal data, reason: " + err); } else { console.log("Journal data saved successfully."); } }) }
static saveJournals() { //get the data we want to save const dataToSave = JSON.stringify(journalData); // use fs.writeFile, specify directory, what to save, and error handling. fs.writeFile('./data/journalJSONData.txt', dataToSave, err => { if (err) { console.log("Couldn't save journal data, reason: " + err); } else { console.log("Journal data saved successfully."); } }) }
JavaScript
static loadJournals() { //variable we'll use to store the loaded and parsed data let parsedData; //read data from file, location, format, error and data handling fs.readFile('./data/journalJSONData.txt', 'utf-8', (err, data) => { //if we got error rather than data - log it if(err) { console.log("Couldn't load journal data for reason: " +err); } // if we got the data back, parse it and assign it to journalData else { parsedData = JSON.parse(data); journalData = parsedData; } }) }
static loadJournals() { //variable we'll use to store the loaded and parsed data let parsedData; //read data from file, location, format, error and data handling fs.readFile('./data/journalJSONData.txt', 'utf-8', (err, data) => { //if we got error rather than data - log it if(err) { console.log("Couldn't load journal data for reason: " +err); } // if we got the data back, parse it and assign it to journalData else { parsedData = JSON.parse(data); journalData = parsedData; } }) }
JavaScript
static saveComments() { //get the data we want to save const dataToSave = JSON.stringify(commentData); //use fs.writeFile, specify location to save, what to save, and error handling. fs.writeFile('../data/commentJSONData.txt', dataToSave, err => { if (err) { console.log("Couldn't save comment data, reason: " + err); } else { console.log("Successfully saved comment data."); } }) }
static saveComments() { //get the data we want to save const dataToSave = JSON.stringify(commentData); //use fs.writeFile, specify location to save, what to save, and error handling. fs.writeFile('../data/commentJSONData.txt', dataToSave, err => { if (err) { console.log("Couldn't save comment data, reason: " + err); } else { console.log("Successfully saved comment data."); } }) }
JavaScript
static loadComments() { //variable we'll use to store the loaded and parsed data let parsedData; //read data from file, location, format, error and data handling fs.readFile('../data/commentJSONData.txt', 'utf-8', (err, data) => { //if we got error rather than data - log it if(err) { console.log("Couldn't load comment data for reason: " +err); } // if we got the data back, parse it and assign it to commentData else { parsedData = JSON.parse(data); commentData = parsedData; } }); }
static loadComments() { //variable we'll use to store the loaded and parsed data let parsedData; //read data from file, location, format, error and data handling fs.readFile('../data/commentJSONData.txt', 'utf-8', (err, data) => { //if we got error rather than data - log it if(err) { console.log("Couldn't load comment data for reason: " +err); } // if we got the data back, parse it and assign it to commentData else { parsedData = JSON.parse(data); commentData = parsedData; } }); }
JavaScript
function Emit(event) { return function(_target, propertyKey, descriptor) { var key = hyphenate(propertyKey) var original = descriptor.value descriptor.value = function emitter() { var _this = this var args = [] for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i] } var emit = function(returnValue) { var emitName = event || key if (returnValue === undefined) { if (args.length === 0) { _this.$emit(emitName) } else if (args.length === 1) { _this.$emit(emitName, args[0]) } else { _this.$emit.apply(_this, [emitName].concat(args)) } } else { if (args.length === 0) { _this.$emit(emitName, returnValue) } else if (args.length === 1) { _this.$emit(emitName, returnValue, args[0]) } else { _this.$emit.apply(_this, [emitName, returnValue].concat(args)) } } } var returnValue = original.apply(this, args) if (isPromise(returnValue)) { returnValue.then(emit) } else { emit(returnValue) } return returnValue } } }
function Emit(event) { return function(_target, propertyKey, descriptor) { var key = hyphenate(propertyKey) var original = descriptor.value descriptor.value = function emitter() { var _this = this var args = [] for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i] } var emit = function(returnValue) { var emitName = event || key if (returnValue === undefined) { if (args.length === 0) { _this.$emit(emitName) } else if (args.length === 1) { _this.$emit(emitName, args[0]) } else { _this.$emit.apply(_this, [emitName].concat(args)) } } else { if (args.length === 0) { _this.$emit(emitName, returnValue) } else if (args.length === 1) { _this.$emit(emitName, returnValue, args[0]) } else { _this.$emit.apply(_this, [emitName, returnValue].concat(args)) } } } var returnValue = original.apply(this, args) if (isPromise(returnValue)) { returnValue.then(emit) } else { emit(returnValue) } return returnValue } } }
JavaScript
function normalizeComponent( scriptExports, render, staticRenderFns, functionalTemplate, injectStyles, scopeId, moduleIdentifier /* server only */, shadowMode /* vue-cli only */ ) { // Vue.extend constructor export interop var options = typeof scriptExports === 'function' ? scriptExports.options : scriptExports // render functions if (render) { options.render = render options.staticRenderFns = staticRenderFns options._compiled = true } // functional template if (functionalTemplate) { options.functional = true } // scopedId if (scopeId) { options._scopeId = 'data-v-' + scopeId } var hook if (moduleIdentifier) { // server build hook = function(context) { // 2.3 injection context = context || // cached call (this.$vnode && this.$vnode.ssrContext) || // stateful (this.parent && this.parent.$vnode && this.parent.$vnode.ssrContext) // functional // 2.2 with runInNewContext: true if (!context && typeof __VUE_SSR_CONTEXT__ !== 'undefined') { context = __VUE_SSR_CONTEXT__ } // inject component styles if (injectStyles) { injectStyles.call(this, context) } // register component module identifier for async chunk inferrence if (context && context._registeredComponents) { context._registeredComponents.add(moduleIdentifier) } } // used by ssr in case component is cached and beforeCreate // never gets called options._ssrRegister = hook } else if (injectStyles) { hook = shadowMode ? function() { injectStyles.call( this, (options.functional ? this.parent : this).$root.$options.shadowRoot ) } : injectStyles } if (hook) { if (options.functional) { // for template-only hot-reload because in that case the render fn doesn't // go through the normalizer options._injectStyles = hook // register for functional component in vue file var originalRender = options.render options.render = function renderWithStyleInjection(h, context) { hook.call(context) return originalRender(h, context) } } else { // inject component registration as beforeCreate hook var existing = options.beforeCreate options.beforeCreate = existing ? [].concat(existing, hook) : [hook] } } return { exports: scriptExports, options: options } }
function normalizeComponent( scriptExports, render, staticRenderFns, functionalTemplate, injectStyles, scopeId, moduleIdentifier /* server only */, shadowMode /* vue-cli only */ ) { // Vue.extend constructor export interop var options = typeof scriptExports === 'function' ? scriptExports.options : scriptExports // render functions if (render) { options.render = render options.staticRenderFns = staticRenderFns options._compiled = true } // functional template if (functionalTemplate) { options.functional = true } // scopedId if (scopeId) { options._scopeId = 'data-v-' + scopeId } var hook if (moduleIdentifier) { // server build hook = function(context) { // 2.3 injection context = context || // cached call (this.$vnode && this.$vnode.ssrContext) || // stateful (this.parent && this.parent.$vnode && this.parent.$vnode.ssrContext) // functional // 2.2 with runInNewContext: true if (!context && typeof __VUE_SSR_CONTEXT__ !== 'undefined') { context = __VUE_SSR_CONTEXT__ } // inject component styles if (injectStyles) { injectStyles.call(this, context) } // register component module identifier for async chunk inferrence if (context && context._registeredComponents) { context._registeredComponents.add(moduleIdentifier) } } // used by ssr in case component is cached and beforeCreate // never gets called options._ssrRegister = hook } else if (injectStyles) { hook = shadowMode ? function() { injectStyles.call( this, (options.functional ? this.parent : this).$root.$options.shadowRoot ) } : injectStyles } if (hook) { if (options.functional) { // for template-only hot-reload because in that case the render fn doesn't // go through the normalizer options._injectStyles = hook // register for functional component in vue file var originalRender = options.render options.render = function renderWithStyleInjection(h, context) { hook.call(context) return originalRender(h, context) } } else { // inject component registration as beforeCreate hook var existing = options.beforeCreate options.beforeCreate = existing ? [].concat(existing, hook) : [hook] } } return { exports: scriptExports, options: options } }
JavaScript
postMessage (message) { if (this.webClient) { this.webClient.chat.postMessage(message).catch(e => { console.error(e) console.error(`Error sending message to channel ${message.channel} in workspace ${this.workspaceId}.\nThe message was:\n\n${message.text}`) }) } else { console.error(`Error sending message to channel ${message.channel} in workspace ${this.workspaceId}.\nThe message was:\n\n${message.text}`) } }
postMessage (message) { if (this.webClient) { this.webClient.chat.postMessage(message).catch(e => { console.error(e) console.error(`Error sending message to channel ${message.channel} in workspace ${this.workspaceId}.\nThe message was:\n\n${message.text}`) }) } else { console.error(`Error sending message to channel ${message.channel} in workspace ${this.workspaceId}.\nThe message was:\n\n${message.text}`) } }
JavaScript
postEphemeral (message) { if (this.webClient) { this.webClient.chat.postEphemeral(message).catch(e => { console.error(e) console.error(`Error sending ephemeral message to user ${message.user} in channel ${message.channel} in workspace ${this.workspaceId}.\nThe message was:\n\n${message.text}`) }) } else { console.error(`Error sending ephemeral message to user ${message.user} in channel ${message.channel} in workspace ${this.workspaceId}.\nThe message was:\n\n${message.text}`) } }
postEphemeral (message) { if (this.webClient) { this.webClient.chat.postEphemeral(message).catch(e => { console.error(e) console.error(`Error sending ephemeral message to user ${message.user} in channel ${message.channel} in workspace ${this.workspaceId}.\nThe message was:\n\n${message.text}`) }) } else { console.error(`Error sending ephemeral message to user ${message.user} in channel ${message.channel} in workspace ${this.workspaceId}.\nThe message was:\n\n${message.text}`) } }
JavaScript
sendMessage (channelId, text) { this.postMessage({ channel: channelId, text }) }
sendMessage (channelId, text) { this.postMessage({ channel: channelId, text }) }
JavaScript
sendProduct (channelId, product, gameTimeout) { const message = { channel: channelId, text: `Qual o preço deste magnífico produto?\nA ronda de palpites dura ${formatTime(gameTimeout)}.`, attachments: [{ title: product.name, image_url: `https:${product.imageUrl}` }] } this.postMessage(message) }
sendProduct (channelId, product, gameTimeout) { const message = { channel: channelId, text: `Qual o preço deste magnífico produto?\nA ronda de palpites dura ${formatTime(gameTimeout)}.`, attachments: [{ title: product.name, image_url: `https:${product.imageUrl}` }] } this.postMessage(message) }
JavaScript
sendEphemeral (channelId, userId, text) { this.postEphemeral({ channel: channelId, user: userId, text: text }) }
sendEphemeral (channelId, userId, text) { this.postEphemeral({ channel: channelId, user: userId, text: text }) }
JavaScript
notifyTimeLeft (channelId, timeLeft) { const text = `Faltam ${formatTime(timeLeft)} para o final da ronda de palpites!` this.sendMessage(channelId, text) }
notifyTimeLeft (channelId, timeLeft) { const text = `Faltam ${formatTime(timeLeft)} para o final da ronda de palpites!` this.sendMessage(channelId, text) }
JavaScript
static oauthAccess (code) { return new WebClient().oauth.access({ client_id: process.env.CLIENT_ID, client_secret: process.env.CLIENT_SECRET, code: code }).then((res) => { const botAccessToken = res.bot.bot_access_token const workspaceId = res.team_id // TODO: Save botAccessToken const webClient = new WebClient(botAccessToken) console.log('Created webclient for workspace ' + workspaceId) return { workspaceId, webClient } }) }
static oauthAccess (code) { return new WebClient().oauth.access({ client_id: process.env.CLIENT_ID, client_secret: process.env.CLIENT_SECRET, code: code }).then((res) => { const botAccessToken = res.bot.bot_access_token const workspaceId = res.team_id // TODO: Save botAccessToken const webClient = new WebClient(botAccessToken) console.log('Created webclient for workspace ' + workspaceId) return { workspaceId, webClient } }) }
JavaScript
startGame (channelId, onGameFinished) { if (this.games.hasOwnProperty(channelId)) { const game = this.games[channelId] if (game.getState() !== GameState.FINISHED) { return new Error('game_not_finished') } } const game = new Game(this, channelId, onGameFinished) this.games[channelId] = game return game.start() }
startGame (channelId, onGameFinished) { if (this.games.hasOwnProperty(channelId)) { const game = this.games[channelId] if (game.getState() !== GameState.FINISHED) { return new Error('game_not_finished') } } const game = new Game(this, channelId, onGameFinished) this.games[channelId] = game return game.start() }
JavaScript
function defineReactive(obj,key){ const dep = new Dep(); let val = obj[key]; console.log('dep.id' ,dep.id) // 遍历生成子元素的reactive observer let childOb = observe(val); Object.defineProperty(obj,key,{ enumerable:true, configurable:true, get:function(){ if (Dep.target){ dep.depend(); // 元素有watcher依赖的话,元素的同样会依赖 if (childOb){ childOb.dep.depend(); } } return val; }, set:function(newVal){ console.log(dep.id); val = newVal; childOb = observe(newVal); dep.notify(); } }) }
function defineReactive(obj,key){ const dep = new Dep(); let val = obj[key]; console.log('dep.id' ,dep.id) // 遍历生成子元素的reactive observer let childOb = observe(val); Object.defineProperty(obj,key,{ enumerable:true, configurable:true, get:function(){ if (Dep.target){ dep.depend(); // 元素有watcher依赖的话,元素的同样会依赖 if (childOb){ childOb.dep.depend(); } } return val; }, set:function(newVal){ console.log(dep.id); val = newVal; childOb = observe(newVal); dep.notify(); } }) }
JavaScript
function rmvClick(){ let li = this.parentNode.parentNode; let ul = li.parentNode; ul.removeChild(li); }
function rmvClick(){ let li = this.parentNode.parentNode; let ul = li.parentNode; ul.removeChild(li); }
JavaScript
function parseDataQueue(data){ var answers = 0, unattended = 0, incoming = 0; var c_hold = 0, holdtime = 0, c_talk = 0, talktime = 0; var call_in_service_level = 0; for (var d in data) { answers = answers + parseInt(data[d].Completed); unattended = unattended + parseInt(data[d].Abandoned); incoming = incoming + parseInt(data[d].Calls); $("[id='data-"+ d + "'] #queue_completed").html(parseInt(data[d].Completed)); $("[id='data-"+ d + "'] #queue_abandoned").html(parseInt(data[d].Abandoned)); $("[id='data-"+ d + "'] #queue_incoming").html(parseInt(data[d].Calls)); $("[id='data-"+ d + "'] #queue_users").html(len(data[d].members)); $(".header-"+ d + " #strategy").html(data[d].Strategy); if (SHOW_SERVICE_LEVEL === true) { $("[id='data-"+ d + "'] #queue_servicelevel").html(data[d].ServicelevelPerf + '%'); call_in_service_level += data[d].Completed * parseFloat(data[d].ServicelevelPerf) / 100; } if (data[d].Abandoned > 0) { $("[id='"+ d + "-percent_abandoned']") .html(parseInt(parseInt(data[d].Abandoned) * 100 / (parseInt(data[d].Abandoned) + parseInt(data[d].Completed) ))); } //Update graph updateGraph(d, data[d]); if (parseInt(data[d].TalkTime) > 0 ) { talktime = talktime + parseInt(data[d].TalkTime); c_talk++; } if (parseInt(data[d].Holdtime) > 0 ) { holdtime = holdtime + parseInt(data[d].Holdtime); c_hold++; } var agent_free = 0, agent_busy = 0, agent_unavailable = 0; for (agent in data[d].members) { var status_agent = parseInt(data[d].members[agent].Status); if (data[d].members[agent].Paused == true) { agent_busy++; } else if (C.status_agent.NOT_INUSE == status_agent) { agent_free++; } else if (status_agent.isUnavailableInAsterisk()) { agent_unavailable++; } else { agent_busy++; } } agents = agent_free + agent_busy + agent_unavailable; //bugfix NaN division by 0 if (agents == 0) { agents = 1; } $("[id='data-"+ d + "'] #queue_free") .html( "{agents} ({percent}% {status})" .format({agents: agent_free, percent: Math.round(agent_free * 100 / agents), status: STATUSES.free })); $("[id='data-"+ d + "'] #queue_busy") .html( "{agents} ({percent}% {status})" .format({agents: agent_busy, percent: Math.round(agent_busy * 100 / agents), status: STATUSES.busy })); $("[id='data-"+ d + "'] #queue_unavailable") .html( "{agents} ({percent}% {status})" .format({agents: agent_unavailable, percent: Math.round(agent_unavailable * 100 / agents), status: STATUSES.unavailable})); } $('#answered').html(answers); $('#abandoned').html(unattended); $('#incoming').html(incoming); if (c_hold > 0 ) { $('#av_wait').html(parseInt((holdtime / c_hold)).toString().toMMSS()); } if (c_talk > 0){ $('#av_time').html(parseInt((talktime / c_talk)).toString().toMMSS()); } if (SHOW_SERVICE_LEVEL === true) { if (answers == 0) { $('#servicelevel').html( "{percent}%".format({percent: 0.0})); } else { $('#servicelevel').html( "{percent}%".format({percent: Math.round(call_in_service_level * 100 / answers)})); } } }
function parseDataQueue(data){ var answers = 0, unattended = 0, incoming = 0; var c_hold = 0, holdtime = 0, c_talk = 0, talktime = 0; var call_in_service_level = 0; for (var d in data) { answers = answers + parseInt(data[d].Completed); unattended = unattended + parseInt(data[d].Abandoned); incoming = incoming + parseInt(data[d].Calls); $("[id='data-"+ d + "'] #queue_completed").html(parseInt(data[d].Completed)); $("[id='data-"+ d + "'] #queue_abandoned").html(parseInt(data[d].Abandoned)); $("[id='data-"+ d + "'] #queue_incoming").html(parseInt(data[d].Calls)); $("[id='data-"+ d + "'] #queue_users").html(len(data[d].members)); $(".header-"+ d + " #strategy").html(data[d].Strategy); if (SHOW_SERVICE_LEVEL === true) { $("[id='data-"+ d + "'] #queue_servicelevel").html(data[d].ServicelevelPerf + '%'); call_in_service_level += data[d].Completed * parseFloat(data[d].ServicelevelPerf) / 100; } if (data[d].Abandoned > 0) { $("[id='"+ d + "-percent_abandoned']") .html(parseInt(parseInt(data[d].Abandoned) * 100 / (parseInt(data[d].Abandoned) + parseInt(data[d].Completed) ))); } //Update graph updateGraph(d, data[d]); if (parseInt(data[d].TalkTime) > 0 ) { talktime = talktime + parseInt(data[d].TalkTime); c_talk++; } if (parseInt(data[d].Holdtime) > 0 ) { holdtime = holdtime + parseInt(data[d].Holdtime); c_hold++; } var agent_free = 0, agent_busy = 0, agent_unavailable = 0; for (agent in data[d].members) { var status_agent = parseInt(data[d].members[agent].Status); if (data[d].members[agent].Paused == true) { agent_busy++; } else if (C.status_agent.NOT_INUSE == status_agent) { agent_free++; } else if (status_agent.isUnavailableInAsterisk()) { agent_unavailable++; } else { agent_busy++; } } agents = agent_free + agent_busy + agent_unavailable; //bugfix NaN division by 0 if (agents == 0) { agents = 1; } $("[id='data-"+ d + "'] #queue_free") .html( "{agents} ({percent}% {status})" .format({agents: agent_free, percent: Math.round(agent_free * 100 / agents), status: STATUSES.free })); $("[id='data-"+ d + "'] #queue_busy") .html( "{agents} ({percent}% {status})" .format({agents: agent_busy, percent: Math.round(agent_busy * 100 / agents), status: STATUSES.busy })); $("[id='data-"+ d + "'] #queue_unavailable") .html( "{agents} ({percent}% {status})" .format({agents: agent_unavailable, percent: Math.round(agent_unavailable * 100 / agents), status: STATUSES.unavailable})); } $('#answered').html(answers); $('#abandoned').html(unattended); $('#incoming').html(incoming); if (c_hold > 0 ) { $('#av_wait').html(parseInt((holdtime / c_hold)).toString().toMMSS()); } if (c_talk > 0){ $('#av_time').html(parseInt((talktime / c_talk)).toString().toMMSS()); } if (SHOW_SERVICE_LEVEL === true) { if (answers == 0) { $('#servicelevel').html( "{percent}%".format({percent: 0.0})); } else { $('#servicelevel').html( "{percent}%".format({percent: Math.round(call_in_service_level * 100 / answers)})); } } }
JavaScript
function parseDataQueue(data){ var answers = 0, unattended = 0, incoming = 0; var c_hold = 0, holdtime = 0, c_talk = 0, talktime = 0; var call_in_service_level = 0; for (var d in data) { answers = answers + parseInt(data[d].Completed); unattended = unattended + parseInt(data[d].Abandoned); incoming = incoming + parseInt(data[d].Calls); $("[id='data-"+ d + "'] #queue_completed").html(parseInt(data[d].Completed)); $("[id='data-"+ d + "'] #queue_abandoned").html(parseInt(data[d].Abandoned)); $("[id='data-"+ d + "'] #queue_incoming").html(parseInt(data[d].Calls)); $("[id='data-"+ d + "'] #queue_users").html(len(data[d].members)); $(".header-"+ d + " #strategy").html(data[d].Strategy); if (SHOW_SERVICE_LEVEL === true) { $("[id='data-"+ d + "'] #queue_servicelevel").html(data[d].ServicelevelPerf + '%'); call_in_service_level += data[d].Completed * parseFloat(data[d].ServicelevelPerf) / 100; } if (data[d].Abandoned > 0) { $("[id='"+ d + "-percent_abandoned']") .html(parseInt(parseInt(data[d].Abandoned) * 100 / (parseInt(data[d].Abandoned) + parseInt(data[d].Completed) ))); } if (parseInt(data[d].TalkTime) > 0 ) { talktime = talktime + parseInt(data[d].TalkTime); c_talk++; } if (parseInt(data[d].Holdtime) > 0 ) { holdtime = holdtime + parseInt(data[d].Holdtime); c_hold++; } var agent_free = 0, agent_busy = 0, agent_unavailable = 0; for (agent in data[d].members) { var status_agent = parseInt(data[d].members[agent].Status); if (data[d].members[agent].Paused == true) { agent_busy++; } else if (C.status_agent.NOT_INUSE == status_agent) { agent_free++; } else if (status_agent.isUnavailableInAsterisk()) { agent_unavailable++; } else { agent_busy++; } } agents = agent_free + agent_busy + agent_unavailable; //bugfix NaN division by 0 if (agents == 0) { agents = 1; } $("[id='data-"+ d + "'] #queue_free") .html( "{agents} ({percent}% {status})" .format({agents: agent_free, percent: Math.round(agent_free * 100 / agents), status: STATUSES.free })); $("[id='data-"+ d + "'] #queue_busy") .html( "{agents} ({percent}% {status})" .format({agents: agent_busy, percent: Math.round(agent_busy * 100 / agents), status: STATUSES.busy })); $("[id='data-"+ d + "'] #queue_unavailable") .html( "{agents} ({percent}% {status})" .format({agents: agent_unavailable, percent: Math.round(agent_unavailable * 100 / agents), status: STATUSES.unavailable})); } $('#answered').html(answers); $('#abandoned').html(unattended); $('#incoming').html(incoming); if (c_hold > 0 ) { $('#av_wait').html(parseInt((holdtime / c_hold)).toString().toMMSS()); } if (c_talk > 0){ $('#av_time').html(parseInt((talktime / c_talk)).toString().toMMSS()); } if (SHOW_SERVICE_LEVEL === true) { if (answers == 0) { $('#servicelevel').html( "{percent}%".format({percent: 0.0})); } else { $('#servicelevel').html( "{percent}%".format({percent: Math.round(call_in_service_level * 100 / answers)})); } } }
function parseDataQueue(data){ var answers = 0, unattended = 0, incoming = 0; var c_hold = 0, holdtime = 0, c_talk = 0, talktime = 0; var call_in_service_level = 0; for (var d in data) { answers = answers + parseInt(data[d].Completed); unattended = unattended + parseInt(data[d].Abandoned); incoming = incoming + parseInt(data[d].Calls); $("[id='data-"+ d + "'] #queue_completed").html(parseInt(data[d].Completed)); $("[id='data-"+ d + "'] #queue_abandoned").html(parseInt(data[d].Abandoned)); $("[id='data-"+ d + "'] #queue_incoming").html(parseInt(data[d].Calls)); $("[id='data-"+ d + "'] #queue_users").html(len(data[d].members)); $(".header-"+ d + " #strategy").html(data[d].Strategy); if (SHOW_SERVICE_LEVEL === true) { $("[id='data-"+ d + "'] #queue_servicelevel").html(data[d].ServicelevelPerf + '%'); call_in_service_level += data[d].Completed * parseFloat(data[d].ServicelevelPerf) / 100; } if (data[d].Abandoned > 0) { $("[id='"+ d + "-percent_abandoned']") .html(parseInt(parseInt(data[d].Abandoned) * 100 / (parseInt(data[d].Abandoned) + parseInt(data[d].Completed) ))); } if (parseInt(data[d].TalkTime) > 0 ) { talktime = talktime + parseInt(data[d].TalkTime); c_talk++; } if (parseInt(data[d].Holdtime) > 0 ) { holdtime = holdtime + parseInt(data[d].Holdtime); c_hold++; } var agent_free = 0, agent_busy = 0, agent_unavailable = 0; for (agent in data[d].members) { var status_agent = parseInt(data[d].members[agent].Status); if (data[d].members[agent].Paused == true) { agent_busy++; } else if (C.status_agent.NOT_INUSE == status_agent) { agent_free++; } else if (status_agent.isUnavailableInAsterisk()) { agent_unavailable++; } else { agent_busy++; } } agents = agent_free + agent_busy + agent_unavailable; //bugfix NaN division by 0 if (agents == 0) { agents = 1; } $("[id='data-"+ d + "'] #queue_free") .html( "{agents} ({percent}% {status})" .format({agents: agent_free, percent: Math.round(agent_free * 100 / agents), status: STATUSES.free })); $("[id='data-"+ d + "'] #queue_busy") .html( "{agents} ({percent}% {status})" .format({agents: agent_busy, percent: Math.round(agent_busy * 100 / agents), status: STATUSES.busy })); $("[id='data-"+ d + "'] #queue_unavailable") .html( "{agents} ({percent}% {status})" .format({agents: agent_unavailable, percent: Math.round(agent_unavailable * 100 / agents), status: STATUSES.unavailable})); } $('#answered').html(answers); $('#abandoned').html(unattended); $('#incoming').html(incoming); if (c_hold > 0 ) { $('#av_wait').html(parseInt((holdtime / c_hold)).toString().toMMSS()); } if (c_talk > 0){ $('#av_time').html(parseInt((talktime / c_talk)).toString().toMMSS()); } if (SHOW_SERVICE_LEVEL === true) { if (answers == 0) { $('#servicelevel').html( "{percent}%".format({percent: 0.0})); } else { $('#servicelevel').html( "{percent}%".format({percent: Math.round(call_in_service_level * 100 / answers)})); } } }
JavaScript
function _safeSetDataURI(fSuccess, fFail) { var self = this; self._fFail = fFail; self._fSuccess = fSuccess; // Check it just once if (self._bSupportDataURI === null) { var el = document.createElement("img"); var fOnError = function() { self._bSupportDataURI = false; if (self._fFail) { self._fFail.call(self); } }; var fOnSuccess = function() { self._bSupportDataURI = true; if (self._fSuccess) { self._fSuccess.call(self); } }; el.onabort = fOnError; el.onerror = fOnError; el.onload = fOnSuccess; el.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAPAAAADwCAYAAAA+VemSAAATSklEQVR4Xu2dwY4kZxGEf7Oyr1wQ55WM/AY8BD76xJN6z7wDkqW1sNYHXoADQlotoBqml9np7qn4/qyozpqOvToqKzIy4s+/e4bhqzHGf0b+VRT4CjzcSWvCG7SIoJ30QMS7gJchRsTaNEgQOmlNeNcUuv50Jz1cPVrrJsB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EatAAAAAElFTkSuQmCC"; // the Image contains '' qrcode data. return; } else if (self._bSupportDataURI === true && self._fSuccess) { self._fSuccess.call(self); } else if (self._bSupportDataURI === false && self._fFail) { self._fFail.call(self); } }
function _safeSetDataURI(fSuccess, fFail) { var self = this; self._fFail = fFail; self._fSuccess = fSuccess; // Check it just once if (self._bSupportDataURI === null) { var el = document.createElement("img"); var fOnError = function() { self._bSupportDataURI = false; if (self._fFail) { self._fFail.call(self); } }; var fOnSuccess = function() { self._bSupportDataURI = true; if (self._fSuccess) { self._fSuccess.call(self); } }; el.onabort = fOnError; el.onerror = fOnError; el.onload = fOnSuccess; el.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAPAAAADwCAYAAAA+VemSAAATSklEQVR4Xu2dwY4kZxGEf7Oyr1wQ55WM/AY8BD76xJN6z7wDkqW1sNYHXoADQlotoBqml9np7qn4/qyozpqOvToqKzIy4s+/e4bhqzHGf0b+VRT4CjzcSWvCG7SIoJ30QMS7gJchRsTaNEgQOmlNeNcUuv50Jz1cPVrrJsB1eUkQOhmW8K6rdLlCJz1cPVrrJsB1eUkQOhmW8K6rlABbNEyA67KSICTAX+rdSY+6E25QIQGui54Az2uYAM9r9/BkAlwU8FFDtUonw5KDR+2P4jrpQbm3wCfA9TGQIHQyLOFdVymfgS0aJsB1WUkQEuB8Bq477kmFBLguZwI8r2GnA22+ixs+mQDXxU+A5zVMgOe1y5dYRe1Oj99DgGnQVE1o3Y1G9nrKzGxgdThHVYmaiujhrO3U28Wb1j395MTZ661rI00S4PNxIQHNP0Yih4PTeC5NaN0E+NmUE+AEWAk+DZp68NC6CXACvOpXairVrMuLnbVXGysAXLxp3QQ4AV61MTVVAnwuqaoJ1ToBToAT4FUF9vtYkQAXtc5n4KKA+RLr4nGQDTxxSj4+gg61BDgBVqyGTAUONVo3V+hcoVf9Sk2lbpt8iVU/LBPgBDgBXlWgHjT1UKOHZQK8Y4BnhjPhLemRb8YYHyWk90c9VBM1CGJrn2GUB62v8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TUVMQnqmPEhtN1bVxN2jyiMBdjtix/rUVMQkpA3Kg9R2Y1VN3D2qPBJgtyN2rE9NRUxC2qA8SG03VtXE3aPKIwF2O2LH+tRUxCSkDcqD1HZjVU3cPao8EmC3I3asT01FTELaoDxIbTdW1cTdo8ojAXY7Ysf61FTEJKQNyoPUdmNVTdw9qjwSYLcjdqxPTUVMQtqgPEhtN1bVxN2jyiMBdjtix/rUVMQkpA3Kg9R2Y1VN3D2qPO4qwO7hH60+MQnpjZp7wbu4EN4LVuVBe3TxmAkw5ULwqn4PQrtFJMSPiJXFhs3RuXw/xngH33E0ONWky2yozjLvBJhKe46XxYavomZNgPvOBo5evsFkA1NlL+AT4A1EFEvQQ63LbMT2PsNk3tnAVNq+p3w2cN/ZUJclwFSxAl4WG76DbpsEOAGGFgucfONK1UqAzxWjmnQ5XOnsZd65QlNp+57y2cB9Z0NdlgBTxQp4WWz4DrptEuAEGFos8Fyh9/UAPdS6HK5UJZl3rtBU2r6nfDZw39lQlyXAVLECXhYbvoNumwT4DgP8X0BrNPEYrEatAAAAAElFTkSuQmCC"; // the Image contains '' qrcode data. return; } else if (self._bSupportDataURI === true && self._fSuccess) { self._fSuccess.call(self); } else if (self._bSupportDataURI === false && self._fFail) { self._fFail.call(self); } }
JavaScript
function renameFiles(names) { const name = names.slice(); const newarr = []; let count = 1; for (let i = 0; i < name.length; i++) { if (!newarr.includes(name[i])) { newarr.push(name[i]); name.splice(i, 1); i -= 1; } else if (newarr.includes(name[i])) { if (newarr.includes(`${name[i]}(${count})`)) { name[i] = `${name[i]}(${count + 1})`; newarr.push(name[i]); } else { name[i] = `${name[i]}(${count})`; newarr.push(name[i]); } } count = 1; } return newarr; }
function renameFiles(names) { const name = names.slice(); const newarr = []; let count = 1; for (let i = 0; i < name.length; i++) { if (!newarr.includes(name[i])) { newarr.push(name[i]); name.splice(i, 1); i -= 1; } else if (newarr.includes(name[i])) { if (newarr.includes(`${name[i]}(${count})`)) { name[i] = `${name[i]}(${count + 1})`; newarr.push(name[i]); } else { name[i] = `${name[i]}(${count})`; newarr.push(name[i]); } } count = 1; } return newarr; }
JavaScript
function minesweeper(matrix) { const matrixs = matrix.slice(); const result = []; for (let i = 0; i < matrixs.length; i++) { result.push(matrixs[i].slice()); } let count = 0; let YoN = false; for (let i = 0; i < matrixs.length; i++) { for (let u = 0; u < matrixs[i].length; u++) { if (matrixs[i][u + 1] === true) { count++; YoN = true; } if (matrixs[i][u - 1] === true) { count++; YoN = true; } if (matrixs[i - 1] !== undefined) { if (matrixs[i - 1][u] === true) { count++; YoN = true; } } if (matrixs[i + 1] !== undefined) { if (matrixs[i + 1][u] === true) { count++; YoN = true; } } if (count >= 2) { result[i][u] = count; } else { result[i][u] = 1; } count = 0; } } if (YoN === false) { for (let i = 0; i < matrixs.length; i++) { for (let u = 0; u < matrixs[i].length; u++) { result[i][u] = 0; } } } return result; }
function minesweeper(matrix) { const matrixs = matrix.slice(); const result = []; for (let i = 0; i < matrixs.length; i++) { result.push(matrixs[i].slice()); } let count = 0; let YoN = false; for (let i = 0; i < matrixs.length; i++) { for (let u = 0; u < matrixs[i].length; u++) { if (matrixs[i][u + 1] === true) { count++; YoN = true; } if (matrixs[i][u - 1] === true) { count++; YoN = true; } if (matrixs[i - 1] !== undefined) { if (matrixs[i - 1][u] === true) { count++; YoN = true; } } if (matrixs[i + 1] !== undefined) { if (matrixs[i + 1][u] === true) { count++; YoN = true; } } if (count >= 2) { result[i][u] = count; } else { result[i][u] = 1; } count = 0; } } if (YoN === false) { for (let i = 0; i < matrixs.length; i++) { for (let u = 0; u < matrixs[i].length; u++) { result[i][u] = 0; } } } return result; }
JavaScript
static updateRound(state, attacker) { if (attacker.combatData.killed) { // entity was removed from the game but update event was still in flight, ignore it return false; } if (!attacker.isInCombat()) { if (!attacker.isNpc) { attacker.removePrompt('combat'); } return false; } let lastRoundStarted = attacker.combatData.roundStarted; attacker.combatData.roundStarted = Date.now(); // cancel if the attacker's combat lag hasn't expired yet if (attacker.combatData.lag > 0) { const elapsed = Date.now() - lastRoundStarted; attacker.combatData.lag -= elapsed; return false; } // currently just grabs the first combatant from their list but could easily be modified to // implement a threat table and grab the attacker with the highest threat let target = null; try { target = Combat.chooseCombatant(attacker); } catch (e) { attacker.removeFromCombat(); attacker.combatData = {}; throw e; } // no targets left, remove attacker from combat if (!target) { attacker.removeFromCombat(); // reset combat data to remove any lag attacker.combatData = {}; return false; } if (target.combatData.killed) { // entity was removed from the game but update event was still in flight, ignore it return false; } /** * Trigger the autostance for the attacker first */ let attackerAutoStance = attacker.getMeta('autostance') || 'none' ; let attackerStance = attacker.getMeta('currentStance') || 'none' ; if( attackerStance === 'none' && attackerAutoStance !== 'none' ) { state.CommandManager.get('stance').execute(attackerAutoStance, attacker); } /** * Trigger the autostance for the defender second */ let targetAutoStance = target.getMeta('autostance') || 'none' ; let targetStance = target.getMeta('currentStance') || 'none' ; if( targetStance === 'none' && targetAutoStance !== 'none' ) { state.CommandManager.get('stance').execute(targetAutoStance, target); } let attacksPerRound = 1; /** * Allow some mobs to swing more than once per round in order to * be able to easily make "bosses" hit significantly harder without * outright one-shotting the player. */ if(attacker.isNPC && attacker.getMetadata('attacksPerRound')){ attacksPerRound = attacker.getMetadata('attacksPerRound'); } /** * For players, we have a lot that we have to check... So let's * check it. */ if( !attacker.isNpc) { attacksPerRound = ( attacker.class === 'vampire' ? (Math.floor(attacker.level/100)+3) : 3); // Add any addtional clandisc related attacks that the player gets attacksPerRound += this.getClanDiscExtraAttacks(attacker); } // Add any additional bonuses that the attacker gets from the stance attacksPerRound += this.getStanceExtraAttacks(attacker); for ( let i = 0; i < attacksPerRound; i++) { Combat.makeAttack(attacker, target); } return true; }
static updateRound(state, attacker) { if (attacker.combatData.killed) { // entity was removed from the game but update event was still in flight, ignore it return false; } if (!attacker.isInCombat()) { if (!attacker.isNpc) { attacker.removePrompt('combat'); } return false; } let lastRoundStarted = attacker.combatData.roundStarted; attacker.combatData.roundStarted = Date.now(); // cancel if the attacker's combat lag hasn't expired yet if (attacker.combatData.lag > 0) { const elapsed = Date.now() - lastRoundStarted; attacker.combatData.lag -= elapsed; return false; } // currently just grabs the first combatant from their list but could easily be modified to // implement a threat table and grab the attacker with the highest threat let target = null; try { target = Combat.chooseCombatant(attacker); } catch (e) { attacker.removeFromCombat(); attacker.combatData = {}; throw e; } // no targets left, remove attacker from combat if (!target) { attacker.removeFromCombat(); // reset combat data to remove any lag attacker.combatData = {}; return false; } if (target.combatData.killed) { // entity was removed from the game but update event was still in flight, ignore it return false; } /** * Trigger the autostance for the attacker first */ let attackerAutoStance = attacker.getMeta('autostance') || 'none' ; let attackerStance = attacker.getMeta('currentStance') || 'none' ; if( attackerStance === 'none' && attackerAutoStance !== 'none' ) { state.CommandManager.get('stance').execute(attackerAutoStance, attacker); } /** * Trigger the autostance for the defender second */ let targetAutoStance = target.getMeta('autostance') || 'none' ; let targetStance = target.getMeta('currentStance') || 'none' ; if( targetStance === 'none' && targetAutoStance !== 'none' ) { state.CommandManager.get('stance').execute(targetAutoStance, target); } let attacksPerRound = 1; /** * Allow some mobs to swing more than once per round in order to * be able to easily make "bosses" hit significantly harder without * outright one-shotting the player. */ if(attacker.isNPC && attacker.getMetadata('attacksPerRound')){ attacksPerRound = attacker.getMetadata('attacksPerRound'); } /** * For players, we have a lot that we have to check... So let's * check it. */ if( !attacker.isNpc) { attacksPerRound = ( attacker.class === 'vampire' ? (Math.floor(attacker.level/100)+3) : 3); // Add any addtional clandisc related attacks that the player gets attacksPerRound += this.getClanDiscExtraAttacks(attacker); } // Add any additional bonuses that the attacker gets from the stance attacksPerRound += this.getStanceExtraAttacks(attacker); for ( let i = 0; i < attacksPerRound; i++) { Combat.makeAttack(attacker, target); } return true; }
JavaScript
static makeAttack(attacker, target) { let amount = this.calculateWeaponDamage(attacker); let critical = false; if (attacker.hasAttribute('critical_strike')) { const critChance = Math.max(attacker.getMaxAttribute('critical_strike') || 0, 0); critical = Random.probability(critChance); if (critical) { amount = Math.ceil(amount * 1.5); } } if(!attacker.isNpc && attacker.getMeta('currentStance') !== 'none') { Combat.improveStance(attacker); Combat.improveWeapon(attacker); let stanceDamage = Combat.calculateStanceDamage(attacker, attacker, amount); amount = Math.ceil(amount + stanceDamage); } const dodgeChance = (target.hasAttribute('dodge') ? target.getAttribute('dodge') : 5); const parryChance = (target.hasAttribute('parry') ? target.getAttribute('parry') : 5); const missChance = (attacker.hasAttribute('hit_chance') ? 10 - Math.floor(attacker.getAttribute('hit_chance')) : 10); let dodge = Random.probability(dodgeChance); let parry = Random.probability(parryChance); let miss = Random.probability(missChance); // Factor in the bonus for the level let levelBonus = attacker.getMeta('class') == 'vampire' ? attacker.level/attacker.getMeta('generation') : attacker.level/13; amount = Math.floor(amount+levelBonus); // You can only dodge or parry an attack that was going to hit if(miss) { B.sayAt(attacker, `Your attack misses ${target.name}`); B.sayAt(target, `${attacker.name} misses their attack.`); return B.sayAtExcept(attacker.room, `${attacker.name} misses their attack on ${target.name}.`, [attacker, target]); } else if( dodge ) { B.sayAt(attacker, `Your attack was dodged by ${target.name}`); B.sayAt(target, `${attacker.name}'s attack was successfully dodged.`); return B.sayAtExcept(attacker.room, `${target.name} skillfully dodges ${attacker.name}'s attack.`, [attacker, target]); } else if (parry) { B.sayAt(attacker, `Your attack was parried by ${target.name}`); B.sayAt(target, `${attacker.name}'s attack was successfully parried.`); return B.sayAtExcept(attacker.room, `${target.name} skillfully parried ${attacker.name}'s attack.`, [attacker, target]); } else { const weapon = attacker.equipment.get('wield'); let newDamage = this.calculateClandiscDamage(attacker, target, amount); amount += newDamage; const damage = new Damage('health', amount, attacker, weapon || attacker, { critical }); damage.commit(target); } // currently lag is really simple, the character's weapon speed = lag attacker.combatData.lag = this.getWeaponSpeed(attacker) * 1000; }
static makeAttack(attacker, target) { let amount = this.calculateWeaponDamage(attacker); let critical = false; if (attacker.hasAttribute('critical_strike')) { const critChance = Math.max(attacker.getMaxAttribute('critical_strike') || 0, 0); critical = Random.probability(critChance); if (critical) { amount = Math.ceil(amount * 1.5); } } if(!attacker.isNpc && attacker.getMeta('currentStance') !== 'none') { Combat.improveStance(attacker); Combat.improveWeapon(attacker); let stanceDamage = Combat.calculateStanceDamage(attacker, attacker, amount); amount = Math.ceil(amount + stanceDamage); } const dodgeChance = (target.hasAttribute('dodge') ? target.getAttribute('dodge') : 5); const parryChance = (target.hasAttribute('parry') ? target.getAttribute('parry') : 5); const missChance = (attacker.hasAttribute('hit_chance') ? 10 - Math.floor(attacker.getAttribute('hit_chance')) : 10); let dodge = Random.probability(dodgeChance); let parry = Random.probability(parryChance); let miss = Random.probability(missChance); // Factor in the bonus for the level let levelBonus = attacker.getMeta('class') == 'vampire' ? attacker.level/attacker.getMeta('generation') : attacker.level/13; amount = Math.floor(amount+levelBonus); // You can only dodge or parry an attack that was going to hit if(miss) { B.sayAt(attacker, `Your attack misses ${target.name}`); B.sayAt(target, `${attacker.name} misses their attack.`); return B.sayAtExcept(attacker.room, `${attacker.name} misses their attack on ${target.name}.`, [attacker, target]); } else if( dodge ) { B.sayAt(attacker, `Your attack was dodged by ${target.name}`); B.sayAt(target, `${attacker.name}'s attack was successfully dodged.`); return B.sayAtExcept(attacker.room, `${target.name} skillfully dodges ${attacker.name}'s attack.`, [attacker, target]); } else if (parry) { B.sayAt(attacker, `Your attack was parried by ${target.name}`); B.sayAt(target, `${attacker.name}'s attack was successfully parried.`); return B.sayAtExcept(attacker.room, `${target.name} skillfully parried ${attacker.name}'s attack.`, [attacker, target]); } else { const weapon = attacker.equipment.get('wield'); let newDamage = this.calculateClandiscDamage(attacker, target, amount); amount += newDamage; const damage = new Damage('health', amount, attacker, weapon || attacker, { critical }); damage.commit(target); } // currently lag is really simple, the character's weapon speed = lag attacker.combatData.lag = this.getWeaponSpeed(attacker) * 1000; }
JavaScript
static handleDeath(state, deadEntity, killer) { // TODO: Add in the concept of morting if(!deadEntity.isNpc && deadEntity.getMeta('pvp_enabled') == true) { B.sayAt(deadEntity, `You are mortally wounded and spraying blood everywhere!`); return B.sayAtExcept(deadEntity.room, `${deadEntity.name} is mortally wounded.`, [deadEntity]); } if (deadEntity.combatData.killed) { return; } deadEntity.combatData.killed = true; deadEntity.removeFromCombat(); if (killer) { deadEntity.combatData.killedBy = killer; killer.emit('deathblow', deadEntity); } deadEntity.emit('killed', killer); if (deadEntity.isNpc) { state.MobManager.removeMob(deadEntity); } }
static handleDeath(state, deadEntity, killer) { // TODO: Add in the concept of morting if(!deadEntity.isNpc && deadEntity.getMeta('pvp_enabled') == true) { B.sayAt(deadEntity, `You are mortally wounded and spraying blood everywhere!`); return B.sayAtExcept(deadEntity.room, `${deadEntity.name} is mortally wounded.`, [deadEntity]); } if (deadEntity.combatData.killed) { return; } deadEntity.combatData.killed = true; deadEntity.removeFromCombat(); if (killer) { deadEntity.combatData.killedBy = killer; killer.emit('deathblow', deadEntity); } deadEntity.emit('killed', killer); if (deadEntity.isNpc) { state.MobManager.removeMob(deadEntity); } }
JavaScript
static calculateWeaponDamage(attacker, average = false) { let weaponDamage = this.getWeaponDamage(attacker); let amount = 0; if (average) { amount = (weaponDamage.min + weaponDamage.max) / 2; } else { amount = Random.inRange(weaponDamage.min, weaponDamage.max); } // Give the attacker 1 damage for every 5 attack power they have amount += attacker.hasAttribute('attack_power') ? Math.floor(attacker.getAttribute('attack_power')/5) : 0; return this.normalizeWeaponDamage(attacker, amount); }
static calculateWeaponDamage(attacker, average = false) { let weaponDamage = this.getWeaponDamage(attacker); let amount = 0; if (average) { amount = (weaponDamage.min + weaponDamage.max) / 2; } else { amount = Random.inRange(weaponDamage.min, weaponDamage.max); } // Give the attacker 1 damage for every 5 attack power they have amount += attacker.hasAttribute('attack_power') ? Math.floor(attacker.getAttribute('attack_power')/5) : 0; return this.normalizeWeaponDamage(attacker, amount); }
JavaScript
static calculateClandiscDamage(attacker, victim, baseDamage) { let attackerGeneration = attacker.getMeta('generation') || 13; let victimGeneration = victim.getMeta('generation') || 13; let bonusDamage = 0; // If the attacker has potence, they get a damage boost if( attacker.getMeta('class') === 'vampire' ) { let potenceRank = attacker.getMeta('clandiscs.potence') || 0; if (potenceRank > 0) { // 10% more damage based on their generation bonusDamage += baseDamage * ((14 - attackerGeneration) * 0.1); } } if( victim.getMeta('class') === 'vampire' ) { let fortitudeRank = victim.getaMeta('clandiscs.fortitude') || 0; if( fortitudeRank > 0 ) { bonusDamage -= bonusDamage * ((14 - attackerGeneration) * 0.1); } } return bonusDamage; }
static calculateClandiscDamage(attacker, victim, baseDamage) { let attackerGeneration = attacker.getMeta('generation') || 13; let victimGeneration = victim.getMeta('generation') || 13; let bonusDamage = 0; // If the attacker has potence, they get a damage boost if( attacker.getMeta('class') === 'vampire' ) { let potenceRank = attacker.getMeta('clandiscs.potence') || 0; if (potenceRank > 0) { // 10% more damage based on their generation bonusDamage += baseDamage * ((14 - attackerGeneration) * 0.1); } } if( victim.getMeta('class') === 'vampire' ) { let fortitudeRank = victim.getaMeta('clandiscs.fortitude') || 0; if( fortitudeRank > 0 ) { bonusDamage -= bonusDamage * ((14 - attackerGeneration) * 0.1); } } return bonusDamage; }
JavaScript
function main() { MongoClient // Hier wordt de URL gemaakt die MongoDB nodig heeft (met de gevoelige data uit de .env) .connect(`mongodb+srv://${MONGO_USER}:${MONGO_PASS}@${MONGO_URI}/${MONGO_DB}?retryWrites=true&w=majority`, { useNewUrlParser: true, useUnifiedTopology: true, }) // Then is een promise, als de connectie er is wordt alles eronder uitgevoerd .then((connection) => { const app = express() // projecttech is de naam van mijn MongoDB database en personen is de naam van mijn collection const db = connection.db('projecttech') const personenCollection = db.collection('personen') // Hier wordt mijn templating engine aangeroepen + bodyparser app.set('view engine', 'ejs'); app.set('views', path.join(__dirname, 'views')); app.use(bodyParser.urlencoded({extended: true})) app.use(express.static('static')) app.get('/', (req, res) => { res.render('pages/home.ejs', {profiel:persoon}) }) // Hier wordt alles uit de database gehaald zodat het op de /liked pagina weergegeven kan worden. app.get('/liked', (req, res) => { db.collection('personen').find().toArray() .then(results => { res.render('pages/liked.ejs', { personen: results, profiel: persoon, }) }) }) // als er op de submit button word geklikt worden de geselecteerde personen naar de database gestuurd. app.post('/liked', (req, res) => { let likes; // wanneer req.body.personen een string is wordt het in een array gezet if (typeof req.body.personen === 'string') { likes = [req.body.personen] } // wanneer het wel een array is. else { likes = req.body.personen } // van de array met gelikete personen wordt een array met promises gemaakt const promises = likes.map( like => { // hier wordt alles in de database gezet. return personenCollection.insertOne({persoon:like}) }) // wanneer alle inserts klaar zijn wordt de gebruiker geredirect naar de liked pagina Promise.all(promises) .then(results => { res.redirect('/liked') }) .catch(error => console.error(error)) }) app.delete('/delete', (req, res) => { // Maakt van de query string een officeel mongodb object id, anders verwijdert mongodb de persoon niet db.collection('personen').deleteOne({'_id':new ObjectID(req.query.id)}) // wanneer het gelukt is om de data te verwijderen wordt er gelukt gesend die gebruikt wordt in de js functie .then((result) => { console.log(result) res.send('Gelukt') }) }) // wanneer er een error is krijg je een error 404 app.use(function (req, res, next) { res.status(404).send('Error 404') }); // Wanneer de server is opgestart krijg je localhost:8000 te zien in de terminal app.listen(port, () => { console.log(`Server opgestart at http://localhost:${port}`)}) }); }
function main() { MongoClient // Hier wordt de URL gemaakt die MongoDB nodig heeft (met de gevoelige data uit de .env) .connect(`mongodb+srv://${MONGO_USER}:${MONGO_PASS}@${MONGO_URI}/${MONGO_DB}?retryWrites=true&w=majority`, { useNewUrlParser: true, useUnifiedTopology: true, }) // Then is een promise, als de connectie er is wordt alles eronder uitgevoerd .then((connection) => { const app = express() // projecttech is de naam van mijn MongoDB database en personen is de naam van mijn collection const db = connection.db('projecttech') const personenCollection = db.collection('personen') // Hier wordt mijn templating engine aangeroepen + bodyparser app.set('view engine', 'ejs'); app.set('views', path.join(__dirname, 'views')); app.use(bodyParser.urlencoded({extended: true})) app.use(express.static('static')) app.get('/', (req, res) => { res.render('pages/home.ejs', {profiel:persoon}) }) // Hier wordt alles uit de database gehaald zodat het op de /liked pagina weergegeven kan worden. app.get('/liked', (req, res) => { db.collection('personen').find().toArray() .then(results => { res.render('pages/liked.ejs', { personen: results, profiel: persoon, }) }) }) // als er op de submit button word geklikt worden de geselecteerde personen naar de database gestuurd. app.post('/liked', (req, res) => { let likes; // wanneer req.body.personen een string is wordt het in een array gezet if (typeof req.body.personen === 'string') { likes = [req.body.personen] } // wanneer het wel een array is. else { likes = req.body.personen } // van de array met gelikete personen wordt een array met promises gemaakt const promises = likes.map( like => { // hier wordt alles in de database gezet. return personenCollection.insertOne({persoon:like}) }) // wanneer alle inserts klaar zijn wordt de gebruiker geredirect naar de liked pagina Promise.all(promises) .then(results => { res.redirect('/liked') }) .catch(error => console.error(error)) }) app.delete('/delete', (req, res) => { // Maakt van de query string een officeel mongodb object id, anders verwijdert mongodb de persoon niet db.collection('personen').deleteOne({'_id':new ObjectID(req.query.id)}) // wanneer het gelukt is om de data te verwijderen wordt er gelukt gesend die gebruikt wordt in de js functie .then((result) => { console.log(result) res.send('Gelukt') }) }) // wanneer er een error is krijg je een error 404 app.use(function (req, res, next) { res.status(404).send('Error 404') }); // Wanneer de server is opgestart krijg je localhost:8000 te zien in de terminal app.listen(port, () => { console.log(`Server opgestart at http://localhost:${port}`)}) }); }
JavaScript
parseTime(offset) { let localTime = new Date(); const options = { weekday: 'short', year: 'numeric', month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' }; let utc = localTime.getTime() + (localTime.getTimezoneOffset() * 60000); let dataTime = new Date(utc + (3600000 * offset)); return dataTime.toLocaleString('en-EN', options); }
parseTime(offset) { let localTime = new Date(); const options = { weekday: 'short', year: 'numeric', month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' }; let utc = localTime.getTime() + (localTime.getTimezoneOffset() * 60000); let dataTime = new Date(utc + (3600000 * offset)); return dataTime.toLocaleString('en-EN', options); }
JavaScript
today(data, imgUrl, { eltern = output, inhalt = '' } = {}) { const today = dom.create({ eltern, klassen: ['today'] }); // current day dom.create({ typ: 'p', inhalt: dom.parseTime(data[0].location.timezone), eltern: today, klassen: ['date'] }); // bookmark dom.create({ typ: 'i', attr: { 'aria-hidden': 'true', 'id': 'bookmark' }, eltern: today, klassen: ['fa', 'fa-heart-o', 'bookmark'] }); // current location dom.create({ typ: 'h2', attr: { 'id': 'currLocation' }, inhalt: data[0].location.name, eltern: today }); // current weather icon dom.create({ inhalt: `<i class="wi ${dom.parseSkycode(data[0].current.skycode)}"></i>`, eltern: today, klassen: ['icon'] }); // current weather description dom.create({ typ: 'h3', inhalt: data[0].current.skytext, eltern: today }); // current temperature dom.create({ typ: 'p', inhalt: `${data[0].current.temperature}°C`, eltern: today, klassen: ['currTemp'] }); // feellike temperature dom.create({ typ: 'p', inhalt: `Feels like ${data[0].current.feelslike} °C`, eltern: today, klassen: ['feelslike'] }); // changeBg dom.changeBg(data[0].current.temperature); return today; }
today(data, imgUrl, { eltern = output, inhalt = '' } = {}) { const today = dom.create({ eltern, klassen: ['today'] }); // current day dom.create({ typ: 'p', inhalt: dom.parseTime(data[0].location.timezone), eltern: today, klassen: ['date'] }); // bookmark dom.create({ typ: 'i', attr: { 'aria-hidden': 'true', 'id': 'bookmark' }, eltern: today, klassen: ['fa', 'fa-heart-o', 'bookmark'] }); // current location dom.create({ typ: 'h2', attr: { 'id': 'currLocation' }, inhalt: data[0].location.name, eltern: today }); // current weather icon dom.create({ inhalt: `<i class="wi ${dom.parseSkycode(data[0].current.skycode)}"></i>`, eltern: today, klassen: ['icon'] }); // current weather description dom.create({ typ: 'h3', inhalt: data[0].current.skytext, eltern: today }); // current temperature dom.create({ typ: 'p', inhalt: `${data[0].current.temperature}°C`, eltern: today, klassen: ['currTemp'] }); // feellike temperature dom.create({ typ: 'p', inhalt: `Feels like ${data[0].current.feelslike} °C`, eltern: today, klassen: ['feelslike'] }); // changeBg dom.changeBg(data[0].current.temperature); return today; }
JavaScript
function Sort (numElements) { this.dataStore = []; this.shellSort = shellSort; this.setData = setData; this.setGaps = setGaps; this.toString = toString; this.gaps = [5,3,1]; this.numElements = numElements; for (var i = 0; i < this.numElements; i++) { this.dataStore[i] = i; } }
function Sort (numElements) { this.dataStore = []; this.shellSort = shellSort; this.setData = setData; this.setGaps = setGaps; this.toString = toString; this.gaps = [5,3,1]; this.numElements = numElements; for (var i = 0; i < this.numElements; i++) { this.dataStore[i] = i; } }
JavaScript
function Queue() { var items = []; // Method enqueue() adds an element at the end of the queue this.enqueue = function(element) { items.push(element); }; // Method dequeue() removes element from the front of the queue and returns it this.dequeue = function() { return items.shift(); }; // Method peek() return element at the front from the queue(does not edit queue, only returns element) this.peek = function() { return items[0]; }; // Method isEmpty() returns true if queue is empty, otherwise false this.isEmpty = function() { return items.length === 0; }; // Method size() returns size of the queue this.size = function() { return items.length; }; // Method print() for printing elements at the queue this.print = function() { console.log(items.toString()); }; }
function Queue() { var items = []; // Method enqueue() adds an element at the end of the queue this.enqueue = function(element) { items.push(element); }; // Method dequeue() removes element from the front of the queue and returns it this.dequeue = function() { return items.shift(); }; // Method peek() return element at the front from the queue(does not edit queue, only returns element) this.peek = function() { return items[0]; }; // Method isEmpty() returns true if queue is empty, otherwise false this.isEmpty = function() { return items.length === 0; }; // Method size() returns size of the queue this.size = function() { return items.length; }; // Method print() for printing elements at the queue this.print = function() { console.log(items.toString()); }; }
JavaScript
function BST() { let Node = function(key) { this.key = key; this.left = null; this.right = null; }; // Helper for inserting new node let insertNode = function(node, newNode) { if (newNode.key < node.key) { if (node.left === null) { node.left = newNode; } else { insertNode(node.left, newNode); } } else { if (node.right === null) { node.right = newNode; } else { insertNode(node.right, newNode); } } }; let root = null; // Method insert() adds a new key/node in the tree this.insert = function(key) { let newNode = new Node(key); if (root === null) { root = newNode; } else { insertNode(root, newNode); } }; }
function BST() { let Node = function(key) { this.key = key; this.left = null; this.right = null; }; // Helper for inserting new node let insertNode = function(node, newNode) { if (newNode.key < node.key) { if (node.left === null) { node.left = newNode; } else { insertNode(node.left, newNode); } } else { if (node.right === null) { node.right = newNode; } else { insertNode(node.right, newNode); } } }; let root = null; // Method insert() adds a new key/node in the tree this.insert = function(key) { let newNode = new Node(key); if (root === null) { root = newNode; } else { insertNode(root, newNode); } }; }
JavaScript
function quickSort(arr) { if (arr.length == 0) { return []; } var lesser = []; var greater = []; var pivot = arr[0]; for (var i = 1; i < arr.length; i++) { if (arr[i] < pivot) { lesser.push(arr[i]); } else { greater.push(arr[i]); } } return quickSort(lesser).concat(pivot, quickSort(greater)); }
function quickSort(arr) { if (arr.length == 0) { return []; } var lesser = []; var greater = []; var pivot = arr[0]; for (var i = 1; i < arr.length; i++) { if (arr[i] < pivot) { lesser.push(arr[i]); } else { greater.push(arr[i]); } } return quickSort(lesser).concat(pivot, quickSort(greater)); }
JavaScript
function count(arr, data) { var count = 0; var position = binSearch(arr, data); if (position > -1) { count++; for (var i = position-1; i > 0; i--) { if (arr[i] == data) { count++; } else { break; } } for (var i = position+1; i < arr.length; i++) { if (arr[i] == data) { count++; } else { break; } } } return count; // return count variable }
function count(arr, data) { var count = 0; var position = binSearch(arr, data); if (position > -1) { count++; for (var i = position-1; i > 0; i--) { if (arr[i] == data) { count++; } else { break; } } for (var i = position+1; i < arr.length; i++) { if (arr[i] == data) { count++; } else { break; } } } return count; // return count variable }
JavaScript
function Sort (numElements) { this.dataStore = []; this.insertionSort = insertionSort; this.toString = toString; this.setData = setData; this.numElements = numElements; for (var i = 0; i <= this.numElements; i++) { this.dataStore[i] = i; } }
function Sort (numElements) { this.dataStore = []; this.insertionSort = insertionSort; this.toString = toString; this.setData = setData; this.numElements = numElements; for (var i = 0; i <= this.numElements; i++) { this.dataStore[i] = i; } }
JavaScript
function insertionSort () { var temp; var inner; for (var i = 1; i < this.dataStore.length-1; i++) { temp = this.dataStore[i]; inner = i; while (inner > 0 && (this.dataStore[inner-1] >= temp)) { this.dataStore[inner] = this.dataStore[inner-1]; inner--; } this.dataStore[inner] = temp; } }
function insertionSort () { var temp; var inner; for (var i = 1; i < this.dataStore.length-1; i++) { temp = this.dataStore[i]; inner = i; while (inner > 0 && (this.dataStore[inner-1] >= temp)) { this.dataStore[inner] = this.dataStore[inner-1]; inner--; } this.dataStore[inner] = temp; } }
JavaScript
function swap (arr, index1, index2) { var tmp = arr[index1]; arr[index1] = arr[index2]; arr[index2] = tmp; }
function swap (arr, index1, index2) { var tmp = arr[index1]; arr[index1] = arr[index2]; arr[index2] = tmp; }
JavaScript
function bubbleSort () { var numElements = this.dataStore.length; for (var i = numElements; i >= 2; i--) { for (var j = 0; j <= i-1 ; j++) { if (this.dataStore[j] > this.dataStore[j+1]) { swap(this.dataStore, j, j+1); } } //console.log(this.toString()); //To visualize sorting process of the algorithm } }
function bubbleSort () { var numElements = this.dataStore.length; for (var i = numElements; i >= 2; i--) { for (var j = 0; j <= i-1 ; j++) { if (this.dataStore[j] > this.dataStore[j+1]) { swap(this.dataStore, j, j+1); } } //console.log(this.toString()); //To visualize sorting process of the algorithm } }
JavaScript
function seqSearch(arr, data) { //sequential algorithm made better //Loop through the array to see each element for (var i = 0; i < arr.length; i++) { //Compare item with data to search for in the array and be in parity of 80% - 20% if (arr[i] === data && i > (arr.length * 0.2)) { //Implement sequential search algorithm with self-organizing data technique swap(arr, i, 0); return true; } else if (arr[i] == data) { return true; } } //Exit if data to search for is not found in the array return false; }
function seqSearch(arr, data) { //sequential algorithm made better //Loop through the array to see each element for (var i = 0; i < arr.length; i++) { //Compare item with data to search for in the array and be in parity of 80% - 20% if (arr[i] === data && i > (arr.length * 0.2)) { //Implement sequential search algorithm with self-organizing data technique swap(arr, i, 0); return true; } else if (arr[i] == data) { return true; } } //Exit if data to search for is not found in the array return false; }
JavaScript
function swap(arr, index, index1) { temp = arr[index]; arr[index] = arr[index1]; arr[index1] = temp; }
function swap(arr, index, index1) { temp = arr[index]; arr[index] = arr[index1]; arr[index1] = temp; }
JavaScript
function dispArray(arr) { //loop through the array to see each item or access each item for (var i = 0; i < arr.length; i++) { //print the item preceding it with space console.log(arr[i] + ""); //print new line if element when divided by 10 returns remainder of 9 if (i % 10 == 9) { console.log('\n'); } } //print new line if element when diveded by 10 returns remainder not equal to 0 if (i % 10 != 0) { console.log('\n'); } }
function dispArray(arr) { //loop through the array to see each item or access each item for (var i = 0; i < arr.length; i++) { //print the item preceding it with space console.log(arr[i] + ""); //print new line if element when divided by 10 returns remainder of 9 if (i % 10 == 9) { console.log('\n'); } } //print new line if element when diveded by 10 returns remainder not equal to 0 if (i % 10 != 0) { console.log('\n'); } }
JavaScript
function Linkedlist() { let Node = function(element, next) { this.element = element; this.next = null; }; let head = null; let length = 0; // Method append() for adding element to the linked list // append() : when list isEmpty(), we are adding its first element, when // the list is not empty, we are appending elements to it. this.append = function(element) { let node = new Node(element); let current; if (head === null) { // if the list is empty head = node; } else { // if the list is not empty current = head; while (current.next) { // loop the list until it finds last item current = current.next; } current.next = node; // assign next to node and make the link/connection } length++; // update size of list }; // Method remove() for removing element from the linked list // Two scenarios for removing element from the linked list: // first one is removing the first element, and the second one // is removing any element but the first one. // method1 for removing an element from a specified position, and // the second one is base on the element value. this.removeAt = function(position) { if (position > -1 && position < length) { // check for out-of-bounds values let current = head; let previous; let index = 0; // removing first item if (position === 0) { head = current.next; } else { while (index++ < position) { previous = current; current = current.next; } // link previous with current's next: skip it to remove previous.next = current.next; } length--; return current.element; } else { return null; } }; // Method insert() for inserting element at specified position this.insert = function(position, element) { if (position > -1 && position < length) { let node = new Node(element); let previous; let current = head; let index = 0; if (position === 0) { node.next = current; head = node; } else { while (index++ < position) { previous = current; current = current.next; } node.next = current; previous.next = node; } length++; return true; } else { return false; } }; // Method toString() for displaying linkedlist this.toString = function() { let current = head; let string = ""; while (current) { string += current.element + (current.next ? "\n" : ""); current = current.next; } return string; }; // Method indexOf() to return index of an element this.indexOf = function(element) { let current = head; let index = -1; while (current) { if (element === current.element) { return index; } index++; current = current.next; } return -1; }; // Method remove() to remove element from the linkedlist // with the help of removeAt() and indexOf() this.remove = function(element) { let index = this.indexOf(element); return this.removeAt(index); }; // Method isEmpty() for checking if linkedlist is empty this.isEmpty = function() { return length === 0; }; // Method size() for returning size of our linkedlist this.size = function() { return length; }; // Method getHead() for returning head of our linkedlist this.getHead = function() { return head; }; }
function Linkedlist() { let Node = function(element, next) { this.element = element; this.next = null; }; let head = null; let length = 0; // Method append() for adding element to the linked list // append() : when list isEmpty(), we are adding its first element, when // the list is not empty, we are appending elements to it. this.append = function(element) { let node = new Node(element); let current; if (head === null) { // if the list is empty head = node; } else { // if the list is not empty current = head; while (current.next) { // loop the list until it finds last item current = current.next; } current.next = node; // assign next to node and make the link/connection } length++; // update size of list }; // Method remove() for removing element from the linked list // Two scenarios for removing element from the linked list: // first one is removing the first element, and the second one // is removing any element but the first one. // method1 for removing an element from a specified position, and // the second one is base on the element value. this.removeAt = function(position) { if (position > -1 && position < length) { // check for out-of-bounds values let current = head; let previous; let index = 0; // removing first item if (position === 0) { head = current.next; } else { while (index++ < position) { previous = current; current = current.next; } // link previous with current's next: skip it to remove previous.next = current.next; } length--; return current.element; } else { return null; } }; // Method insert() for inserting element at specified position this.insert = function(position, element) { if (position > -1 && position < length) { let node = new Node(element); let previous; let current = head; let index = 0; if (position === 0) { node.next = current; head = node; } else { while (index++ < position) { previous = current; current = current.next; } node.next = current; previous.next = node; } length++; return true; } else { return false; } }; // Method toString() for displaying linkedlist this.toString = function() { let current = head; let string = ""; while (current) { string += current.element + (current.next ? "\n" : ""); current = current.next; } return string; }; // Method indexOf() to return index of an element this.indexOf = function(element) { let current = head; let index = -1; while (current) { if (element === current.element) { return index; } index++; current = current.next; } return -1; }; // Method remove() to remove element from the linkedlist // with the help of removeAt() and indexOf() this.remove = function(element) { let index = this.indexOf(element); return this.removeAt(index); }; // Method isEmpty() for checking if linkedlist is empty this.isEmpty = function() { return length === 0; }; // Method size() for returning size of our linkedlist this.size = function() { return length; }; // Method getHead() for returning head of our linkedlist this.getHead = function() { return head; }; }
JavaScript
function deepCopy(arr1, arr2) { for (var i = 0; i < arr1.length; i++) { arr2[i] = arr1[i]; } }
function deepCopy(arr1, arr2) { for (var i = 0; i < arr1.length; i++) { arr2[i] = arr1[i]; } }
JavaScript
function searchArray(arr, itemToSearch) { var position = arr.indexOf(itemToSearch); if (position > 0) { console.log('Found ' + itemToSearch + ' at position ' + position); } else { console.log(itemToSearch + ' not found in the array'); } }
function searchArray(arr, itemToSearch) { var position = arr.indexOf(itemToSearch); if (position > 0) { console.log('Found ' + itemToSearch + ' at position ' + position); } else { console.log(itemToSearch + ' not found in the array'); } }
JavaScript
function Sort (numElements) { this.dataStore = []; this.numElements = numElements; this.setData = setData; this.selectionSort = selectionSort; this.toString = toString; this.swap = swap; for (var i = 0; i < this.numElements; i++) { this.dataStore[i] = i; } }
function Sort (numElements) { this.dataStore = []; this.numElements = numElements; this.setData = setData; this.selectionSort = selectionSort; this.toString = toString; this.swap = swap; for (var i = 0; i < this.numElements; i++) { this.dataStore[i] = i; } }
JavaScript
function selectionSort () { var min; for (var i = 0; i <= this.dataStore.length-2; i++) { min = i; for (var j = i+1; j <= this.dataStore.length-1; j++) { if (this.dataStore[j] < this.dataStore[min]) { min = j; } swap(this.dataStore, i, min); //console.log(this.toString()); } } }
function selectionSort () { var min; for (var i = 0; i <= this.dataStore.length-2; i++) { min = i; for (var j = i+1; j <= this.dataStore.length-1; j++) { if (this.dataStore[j] < this.dataStore[min]) { min = j; } swap(this.dataStore, i, min); //console.log(this.toString()); } } }
JavaScript
function Stack() { var items = []; // Method for adding new elements to the top of the stack this.push = function(item) { items.push(item); }; // Method for removing an item from the stack(last item added is the first item to be removed) this.pop = function() { return items.pop(); }; // Method for returning the top element in the stack this.peek = function() { return items[items.length - 1]; }; // Method for showing if the stack is empty this.isEmpty = function() { return items.length === 0; }; // Method for returning the size of our stack this.size = function() { return items.length; }; // Method to clear our stack/Another method would be the pop() until out stack is empty() this.clear = function() { items = []; }; // Method for printing elements of the stack to inspect elements this.print = function() { console.log(items.toString()); }; }
function Stack() { var items = []; // Method for adding new elements to the top of the stack this.push = function(item) { items.push(item); }; // Method for removing an item from the stack(last item added is the first item to be removed) this.pop = function() { return items.pop(); }; // Method for returning the top element in the stack this.peek = function() { return items[items.length - 1]; }; // Method for showing if the stack is empty this.isEmpty = function() { return items.length === 0; }; // Method for returning the size of our stack this.size = function() { return items.length; }; // Method to clear our stack/Another method would be the pop() until out stack is empty() this.clear = function() { items = []; }; // Method for printing elements of the stack to inspect elements this.print = function() { console.log(items.toString()); }; }
JavaScript
function toBase2(number) { var stack = new Stack(); var remainder; var binaryString = ""; while (number > 0) { remainder = Math.floor(number % 2); stack.push(remainder); number = Math.floor(number / 2); }; while (!stack.isEmpty()) { binaryString += stack.pop().toString(); }; return binaryString; }
function toBase2(number) { var stack = new Stack(); var remainder; var binaryString = ""; while (number > 0) { remainder = Math.floor(number % 2); stack.push(remainder); number = Math.floor(number / 2); }; while (!stack.isEmpty()) { binaryString += stack.pop().toString(); }; return binaryString; }
JavaScript
function Dictionary() { var items = {}; // Method for checking if key exists in the Dictionary // and return true if true, otherwise false this.has = function(key) { return key in items; }; // Method adds new item to the Dictionary or update existing key this.set = function(key, value) { items[key] = value; }; // Method for removing value from the dictionary using a key this.delete = function(key) { if(this.has(key)) { delete items[key]; return true; } return false; }; // Method for searching a specific value by the key this.get = function(key) { return this.has(key) ? items[key] : undefined; }; // Method for retrieving an array of all the values // instance present in the Dictionary this.values = function() { var values = []; for (var k in items) { if (this.has(k)) { values.push(items[k]); } } return values; }; // Method to return all the keys in our Dictionary class this.keys = function() { return Object.keys(items); }; // Method to return the Dictionary items this.getItems = function() { return items; }; // Method to return number or length // of Dictionary items this.size = function() { return Object.keys(items).length; }; // Method to clear dictionary this.clear = function() { items = {}; }; }
function Dictionary() { var items = {}; // Method for checking if key exists in the Dictionary // and return true if true, otherwise false this.has = function(key) { return key in items; }; // Method adds new item to the Dictionary or update existing key this.set = function(key, value) { items[key] = value; }; // Method for removing value from the dictionary using a key this.delete = function(key) { if(this.has(key)) { delete items[key]; return true; } return false; }; // Method for searching a specific value by the key this.get = function(key) { return this.has(key) ? items[key] : undefined; }; // Method for retrieving an array of all the values // instance present in the Dictionary this.values = function() { var values = []; for (var k in items) { if (this.has(k)) { values.push(items[k]); } } return values; }; // Method to return all the keys in our Dictionary class this.keys = function() { return Object.keys(items); }; // Method to return the Dictionary items this.getItems = function() { return items; }; // Method to return number or length // of Dictionary items this.size = function() { return Object.keys(items).length; }; // Method to clear dictionary this.clear = function() { items = {}; }; }
JavaScript
function transformDataForFirestore (data) { const collections = data delete collections.stats const collectionsById = {} Object.keys(collections).forEach((collectionKey) => { collectionsById[collectionKey] = {} const collection = collections[collectionKey] collection.forEach((record) => { collectionsById[collectionKey][record.id] = record delete collectionsById[collectionKey][record.id].id }) }) return collectionsById }
function transformDataForFirestore (data) { const collections = data delete collections.stats const collectionsById = {} Object.keys(collections).forEach((collectionKey) => { collectionsById[collectionKey] = {} const collection = collections[collectionKey] collection.forEach((record) => { collectionsById[collectionKey][record.id] = record delete collectionsById[collectionKey][record.id].id }) }) return collectionsById }
JavaScript
function initializePage() { console.log("Javascript connected!"); $('h3').click(function(event){ console.log('click'); event.preventDefault(); var newName = anagrammedName($(this).text()); $(this).text(newName); }); }
function initializePage() { console.log("Javascript connected!"); $('h3').click(function(event){ console.log('click'); event.preventDefault(); var newName = anagrammedName($(this).text()); $(this).text(newName); }); }
JavaScript
function onRobotConnection(connected) { var state = 'ROBOT STATUS: ' + (connected ? 'connected' : 'disconnected'); console.log(state); ui.robotState.textContent = state; if (connected) { // On connect hide the connect popup // ui.robotState.classList.addClass('green-status'); document.body.classList.toggle('login', false); } else { // On disconnect show the connect popup document.body.classList.toggle('login', true); // ui.robotState.classList.addClass('red-status'); // Add Enter key handler address.onkeydown = ev => { if (ev.key === 'Enter') connect.click(); }; // Enable the input and the button address.disabled = connect.disabled = false; connect.textContent = 'Connect'; // Add the default address and select xxxx address.value = 'roborio-1661-frc.local'; address.focus(); // address.setSelectionRange(8, 12); // On click try to connect and disable the input and the button connect.onclick = () => { ipc.send('connect', address.value); address.disabled = connect.disabled = true; connect.textContent = 'Connecting...'; }; } }
function onRobotConnection(connected) { var state = 'ROBOT STATUS: ' + (connected ? 'connected' : 'disconnected'); console.log(state); ui.robotState.textContent = state; if (connected) { // On connect hide the connect popup // ui.robotState.classList.addClass('green-status'); document.body.classList.toggle('login', false); } else { // On disconnect show the connect popup document.body.classList.toggle('login', true); // ui.robotState.classList.addClass('red-status'); // Add Enter key handler address.onkeydown = ev => { if (ev.key === 'Enter') connect.click(); }; // Enable the input and the button address.disabled = connect.disabled = false; connect.textContent = 'Connect'; // Add the default address and select xxxx address.value = 'roborio-1661-frc.local'; address.focus(); // address.setSelectionRange(8, 12); // On click try to connect and disable the input and the button connect.onclick = () => { ipc.send('connect', address.value); address.disabled = connect.disabled = true; connect.textContent = 'Connecting...'; }; } }
JavaScript
includeInBundle () { let addedNewNodes = !this.included; this.included = true; this.eachChild( childNode => { if ( childNode.includeInBundle() ) { addedNewNodes = true; } } ); return addedNewNodes; }
includeInBundle () { let addedNewNodes = !this.included; this.included = true; this.eachChild( childNode => { if ( childNode.includeInBundle() ) { addedNewNodes = true; } } ); return addedNewNodes; }
JavaScript
shouldBeIncluded () { return this.included || this.hasEffects( ExecutionPathOptions.create() ) || this.hasIncludedChild(); }
shouldBeIncluded () { return this.included || this.hasEffects( ExecutionPathOptions.create() ) || this.hasIncludedChild(); }
JavaScript
function initializeCounters(){ currentTick = 1; currentBeat = 1; currentSubBeat = 1; currentBar = 1; return true; }
function initializeCounters(){ currentTick = 1; currentBeat = 1; currentSubBeat = 1; currentBar = 1; return true; }
JavaScript
function formatTimestamp(duration){ // quick and dirty patch : formating fails when duration is lower than 3 ms if(duration<3) return '00:00:00.00'; var milliseconds = parseInt((duration%1000)/10); var seconds = parseInt((duration/1000)%60); var minutes = parseInt((duration/(1000*60))%60); var hours = parseInt((duration/(1000*60*60))%24); hours = (hours < 10) ? "0" + hours : hours; minutes = (minutes < 10) ? "0" + minutes : minutes; seconds = (seconds < 10) ? "0" + seconds : seconds; milliseconds = (milliseconds < 10) ? "0" + milliseconds : milliseconds; return hours + ":" + minutes + ":" + seconds + "." + milliseconds; }
function formatTimestamp(duration){ // quick and dirty patch : formating fails when duration is lower than 3 ms if(duration<3) return '00:00:00.00'; var milliseconds = parseInt((duration%1000)/10); var seconds = parseInt((duration/1000)%60); var minutes = parseInt((duration/(1000*60))%60); var hours = parseInt((duration/(1000*60*60))%24); hours = (hours < 10) ? "0" + hours : hours; minutes = (minutes < 10) ? "0" + minutes : minutes; seconds = (seconds < 10) ? "0" + seconds : seconds; milliseconds = (milliseconds < 10) ? "0" + milliseconds : milliseconds; return hours + ":" + minutes + ":" + seconds + "." + milliseconds; }
JavaScript
function nextTick(){ currentTick++; currentSubBeat++; // update musical counters (currentBeat, currentBar) let subBeatsPerBeat = BEAT_SUBDIVISION[beatSubdivisionMode][beatResolutionFactor]; if (currentSubBeat > subBeatsPerBeat ){ // if end of beat reached... currentSubBeat = 1; currentBeat++; let beatsPerBar = (beatSubdivisionMode === SUBDIVISION_BINARY) ? signatureNominator : signatureNominator / 3; if(currentBeat > beatsPerBar){ // if complete bar beats reached... currentBeat = 1; currentBar++; } } CALLBACK(); return true; }
function nextTick(){ currentTick++; currentSubBeat++; // update musical counters (currentBeat, currentBar) let subBeatsPerBeat = BEAT_SUBDIVISION[beatSubdivisionMode][beatResolutionFactor]; if (currentSubBeat > subBeatsPerBeat ){ // if end of beat reached... currentSubBeat = 1; currentBeat++; let beatsPerBar = (beatSubdivisionMode === SUBDIVISION_BINARY) ? signatureNominator : signatureNominator / 3; if(currentBeat > beatsPerBar){ // if complete bar beats reached... currentBeat = 1; currentBar++; } } CALLBACK(); return true; }
JavaScript
function addRandomGreeting() { const greetings = ['My favorite sports team is the Angels!','General Kenobi...you are a bold one', 'I enjoy watching Star Wars', 'I have a fear of spiders. I just cant deal with them','One of my favorite flavors is peanut butter!', 'I love all types of fruits but apples are my favorite']; // Pick a random greeting. const greeting = greetings[Math.floor(Math.random() * greetings.length)]; // Add it to the page. const greetingContainer = document.getElementById('greeting-container'); greetingContainer.innerText = greeting; }
function addRandomGreeting() { const greetings = ['My favorite sports team is the Angels!','General Kenobi...you are a bold one', 'I enjoy watching Star Wars', 'I have a fear of spiders. I just cant deal with them','One of my favorite flavors is peanut butter!', 'I love all types of fruits but apples are my favorite']; // Pick a random greeting. const greeting = greetings[Math.floor(Math.random() * greetings.length)]; // Add it to the page. const greetingContainer = document.getElementById('greeting-container'); greetingContainer.innerText = greeting; }
JavaScript
function loadMessages() { fetch('/list-messages').then(response => response.json()).then((messages) => { const messageListElement = document.getElementById('message-list'); messages.forEach((message) => { messageListElement.appendChild(createMessageElement(message)); }) }); }
function loadMessages() { fetch('/list-messages').then(response => response.json()).then((messages) => { const messageListElement = document.getElementById('message-list'); messages.forEach((message) => { messageListElement.appendChild(createMessageElement(message)); }) }); }
JavaScript
function createMessageElement(message) { const messageElement = document.createElement('li'); messageElement.className = 'task'; const titleElement = document.createElement('span'); titleElement.innerText = message; messageElement.appendChild(titleElement); return messageElement; }
function createMessageElement(message) { const messageElement = document.createElement('li'); messageElement.className = 'task'; const titleElement = document.createElement('span'); titleElement.innerText = message; messageElement.appendChild(titleElement); return messageElement; }
JavaScript
function init() { // Get the specific canvas element from the HTML document canvas = document.getElementById('canvas-draft'); // If the browser supports the canvas tag, get the 2d drawing context for this canvas if (canvas.getContext) ctx = canvas.getContext('2d'); // Check that we have a valid context to draw on/with before adding event handlers if (ctx) { // React to mouse events on the canvas, and mouseup on the entire document /*canvas.addEventListener('mousedown', sketchpad_mouseDown, false); canvas.addEventListener('mousemove', sketchpad_mouseMove, false); window.addEventListener('mouseup', sketchpad_mouseUp, false); */ // React to touch events on the canvas canvas.addEventListener('touchstart', sketchpad_touchStart, false); canvas.addEventListener('touchend', sketchpad_touchEnd, false); canvas.addEventListener('touchmove', sketchpad_touchMove, false); } }
function init() { // Get the specific canvas element from the HTML document canvas = document.getElementById('canvas-draft'); // If the browser supports the canvas tag, get the 2d drawing context for this canvas if (canvas.getContext) ctx = canvas.getContext('2d'); // Check that we have a valid context to draw on/with before adding event handlers if (ctx) { // React to mouse events on the canvas, and mouseup on the entire document /*canvas.addEventListener('mousedown', sketchpad_mouseDown, false); canvas.addEventListener('mousemove', sketchpad_mouseMove, false); window.addEventListener('mouseup', sketchpad_mouseUp, false); */ // React to touch events on the canvas canvas.addEventListener('touchstart', sketchpad_touchStart, false); canvas.addEventListener('touchend', sketchpad_touchEnd, false); canvas.addEventListener('touchmove', sketchpad_touchMove, false); } }
JavaScript
function drawLine(ctx,x,y,size) { // If lastX is not set, set lastX and lastY to the current position if (lastX==-1) { lastX=x; lastY=y; } // Let's use black by setting RGB values to 0, and 255 alpha (completely opaque) r=0; g=0; b=0; a=255; // Select a fill style ctx.strokeStyle = "rgba("+r+","+g+","+b+","+(a/255)+")"; // Set the line "cap" style to round, so lines at different angles can join into each other ctx.lineCap = "round"; //ctx.lineJoin = "round"; // Draw a filled line ctx.beginPath(); // First, move to the old (previous) position ctx.moveTo(lastX,lastY); // Now draw a line to the current touch/pointer position ctx.lineTo(x,y); // Set the line thickness and draw the line ctx.lineWidth = size; ctx.stroke(); ctx.closePath(); // Update the last position to reference the current position lastX=x; lastY=y; }
function drawLine(ctx,x,y,size) { // If lastX is not set, set lastX and lastY to the current position if (lastX==-1) { lastX=x; lastY=y; } // Let's use black by setting RGB values to 0, and 255 alpha (completely opaque) r=0; g=0; b=0; a=255; // Select a fill style ctx.strokeStyle = "rgba("+r+","+g+","+b+","+(a/255)+")"; // Set the line "cap" style to round, so lines at different angles can join into each other ctx.lineCap = "round"; //ctx.lineJoin = "round"; // Draw a filled line ctx.beginPath(); // First, move to the old (previous) position ctx.moveTo(lastX,lastY); // Now draw a line to the current touch/pointer position ctx.lineTo(x,y); // Set the line thickness and draw the line ctx.lineWidth = size; ctx.stroke(); ctx.closePath(); // Update the last position to reference the current position lastX=x; lastY=y; }
JavaScript
function filterResults(report, msgKey, options) { var newResults = {}; var totalErrors = 0; var totalWarnings = 0; var totalFixableErrors = 0; var totalFixableWarnings = 0; newResults.results = report.results.map(function (result) { var filteredMessages = result.messages.filter(function (msg) { if (options.present) { return msg[msgKey]; } if (options.compareVal) { return msg[msgKey] === options.compareVal; } return false; }); if (filteredMessages) { var _getCounts = getCounts(filteredMessages), errorCount = _getCounts.errorCount, warningCount = _getCounts.warningCount, fixableErrorCount = _getCounts.fixableErrorCount, fixableWarningCount = _getCounts.fixableWarningCount; totalErrors += errorCount; totalWarnings += warningCount; totalFixableErrors += fixableErrorCount; totalFixableWarnings += fixableWarningCount; // fixableErrors += fixableErrors; return { filePath: result.filePath, messages: filteredMessages, errorCount: errorCount, warningCount: warningCount, fixableErrorCount: fixableErrorCount, fixableWarningCount: fixableWarningCount }; } return {}; }); newResults.errorCount = totalErrors; newResults.warningCount = totalWarnings; newResults.fixableErrorCount = totalFixableErrors; newResults.fixableWarningCount = totalFixableWarnings; return newResults; }
function filterResults(report, msgKey, options) { var newResults = {}; var totalErrors = 0; var totalWarnings = 0; var totalFixableErrors = 0; var totalFixableWarnings = 0; newResults.results = report.results.map(function (result) { var filteredMessages = result.messages.filter(function (msg) { if (options.present) { return msg[msgKey]; } if (options.compareVal) { return msg[msgKey] === options.compareVal; } return false; }); if (filteredMessages) { var _getCounts = getCounts(filteredMessages), errorCount = _getCounts.errorCount, warningCount = _getCounts.warningCount, fixableErrorCount = _getCounts.fixableErrorCount, fixableWarningCount = _getCounts.fixableWarningCount; totalErrors += errorCount; totalWarnings += warningCount; totalFixableErrors += fixableErrorCount; totalFixableWarnings += fixableWarningCount; // fixableErrors += fixableErrors; return { filePath: result.filePath, messages: filteredMessages, errorCount: errorCount, warningCount: warningCount, fixableErrorCount: fixableErrorCount, fixableWarningCount: fixableWarningCount }; } return {}; }); newResults.errorCount = totalErrors; newResults.warningCount = totalWarnings; newResults.fixableErrorCount = totalFixableErrors; newResults.fixableWarningCount = totalFixableWarnings; return newResults; }
JavaScript
function testAPI() { console.log('Welcome! Fetching your information.... '); FB.api('me?fields=name,email,gender,birthday,first_name,last_name,location,picture', function (response) { if (response && !response.error) { document.getElementById('status').innerHTML = '<img src="' + response.picture.data.url + '" /><br/>' + 'Thanks for logging in, ' + response.name + '!' + '<br/>email: ' + response.email + '<br/>gender: ' + response.gender + '<br/>birthday: ' + response.birthday + '<br/>first_name: ' + response.first_name + '<br/>last_name: ' + response.last_name + '<br/>location: ' + response.location.name; console.log("the email is: "); console.log(response); } else { document.getElementById('status').innerHTML = "Errore nel login :(" } } ) }
function testAPI() { console.log('Welcome! Fetching your information.... '); FB.api('me?fields=name,email,gender,birthday,first_name,last_name,location,picture', function (response) { if (response && !response.error) { document.getElementById('status').innerHTML = '<img src="' + response.picture.data.url + '" /><br/>' + 'Thanks for logging in, ' + response.name + '!' + '<br/>email: ' + response.email + '<br/>gender: ' + response.gender + '<br/>birthday: ' + response.birthday + '<br/>first_name: ' + response.first_name + '<br/>last_name: ' + response.last_name + '<br/>location: ' + response.location.name; console.log("the email is: "); console.log(response); } else { document.getElementById('status').innerHTML = "Errore nel login :(" } } ) }
JavaScript
function Parent(param){ // assign attributes here this.param1 = param.param1; this.param2 = param.param2; this.param3 = param.param3; }
function Parent(param){ // assign attributes here this.param1 = param.param1; this.param2 = param.param2; this.param3 = param.param3; }
JavaScript
function sanitizeEventArgs(evt) { var data = {}; for (var i in evt) { var value = evt[i]; if (isSafeValue(value)) { data[i] = value; } } return data; }
function sanitizeEventArgs(evt) { var data = {}; for (var i in evt) { var value = evt[i]; if (isSafeValue(value)) { data[i] = value; } } return data; }
JavaScript
function dispatchControllerButtonEvent(type, state) { //console.log(type); dispatchEvent(type, { controller: state._ctrlIndex_, button: state._button_._name_, repeated: state._repeat_, value: state._value_, isHandled: false }); }
function dispatchControllerButtonEvent(type, state) { //console.log(type); dispatchEvent(type, { controller: state._ctrlIndex_, button: state._button_._name_, repeated: state._repeat_, value: state._value_, isHandled: false }); }
JavaScript
function ControllerButtonState(controller_index, button) { // The interval to invoke ButtonDown event repeatedly when holding var MAX_HOLD_TIMEOUT = 18; var MIN_HOLD_TIMEOUT = 2; // The time between down and up to qualify as tap var TAP_TIMEOUT = 12; // The time between taps to qualify as double tap var DOUBLE_TAP_TIMEOUT = 24; this._ctrlIndex_ = controller_index; this._button_ = button; this._value_ = 0; this._is_down_ = false; this._repeat_ = 0 var _hold_timer = 0; var _hold_timeout = MAX_HOLD_TIMEOUT; var _tap_timer = 0; var _double_tap_timer = 0; this._update_ = function(isDown, value) { this._value_ = value || 0; if (isDown) { // Repeat firing down event on hold if (_hold_timer > 0) { _hold_timer--; } else { dispatchControllerButtonEvent("buttondown", this); this._repeat_++; _hold_timer = _hold_timeout; if (_hold_timeout > MIN_HOLD_TIMEOUT) _hold_timeout = _hold_timeout * 2 / 3; } if (!this._is_down_) // just down { _tap_timer = TAP_TIMEOUT; } if (_tap_timer > 0) { _tap_timer--; } } else if (this._is_down_) // just up { dispatchControllerButtonEvent("buttonup", this); _hold_timer = 0; _hold_timeout = MAX_HOLD_TIMEOUT; this._repeat_ = 0; if (_tap_timer > 0) { if (_double_tap_timer > 0) { dispatchControllerButtonEvent("buttondbltap", this); _double_tap_timer = 0; } else { _double_tap_timer = DOUBLE_TAP_TIMEOUT; } } } if (_double_tap_timer > 0) { _double_tap_timer--; if (_double_tap_timer == 0) { dispatchControllerButtonEvent("buttontap", this); } } this._is_down_ = isDown; } }
function ControllerButtonState(controller_index, button) { // The interval to invoke ButtonDown event repeatedly when holding var MAX_HOLD_TIMEOUT = 18; var MIN_HOLD_TIMEOUT = 2; // The time between down and up to qualify as tap var TAP_TIMEOUT = 12; // The time between taps to qualify as double tap var DOUBLE_TAP_TIMEOUT = 24; this._ctrlIndex_ = controller_index; this._button_ = button; this._value_ = 0; this._is_down_ = false; this._repeat_ = 0 var _hold_timer = 0; var _hold_timeout = MAX_HOLD_TIMEOUT; var _tap_timer = 0; var _double_tap_timer = 0; this._update_ = function(isDown, value) { this._value_ = value || 0; if (isDown) { // Repeat firing down event on hold if (_hold_timer > 0) { _hold_timer--; } else { dispatchControllerButtonEvent("buttondown", this); this._repeat_++; _hold_timer = _hold_timeout; if (_hold_timeout > MIN_HOLD_TIMEOUT) _hold_timeout = _hold_timeout * 2 / 3; } if (!this._is_down_) // just down { _tap_timer = TAP_TIMEOUT; } if (_tap_timer > 0) { _tap_timer--; } } else if (this._is_down_) // just up { dispatchControllerButtonEvent("buttonup", this); _hold_timer = 0; _hold_timeout = MAX_HOLD_TIMEOUT; this._repeat_ = 0; if (_tap_timer > 0) { if (_double_tap_timer > 0) { dispatchControllerButtonEvent("buttondbltap", this); _double_tap_timer = 0; } else { _double_tap_timer = DOUBLE_TAP_TIMEOUT; } } } if (_double_tap_timer > 0) { _double_tap_timer--; if (_double_tap_timer == 0) { dispatchControllerButtonEvent("buttontap", this); } } this._is_down_ = isDown; } }
JavaScript
function compressKeys(text) { var dict = {}; var keys = text.match(/\b_\w*_\b/g); if (keys) { keys.forEach(function(k) { if (!dict[k]) dict[k] = makeUniqueId(); }); for (var i in dict) { var regex = new RegExp('\\b' + i + '\\b', 'g'); text = text.replace(regex, dict[i]); } } return text; }
function compressKeys(text) { var dict = {}; var keys = text.match(/\b_\w*_\b/g); if (keys) { keys.forEach(function(k) { if (!dict[k]) dict[k] = makeUniqueId(); }); for (var i in dict) { var regex = new RegExp('\\b' + i + '\\b', 'g'); text = text.replace(regex, dict[i]); } } return text; }
JavaScript
function resize() { var w = thisWindow.innerWidth, h = thisWindow.innerHeight, l, t; var body = document.body; body.parentNode.style.overflow = auto_scale? "hidden":"auto"; if (auto_scale) { abScale = Math.min(h / abH, w / abW); l = (w - abScale * abW) / 2; t = (h - abScale * abH) / 2; } else { abScale = 1; l = w < abW ? 0 : (w - abW) / 2; t = h < abH ? 0 : (h - abH) / 2; } select(body).style({ background: is_embedded? "none" : settings.background, width: abW + "px", height: abH + "px", transform: "translate(" + l + "px," + t + "px)" + " scale(" + abScale + ")" }) }
function resize() { var w = thisWindow.innerWidth, h = thisWindow.innerHeight, l, t; var body = document.body; body.parentNode.style.overflow = auto_scale? "hidden":"auto"; if (auto_scale) { abScale = Math.min(h / abH, w / abW); l = (w - abScale * abW) / 2; t = (h - abScale * abH) / 2; } else { abScale = 1; l = w < abW ? 0 : (w - abW) / 2; t = h < abH ? 0 : (h - abH) / 2; } select(body).style({ background: is_embedded? "none" : settings.background, width: abW + "px", height: abH + "px", transform: "translate(" + l + "px," + t + "px)" + " scale(" + abScale + ")" }) }
JavaScript
function CrossTalk(handlers) { var pending_requests = {}; var request_count = 0; function sendMessage(win, request_type, passdata, callback) { if (win) { var request_id = "r" + (request_count++); if (callback) pending_requests[request_id] = callback; win.postMessage({ _id_: request_id, _waiting_: !!callback, _type_: request_type, _data_: passdata }, "*"); } } function sendMessages(nodes, request_type, passdata, callback) { var n = nodes.length; var results = []; if (!n && callback) callback(results); nodes.map(function(node, i) { var data = isFunction(passdata) ? passdata(node, i) : passdata; sendMessage(node._window_, request_type, data, function(d) { results[i] = d; if (!(--n) && callback) { callback(results); } }); }); } function receiveMessage(evt) { var d = evt.data, data = d._data_, type = d._type_; if (type == 0) { var respond_id = data._id_; if (pending_requests[respond_id]) { pending_requests[respond_id](data._data_); pending_requests[respond_id] = null; } return; } else { var callback = d._waiting_ ? function(result) { crosstalk._reply_(evt, result); } : null; var handler = handlers[type]; if (handler) handler.call(evt, data, callback); } } function respond(evt, content) { sendMessage(evt.source, 0, { _id_: evt.data._id_, _data_: content }); } listenTo("message", receiveMessage); return { _send_: sendMessage, _sendAll_: sendMessages, _reply_: respond } }
function CrossTalk(handlers) { var pending_requests = {}; var request_count = 0; function sendMessage(win, request_type, passdata, callback) { if (win) { var request_id = "r" + (request_count++); if (callback) pending_requests[request_id] = callback; win.postMessage({ _id_: request_id, _waiting_: !!callback, _type_: request_type, _data_: passdata }, "*"); } } function sendMessages(nodes, request_type, passdata, callback) { var n = nodes.length; var results = []; if (!n && callback) callback(results); nodes.map(function(node, i) { var data = isFunction(passdata) ? passdata(node, i) : passdata; sendMessage(node._window_, request_type, data, function(d) { results[i] = d; if (!(--n) && callback) { callback(results); } }); }); } function receiveMessage(evt) { var d = evt.data, data = d._data_, type = d._type_; if (type == 0) { var respond_id = data._id_; if (pending_requests[respond_id]) { pending_requests[respond_id](data._data_); pending_requests[respond_id] = null; } return; } else { var callback = d._waiting_ ? function(result) { crosstalk._reply_(evt, result); } : null; var handler = handlers[type]; if (handler) handler.call(evt, data, callback); } } function respond(evt, content) { sendMessage(evt.source, 0, { _id_: evt.data._id_, _data_: content }); } listenTo("message", receiveMessage); return { _send_: sendMessage, _sendAll_: sendMessages, _reply_: respond } }