language
stringclasses
6 values
original_string
stringlengths
25
887k
text
stringlengths
25
887k
JavaScript
function findStartLine(fileLines, functionName, lineNumber) { var startLine = lineNumber - 1 while(true) { if(startLine < 0) { return 'lineOfCodeNotFound' // something went wrong if this is being returned (the functionName wasn't found above - means you didn't get the function name right) } var line = fileLines[startLine] if(line === undefined) { return 'sourceNotAvailable' } //lines.push(line.trim()) var containsFunction = line.indexOf(functionName) !== -1 if(containsFunction) { return startLine } startLine-- } }
function findStartLine(fileLines, functionName, lineNumber) { var startLine = lineNumber - 1 while(true) { if(startLine < 0) { return 'lineOfCodeNotFound' // something went wrong if this is being returned (the functionName wasn't found above - means you didn't get the function name right) } var line = fileLines[startLine] if(line === undefined) { return 'sourceNotAvailable' } //lines.push(line.trim()) var containsFunction = line.indexOf(functionName) !== -1 if(containsFunction) { return startLine } startLine-- } }
JavaScript
function createChainFuture(that) { var f = new Future f.n = that.n + 1 if(Future.debug) { f.location = createException() // used for long traces } return f }
function createChainFuture(that) { var f = new Future f.n = that.n + 1 if(Future.debug) { f.location = createException() // used for long traces } return f }
JavaScript
function executeCallback(cb, arg) { var r = cb(arg) if(r !== undefined && !isLikeAFuture(r) ) throw Error("Value returned from then or catch ("+r+") is *not* a Future. Callback: "+cb.toString()) return r }
function executeCallback(cb, arg) { var r = cb(arg) if(r !== undefined && !isLikeAFuture(r) ) throw Error("Value returned from then or catch ("+r+") is *not* a Future. Callback: "+cb.toString()) return r }
JavaScript
function checkCleanClose(that) { if(that.closing && Object.keys(that.commandState).length === 0) { closeInternal(that) } }
function checkCleanClose(that) { if(that.closing && Object.keys(that.commandState).length === 0) { closeInternal(that) } }
JavaScript
function createErrorInfo(error) { var data = {}, any = false for(var k in error) { if(k !== 'message') { data[k] = error[k] any = true } } var errorInfo = [error.message] if(any) { errorInfo.push(data) } return errorInfo }
function createErrorInfo(error) { var data = {}, any = false for(var k in error) { if(k !== 'message') { data[k] = error[k] any = true } } var errorInfo = [error.message] if(any) { errorInfo.push(data) } return errorInfo }
JavaScript
function validateId(that, id) { if(id > that.maxId) { var reason = "Id greater than " if(that.maxId === defaultMaxId) reason += "2^53" else reason += that.maxId } else if(that.server) { if(id%2 !== 1) { var reason = "Id from client not odd" } } else if(id%2 !== 0) { var reason = "Id from server not even" } if(reason !== undefined) { that.fire("error", {message: 'rpepInvalidId', reason: reason}) return false } else { return true } }
function validateId(that, id) { if(id > that.maxId) { var reason = "Id greater than " if(that.maxId === defaultMaxId) reason += "2^53" else reason += that.maxId } else if(that.server) { if(id%2 !== 1) { var reason = "Id from client not odd" } } else if(id%2 !== 0) { var reason = "Id from server not even" } if(reason !== undefined) { that.fire("error", {message: 'rpepInvalidId', reason: reason}) return false } else { return true } }
JavaScript
function lateEventCheck() { if(ended && !lateEventsWarningPrinted) { mainGroup.add(Text('lateEventsWarning', "Warning: some events happened after the test ended.")) lateEventsWarningPrinted = true } }
function lateEventCheck() { if(ended && !lateEventsWarningPrinted) { mainGroup.add(Text('lateEventsWarning', "Warning: some events happened after the test ended.")) lateEventsWarningPrinted = true } }
JavaScript
function updateCountSuccess(that) { if(that.expected !== undefined) { var countSuccess = that.count === that.expected that.countBlock.state.set("success", countSuccess) if(that.groupEnded) that.countBlock.results.state.set("late", true) if(countSuccess) { that.mainGroup.title.testTotalPasses++ that.title.passed++ if(that.groupEnded) { that.mainGroup.title.testTotalFailures-- that.groupEndCountSubtracted = true // marks that failures were subtracted after the test finished (so successes can be later subtracted correctly if need be) } } else if(that.groupEndCountSubtracted || that.count - 1 === that.expected) { that.title.passed-- that.mainGroup.title.testTotalPasses-- if(that.groupEnded) { that.mainGroup.title.testTotalFailures++ } } } }
function updateCountSuccess(that) { if(that.expected !== undefined) { var countSuccess = that.count === that.expected that.countBlock.state.set("success", countSuccess) if(that.groupEnded) that.countBlock.results.state.set("late", true) if(countSuccess) { that.mainGroup.title.testTotalPasses++ that.title.passed++ if(that.groupEnded) { that.mainGroup.title.testTotalFailures-- that.groupEndCountSubtracted = true // marks that failures were subtracted after the test finished (so successes can be later subtracted correctly if need be) } } else if(that.groupEndCountSubtracted || that.count - 1 === that.expected) { that.title.passed-- that.mainGroup.title.testTotalPasses-- if(that.groupEnded) { that.mainGroup.title.testTotalFailures++ } } } }
JavaScript
function appendInternal(that, propertyList, args, options) { var arrayToAppend = args[0] if(arrayToAppend.length === 0) return; //nothing to do var array = getPropertyValue(that.subject, propertyList) var originalLength = array.length var spliceArgs = [originalLength, 0] spliceArgs = spliceArgs.concat(arrayToAppend) var oldLength = array.length array.splice.apply(array, spliceArgs) var internalObservees = unionizeList(array, oldLength, array.length, options.union) var event = {type: 'added', property: propertyList, index: originalLength, count: arrayToAppend.length} if(options.data !== undefined) event.data = event.id = options.data that.emit('change', event) unionizeListEvents(that, internalObservees, propertyList, options.union) }
function appendInternal(that, propertyList, args, options) { var arrayToAppend = args[0] if(arrayToAppend.length === 0) return; //nothing to do var array = getPropertyValue(that.subject, propertyList) var originalLength = array.length var spliceArgs = [originalLength, 0] spliceArgs = spliceArgs.concat(arrayToAppend) var oldLength = array.length array.splice.apply(array, spliceArgs) var internalObservees = unionizeList(array, oldLength, array.length, options.union) var event = {type: 'added', property: propertyList, index: originalLength, count: arrayToAppend.length} if(options.data !== undefined) event.data = event.id = options.data that.emit('change', event) unionizeListEvents(that, internalObservees, propertyList, options.union) }
JavaScript
function unionizeList(array, start, count, union) { var internalObservees = [] // list of observees and their property path if(union !== undefined) { var afterEnd = start+count for(var n=start; n<afterEnd; n++) { internalObservees.push({obj: array[n], index: n}) if(union === true) array[n] = array[n].subject } } return internalObservees }
function unionizeList(array, start, count, union) { var internalObservees = [] // list of observees and their property path if(union !== undefined) { var afterEnd = start+count for(var n=start; n<afterEnd; n++) { internalObservees.push({obj: array[n], index: n}) if(union === true) array[n] = array[n].subject } } return internalObservees }
JavaScript
function unionizeListEvents(that, internalObservees, propertyList, collapse) { for(var n=0; n<internalObservees.length; n++) { unionizeEvents(that, internalObservees[n].obj, propertyList.concat(internalObservees[n].index+''), collapse) } }
function unionizeListEvents(that, internalObservees, propertyList, collapse) { for(var n=0; n<internalObservees.length; n++) { unionizeEvents(that, internalObservees[n].obj, propertyList.concat(internalObservees[n].index+''), collapse) } }
JavaScript
function unionizeEvents(that, innerObservee, propertyList, collapse) { var propertyListDepth = propertyList.length if(innerObservee.on === undefined || innerObservee.emit === undefined || innerObservee.removeListener === undefined || innerObservee.set === undefined) { throw new Error("Attempting to union a value that isn't an observee") } var innerChangeHandler, containerChangeHandler var ignorableContainerEvents = [], ignorableInnerEvents = [] innerObservee.on('change', innerChangeHandler = function(change) { if(ignorableInnerEvents.indexOf(change) === -1) { // don't run this for events generated by the union event handlers if(collapse) { var property = propertyList.concat(change.property) } else { var property = propertyList.concat(['subject']).concat(change.property) } var containerChange = utils.merge({}, change, {property: property}) ignorableContainerEvents.push(containerChange) that.emit('change', containerChange) } }) that.onChangeInternal(containerChangeHandler = function(change) { var changedPropertyDepth = change.property.length if(collapse) { var propertyListToAskFor = propertyList } else { var propertyListToAskFor = propertyList.concat(['subject']) } var answers = changeQuestions(propertyListToAskFor, change, true) var changeIsWithinInnerProperty = answers.isWithin var changeCouldRelocateInnerProperty = answers.couldRelocate if(changeIsWithinInnerProperty && ignorableContainerEvents.indexOf(change) === -1) { // don't run this for events generated by the union event handlers if(collapse) { var property = change.property.slice(propertyListDepth) } else { var property = change.property.slice(propertyListDepth+1) // +1 for the 'subject' } var innerObserveeEvent = utils.merge({}, change, {property: property}) ignorableInnerEvents.push(innerObserveeEvent) innerObservee.emit('change', innerObserveeEvent) } else if(changeCouldRelocateInnerProperty) { if(change.type === 'set' /*&& changedPropertyDepth <= propertyListDepth - this part already done above*/) { removeUnion() } else if(change.type === 'removed') { var relevantIndex = propertyList[change.property.length] var removedIndexesContainsIndexOfInnerObservee = change.index <= relevantIndex && relevantIndex <= change.index + change.removed.length - 1 var removedIndexesAreBeforeIndexOfInnerObservee = change.index + change.removed.length - 1 < relevantIndex && relevantIndex if(removedIndexesContainsIndexOfInnerObservee && changedPropertyDepth <= propertyListDepth+1) { removeUnion() } else if(removedIndexesAreBeforeIndexOfInnerObservee) { propertyList[change.property.length] = relevantIndex - change.removed.length // change the propertyList to match the new index } } else if(change.type === 'added') { var relevantIndex = propertyList[change.property.length] if(change.index < relevantIndex) { propertyList[change.property.length] = relevantIndex + change.count // change the propertyList to match the new index } } } }) var removeUnion = function() { innerObservee.removeListener('change', innerChangeHandler) that.offChangeInternal(containerChangeHandler) } }
function unionizeEvents(that, innerObservee, propertyList, collapse) { var propertyListDepth = propertyList.length if(innerObservee.on === undefined || innerObservee.emit === undefined || innerObservee.removeListener === undefined || innerObservee.set === undefined) { throw new Error("Attempting to union a value that isn't an observee") } var innerChangeHandler, containerChangeHandler var ignorableContainerEvents = [], ignorableInnerEvents = [] innerObservee.on('change', innerChangeHandler = function(change) { if(ignorableInnerEvents.indexOf(change) === -1) { // don't run this for events generated by the union event handlers if(collapse) { var property = propertyList.concat(change.property) } else { var property = propertyList.concat(['subject']).concat(change.property) } var containerChange = utils.merge({}, change, {property: property}) ignorableContainerEvents.push(containerChange) that.emit('change', containerChange) } }) that.onChangeInternal(containerChangeHandler = function(change) { var changedPropertyDepth = change.property.length if(collapse) { var propertyListToAskFor = propertyList } else { var propertyListToAskFor = propertyList.concat(['subject']) } var answers = changeQuestions(propertyListToAskFor, change, true) var changeIsWithinInnerProperty = answers.isWithin var changeCouldRelocateInnerProperty = answers.couldRelocate if(changeIsWithinInnerProperty && ignorableContainerEvents.indexOf(change) === -1) { // don't run this for events generated by the union event handlers if(collapse) { var property = change.property.slice(propertyListDepth) } else { var property = change.property.slice(propertyListDepth+1) // +1 for the 'subject' } var innerObserveeEvent = utils.merge({}, change, {property: property}) ignorableInnerEvents.push(innerObserveeEvent) innerObservee.emit('change', innerObserveeEvent) } else if(changeCouldRelocateInnerProperty) { if(change.type === 'set' /*&& changedPropertyDepth <= propertyListDepth - this part already done above*/) { removeUnion() } else if(change.type === 'removed') { var relevantIndex = propertyList[change.property.length] var removedIndexesContainsIndexOfInnerObservee = change.index <= relevantIndex && relevantIndex <= change.index + change.removed.length - 1 var removedIndexesAreBeforeIndexOfInnerObservee = change.index + change.removed.length - 1 < relevantIndex && relevantIndex if(removedIndexesContainsIndexOfInnerObservee && changedPropertyDepth <= propertyListDepth+1) { removeUnion() } else if(removedIndexesAreBeforeIndexOfInnerObservee) { propertyList[change.property.length] = relevantIndex - change.removed.length // change the propertyList to match the new index } } else if(change.type === 'added') { var relevantIndex = propertyList[change.property.length] if(change.index < relevantIndex) { propertyList[change.property.length] = relevantIndex + change.count // change the propertyList to match the new index } } } }) var removeUnion = function() { innerObservee.removeListener('change', innerChangeHandler) that.offChangeInternal(containerChangeHandler) } }
JavaScript
function iterateThroughLeafNodes(element, callback) { var nodeStack = [element], node; while (node = nodeStack.pop()) { if (node.nodeType == 3) { if(callback(node) === true) break; } else { var i = node.childNodes.length; while (i--) { nodeStack.push(node.childNodes[i]); } } } }
function iterateThroughLeafNodes(element, callback) { var nodeStack = [element], node; while (node = nodeStack.pop()) { if (node.nodeType == 3) { if(callback(node) === true) break; } else { var i = node.childNodes.length; while (i--) { nodeStack.push(node.childNodes[i]); } } } }
JavaScript
function swapPseudoElSyntax(selector) { if (doubleColonPseudoElRegex.exec(selector)) { return toSingleColonPseudoElements(selector); } return selector; }
function swapPseudoElSyntax(selector) { if (doubleColonPseudoElRegex.exec(selector)) { return toSingleColonPseudoElements(selector); } return selector; }
JavaScript
function eachTest(test, callback, parent) { test.results.forEach(function(result) { if(result.type === 'group') { eachTest(result, callback, test) } }) callback(test, parent) }
function eachTest(test, callback, parent) { test.results.forEach(function(result) { if(result.type === 'group') { eachTest(result, callback, test) } }) callback(test, parent) }
JavaScript
function printStackTrace(options) { options = options || {guess: true}; var ex = options.e || null, guess = !!options.guess; var p = new printStackTrace.implementation(), result = p.run(ex); return (guess) ? p.guessAnonymousFunctions(result) : result; }
function printStackTrace(options) { options = options || {guess: true}; var ex = options.e || null, guess = !!options.guess; var p = new printStackTrace.implementation(), result = p.run(ex); return (guess) ? p.guessAnonymousFunctions(result) : result; }
JavaScript
function init_token() { // (immediate values) // positive fixint -- 0x00 - 0x7f // nil -- 0xc0 // false -- 0xc2 // true -- 0xc3 // negative fixint -- 0xe0 - 0xff var token = uint8.slice(); // bin 8 -- 0xc4 // bin 16 -- 0xc5 // bin 32 -- 0xc6 token[0xc4] = write1(0xc4); token[0xc5] = write2(0xc5); token[0xc6] = write4(0xc6); // ext 8 -- 0xc7 // ext 16 -- 0xc8 // ext 32 -- 0xc9 token[0xc7] = write1(0xc7); token[0xc8] = write2(0xc8); token[0xc9] = write4(0xc9); // float 32 -- 0xca // float 64 -- 0xcb token[0xca] = writeN(0xca, 4, (Buffer_prototype.writeFloatBE || writeFloatBE), true); token[0xcb] = writeN(0xcb, 8, (Buffer_prototype.writeDoubleBE || writeDoubleBE), true); // uint 8 -- 0xcc // uint 16 -- 0xcd // uint 32 -- 0xce // uint 64 -- 0xcf token[0xcc] = write1(0xcc); token[0xcd] = write2(0xcd); token[0xce] = write4(0xce); token[0xcf] = writeN(0xcf, 8, writeUInt64BE); // int 8 -- 0xd0 // int 16 -- 0xd1 // int 32 -- 0xd2 // int 64 -- 0xd3 token[0xd0] = write1(0xd0); token[0xd1] = write2(0xd1); token[0xd2] = write4(0xd2); token[0xd3] = writeN(0xd3, 8, writeInt64BE); // str 8 -- 0xd9 // str 16 -- 0xda // str 32 -- 0xdb token[0xd9] = write1(0xd9); token[0xda] = write2(0xda); token[0xdb] = write4(0xdb); // array 16 -- 0xdc // array 32 -- 0xdd token[0xdc] = write2(0xdc); token[0xdd] = write4(0xdd); // map 16 -- 0xde // map 32 -- 0xdf token[0xde] = write2(0xde); token[0xdf] = write4(0xdf); return token; }
function init_token() { // (immediate values) // positive fixint -- 0x00 - 0x7f // nil -- 0xc0 // false -- 0xc2 // true -- 0xc3 // negative fixint -- 0xe0 - 0xff var token = uint8.slice(); // bin 8 -- 0xc4 // bin 16 -- 0xc5 // bin 32 -- 0xc6 token[0xc4] = write1(0xc4); token[0xc5] = write2(0xc5); token[0xc6] = write4(0xc6); // ext 8 -- 0xc7 // ext 16 -- 0xc8 // ext 32 -- 0xc9 token[0xc7] = write1(0xc7); token[0xc8] = write2(0xc8); token[0xc9] = write4(0xc9); // float 32 -- 0xca // float 64 -- 0xcb token[0xca] = writeN(0xca, 4, (Buffer_prototype.writeFloatBE || writeFloatBE), true); token[0xcb] = writeN(0xcb, 8, (Buffer_prototype.writeDoubleBE || writeDoubleBE), true); // uint 8 -- 0xcc // uint 16 -- 0xcd // uint 32 -- 0xce // uint 64 -- 0xcf token[0xcc] = write1(0xcc); token[0xcd] = write2(0xcd); token[0xce] = write4(0xce); token[0xcf] = writeN(0xcf, 8, writeUInt64BE); // int 8 -- 0xd0 // int 16 -- 0xd1 // int 32 -- 0xd2 // int 64 -- 0xd3 token[0xd0] = write1(0xd0); token[0xd1] = write2(0xd1); token[0xd2] = write4(0xd2); token[0xd3] = writeN(0xd3, 8, writeInt64BE); // str 8 -- 0xd9 // str 16 -- 0xda // str 32 -- 0xdb token[0xd9] = write1(0xd9); token[0xda] = write2(0xda); token[0xdb] = write4(0xdb); // array 16 -- 0xdc // array 32 -- 0xdd token[0xdc] = write2(0xdc); token[0xdd] = write4(0xdd); // map 16 -- 0xde // map 32 -- 0xdf token[0xde] = write2(0xde); token[0xdf] = write4(0xdf); return token; }
JavaScript
function init_safe() { // (immediate values) // positive fixint -- 0x00 - 0x7f // nil -- 0xc0 // false -- 0xc2 // true -- 0xc3 // negative fixint -- 0xe0 - 0xff var token = uint8.slice(); // bin 8 -- 0xc4 // bin 16 -- 0xc5 // bin 32 -- 0xc6 token[0xc4] = writeN(0xc4, 1, Buffer.prototype.writeUInt8); token[0xc5] = writeN(0xc5, 2, Buffer.prototype.writeUInt16BE); token[0xc6] = writeN(0xc6, 4, Buffer.prototype.writeUInt32BE); // ext 8 -- 0xc7 // ext 16 -- 0xc8 // ext 32 -- 0xc9 token[0xc7] = writeN(0xc7, 1, Buffer.prototype.writeUInt8); token[0xc8] = writeN(0xc8, 2, Buffer.prototype.writeUInt16BE); token[0xc9] = writeN(0xc9, 4, Buffer.prototype.writeUInt32BE); // float 32 -- 0xca // float 64 -- 0xcb token[0xca] = writeN(0xca, 4, Buffer.prototype.writeFloatBE); token[0xcb] = writeN(0xcb, 8, Buffer.prototype.writeDoubleBE); // uint 8 -- 0xcc // uint 16 -- 0xcd // uint 32 -- 0xce // uint 64 -- 0xcf token[0xcc] = writeN(0xcc, 1, Buffer.prototype.writeUInt8); token[0xcd] = writeN(0xcd, 2, Buffer.prototype.writeUInt16BE); token[0xce] = writeN(0xce, 4, Buffer.prototype.writeUInt32BE); token[0xcf] = writeN(0xcf, 8, writeUInt64BE); // int 8 -- 0xd0 // int 16 -- 0xd1 // int 32 -- 0xd2 // int 64 -- 0xd3 token[0xd0] = writeN(0xd0, 1, Buffer.prototype.writeInt8); token[0xd1] = writeN(0xd1, 2, Buffer.prototype.writeInt16BE); token[0xd2] = writeN(0xd2, 4, Buffer.prototype.writeInt32BE); token[0xd3] = writeN(0xd3, 8, writeInt64BE); // str 8 -- 0xd9 // str 16 -- 0xda // str 32 -- 0xdb token[0xd9] = writeN(0xd9, 1, Buffer.prototype.writeUInt8); token[0xda] = writeN(0xda, 2, Buffer.prototype.writeUInt16BE); token[0xdb] = writeN(0xdb, 4, Buffer.prototype.writeUInt32BE); // array 16 -- 0xdc // array 32 -- 0xdd token[0xdc] = writeN(0xdc, 2, Buffer.prototype.writeUInt16BE); token[0xdd] = writeN(0xdd, 4, Buffer.prototype.writeUInt32BE); // map 16 -- 0xde // map 32 -- 0xdf token[0xde] = writeN(0xde, 2, Buffer.prototype.writeUInt16BE); token[0xdf] = writeN(0xdf, 4, Buffer.prototype.writeUInt32BE); return token; }
function init_safe() { // (immediate values) // positive fixint -- 0x00 - 0x7f // nil -- 0xc0 // false -- 0xc2 // true -- 0xc3 // negative fixint -- 0xe0 - 0xff var token = uint8.slice(); // bin 8 -- 0xc4 // bin 16 -- 0xc5 // bin 32 -- 0xc6 token[0xc4] = writeN(0xc4, 1, Buffer.prototype.writeUInt8); token[0xc5] = writeN(0xc5, 2, Buffer.prototype.writeUInt16BE); token[0xc6] = writeN(0xc6, 4, Buffer.prototype.writeUInt32BE); // ext 8 -- 0xc7 // ext 16 -- 0xc8 // ext 32 -- 0xc9 token[0xc7] = writeN(0xc7, 1, Buffer.prototype.writeUInt8); token[0xc8] = writeN(0xc8, 2, Buffer.prototype.writeUInt16BE); token[0xc9] = writeN(0xc9, 4, Buffer.prototype.writeUInt32BE); // float 32 -- 0xca // float 64 -- 0xcb token[0xca] = writeN(0xca, 4, Buffer.prototype.writeFloatBE); token[0xcb] = writeN(0xcb, 8, Buffer.prototype.writeDoubleBE); // uint 8 -- 0xcc // uint 16 -- 0xcd // uint 32 -- 0xce // uint 64 -- 0xcf token[0xcc] = writeN(0xcc, 1, Buffer.prototype.writeUInt8); token[0xcd] = writeN(0xcd, 2, Buffer.prototype.writeUInt16BE); token[0xce] = writeN(0xce, 4, Buffer.prototype.writeUInt32BE); token[0xcf] = writeN(0xcf, 8, writeUInt64BE); // int 8 -- 0xd0 // int 16 -- 0xd1 // int 32 -- 0xd2 // int 64 -- 0xd3 token[0xd0] = writeN(0xd0, 1, Buffer.prototype.writeInt8); token[0xd1] = writeN(0xd1, 2, Buffer.prototype.writeInt16BE); token[0xd2] = writeN(0xd2, 4, Buffer.prototype.writeInt32BE); token[0xd3] = writeN(0xd3, 8, writeInt64BE); // str 8 -- 0xd9 // str 16 -- 0xda // str 32 -- 0xdb token[0xd9] = writeN(0xd9, 1, Buffer.prototype.writeUInt8); token[0xda] = writeN(0xda, 2, Buffer.prototype.writeUInt16BE); token[0xdb] = writeN(0xdb, 4, Buffer.prototype.writeUInt32BE); // array 16 -- 0xdc // array 32 -- 0xdd token[0xdc] = writeN(0xdc, 2, Buffer.prototype.writeUInt16BE); token[0xdd] = writeN(0xdd, 4, Buffer.prototype.writeUInt32BE); // map 16 -- 0xde // map 32 -- 0xdf token[0xde] = writeN(0xde, 2, Buffer.prototype.writeUInt16BE); token[0xdf] = writeN(0xdf, 4, Buffer.prototype.writeUInt32BE); return token; }
JavaScript
async requireAuthentication(transition, routeOrCallback) { await this.initClerk(); let isAuthenticated = this.isAuthenticated; if (!isAuthenticated) { if (transition) { this.attemptedTransition = transition; } let argType = typeof routeOrCallback; if (argType === 'string') { this.router.transitionTo(routeOrCallback); } else if (argType === 'function') { routeOrCallback(); } else { assert( `The second argument to requireAuthentication must be a String or Function, got "${argType}"!`, false ); } } return isAuthenticated; }
async requireAuthentication(transition, routeOrCallback) { await this.initClerk(); let isAuthenticated = this.isAuthenticated; if (!isAuthenticated) { if (transition) { this.attemptedTransition = transition; } let argType = typeof routeOrCallback; if (argType === 'string') { this.router.transitionTo(routeOrCallback); } else if (argType === 'function') { routeOrCallback(); } else { assert( `The second argument to requireAuthentication must be a String or Function, got "${argType}"!`, false ); } } return isAuthenticated; }
JavaScript
async prohibitAuthentication(routeOrCallback) { await this.initClerk(); let isAuthenticated = this.isAuthenticated; if (isAuthenticated) { let argType = typeof routeOrCallback; if (argType === 'string') { this.router.transitionTo(routeOrCallback); } else if (argType === 'function') { routeOrCallback(); } else { assert( `The first argument to prohibitAuthentication must be a String or Function, got "${argType}"!`, false ); } } return !isAuthenticated; }
async prohibitAuthentication(routeOrCallback) { await this.initClerk(); let isAuthenticated = this.isAuthenticated; if (isAuthenticated) { let argType = typeof routeOrCallback; if (argType === 'string') { this.router.transitionTo(routeOrCallback); } else if (argType === 'function') { routeOrCallback(); } else { assert( `The first argument to prohibitAuthentication must be a String or Function, got "${argType}"!`, false ); } } return !isAuthenticated; }
JavaScript
function terpFn(x0, x1, t) { var r = (Math.PI / 2.0) * t; var s = Math.sin(r); var si = 1.0 - s; return (x0 * si + x1 * s); }
function terpFn(x0, x1, t) { var r = (Math.PI / 2.0) * t; var s = Math.sin(r); var si = 1.0 - s; return (x0 * si + x1 * s); }
JavaScript
function animateTo(destPanel, dur, done) { if (dur === void 0) { dur = slideDuration; } if (isAnimating) { console.warn("Cannot animateTo - already animating"); return; } if (dragger.isDragging()) { console.warn("Cannot animateTo - currently dragging"); return; } isAnimating = true; var startX = curPosX; var destX = -destPanel * panelWidth; function finish() { curPanel = destPanel; isAnimating = false; emit('animationstatechange', false); done && done(curPanel); } function loop() { var t = Date.now(); var destX = -destPanel * panelWidth; var totalT = t - startT; var animT = Math.min(totalT, dur); curPosX = terp(startX, destX, animT / dur); transform_1.setX(element, curPosX); emit('animate', -curPosX / panelWidth); if (totalT < dur) { requestAnimationFrame(loop); } else { finish(); } } if (destX === startX) { requestAnimationFrame(finish); emit('animationstatechange', true); return; } var startT = Date.now(); requestAnimationFrame(loop); emit('animationstatechange', true); }
function animateTo(destPanel, dur, done) { if (dur === void 0) { dur = slideDuration; } if (isAnimating) { console.warn("Cannot animateTo - already animating"); return; } if (dragger.isDragging()) { console.warn("Cannot animateTo - currently dragging"); return; } isAnimating = true; var startX = curPosX; var destX = -destPanel * panelWidth; function finish() { curPanel = destPanel; isAnimating = false; emit('animationstatechange', false); done && done(curPanel); } function loop() { var t = Date.now(); var destX = -destPanel * panelWidth; var totalT = t - startT; var animT = Math.min(totalT, dur); curPosX = terp(startX, destX, animT / dur); transform_1.setX(element, curPosX); emit('animate', -curPosX / panelWidth); if (totalT < dur) { requestAnimationFrame(loop); } else { finish(); } } if (destX === startX) { requestAnimationFrame(finish); emit('animationstatechange', true); return; } var startT = Date.now(); requestAnimationFrame(loop); emit('animationstatechange', true); }
JavaScript
function resize() { var rc = element.getBoundingClientRect(); panelWidth = rc.width; fullWidth = panelWidth * numPanels; curPosX = -curPanel * panelWidth; transform_1.setX(element, curPosX); }
function resize() { var rc = element.getBoundingClientRect(); panelWidth = rc.width; fullWidth = panelWidth * numPanels; curPosX = -curPanel * panelWidth; transform_1.setX(element, curPosX); }
JavaScript
function destroy() { // Remove event listeners window.removeEventListener('resize', resize); dragger.destroy(); Object.keys(emitters).forEach(function (k) { emitters[k].length = 0; }); element = undefined; }
function destroy() { // Remove event listeners window.removeEventListener('resize', resize); dragger.destroy(); Object.keys(emitters).forEach(function (k) { emitters[k].length = 0; }); element = undefined; }
JavaScript
function createSpeedo(numSamples) { if (numSamples === void 0) { numSamples = DEFAULT_SAMPLES; } var index = 0; var count = 0; var samples = new Array(numSamples); for (var i = 0; i < numSamples; ++i) { samples[i] = { x: 0, t: 0 }; } function start(x, t) { index = 0; count = 0; samples[index].x = x; samples[index].t = t; index = 1; count = 1; } function addSample(x, t) { samples[index].x = x; samples[index].t = t; index = (index + 1) % numSamples; count += 1; } function getVel() { if (count < 1) return 0; var n = count > numSamples ? numSamples : count; var iLast = math_1.pmod(index - 1, numSamples); var iFirst = math_1.pmod(index - n, numSamples); var deltaT = samples[iLast].t - samples[iFirst].t; var dx = samples[iLast].x - samples[iFirst].x; return dx / deltaT; } return { start: start, addSample: addSample, getVel: getVel }; }
function createSpeedo(numSamples) { if (numSamples === void 0) { numSamples = DEFAULT_SAMPLES; } var index = 0; var count = 0; var samples = new Array(numSamples); for (var i = 0; i < numSamples; ++i) { samples[i] = { x: 0, t: 0 }; } function start(x, t) { index = 0; count = 0; samples[index].x = x; samples[index].t = t; index = 1; count = 1; } function addSample(x, t) { samples[index].x = x; samples[index].t = t; index = (index + 1) % numSamples; count += 1; } function getVel() { if (count < 1) return 0; var n = count > numSamples ? numSamples : count; var iLast = math_1.pmod(index - 1, numSamples); var iFirst = math_1.pmod(index - n, numSamples); var deltaT = samples[iLast].t - samples[iFirst].t; var dx = samples[iLast].x - samples[iFirst].x; return dx / deltaT; } return { start: start, addSample: addSample, getVel: getVel }; }
JavaScript
function renderLicenseBadge(data) { switch (data) { case "GPL": badge = "[![License: GPL v3](https://img.shields.io/badge/License-GPLv3-blue.svg)](https://www.gnu.org/licenses/gpl-3.0)"; break; case "Apache": badge = "[![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)"; break; case "BSD": badge = "[![License](https://img.shields.io/badge/License-BSD%203--Clause-blue.svg)](https://opensource.org/licenses/BSD-3-Clause)"; break; case "MIT": badge = "[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)"; break; case "None": badge= "" break; } return badge }
function renderLicenseBadge(data) { switch (data) { case "GPL": badge = "[![License: GPL v3](https://img.shields.io/badge/License-GPLv3-blue.svg)](https://www.gnu.org/licenses/gpl-3.0)"; break; case "Apache": badge = "[![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)"; break; case "BSD": badge = "[![License](https://img.shields.io/badge/License-BSD%203--Clause-blue.svg)](https://opensource.org/licenses/BSD-3-Clause)"; break; case "MIT": badge = "[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)"; break; case "None": badge= "" break; } return badge }
JavaScript
function renderLicenseLink(data) { if (data !== "None") { return "* [License](#license)"; } else { return ""; } }
function renderLicenseLink(data) { if (data !== "None") { return "* [License](#license)"; } else { return ""; } }
JavaScript
function renderLicenseSection(data) { if (data !== "None") { return "## License"; } else { return ""; } }
function renderLicenseSection(data) { if (data !== "None") { return "## License"; } else { return ""; } }
JavaScript
function renderLicenseSectionBody(data) { if (data !== "None") { return `This software is distributed with the ${data} license`; } else { return ""; } }
function renderLicenseSectionBody(data) { if (data !== "None") { return `This software is distributed with the ${data} license`; } else { return ""; } }
JavaScript
function generateMarkdown(data) { return `${renderLicenseBadge(data.license)} # ${data.projectTitle} ## Description ${data.projDesc} ## Table of Contents * [Installation](#installation) * [Usage](#usage) * [Testing](#testing) * [Contribute](#contribute) * [Questions](#questions) ${renderLicenseLink(data.license)} ## Installation \`\`\` ${data.installDesc} \`\`\` ## Usage ${data.usage} ## Testing To run tests, please execute the following command: \`\`\` ${data.test} \`\`\` ## Contribute ${data.contribution} ## Questions If you have any questions about this project contact me through my Github [${data.gitHubUsername}](https://github.com/${data.gitHubUsername}) or through my email [${data.email}](${data.email}). ${renderLicenseSection(data.license)} ${renderLicenseSectionBody(data.license)} `; }
function generateMarkdown(data) { return `${renderLicenseBadge(data.license)} # ${data.projectTitle} ## Description ${data.projDesc} ## Table of Contents * [Installation](#installation) * [Usage](#usage) * [Testing](#testing) * [Contribute](#contribute) * [Questions](#questions) ${renderLicenseLink(data.license)} ## Installation \`\`\` ${data.installDesc} \`\`\` ## Usage ${data.usage} ## Testing To run tests, please execute the following command: \`\`\` ${data.test} \`\`\` ## Contribute ${data.contribution} ## Questions If you have any questions about this project contact me through my Github [${data.gitHubUsername}](https://github.com/${data.gitHubUsername}) or through my email [${data.email}](${data.email}). ${renderLicenseSection(data.license)} ${renderLicenseSectionBody(data.license)} `; }
JavaScript
function edit_stdnt_btn(e){ var sid = $(this).attr('sid'); $("#student_id").val(sid); $('.bd-example-modal-lg').modal('show'); $(".grade_input").val("0"); $.ajax( { type:"post", url: "get_grades", data:{ sid:sid}, dataType : 'json', success:function(response) { //console.log(response); response.forEach(update_grades_fields); }, error: function() { alert("Invalide!"); } } ); }
function edit_stdnt_btn(e){ var sid = $(this).attr('sid'); $("#student_id").val(sid); $('.bd-example-modal-lg').modal('show'); $(".grade_input").val("0"); $.ajax( { type:"post", url: "get_grades", data:{ sid:sid}, dataType : 'json', success:function(response) { //console.log(response); response.forEach(update_grades_fields); }, error: function() { alert("Invalide!"); } } ); }
JavaScript
function refresh_pagination(page,element) { var start_page = page-before_links; var bool=0; $('.link_page').each(function(i, obj) { if($(element).attr("page")!=$(obj).attr("page")){ // console.log($(element).attr("page")+" "+$(obj).attr("page")) //console.log(start_page) $(this).remove() start_page++; } else{bool=1; start_page++; } }); start_page = page-before_links; bool=0; for(var i=0 ; i<=num_links;i++){ if(start_page+i!=$(element).attr('page')){ if(!bool){ if((start_page+i)>0) $( ' <li class="page-item"><a class="page-link link_page" page="'+(start_page+i)+'"href="/students/get_student/'+(start_page+i)+'">'+(start_page+i)+'</a></li>').insertBefore(element.parent()); } else { if((start_page+i)<=total_pages) $( ' <li class="page-item"><a class="page-link link_page" page="'+(start_page+i)+'"href="/students/get_student/'+(start_page+i)+'">'+(start_page+i)+'</a></li>').insertAfter($('.link_page').last().parent()); } } else{ bool=1; } } $(".link_page").click(link_page_click); }
function refresh_pagination(page,element) { var start_page = page-before_links; var bool=0; $('.link_page').each(function(i, obj) { if($(element).attr("page")!=$(obj).attr("page")){ // console.log($(element).attr("page")+" "+$(obj).attr("page")) //console.log(start_page) $(this).remove() start_page++; } else{bool=1; start_page++; } }); start_page = page-before_links; bool=0; for(var i=0 ; i<=num_links;i++){ if(start_page+i!=$(element).attr('page')){ if(!bool){ if((start_page+i)>0) $( ' <li class="page-item"><a class="page-link link_page" page="'+(start_page+i)+'"href="/students/get_student/'+(start_page+i)+'">'+(start_page+i)+'</a></li>').insertBefore(element.parent()); } else { if((start_page+i)<=total_pages) $( ' <li class="page-item"><a class="page-link link_page" page="'+(start_page+i)+'"href="/students/get_student/'+(start_page+i)+'">'+(start_page+i)+'</a></li>').insertAfter($('.link_page').last().parent()); } } else{ bool=1; } } $(".link_page").click(link_page_click); }
JavaScript
function update_grades_fields(record) { //console.log(record); $("#work_"+record["course_id"]).val(record["work"]) $("#oral_"+record["course_id"]).val(record["oral"]) $("#exam_"+record["course_id"]).val(record["exam"]) }
function update_grades_fields(record) { //console.log(record); $("#work_"+record["course_id"]).val(record["work"]) $("#oral_"+record["course_id"]).val(record["oral"]) $("#exam_"+record["course_id"]).val(record["exam"]) }
JavaScript
function followLoginRedirect(response) { if (response.statusCode !== 302) { // Status Codes other than 302 let err = { message: `The statuscode for the Sainsbury login needs to be 302, but was ${response.statusCode}`, statusCode: response.statusCode, error: response.body, options: loginOptions, response: response } throw err } // Follow the redirect which completes the login return rp.get(response.headers.location) }
function followLoginRedirect(response) { if (response.statusCode !== 302) { // Status Codes other than 302 let err = { message: `The statuscode for the Sainsbury login needs to be 302, but was ${response.statusCode}`, statusCode: response.statusCode, error: response.body, options: loginOptions, response: response } throw err } // Follow the redirect which completes the login return rp.get(response.headers.location) }
JavaScript
function saveSearchedCity() { city = $("#city-input").val().trim(); localStorage.setItem("searchedCity", JSON.stringify(city)); cityNames.push(city); localStorage.setItem("cities", JSON.stringify(cityNames)); }
function saveSearchedCity() { city = $("#city-input").val().trim(); localStorage.setItem("searchedCity", JSON.stringify(city)); cityNames.push(city); localStorage.setItem("cities", JSON.stringify(cityNames)); }
JavaScript
function addCityButtons() { $("#add-city-div").empty(); for (var i = 0; i < cityNames.length; i++) { var newCityBtn = $("<button>"); newCityBtn.addClass("btn btn-outline-secondary city-btn"); newCityBtn.attr("city-name", cityNames[i]); newCityBtn.text(cityNames[i]); $("#add-city-div").prepend(newCityBtn) } }
function addCityButtons() { $("#add-city-div").empty(); for (var i = 0; i < cityNames.length; i++) { var newCityBtn = $("<button>"); newCityBtn.addClass("btn btn-outline-secondary city-btn"); newCityBtn.attr("city-name", cityNames[i]); newCityBtn.text(cityNames[i]); $("#add-city-div").prepend(newCityBtn) } }
JavaScript
function clickedCityInfo() { city = $(this).attr("city-name"); localStorage.setItem("searchedCity", JSON.stringify(city)); cityLongLat(); }
function clickedCityInfo() { city = $(this).attr("city-name"); localStorage.setItem("searchedCity", JSON.stringify(city)); cityLongLat(); }
JavaScript
function cityLongLat() { var queryURL = "https://api.openweathermap.org/data/2.5/weather?q=" + city + "&appid=" + apiKey; $.ajax({ url: queryURL, method: "GET", }).then(function (response) { console.log(response); longitude = response.coord.lon; latitude = response.coord.lat; getWeatherInfo(); }); }
function cityLongLat() { var queryURL = "https://api.openweathermap.org/data/2.5/weather?q=" + city + "&appid=" + apiKey; $.ajax({ url: queryURL, method: "GET", }).then(function (response) { console.log(response); longitude = response.coord.lon; latitude = response.coord.lat; getWeatherInfo(); }); }
JavaScript
function renderCityInfo(response) { var temp = fromKelvinToCelsius(response.current.temp); var humidity = response.current.humidity; var windSpeed = mPerSectoMPH(response.current.wind_speed); var uvIndex = response.current.uvi; $(".present-temp").text("Temperature: " + temp + "°C"); $(".present-humidity").text("Humidity: " + humidity + "%"); $(".present-wind").text("Wind Speed: " + windSpeed + "MPH"); $("#uvi-value").text(uvIndex); uvIndexIndicator(uvIndex); }
function renderCityInfo(response) { var temp = fromKelvinToCelsius(response.current.temp); var humidity = response.current.humidity; var windSpeed = mPerSectoMPH(response.current.wind_speed); var uvIndex = response.current.uvi; $(".present-temp").text("Temperature: " + temp + "°C"); $(".present-humidity").text("Humidity: " + humidity + "%"); $(".present-wind").text("Wind Speed: " + windSpeed + "MPH"); $("#uvi-value").text(uvIndex); uvIndexIndicator(uvIndex); }
JavaScript
function uvIndexIndicator(uvIndex) { if (uvIndex <= 2) { $("#uvi-value").addClass("low"); $("#uvi-value").removeClass("moderate severe"); } else if (uvIndex > 2 && uvIndex <= 5) { $("#uvi-value").addClass("moderate"); $("#uvi-value").removeClass("low severe"); } else if (uvIndex >= 6) { $("#uvi-value").addClass("severe"); $("#uvi-value").removeClass("low moderate"); } }
function uvIndexIndicator(uvIndex) { if (uvIndex <= 2) { $("#uvi-value").addClass("low"); $("#uvi-value").removeClass("moderate severe"); } else if (uvIndex > 2 && uvIndex <= 5) { $("#uvi-value").addClass("moderate"); $("#uvi-value").removeClass("low severe"); } else if (uvIndex >= 6) { $("#uvi-value").addClass("severe"); $("#uvi-value").removeClass("low moderate"); } }
JavaScript
function currentCityTitle(response) { var cityTitle = $("#city-date"); var date = moment().format('L'); var titleIcon = $("<img>"); var iconCode = response.current.weather[0].icon; cityTitle.text(city + "" + "(" + date + ")"); titleIcon.attr("src", displayIcon(iconCode)); cityTitle.append(titleIcon); }
function currentCityTitle(response) { var cityTitle = $("#city-date"); var date = moment().format('L'); var titleIcon = $("<img>"); var iconCode = response.current.weather[0].icon; cityTitle.text(city + "" + "(" + date + ")"); titleIcon.attr("src", displayIcon(iconCode)); cityTitle.append(titleIcon); }
JavaScript
function display5DayForecast(response) { for (var i = 1; i <= 5; i++) { displayDailyDate(response, i); displayDailyForecastIcon(response, i); dailyForecast(response, i); } }
function display5DayForecast(response) { for (var i = 1; i <= 5; i++) { displayDailyDate(response, i); displayDailyForecastIcon(response, i); dailyForecast(response, i); } }
JavaScript
function displayDailyForecastIcon(response, i) { var iconCode = response.daily[i].weather[0].icon; var dailyIcon = "#day-icon-" + i; displayIcon(iconCode); $(dailyIcon).attr("src", displayIcon(iconCode)); }
function displayDailyForecastIcon(response, i) { var iconCode = response.daily[i].weather[0].icon; var dailyIcon = "#day-icon-" + i; displayIcon(iconCode); $(dailyIcon).attr("src", displayIcon(iconCode)); }
JavaScript
function differenceFromPoint(array, point){ var tArray=[]; for( var i=0; i<array.length; i++ ){ tArray.push( RoundNumber( (array[i] - array[point] )/ array[point] * 100.0 ) ); } return tArray; }
function differenceFromPoint(array, point){ var tArray=[]; for( var i=0; i<array.length; i++ ){ tArray.push( RoundNumber( (array[i] - array[point] )/ array[point] * 100.0 ) ); } return tArray; }
JavaScript
disponivel(lin, col) { let tabu = { new: jogo.tab }; if(tabu.new[lin][col] == 0) { return true; } else { return false; } }
disponivel(lin, col) { let tabu = { new: jogo.tab }; if(tabu.new[lin][col] == 0) { return true; } else { return false; } }
JavaScript
verifica_fim() { let tabu = jogo.tab; let res = { qual : 0, ganhador: false }; let i = 0; //verifica linhas e colunas while((res.ganhador == false) && (i <= 2)) { if(tabu[i][i] !== 0) { //0- linha 1- coluna res.ganhador = ctrl.veri_lincol(tabu, i, 0) || ctrl.veri_lincol(tabu, i, 1); res.qual = tabu[i][i]; } i++; } if(res.ganhador) { return res.qual; } //verifica diagonal se ninguem ganhou else { if(ctrl.veri_lincol(tabu, 1, 2)) { return tabu[1][1]; } else{ return 0; } } }
verifica_fim() { let tabu = jogo.tab; let res = { qual : 0, ganhador: false }; let i = 0; //verifica linhas e colunas while((res.ganhador == false) && (i <= 2)) { if(tabu[i][i] !== 0) { //0- linha 1- coluna res.ganhador = ctrl.veri_lincol(tabu, i, 0) || ctrl.veri_lincol(tabu, i, 1); res.qual = tabu[i][i]; } i++; } if(res.ganhador) { return res.qual; } //verifica diagonal se ninguem ganhou else { if(ctrl.veri_lincol(tabu, 1, 2)) { return tabu[1][1]; } else{ return 0; } } }
JavaScript
verifica_velha() { let tabu = jogo.tab; let veri = 0; for(let i = 0; i < 3; i++){ for(let j = 0; j < 3; j++){ if(tabu[i][j] !== 0){ veri++; } } } if(veri == 9){ return true; } else{ return false; } }
verifica_velha() { let tabu = jogo.tab; let veri = 0; for(let i = 0; i < 3; i++){ for(let j = 0; j < 3; j++){ if(tabu[i][j] !== 0){ veri++; } } } if(veri == 9){ return true; } else{ return false; } }
JavaScript
read(action, params, ttl) { const cacheKey = ADCWrapAPI.createCacheKey(action, params); if (!this.cache.has(cacheKey)) { const response = this.send(action, params); const onExpire = () => { if (this.cache.get(cacheKey) === response) { this.cache.delete(cacheKey); } }; response .then(() => new Promise(resolve => setTimeout(resolve, ttl))) .then(onExpire, onExpire); this.cache.set(cacheKey, response); } return this.cache.get(cacheKey); }
read(action, params, ttl) { const cacheKey = ADCWrapAPI.createCacheKey(action, params); if (!this.cache.has(cacheKey)) { const response = this.send(action, params); const onExpire = () => { if (this.cache.get(cacheKey) === response) { this.cache.delete(cacheKey); } }; response .then(() => new Promise(resolve => setTimeout(resolve, ttl))) .then(onExpire, onExpire); this.cache.set(cacheKey, response); } return this.cache.get(cacheKey); }
JavaScript
send(action, params) { if (!action.match(/^\w+\/(latest|\d+\.\d+\.\d+$)/)) { throw new Error(`Invalid \`action\` supplied: ${action}`); } const apiPath = `${this.config.apiUsername}/alarmdotcom/${action}`; return rp({ json: true, qs: Object.assign({ wrapAPIKey: this.config.apiKey }, params), url: `https://wrapapi.com/use/${apiPath}`, }).then( json => { if (!json.success) { const errorMessage = `Request \`${apiPath}\` was unsuccessful:\n` + json.messages.map(message => ' - ' + message).join('\n'); this.log(errorMessage); throw new Error(errorMessage); } if (json.success && action.indexOf('login') != -1 && json.outputScenario === 'Login Failure') { this.log('alarm.com - ' + json.data.errorMessage); } return json; }, reason => { this.log( 'Error in `%s` (status code %s): %s', apiPath, reason.response.statusCode, reason.error ); throw reason.error; } ); }
send(action, params) { if (!action.match(/^\w+\/(latest|\d+\.\d+\.\d+$)/)) { throw new Error(`Invalid \`action\` supplied: ${action}`); } const apiPath = `${this.config.apiUsername}/alarmdotcom/${action}`; return rp({ json: true, qs: Object.assign({ wrapAPIKey: this.config.apiKey }, params), url: `https://wrapapi.com/use/${apiPath}`, }).then( json => { if (!json.success) { const errorMessage = `Request \`${apiPath}\` was unsuccessful:\n` + json.messages.map(message => ' - ' + message).join('\n'); this.log(errorMessage); throw new Error(errorMessage); } if (json.success && action.indexOf('login') != -1 && json.outputScenario === 'Login Failure') { this.log('alarm.com - ' + json.data.errorMessage); } return json; }, reason => { this.log( 'Error in `%s` (status code %s): %s', apiPath, reason.response.statusCode, reason.error ); throw reason.error; } ); }
JavaScript
function textCounter(field, countfield, maxlimit) { if (field.value.length > maxlimit) field.value = field.value.substring(0, maxlimit); else countfield.value = maxlimit - field.value.length; }
function textCounter(field, countfield, maxlimit) { if (field.value.length > maxlimit) field.value = field.value.substring(0, maxlimit); else countfield.value = maxlimit - field.value.length; }
JavaScript
function makeId(){ var text = '' , possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789' ; for (var i = 0; i < 8; i++){ text += possible.charAt(Math.floor(Math.random() * possible.length)); } return text; }
function makeId(){ var text = '' , possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789' ; for (var i = 0; i < 8; i++){ text += possible.charAt(Math.floor(Math.random() * possible.length)); } return text; }
JavaScript
function saveEmail(id, envelope, mailObject){ var object = clone(mailObject); object.id = id; object.time = new Date(); object.read = false; object.envelope = envelope; store.push(object); logger.log('Saving email: ', mailObject.subject); eventEmitter.emit('new', object); }
function saveEmail(id, envelope, mailObject){ var object = clone(mailObject); object.id = id; object.time = new Date(); object.read = false; object.envelope = envelope; store.push(object); logger.log('Saving email: ', mailObject.subject); eventEmitter.emit('new', object); }
JavaScript
function clearTempFolder(){ fs.readdir(tempDir, function(err, files){ if (err) throw err; files.forEach(function(file){ fs.unlink( path.join(tempDir, file), function(err) { if (err) throw err; }); }); }); }
function clearTempFolder(){ fs.readdir(tempDir, function(err, files){ if (err) throw err; files.forEach(function(file){ fs.unlink( path.join(tempDir, file), function(err) { if (err) throw err; }); }); }); }
JavaScript
function deleteAttachments(attachments) { attachments.forEach(function(attachment){ fs.unlink( path.join(tempDir, attachment.contentId), function (err) { if (err) console.error(err); }); }); }
function deleteAttachments(attachments) { attachments.forEach(function(attachment){ fs.unlink( path.join(tempDir, attachment.contentId), function (err) { if (err) console.error(err); }); }); }
JavaScript
function create_dir(path) { const path_exists = fs.existsSync(path); if (path_exists && fs.statSync(path).isDirectory()) { console.log(path + " already exists. Skipping."); return; } try { fs.mkdirSync(path, { recursive: true }); } catch { throw "Folder can not be created at " + path; } }
function create_dir(path) { const path_exists = fs.existsSync(path); if (path_exists && fs.statSync(path).isDirectory()) { console.log(path + " already exists. Skipping."); return; } try { fs.mkdirSync(path, { recursive: true }); } catch { throw "Folder can not be created at " + path; } }
JavaScript
function create_file(path) { const pdir = get_parent_dir(path); try { fs.accessSync(pdir, fs.constants.W_OK); try { fs.closeSync(fs.openSync(path, "w")); } catch { throw "File can not be created at " + path; } } catch { throw "Not enough permissions to create file at " + pdir; } }
function create_file(path) { const pdir = get_parent_dir(path); try { fs.accessSync(pdir, fs.constants.W_OK); try { fs.closeSync(fs.openSync(path, "w")); } catch { throw "File can not be created at " + path; } } catch { throw "Not enough permissions to create file at " + pdir; } }
JavaScript
function write_to_json_file(path, content) { try { fs.accessSync(path, fs.constants.W_OK); try { fs.writeSync(fs.openSync(path, "w"), content); } catch { throw "File can not be reached at " + path; } } catch (e) { throw "Not enough permissions to write at " + path; } }
function write_to_json_file(path, content) { try { fs.accessSync(path, fs.constants.W_OK); try { fs.writeSync(fs.openSync(path, "w"), content); } catch { throw "File can not be reached at " + path; } } catch (e) { throw "Not enough permissions to write at " + path; } }
JavaScript
check_react_install() { try { this.run(this.npx + " --version"); } catch { throw "npx not found. Please install/reinstall node"; } try { this.run(this.npm + " --version"); } catch { throw "npm not found. Please install/reinstall node"; } try { this.run(this.node + " --version"); } catch { throw "nodejs not found. Please install/reinstall node"; } }
check_react_install() { try { this.run(this.npx + " --version"); } catch { throw "npx not found. Please install/reinstall node"; } try { this.run(this.npm + " --version"); } catch { throw "npm not found. Please install/reinstall node"; } try { this.run(this.node + " --version"); } catch { throw "nodejs not found. Please install/reinstall node"; } }
JavaScript
create_react_app(project_name, rename_to, working_dir = ".") { this.run( this.npx + " create-react-app " + project_name + " --use-npm --template cra-template-pwa", working_dir ); const src = path.join(working_dir, project_name); const destn = path.join(".", rename_to); try { fs.renameSync(src, destn); } catch (e) { throw e; } }
create_react_app(project_name, rename_to, working_dir = ".") { this.run( this.npx + " create-react-app " + project_name + " --use-npm --template cra-template-pwa", working_dir ); const src = path.join(working_dir, project_name); const destn = path.join(".", rename_to); try { fs.renameSync(src, destn); } catch (e) { throw e; } }
JavaScript
__getSafeName(link) { varName = ""; var regex = /^[0-9a-z]+$/; for (ch in link) { _ch = link.charAt(ch); if (!_ch.match(regex)) { _ch = "_"; } varName += _ch; } return varName; }
__getSafeName(link) { varName = ""; var regex = /^[0-9a-z]+$/; for (ch in link) { _ch = link.charAt(ch); if (!_ch.match(regex)) { _ch = "_"; } varName += _ch; } return varName; }
JavaScript
__getLinkInfo(link, filepath_from_src, no_var = false) { if (link) { pathToLink = path.join(this.src_dir, filepath_from_src, link); pathToIndexLink = path.join(pathToLink, "index.html"); stats_pathToLink = fs.statSync(pathToLink); stats_pathToIndexLink = fs.statSync(pathToIndexLink); if (stats_pathToLink || stats_pathToIndexLink) { var_ = this.__getSafeName(link); if (no_var) { this.add_to_import.push("import " + link); return undefined; } else { this.add_to_import.push("import " + var_ + " from " + link); } this.add_variables.push(var_); return "{" + var_ + "}"; } } else { return link; } }
__getLinkInfo(link, filepath_from_src, no_var = false) { if (link) { pathToLink = path.join(this.src_dir, filepath_from_src, link); pathToIndexLink = path.join(pathToLink, "index.html"); stats_pathToLink = fs.statSync(pathToLink); stats_pathToIndexLink = fs.statSync(pathToIndexLink); if (stats_pathToLink || stats_pathToIndexLink) { var_ = this.__getSafeName(link); if (no_var) { this.add_to_import.push("import " + link); return undefined; } else { this.add_to_import.push("import " + var_ + " from " + link); } this.add_variables.push(var_); return "{" + var_ + "}"; } } else { return link; } }
JavaScript
__getAttrsWithLink(attrs, linkAttr, filepath_from_src, no_var = false) { final_attrs = {}; for (const [key, value] of Object.entries(attrs)) { if (key == linkAttr) { link_info = this.__getLinkInfo(value, filepath_from_src, no_var); if (link_info == undefined) { return; } final_attrs[linkAttr] = link_info; } else { final_attrs[key] = value; } } return final_attrs; }
__getAttrsWithLink(attrs, linkAttr, filepath_from_src, no_var = false) { final_attrs = {}; for (const [key, value] of Object.entries(attrs)) { if (key == linkAttr) { link_info = this.__getLinkInfo(value, filepath_from_src, no_var); if (link_info == undefined) { return; } final_attrs[linkAttr] = link_info; } else { final_attrs[key] = value; } } return final_attrs; }
JavaScript
__getAttrsForRouterLink(attrs, filepath_from_src) { final_attrs = {}; is_internal = false; for (const [key, value] of Object.entries(attrs)) { if (key == "href") { href_info = value; pathRef = path.join(this.src_dir, filepath_from_src, href_info); pathRefIndex = path.join( this.src_dir, filepath_from_src, href_info, "index.html" ); stats_pathToLink = fs.statSync(pathToLink); stats_pathToIndexLink = fs.statSync(pathToIndexLink); if (stats_pathToLink || stats_pathToIndexLink) { htmlPath = path.normalize(path.join(filepath_from_src, href_info)); jsPath = htmlPath.split(path.sep).join("/"); jsPath = jsPath.replace(".html", ""); if (jsPath == "index") { jsPath = "/"; } is_internal = true; final_attrs["to"] = jsPath; } else { final_attrs["href"] = href_info; } } else { final_attrs[key] = value; } } return [final_attrs, is_internal]; }
__getAttrsForRouterLink(attrs, filepath_from_src) { final_attrs = {}; is_internal = false; for (const [key, value] of Object.entries(attrs)) { if (key == "href") { href_info = value; pathRef = path.join(this.src_dir, filepath_from_src, href_info); pathRefIndex = path.join( this.src_dir, filepath_from_src, href_info, "index.html" ); stats_pathToLink = fs.statSync(pathToLink); stats_pathToIndexLink = fs.statSync(pathToIndexLink); if (stats_pathToLink || stats_pathToIndexLink) { htmlPath = path.normalize(path.join(filepath_from_src, href_info)); jsPath = htmlPath.split(path.sep).join("/"); jsPath = jsPath.replace(".html", ""); if (jsPath == "index") { jsPath = "/"; } is_internal = true; final_attrs["to"] = jsPath; } else { final_attrs["href"] = href_info; } } else { final_attrs[key] = value; } } return [final_attrs, is_internal]; }
JavaScript
__customTagAttrsHandler(attrs, tag_handler, filepath_from_src) { final_attrs = {}; if (tag_handler == this.__A_TAG_HANDLER) { res = this.__getAttrsForRouterLink(attrs, filepath_from_src); final_attrs = res[0]; is_internal_link = res[1]; if (!this.router_link_imported && is_internal_link) { this.add_to_import.push('import Link from "react-router-dom";'); this.router_link_imported = true; } } else if (tag_handler == this.IMAGE_TAG_HANDLER) { final_attrs = this.__getAttrsWithLink(attrs, "src", filepath_from_src); } else if (tag_handler == this.__SCRIPT_TAG_HANDLER) { if ("src" in attrs) { final_attrs = this.__getAttrsWithLink(attrs, "src", filepath_from_src); } else { return undefined; } } else if (tag_handler == this.__STYLE_TAG_HANDLER) { return undefined; } else if (tag_handler == this.__LINK_TAG_HANDLER) { if (attrs["rel"] == "stylesheet") { final_attrs = this.__getAttrsWithLink( attrs, "href", filepath_from_src, (no_var = true) ); } return None; } return final_attrs; }
__customTagAttrsHandler(attrs, tag_handler, filepath_from_src) { final_attrs = {}; if (tag_handler == this.__A_TAG_HANDLER) { res = this.__getAttrsForRouterLink(attrs, filepath_from_src); final_attrs = res[0]; is_internal_link = res[1]; if (!this.router_link_imported && is_internal_link) { this.add_to_import.push('import Link from "react-router-dom";'); this.router_link_imported = true; } } else if (tag_handler == this.IMAGE_TAG_HANDLER) { final_attrs = this.__getAttrsWithLink(attrs, "src", filepath_from_src); } else if (tag_handler == this.__SCRIPT_TAG_HANDLER) { if ("src" in attrs) { final_attrs = this.__getAttrsWithLink(attrs, "src", filepath_from_src); } else { return undefined; } } else if (tag_handler == this.__STYLE_TAG_HANDLER) { return undefined; } else if (tag_handler == this.__LINK_TAG_HANDLER) { if (attrs["rel"] == "stylesheet") { final_attrs = this.__getAttrsWithLink( attrs, "href", filepath_from_src, (no_var = true) ); } return None; } return final_attrs; }
JavaScript
__getReactAttrs(attrs) { final_attrs = {}; for (const [key, value] of Object.entries(attrs)) { if (key == "style") { continue; } if (key.startsWith("on")) { continue; } if (key in this.props_map) { useKey = this.props_map[attrKey]; } else { useKey = key; } final_attrs[useKey] = value; } return final_attrs; }
__getReactAttrs(attrs) { final_attrs = {}; for (const [key, value] of Object.entries(attrs)) { if (key == "style") { continue; } if (key.startsWith("on")) { continue; } if (key in this.props_map) { useKey = this.props_map[attrKey]; } else { useKey = key; } final_attrs[useKey] = value; } return final_attrs; }
JavaScript
__replaceAttrs($, tag_name, or_attrs, f_attrs) { if (or_attrs == f_attrs) { return; } const selector = $(this.__getTagWithAttribute(tag_name, or_attrs)); var htmlTag = selector.first().attr(); upperAttrs = {}; lowerAttrs = {}; if (htmlTag == undefined) { for (const [attr] of Object.entries(or_attrs)) { upperAttrs[attr] = or_attrs[attr].toUpperCase(); lowerAttrs[attr] = or_attrs[attr].toLowerCase(); } htmlTag = $(this.__getTagWithAttribute(tag_name, upperAttrs)) .first() .attr(); if (htmlTag == undefined) { htmlTag = $(this.__getTagWithAttribute(tag_name, lowerAttrs)) .first() .attr(); } } if (htmlTag != undefined) { $(htmlTag.first().attr(f_attrs)); if (tag_name == "a" && "to" in f_attrs) { $((htmlTag.first().get(0).tagName = "Link")); } } }
__replaceAttrs($, tag_name, or_attrs, f_attrs) { if (or_attrs == f_attrs) { return; } const selector = $(this.__getTagWithAttribute(tag_name, or_attrs)); var htmlTag = selector.first().attr(); upperAttrs = {}; lowerAttrs = {}; if (htmlTag == undefined) { for (const [attr] of Object.entries(or_attrs)) { upperAttrs[attr] = or_attrs[attr].toUpperCase(); lowerAttrs[attr] = or_attrs[attr].toLowerCase(); } htmlTag = $(this.__getTagWithAttribute(tag_name, upperAttrs)) .first() .attr(); if (htmlTag == undefined) { htmlTag = $(this.__getTagWithAttribute(tag_name, lowerAttrs)) .first() .attr(); } } if (htmlTag != undefined) { $(htmlTag.first().attr(f_attrs)); if (tag_name == "a" && "to" in f_attrs) { $((htmlTag.first().get(0).tagName = "Link")); } } }
JavaScript
__deleteTag($, tag_name, attrs) { const selector = $(this.__getTagWithAttribute(tag_name, attrs)); var htmlTag = selector.first().attr(); upperAttrs = {}; lowerAttrs = {}; if (htmlTag == undefined) { for (const [attr] of Object.entries(attrs)) { upperAttrs[attr] = attrs[attr].toUpperCase(); lowerAttrs[attr] = attrs[attr].toLowerCase(); } htmlTag = $(this.__getTagWithAttribute(tag_name, upperAttrs)) .first() .attr(); if (htmlTag == undefined) { htmlTag = $(this.__getTagWithAttribute(tag_name, lowerAttrs)) .first() .attr(); } } if (htmlTag != undefined) { htmlTag.remove(); } }
__deleteTag($, tag_name, attrs) { const selector = $(this.__getTagWithAttribute(tag_name, attrs)); var htmlTag = selector.first().attr(); upperAttrs = {}; lowerAttrs = {}; if (htmlTag == undefined) { for (const [attr] of Object.entries(attrs)) { upperAttrs[attr] = attrs[attr].toUpperCase(); lowerAttrs[attr] = attrs[attr].toLowerCase(); } htmlTag = $(this.__getTagWithAttribute(tag_name, upperAttrs)) .first() .attr(); if (htmlTag == undefined) { htmlTag = $(this.__getTagWithAttribute(tag_name, lowerAttrs)) .first() .attr(); } } if (htmlTag != undefined) { htmlTag.remove(); } }
JavaScript
__generateReactFileContent($, function_name, filepath_from_src) { styleTags = []; $("style").each((i, el) => { styleTags.push($(el).toString()); }); scriptTags = []; $("script").each((i, el) => { var s = $(el).toString(); if (!s.includes("src")) { scriptTags.push(s); } }); let arr = $.html().match(/\<(.*?)\>/g); arr.shift(); let tag_arr = arr.filter((item) => !item.startsWith("</")); let tag_with_attributes = this.get_tags_with_attributes(tag_arr); let reactCodeMapper = new ReactCodeMapper( this.src_dir, this.dest_dir, this.props_map ); let react_map = reactCodeMapper.getReactMap( tag_with_attributes, filepath_from_src ); let final_tags = react_map["tags"]; let react_variables = react_map["variables"]; for ( let i = 0; i < Math.min(tag_with_attributes.length, final_tags.length); i++ ) { let orignal_tag_dict = tag_with_attributes[i]; let final_tag_dict = final_tags[i]; let or_tag_name = Object.keys(orignal_tag_dict)[0]; let or_attrs = orignal_tag_dict[or_tag_name]; let final_tag_name = Object.keys(final_tag_dict)[0]; let final_attrs = final_tag_dict[final_tag_name]; if (or_tag_name == final_tag_name) { if (final_attrs == undefined) { this.__deleteTag($, or_tag_name, or_attrs); } else { this.__replaceAttrs($, or_tag_name, or_attrs, final_attrs); } } else { throw "There's an error in processing " + or_tag_name; } } let reactHead = undefined; if ($.html().toString().includes("<head>")) { head_str = $("head").toString(); $("head").first().get(0).tagName = "Helmet"; reactHead = head_str.replace(new RegExp("head", "g"), "Helmet"); } else { if (styleTags.length > 0) { $("html").append("<New_Tag></New_Tag>"); reactHead = $("new_tag").first().get(0).tagName = "Helmet"; } } reacthead_start = reactHead.substring(0, reactHead.length - 9); if (styleTags.length > 0) { for (let i = 0; i < styleTags.length; i++) { reacthead_start += styleTags[i]; } reactHead = reacthead_start + "</Helmet>"; } let body_str = ""; $("body").each((i, el) => { body_str += $(el).toString(); }); body_str = body_str.substring(6, body_str.length - 7); let content_str = ""; if (reactHead) { content_str = reactHead + body_str; react_map["imports"] += "import Helmet from 'react-helmet';"; } else { content_str = reactHead + body_str; } for (let j = 0; j < react_variables.length; j++) { variable = react_variables[j]; content_str = content_str.replace( new RegExp('"{' + variable + '}"', "g"), "{" + variable + "}" ); } let useEffect = ""; if (scriptTags.length) { react_map["imports"] += "import React, { useEffect } from 'react';"; let scriptContent = ""; $("script").each((i, el) => { let script_str = $(el).toString(); let script_sub_str = script_str.substring(8, script_str.length - 9); scriptContent += script_sub_str; }); useEffect = "useEffect(() => {" + scriptContent + "}, []);"; } else { react_map["imports"] += "import React from 'react';"; useEffect = ""; } if (styleTags.length > 0) { content_str.replace(new RegExp("<style", "g"), "<style>{`"); content_str.replace(new RegExp("</style>", "g"), "`}</style>"); } let react_function = "function " + function_name + "() { " + useEffect + " return (<>" + content_str + "</>);}"; return ( "\n" + react_map["imports"] + "\n\n" + react_function + "\n\n" + "export default" + function_name ); }
__generateReactFileContent($, function_name, filepath_from_src) { styleTags = []; $("style").each((i, el) => { styleTags.push($(el).toString()); }); scriptTags = []; $("script").each((i, el) => { var s = $(el).toString(); if (!s.includes("src")) { scriptTags.push(s); } }); let arr = $.html().match(/\<(.*?)\>/g); arr.shift(); let tag_arr = arr.filter((item) => !item.startsWith("</")); let tag_with_attributes = this.get_tags_with_attributes(tag_arr); let reactCodeMapper = new ReactCodeMapper( this.src_dir, this.dest_dir, this.props_map ); let react_map = reactCodeMapper.getReactMap( tag_with_attributes, filepath_from_src ); let final_tags = react_map["tags"]; let react_variables = react_map["variables"]; for ( let i = 0; i < Math.min(tag_with_attributes.length, final_tags.length); i++ ) { let orignal_tag_dict = tag_with_attributes[i]; let final_tag_dict = final_tags[i]; let or_tag_name = Object.keys(orignal_tag_dict)[0]; let or_attrs = orignal_tag_dict[or_tag_name]; let final_tag_name = Object.keys(final_tag_dict)[0]; let final_attrs = final_tag_dict[final_tag_name]; if (or_tag_name == final_tag_name) { if (final_attrs == undefined) { this.__deleteTag($, or_tag_name, or_attrs); } else { this.__replaceAttrs($, or_tag_name, or_attrs, final_attrs); } } else { throw "There's an error in processing " + or_tag_name; } } let reactHead = undefined; if ($.html().toString().includes("<head>")) { head_str = $("head").toString(); $("head").first().get(0).tagName = "Helmet"; reactHead = head_str.replace(new RegExp("head", "g"), "Helmet"); } else { if (styleTags.length > 0) { $("html").append("<New_Tag></New_Tag>"); reactHead = $("new_tag").first().get(0).tagName = "Helmet"; } } reacthead_start = reactHead.substring(0, reactHead.length - 9); if (styleTags.length > 0) { for (let i = 0; i < styleTags.length; i++) { reacthead_start += styleTags[i]; } reactHead = reacthead_start + "</Helmet>"; } let body_str = ""; $("body").each((i, el) => { body_str += $(el).toString(); }); body_str = body_str.substring(6, body_str.length - 7); let content_str = ""; if (reactHead) { content_str = reactHead + body_str; react_map["imports"] += "import Helmet from 'react-helmet';"; } else { content_str = reactHead + body_str; } for (let j = 0; j < react_variables.length; j++) { variable = react_variables[j]; content_str = content_str.replace( new RegExp('"{' + variable + '}"', "g"), "{" + variable + "}" ); } let useEffect = ""; if (scriptTags.length) { react_map["imports"] += "import React, { useEffect } from 'react';"; let scriptContent = ""; $("script").each((i, el) => { let script_str = $(el).toString(); let script_sub_str = script_str.substring(8, script_str.length - 9); scriptContent += script_sub_str; }); useEffect = "useEffect(() => {" + scriptContent + "}, []);"; } else { react_map["imports"] += "import React from 'react';"; useEffect = ""; } if (styleTags.length > 0) { content_str.replace(new RegExp("<style", "g"), "<style>{`"); content_str.replace(new RegExp("</style>", "g"), "`}</style>"); } let react_function = "function " + function_name + "() { " + useEffect + " return (<>" + content_str + "</>);}"; return ( "\n" + react_map["imports"] + "\n\n" + react_function + "\n\n" + "export default" + function_name ); }
JavaScript
__getReactComponentName(link) { varName = ""; var regex = /^[0-9a-z]+$/; for (ch in link) { _ch = link.charAt(ch); if (!_ch.match(regex)) { _ch = "_"; } varName += _ch; } return "REACTONITE" + varName.toUpperCase(); }
__getReactComponentName(link) { varName = ""; var regex = /^[0-9a-z]+$/; for (ch in link) { _ch = link.charAt(ch); if (!_ch.match(regex)) { _ch = "_"; } varName += _ch; } return "REACTONITE" + varName.toUpperCase(); }
JavaScript
__rebuildIndexJs() { pathToIndexJs = path.join(this.dest_dir, "src", "index.js"); if (!fs.statSync(pathToIndexJs)) { throw new Error( "Looks like you are missing index.js file in \ React directory! It seems to be an NPM/React issue rather." ); } fs.open(path, "w", function (err, fd) { if (err) { throw "Error opening the file" + err; } file_content = this.__generateIndexJsContent(); fs.write(fd, file_content, 0, file_content.length, null, function (err) { if (err) { throw "Error writing file: " + err; } }); }); NodeWrapper().prettify((path = pathToIndexJs)); }
__rebuildIndexJs() { pathToIndexJs = path.join(this.dest_dir, "src", "index.js"); if (!fs.statSync(pathToIndexJs)) { throw new Error( "Looks like you are missing index.js file in \ React directory! It seems to be an NPM/React issue rather." ); } fs.open(path, "w", function (err, fd) { if (err) { throw "Error opening the file" + err; } file_content = this.__generateIndexJsContent(); fs.write(fd, file_content, 0, file_content.length, null, function (err) { if (err) { throw "Error writing file: " + err; } }); }); NodeWrapper().prettify((path = pathToIndexJs)); }
JavaScript
__addRoutesToIndexLinkArray(filePathFromSrc, filenameNoExt) { if (filenameNoExt == "index") { htmlPath = path.normalize(filePathFromSrc); jsPath = htmlPath.split(path.sep).join("./"); this.index_routes[jsPath] = "./" + jsPath + "/index"; } else { htmlPath = path.normalize(path.join(filePathFromSrc, filenameNoExt)); jsPath = htmlPath.split(path.sep).join("./"); this.index_routes[jsPath] = "./" + jsPath; } }
__addRoutesToIndexLinkArray(filePathFromSrc, filenameNoExt) { if (filenameNoExt == "index") { htmlPath = path.normalize(filePathFromSrc); jsPath = htmlPath.split(path.sep).join("./"); this.index_routes[jsPath] = "./" + jsPath + "/index"; } else { htmlPath = path.normalize(path.join(filePathFromSrc, filenameNoExt)); jsPath = htmlPath.split(path.sep).join("./"); this.index_routes[jsPath] = "./" + jsPath; } }
JavaScript
__generateIndexJsContent() { var router = 'import {\n BrowserRouter as Router,\n Switch, \nRoute \n} from "react-router-dom";'; var imports = []; var routes = []; for (const [key, value] of Object.entries(this.index_routes)) { var componentName = this.__getReactComponentName(value); var importReact = "import " + componentName + ' from "' + value + '";'; imports.push(importReact); var routeReact = '<Route path="/' + key + '">\n<' + componentName + "/>\n</Route>"; routes.push(routeReact); } imports = imports.join("/"); routes = routes.join("/"); return ( 'import React from "react";\n\ import ReactDOM from "react-dom";\n\ import * as serviceWorkerRegistration from ./serviceWorkerRegistration";\n\ import reportWebVitals from "./reportWebVitals";\n' + router + 'import App from "./App";\n' + imports + "ReactDOM.render(\n\ <Router>\n\ <Switch>\n" + routes + '<Route path="/">\n\ <App />\n\ </Route>\n\ </Switch>\n\ </Router>,\n\ document.getElementById("root")\n\ );\n' + "// If you dont want your app to work offline, you can change\n\ // register() to unregister() below. Note this comes with some\n\ // pitfalls. Learn more about service workers: https://cra.link/PWA\n\ serviceWorkerRegistration.register();\n\ // If you want to start measuring performance in your app, pass a\n\ // function to log results (for example: reportWebVitals(console.log))\n\ // or send to analytics endpoint. Learn more: https://bit.ly/CRA-vitals\n\ reportWebVitals();\n" ); }
__generateIndexJsContent() { var router = 'import {\n BrowserRouter as Router,\n Switch, \nRoute \n} from "react-router-dom";'; var imports = []; var routes = []; for (const [key, value] of Object.entries(this.index_routes)) { var componentName = this.__getReactComponentName(value); var importReact = "import " + componentName + ' from "' + value + '";'; imports.push(importReact); var routeReact = '<Route path="/' + key + '">\n<' + componentName + "/>\n</Route>"; routes.push(routeReact); } imports = imports.join("/"); routes = routes.join("/"); return ( 'import React from "react";\n\ import ReactDOM from "react-dom";\n\ import * as serviceWorkerRegistration from ./serviceWorkerRegistration";\n\ import reportWebVitals from "./reportWebVitals";\n' + router + 'import App from "./App";\n' + imports + "ReactDOM.render(\n\ <Router>\n\ <Switch>\n" + routes + '<Route path="/">\n\ <App />\n\ </Route>\n\ </Switch>\n\ </Router>,\n\ document.getElementById("root")\n\ );\n' + "// If you dont want your app to work offline, you can change\n\ // register() to unregister() below. Note this comes with some\n\ // pitfalls. Learn more about service workers: https://cra.link/PWA\n\ serviceWorkerRegistration.register();\n\ // If you want to start measuring performance in your app, pass a\n\ // function to log results (for example: reportWebVitals(console.log))\n\ // or send to analytics endpoint. Learn more: https://bit.ly/CRA-vitals\n\ reportWebVitals();\n" ); }
JavaScript
transpileFile(filepath) { components = filepath.split(path.sep); index = components.indexOf("src"); file_name_with_extension = components.pop(); file_name_split = file_name_with_extension.split("."); filenameWithNoExtension = file_name_split[0]; extension = file_name_split[1]; filePathFromSrc = components.slice(index + 1).join("/"); if (extension != "html") { var dest_filepath = path.join( this.dest_dir, "src", filePathFromSrc, file_name_with_extension ); if (this.verbose) { console.log( "Copying file " + String(filepath) + " -> " + String(dest_filepath) ); } try { fs.mkdirSync(path.dirname(dest_filepath), true); } catch { console.log("Error making a new directory"); } fse.copyFileSync(filepath, dest_filepath); return; } var stats = fs.statSync(filepath); if (stats || !stats.isFile()) { throw filepath + " file not found"; } var is_entry_point = false; var entry_point_html = path.join(this.src_dir, "index.html"); if (entry_point_html == filepath) { is_entry_point = true; filenameWithNoExtension = "App"; } file_name_with_extension = filenameWithNoExtension + ".js"; stats = fs.statSync(path.join(this.dest_dir, "src")); if (stats || !stats.isDirectory()) { throw ( "Looks like your React project didn't get \n\ created please check your " + this.dest_dir + " for a src \n\ folder" ); } dest_filepath = path.join( this.dest_dir, "src", filePathFromSrc, file_name_with_extension ); if (this.verbose) { console.log( "Transpiling file " + String(filepath) + " -> " + String(dest_filepath) ); } var htmlString = fs.readFileSync(filepath); const $ = cheerio.load(htmlString); // removing comments $("html") .contents() .filter(function () { return this.type === "comment"; }) .remove(); try { fs.mkdirSync(path.dirname(dest_filepath), true); } catch { console.log("Error making a new directory"); } filenameWithNoExtension = filenameWithNoExtension.charAt(0).toUpperCase() + filenameWithNoExtension.substring(1).toLowerCase(); var file_content = this.__generateReactFileContent( $, filenameWithNoExtension, filePathFromSrc ); try { var fd = fs.openSync(dest_filepath, "w"); try { fs.close(fs.write(fd, file_content)); } catch { throw new Error("Error writing file"); } } catch { throw new Error("File can not be reached at ", path); } NodeWrapper().prettify((path = dest_filepath)); if (!is_entry_point) { this.__addRoutesToIndexLinkArray( filePathFromSrc, filenameWithNoExtension ); } }
transpileFile(filepath) { components = filepath.split(path.sep); index = components.indexOf("src"); file_name_with_extension = components.pop(); file_name_split = file_name_with_extension.split("."); filenameWithNoExtension = file_name_split[0]; extension = file_name_split[1]; filePathFromSrc = components.slice(index + 1).join("/"); if (extension != "html") { var dest_filepath = path.join( this.dest_dir, "src", filePathFromSrc, file_name_with_extension ); if (this.verbose) { console.log( "Copying file " + String(filepath) + " -> " + String(dest_filepath) ); } try { fs.mkdirSync(path.dirname(dest_filepath), true); } catch { console.log("Error making a new directory"); } fse.copyFileSync(filepath, dest_filepath); return; } var stats = fs.statSync(filepath); if (stats || !stats.isFile()) { throw filepath + " file not found"; } var is_entry_point = false; var entry_point_html = path.join(this.src_dir, "index.html"); if (entry_point_html == filepath) { is_entry_point = true; filenameWithNoExtension = "App"; } file_name_with_extension = filenameWithNoExtension + ".js"; stats = fs.statSync(path.join(this.dest_dir, "src")); if (stats || !stats.isDirectory()) { throw ( "Looks like your React project didn't get \n\ created please check your " + this.dest_dir + " for a src \n\ folder" ); } dest_filepath = path.join( this.dest_dir, "src", filePathFromSrc, file_name_with_extension ); if (this.verbose) { console.log( "Transpiling file " + String(filepath) + " -> " + String(dest_filepath) ); } var htmlString = fs.readFileSync(filepath); const $ = cheerio.load(htmlString); // removing comments $("html") .contents() .filter(function () { return this.type === "comment"; }) .remove(); try { fs.mkdirSync(path.dirname(dest_filepath), true); } catch { console.log("Error making a new directory"); } filenameWithNoExtension = filenameWithNoExtension.charAt(0).toUpperCase() + filenameWithNoExtension.substring(1).toLowerCase(); var file_content = this.__generateReactFileContent( $, filenameWithNoExtension, filePathFromSrc ); try { var fd = fs.openSync(dest_filepath, "w"); try { fs.close(fs.write(fd, file_content)); } catch { throw new Error("Error writing file"); } } catch { throw new Error("File can not be reached at ", path); } NodeWrapper().prettify((path = dest_filepath)); if (!is_entry_point) { this.__addRoutesToIndexLinkArray( filePathFromSrc, filenameWithNoExtension ); } }
JavaScript
transpile_project(copy_static = true) { var entry_point_html = path.join(this.src_dir, "index.html"); var stats = fs.statSync(entry_point_html); if (stats || !stats.isFile()) { throw "Entry point file doesn't exist at " + String(entry_point_html); } if (this.verbose) { console.log("Transpiling files..."); } var filepaths = glob.sync(path.join("src", "**/**")); for (var i = 0; i < filepaths.length; i++) { var file = filepaths[i]; if (fs.statSync(file).isFile()) { var components = file.split(path.sep); var file_name_with_extension = components.pop(); var file_name_split = file_name_with_extension.split("."); var extension = file_name_split[1]; if (extension == "html" || copy_static) { this.transpileFile(file); } } } this.__rebuildIndexJs(); }
transpile_project(copy_static = true) { var entry_point_html = path.join(this.src_dir, "index.html"); var stats = fs.statSync(entry_point_html); if (stats || !stats.isFile()) { throw "Entry point file doesn't exist at " + String(entry_point_html); } if (this.verbose) { console.log("Transpiling files..."); } var filepaths = glob.sync(path.join("src", "**/**")); for (var i = 0; i < filepaths.length; i++) { var file = filepaths[i]; if (fs.statSync(file).isFile()) { var components = file.split(path.sep); var file_name_with_extension = components.pop(); var file_name_split = file_name_with_extension.split("."); var extension = file_name_split[1]; if (extension == "html" || copy_static) { this.transpileFile(file); } } } this.__rebuildIndexJs(); }
JavaScript
save_config() { if (!fs.existsSync(this.config_path)) { create_file(this.config_path); } write_to_json_file(this.config_path, JSON.stringify(this.config)); }
save_config() { if (!fs.existsSync(this.config_path)) { create_file(this.config_path); } write_to_json_file(this.config_path, JSON.stringify(this.config)); }
JavaScript
function saveHtml(content, loc) { var html_front = '<!doctype html><html lang="en"><head><meta charset="utf-8"/><title>The HTML5 Herald</title><meta name="description" content="The HTML5 Herald"/><meta name="author" content="SitePoint"/><link rel="stylesheet" href="./main.css"/></head><body>'; var html_back = "</body></html>"; var html_content = html_front + content + html_back; fs.writeFileSync(path.join(loc, "index.html"), html_content, { flag: "w+" }); }
function saveHtml(content, loc) { var html_front = '<!doctype html><html lang="en"><head><meta charset="utf-8"/><title>The HTML5 Herald</title><meta name="description" content="The HTML5 Herald"/><meta name="author" content="SitePoint"/><link rel="stylesheet" href="./main.css"/></head><body>'; var html_back = "</body></html>"; var html_content = html_front + content + html_back; fs.writeFileSync(path.join(loc, "index.html"), html_content, { flag: "w+" }); }
JavaScript
function _persistMarvelCache(cache) { if (storage) { storage.setItem('MarvelQuizApp', angular.toJson(cache)); } }
function _persistMarvelCache(cache) { if (storage) { storage.setItem('MarvelQuizApp', angular.toJson(cache)); } }
JavaScript
function _future(value) { var deferred = $q.defer(); deferred.resolve(value); return deferred.promise; }
function _future(value) { var deferred = $q.defer(); deferred.resolve(value); return deferred.promise; }
JavaScript
function _marvelServiceError(res) { var errorLog = ''; if (res.status === 429) { GoogleAnalytics.marvelServiceLimitExceeded(); MarvelApiStatus.apiLimitExceeded(true); } else if(res.status === 0) { GoogleAnalytics.marvelServiceError('0 - Aborted'); } else { errorLog += res.status; if (res.data.code) { errorLog += ' - ' + res.data.code; } if (res.data.message) { errorLog += ' - ' + res.data.message; } GoogleAnalytics.marvelServiceError(errorLog); } return $q.reject(res); }
function _marvelServiceError(res) { var errorLog = ''; if (res.status === 429) { GoogleAnalytics.marvelServiceLimitExceeded(); MarvelApiStatus.apiLimitExceeded(true); } else if(res.status === 0) { GoogleAnalytics.marvelServiceError('0 - Aborted'); } else { errorLog += res.status; if (res.data.code) { errorLog += ' - ' + res.data.code; } if (res.data.message) { errorLog += ' - ' + res.data.message; } GoogleAnalytics.marvelServiceError(errorLog); } return $q.reject(res); }
JavaScript
function totalCharacters() { var CACHE_KEY = 'totalCharacters'; var cacheValue = Cache.get(CACHE_KEY); if (cacheValue) { GoogleAnalytics.marvelServiceCacheHit('characters'); return _future(cacheValue); } else { return $http.get(BASE_URL + '/characters', { params: { limit: 1, apikey: apiKey } }).then( function (res) { var count = res.data.data.total; Cache.put(CACHE_KEY, count); GoogleAnalytics.marvelServiceRequest('characters'); return count; }, _marvelServiceError ); } }
function totalCharacters() { var CACHE_KEY = 'totalCharacters'; var cacheValue = Cache.get(CACHE_KEY); if (cacheValue) { GoogleAnalytics.marvelServiceCacheHit('characters'); return _future(cacheValue); } else { return $http.get(BASE_URL + '/characters', { params: { limit: 1, apikey: apiKey } }).then( function (res) { var count = res.data.data.total; Cache.put(CACHE_KEY, count); GoogleAnalytics.marvelServiceRequest('characters'); return count; }, _marvelServiceError ); } }
JavaScript
function characters(params) { var CACHE_KEY = 'characters/' + angular.toJson(params); var cacheValue = Cache.get(CACHE_KEY); if (cacheValue) { GoogleAnalytics.marvelServiceCacheHit('characters'); return _future(cacheValue); } else { return $http.get(BASE_URL + '/characters', { params: angular.extend(params, { apikey: apiKey }) }).then( function (res) { var characters = res.data.data.results; Cache.put(CACHE_KEY, characters); GoogleAnalytics.marvelServiceRequest('characters'); return characters; }, _marvelServiceError ); } }
function characters(params) { var CACHE_KEY = 'characters/' + angular.toJson(params); var cacheValue = Cache.get(CACHE_KEY); if (cacheValue) { GoogleAnalytics.marvelServiceCacheHit('characters'); return _future(cacheValue); } else { return $http.get(BASE_URL + '/characters', { params: angular.extend(params, { apikey: apiKey }) }).then( function (res) { var characters = res.data.data.results; Cache.put(CACHE_KEY, characters); GoogleAnalytics.marvelServiceRequest('characters'); return characters; }, _marvelServiceError ); } }
JavaScript
function _charactersGetPage(pageNum) { return MarvelWrapper.characters({ limit: PAGE_SIZE, offset: PAGE_SIZE * ( pageNum - 1 ) }); }
function _charactersGetPage(pageNum) { return MarvelWrapper.characters({ limit: PAGE_SIZE, offset: PAGE_SIZE * ( pageNum - 1 ) }); }
JavaScript
function _charactersGetRandom(totalCharacters) { var randomCharacterNum, randomPage; if (randomIdsPtr < 0) { randomIds = Utils.getRandomArray(0, totalCharacters - 1); randomIdsPtr = totalCharacters - 1; } randomCharacterNum = randomIds[randomIdsPtr--]; randomPage = Math.ceil((randomCharacterNum + 1 ) / PAGE_SIZE); return _charactersGetPage(randomPage) .then(function (characters) { return characters[randomCharacterNum % PAGE_SIZE]; }); }
function _charactersGetRandom(totalCharacters) { var randomCharacterNum, randomPage; if (randomIdsPtr < 0) { randomIds = Utils.getRandomArray(0, totalCharacters - 1); randomIdsPtr = totalCharacters - 1; } randomCharacterNum = randomIds[randomIdsPtr--]; randomPage = Math.ceil((randomCharacterNum + 1 ) / PAGE_SIZE); return _charactersGetPage(randomPage) .then(function (characters) { return characters[randomCharacterNum % PAGE_SIZE]; }); }
JavaScript
function _charactersGetRandomWithAvailableImage(totalCharacters) { return _charactersGetRandom(totalCharacters) .then(function (character) { if (isImageAvailable(character)) { return character; } else { return _charactersGetRandomWithAvailableImage(totalCharacters); } }); }
function _charactersGetRandomWithAvailableImage(totalCharacters) { return _charactersGetRandom(totalCharacters) .then(function (character) { if (isImageAvailable(character)) { return character; } else { return _charactersGetRandomWithAvailableImage(totalCharacters); } }); }
JavaScript
function shuffleArray(array) { var currentIndex = array.length, tmp, randomIndex; // while there are elements to shuffle... while (0 !== currentIndex) { // pick a remaining element... randomIndex = Math.floor(Math.random() * currentIndex); currentIndex -= 1; // swap it with the current element. tmp = array[currentIndex]; array[currentIndex] = array[randomIndex]; array[randomIndex] = tmp; } return array; }
function shuffleArray(array) { var currentIndex = array.length, tmp, randomIndex; // while there are elements to shuffle... while (0 !== currentIndex) { // pick a remaining element... randomIndex = Math.floor(Math.random() * currentIndex); currentIndex -= 1; // swap it with the current element. tmp = array[currentIndex]; array[currentIndex] = array[randomIndex]; array[randomIndex] = tmp; } return array; }
JavaScript
function buildImageUrl(thumbnailObj) { var url = thumbnailObj.path; url += '/landscape_incredible.'; url += thumbnailObj.extension; return url; }
function buildImageUrl(thumbnailObj) { var url = thumbnailObj.path; url += '/landscape_incredible.'; url += thumbnailObj.extension; return url; }
JavaScript
function _updateScoreToCurrentVersion(scores) { if (angular.isUndefined(scores.version)) { scores.version = 1; } if (scores.version === 1) { scores.version = 2; scores.points = {}; } return scores; }
function _updateScoreToCurrentVersion(scores) { if (angular.isUndefined(scores.version)) { scores.version = 1; } if (scores.version === 1) { scores.version = 2; scores.points = {}; } return scores; }
JavaScript
function _getAttemptedQuizzesTotal() { var result = 0; angular.forEach(scoreValues.attemptedQuizzes, function (val) { result += val; }); return result; }
function _getAttemptedQuizzesTotal() { var result = 0; angular.forEach(scoreValues.attemptedQuizzes, function (val) { result += val; }); return result; }
JavaScript
function registerAttemptedQuiz(quizName) { if (!angular.isString(quizName)) { throw new Error('Score[registerAttemptedQuiz()]: quizName parameter is not valid'); } scoreValues.attemptedQuizzes[quizName] = ( scoreValues.attemptedQuizzes[quizName] || 0 ) + 1; _saveScoreValues(); return scoreValues.attemptedQuizzes[quizName]; }
function registerAttemptedQuiz(quizName) { if (!angular.isString(quizName)) { throw new Error('Score[registerAttemptedQuiz()]: quizName parameter is not valid'); } scoreValues.attemptedQuizzes[quizName] = ( scoreValues.attemptedQuizzes[quizName] || 0 ) + 1; _saveScoreValues(); return scoreValues.attemptedQuizzes[quizName]; }
JavaScript
function registerCorrectAnswer(args) { var quizName = args.quizName; if (!angular.isString(quizName)) { throw new Error('Score[registerCorrectAnswer()]: quizName parameter is not valid'); } scoreValues.correctAnswers[quizName] = ( scoreValues.correctAnswers[quizName] || 0 ) + 1; scoreValues.points[quizName] = ( scoreValues.points[quizName] || 0 ) + ( args.points || 0 ); _saveScoreValues(); return scoreValues.correctAnswers[quizName]; }
function registerCorrectAnswer(args) { var quizName = args.quizName; if (!angular.isString(quizName)) { throw new Error('Score[registerCorrectAnswer()]: quizName parameter is not valid'); } scoreValues.correctAnswers[quizName] = ( scoreValues.correctAnswers[quizName] || 0 ) + 1; scoreValues.points[quizName] = ( scoreValues.points[quizName] || 0 ) + ( args.points || 0 ); _saveScoreValues(); return scoreValues.correctAnswers[quizName]; }
JavaScript
function _getCorrectAnswersTotal() { var result = 0; angular.forEach(scoreValues.correctAnswers, function (val) { result += val; }); return result; }
function _getCorrectAnswersTotal() { var result = 0; angular.forEach(scoreValues.correctAnswers, function (val) { result += val; }); return result; }
JavaScript
function _getPointsTotal() { var result = 0; angular.forEach(scoreValues.points, function (val) { result += val; }); return result; }
function _getPointsTotal() { var result = 0; angular.forEach(scoreValues.points, function (val) { result += val; }); return result; }
JavaScript
function registerWrongAnswer(quizName) { if (!angular.isString(quizName)) { throw new Error('Score[registerWrongAnswer()]: quizName parameter is not valid'); } scoreValues.wrongAnswers[quizName] = ( scoreValues.wrongAnswers[quizName] || 0 ) + 1; _saveScoreValues(); return scoreValues.wrongAnswers[quizName]; }
function registerWrongAnswer(quizName) { if (!angular.isString(quizName)) { throw new Error('Score[registerWrongAnswer()]: quizName parameter is not valid'); } scoreValues.wrongAnswers[quizName] = ( scoreValues.wrongAnswers[quizName] || 0 ) + 1; _saveScoreValues(); return scoreValues.wrongAnswers[quizName]; }
JavaScript
function successRate(quizName) { var rate, attemptedQuizzes, correctAnswers; if (!quizName) { attemptedQuizzes = _getAttemptedQuizzesTotal(); correctAnswers = _getCorrectAnswersTotal(); } else { attemptedQuizzes = scoreValues.attemptedQuizzes[quizName] || 0; correctAnswers = scoreValues.correctAnswers[quizName] || 0; } rate = attemptedQuizzes !== 0 ? correctAnswers / attemptedQuizzes : 0; return (rate * 100).toFixed(2); }
function successRate(quizName) { var rate, attemptedQuizzes, correctAnswers; if (!quizName) { attemptedQuizzes = _getAttemptedQuizzesTotal(); correctAnswers = _getCorrectAnswersTotal(); } else { attemptedQuizzes = scoreValues.attemptedQuizzes[quizName] || 0; correctAnswers = scoreValues.correctAnswers[quizName] || 0; } rate = attemptedQuizzes !== 0 ? correctAnswers / attemptedQuizzes : 0; return (rate * 100).toFixed(2); }
JavaScript
function currentPoints(quizName) { if (!quizName) { return _getPointsTotal(); } else { return scoreValues.points[quizName] || 0; } }
function currentPoints(quizName) { if (!quizName) { return _getPointsTotal(); } else { return scoreValues.points[quizName] || 0; } }
JavaScript
function _camelCaseToSeparator(text, separator) { if (separator === undefined) { separator = ' '; } return text.replace(/[A-Z]/g, function(match) { return(separator + match.toLowerCase()); }); }
function _camelCaseToSeparator(text, separator) { if (separator === undefined) { separator = ' '; } return text.replace(/[A-Z]/g, function(match) { return(separator + match.toLowerCase()); }); }
JavaScript
function _ucwords(text) { return text.replace(/^([a-z])|\s+([a-z])/g, function ($1) { return $1.toUpperCase(); }); }
function _ucwords(text) { return text.replace(/^([a-z])|\s+([a-z])/g, function ($1) { return $1.toUpperCase(); }); }
JavaScript
function _getDisplayName(quizDescriptor) { if (quizDescriptor.displayName) { return quizDescriptor.displayName; } else { return _ucwords(_camelCaseToSeparator(_removePrefix(quizDescriptor.uniqueName))); } }
function _getDisplayName(quizDescriptor) { if (quizDescriptor.displayName) { return quizDescriptor.displayName; } else { return _ucwords(_camelCaseToSeparator(_removePrefix(quizDescriptor.uniqueName))); } }
JavaScript
purchaseItem(id, tipo, price) { const headers = {'headers': {'x-access-token': sessionStorage.getItem('token')}} return http .post('/do-purchaseItem/', {'id': id, 'tipo': tipo, 'price': price}, headers); }
purchaseItem(id, tipo, price) { const headers = {'headers': {'x-access-token': sessionStorage.getItem('token')}} return http .post('/do-purchaseItem/', {'id': id, 'tipo': tipo, 'price': price}, headers); }
JavaScript
createAccount(nickname, name, email, date, country, password, image){ return http .post('/do-create', {'nickname': nickname, 'name': name, 'email': email, 'date': date, 'country': country, 'pwd': password, 'image': image}) .then(response => { //le pido al back, ¿hay cambios? ¿hay cambios? //setTimeout(this.authenticate, 1000); return response.data; //Si no hay respuesta del backend, espera 1 segundo y vuelve a intentarlo }, () => { //setTimeout(this.authenticate, 1000); return false; }); }
createAccount(nickname, name, email, date, country, password, image){ return http .post('/do-create', {'nickname': nickname, 'name': name, 'email': email, 'date': date, 'country': country, 'pwd': password, 'image': image}) .then(response => { //le pido al back, ¿hay cambios? ¿hay cambios? //setTimeout(this.authenticate, 1000); return response.data; //Si no hay respuesta del backend, espera 1 segundo y vuelve a intentarlo }, () => { //setTimeout(this.authenticate, 1000); return false; }); }