anchor
stringlengths
10
14.3k
positive
stringlengths
10
14.9k
async function testRevokeVestingSchedule(owner, account, [totalAmount, vestingAmount, startDay], [duration, cliffDuration, interval, isRevocable], revokeOnDay) { const ownerBalanceBefore = await CpuCoin.methods.balanceOf(owner).call(); const accountBalanceBefore = await CpuCoin.methods.balanceOf(account...
================================================================================ === Test grant revocation ================================================================================
getDateFormated(date) { const formatDate = new Intl.DateTimeFormat('en-GB', { day: 'numeric', month: 'short', year: 'numeric' }).format; return formatDate(date); }
format date of order
function onlyProgressBar(props, propName, componentName) { var children = props[propName]; if (!children) { return null; } var error = null; __WEBPACK_IMPORTED_MODULE_7_react___default.a.Children.forEach(children, function (child) { if (error) { return; } // eslint-disable-next-line n...
Validate that children, if any, are instances of ``.
function generateFrequencyTable() { var noteNames = ['A', 'A#', 'B', 'C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#']; var root12_2 = 1.059463094359; var freq_by_note = {}; // fill 4, 5, 6, and 7 octaves var freq = 440.0; // A4 ['4', '5', '6', '7'].forEach(function(octave) { var f =...
generates table of frequencies for notes see:
function winnow(elements, qualifier, not) { if (jQuery.isFunction(qualifier)) { return jQuery.grep(elements, function (elem, i) { /* jshint -W018 */ return !!qualifier.call(elem, i, elem) !== not; }); } if (qualifier.nodeType) { ...
Implement the identical functionality for filter and not
set(_value) { if (this.differs(_value)) { this.value = _value; if (this.id) { require('comm/values').changed(this); } Queue.push(() => { this.refresh(); }); } }
= Description Replaces the data of the value. Extend this method, if you want clientside validation in the value itself. = Parameters +_value+:: The new data to replace the old data with.
async purchase(quantity, price) { try { const symbol = this.symbol.meta; const tickSize = symbol.tickSize; //minimum price difference you can trade by const priceSigFig = symbol.priceSigFig; const quantitySigFig = symbol.quantitySigFig; const unconfir...
push an unfilled limit purchase order to the queue
function createVirtualTable() { var rows = domTable.rows; for (var rowIndex = 0; rowIndex < rows.length; rowIndex++) { var cells = rows[rowIndex].cells; for (var cellIndex = 0; cellIndex < cells.length; cellIndex++) { addCellInfoToVirtual(rows[rowIndex],...
Create virtual table of cells with all cells, including span cells.
function loadTriggers(){ Triggers.find({}, function (err, triggers) { if (err) throw err; triggers.forEach(function(elem){ triggerObj[elem.triggerId] = elem.triggers; }); console.log("TRIGGER OBJ UPDATED", triggerObj); }); }
Load Triggers from Database to memory
function saveGameClient() { // The global variable gameState is updated with a new object // representing the state of play (ie the values of the set of // global variables representing the state of play) after every // corrent guess. It is also updated with saving to the cloud. gameState = { gameAnswers,...
This section of function declarations defines functions used to save and reload the state of game play. One of the simplest functions in this app. Just bundle up the current values of the set of global variables representing the current state of play, and turn then into an object with a timestamp of now. Then store it ...
function getRandomInt(max){ return Math.floor(Math.random() * Math.floor(max)); }
random number upto max
componentDidMount() { const { dispatch } = this.props; }
Unused at the moment, but likely to be required for fetching any initial data that may be needed appwide or on first load. Best approach is to have the retrieve data maintained in redux's store, then have lowerlevel containers connect/listen to the store. Avoids needing to map the props directly to children components/...
function addExample(rowName, centroid, stddev) { var row = []; for (var i = 0; i < centroid.length; ++i) { row.push([names[i], centroid[i] + rng.normal(0, stddev), now]); } //plugin.log("normal dist = ", rng.normal()); dataset.recordRow(rowName, row) }
Create an example with gaussians to train the kmeans opn
constructor() { this.debug = false; this.version = 1.6; this.production = false; this.myRoute = 'serviceWorker.js'; this.lastRequestTime = 0; this.log('running from scratch...'); this.addEventListeners(); }
This service worker has a cache strategy: cache first except for resources where you mark another strategy, these can be network first or network only When you change version below you invalide the cache (this happens immediately not on next page load) ironboy 2019
function createNewElement(elementType, newElementUniqueIdentifier, elementStr, parentElementID) { var newElement = document.createElement(elementType); newElement.setAttribute("id", newElementUniqueIdentifier) var elementText = document.createTextNode(elementStr); newElement.appendChild(elementText); document...
function creates a new element with text. A unique identifier is set to the new element
function Plugin( element, options ) { this.element = element; // jQuery has an extend method which merges the contents of two or // more objects, storing the result in the first object. The first object // is generally empty as we don't want to alter the default options for // f...
The actual plugin constructor
function normalizeDirectives (options) { var dirs = options.directives; if (dirs) { for (var key in dirs) { var def = dirs[key]; if (typeof def === 'function') { dirs[key] = { bind: def, update: def }; } } } }
Normalize raw function directives into object format.
function onScroll() { logTrace('invoking onScroll()'); if (pageLoads === true) { logWarn('Cancelled emitted scroll event, because page load is in progress.'); return false; } let remainingItems; if ( (currentPageType !== 'following') || (hideFollowing === true) ) { remainingItems = filte...
Event that is emitted whenever unprocessed items appear in the directory of the current page. Returns if filtering was invoked.
function printStored(){ document.getElementById("characters").innerHTML = (winningPhrase.join(" ")); }
document.getElementById("characters").innerHTML = ""; continue; popArr(); let requestData = request.response.split("\n");
function positionToOffsetFactory(indices) { return positionToOffset /* Get the `offset` for a line and column-based * `position` in the bound indices. */ function positionToOffset(position) { var line = position && position.line var column = position && position.column if (!isNaN(line) && !isNaN(...
Factory to get the `offset` for a line and columnbased `position` in the bound indices.
function normalizeAcceleration(acceleration) { var flipAcceleration = (window.orientation == 90 || window.orientation == 180) ? 1 : -1; var xDirection = (window.orientation == 0 || window.orientation == 180) ? acceleration.x : acceleration.y; return { x: xDirection * flipAcceleration, z: acceler...
inverts the Z axis uses Y for X and flips it and inverts it depending on the orientation so it maps to left and right this is basically emulating a steering wheel
function drawSceneObjects() { for (var i = 0; i < sceneWidth / tileSize; i++) { for (var j = 0; j < sceneHeight / tileSize; j++) { if (sceneObj[i] != null && sceneObj[i][j] != null) { ctx.drawImage(sceneObj[i][j].image, sceneObj[i][j].x, sceneObj[i][j].y); } } } if (selectedO...
Draws all objects in sceneObj[][] on the screen
function subtractVars() { }
strings go in quotation marks and should be separate from variables
function ensureSendMessage(tabId, message, callback){ chrome.tabs.executeScript(tabId, {file: "cscript.js"}, function(){ if(chrome.runtime.lastError) { console.error(chrome.runtime.lastError); throw Error("Unable to inject script into tab " + tabId); } // Now it's inj...
After 5 hours of debugging, I found out that sometimes the content script does not get automatically injected. Therefore, I ensure that the content script becomes injected by executing it explicitly.
function createHttpErrorConstructor() { function HttpError() { throw new TypeError('cannot construct abstract class'); } inherits(HttpError, Error); return HttpError; }
Create HTTP error abstract base class.
function getDepsRecursive(field, visited = []) { if (visited.indexOf(field) !== -1) return visited.push(field) for (let dep of field.directDependencies) getDepsRecursive(dep, visited) return visited }
Gets all dependencies recursively on a codebook. Only works where getDirectDeps has been used to populate directDependencies
function fOcts (f) { return Math.floor(f * 7 / 12) }
Given a number of fifths, return the octaves they span
addOrder() { /* order musi mit user _id, a veci v cart */ const db = getDb(); return this.getCart().then(products => { const order = { items: products, user: { _id: new ObjectId(this._id), name: this.username, } }; /* vytvorime v orders ...
chceme orders uchovavat v userovi / pro orders pouzijeme novou collection, muzou byt velmi velke (order history)
function revExists(revs, rev) { var toVisit = revs.slice(); var splitRev = rev.split('-'); var targetPos = parseInt(splitRev[0], 10); var targetId = splitRev[1]; var node; while ((node = toVisit.pop())) { if (node.pos === targetPos && node.ids[0] === targetId) { return true; } var branche...
return true if a rev exists in the rev tree, false otherwise
function SecurityMode (id, controller) { // Call superconstructor first (AutomationModule) SecurityMode.super_.call(this, id, controller); var self = this; this._testRule = function () { // wrapper to correct this and parameters in testRule self.testRule.call(self, null); }; // Create instance variables th...
Class definition, inheritance and setup
function VehicleFactory() { }
A bit "area of improvement" example on my opinion he tries to show 2 approaches, thus no one is good :)
function validarCedula(elemento) { if(elemento.value.length > 0 && elemento.value.length < 11){ var codigA = elemento.value.charCodeAt(elemento.value.length-1) if((codigA >= 48 && codigA <= 57)){ }else { elemento.value = elemento.value.substring(0, elemento.value.length-1) ...
Cedula 4857 rango de numeros
function temperature() { let temperature1 = document.querySelector('#temperature1').value; let temperature2 = document.querySelector('#temperature2').value; let number1 = document.querySelector('#number1').value; let number2 = document.querySelector('#number2').value; let temp1 = document.querySelector('#temp...
Function to: Convert temperature of both an input and select field respectively, In celsius, fahrenheit and kelvin
function App(){ const [posts, setPosts] = useState([]); const fetchPosts = ()=>{ const res = getPosts(); res.then((posts) => { console.log(posts) setPosts(posts.reverse()) }); } useEffect(()=>{fetchPosts()}, []) return( <> <Router> <Navbar/> <Switch> <R...
keep routes in my switch staetment
function cfnFunctionTracingConfigPropertyToCloudFormation(properties) { if (!cdk.canInspect(properties)) { return properties; } CfnFunction_TracingConfigPropertyValidator(properties).assertSuccess(); return { Mode: cdk.stringToCloudFormation(properties.mode), }; }
Renders the AWS CloudFormation properties of an ``AWS::Lambda::Function.TracingConfig`` resource
constructor(x, y, w, h, myString){ this.x = x; this.y = y; this.w = w; this.h = h; this.myString = myString; this.strokeGreen = 0 // keep track of how many times this object has been hit this.time = 6; }
store our working values
get pageContext () { return (this.currentContext && this.currentContext.page) || this.page }
Gets the current page context that we're using.
onTopicClick(topic) { if (topic.rowid === this.currentTopic) { return; } this.currentTopic = topic.rowid; localStorage.setItem('currentTopic', this.currentTopic); this.loadSelections(); }
change current topic on click if not current was clicked
static getCampus() { return [ { name: 'BI', code: 3, }, { name: 'GI', code: 2, }, { name: 'AR', code: 1, }, ]; }
Returns an array with the diferent campus
function createNotification(message, type, seconds){ currentNotifications.push({ message : message, cyclesRemaining : seconds, type : type }); var typeClass = ""; var typeText = ""; if(type == "positive"){ typeClass = "positive-notification"; typeText = "dark-text"; }else if(type == "negative"){ typeClass =...
Creates notification. It creates and stores the new object in the master list of them. Appends the html to the notification section
function generate() { var str = ''; var seconds = Math.floor((Date.now() - REDUCE_TIME) * 0.001); if (seconds === previousSeconds) { counter++; } else { counter = 0; previousSeconds = seconds; } str = str + encode(alphabet.lookup, version); str = str...
Generate unique id Returns string id
function isInstalled(projectConfig, dependencyConfig) { const project = _xcode().default.project(projectConfig.pbxprojPath).parseSync(); const libraries = (0, _getGroup.default)(project, projectConfig.libraryFolder); if (!libraries) { return false; } return (0, _hasLibraryImported.default)(libraries, d...
Copyright (c) Facebook, Inc. and its affiliates. This source code is licensed under the MIT license found in the LICENSE file in the root directory of this source tree.
function expandFilePathInOutput(output, cwd) { const lines = output.split('\n'); for (let i = 0; i < lines.length; i++) { const matches = lines[i].match(/\s*(\S+\.go):(\d+):/); if (matches && matches[1] && !path.isAbsolute(matches[1])) { lines[i] = lines[i].replace(matches[1], path.j...
Returns output with relative filepaths expanded using the provided directory
function main(maths, physics, computer) { function average() { var average = (maths + physics + computer) / 3; return average; } function percentage() { var percentage = ((maths + physics + computer) / 300) * 100; return percentage; } average(); percentage(); ...
4. Write a function that receives marks received by a student in 3 subjects and returns the average and percentage of these marks. there should be 3 functions one is the mainFunction and other are for average and percentage. Call those functions from mainFunction and display result in mainFunction
function findBestCircles(arrValidCircles) { var i; for (i = 0; i < arrValidCircles.length; i++) { iCount = arrayMarkCount(arrValidCircles[i][0], arrValidCircles[i][1], arrValidCircles[i][2], arrValidCircles[i][3]); if ((iCount > 0) && arrayCircleCheck(arrValidCircles[i][0], arrValidCircles[i][1], arrVali...
finds the circle with the most marked cells keeps looping until it no longer finds circles with any marked cells
function processAnswer(answer) { // set boolean switch to false displayQuestion = false; // clear page clearPage(); // set timeLeft to 3 for between question time timeLeft = 3; run(); // declare correct answer var correctAnswer = questions[que...
create function to process if answer is correct
function createLabels(varname, positions, range) { if (!positions) { console.log('[error] Create labels requires positions (x,y,z) array'); return; } if (positions.length % 3 !== 0) { console.log('[error] Create labels require positions array contain 3d points'); return; } ...
Create labels for the legend
function uniqueCellWriter(column, record) { var html = column.attributeWriter(record), input ='', td = '<td'; if (column.index % 5 === 4) { html = ''; input = '<input class="recollection-id" type="hidden" value=' + record['id'] + '><input class="recollection-input" type="text" maxlength="1">'; } ...
function to create first table and update
function resetGame() { console.log("resetGame was called"); playerCount = 0; for (i=0; i<globalBoard.length; i++) for (j=0; j<globalBoard.length; j++) globalBoard[i][j] = null; return globalBoard; }
Set the game state back to its original state to play another game.
function swapCase(string) { let output = []; string.split("").forEach((char) => { if (char === char.toUpperCase()) { output.push(char.toLowerCase()); } else { output.push(char.toUpperCase()); } }); return output.join(""); }
Return a new string that swaps the case of all of the letters:
function debugCallback(mydata){ //appending the text label of "GeoJSON data: " as well as the actual //text of the GeoJSON file. //JSON stringify is what helps label the data file. $("#mydiv").append('<br>GeoJSON data: <br>' + JSON.stringify(mydata)); }
debugCallback function is primarily for just making sure the GeoJSON labels itself in the div and below the cities table. mydata is the only variable that will be called in this function, but is created in the next function.
function changeColor(event){ // console.log(event); var x = event.which || event.keyCode; // console.log(x); if (x == 66){ ctx.strokeStyle = 'blue'; } if (x == 71){ ctx.strokeStyle = 'green'; } if (x == 82){ ctx.strokeStyle = 'red'; } if (x == 89)...
var event = window.event;
function init() { let dropdownMenu = d3.select("#selDataset"); // Read json data d3.json("samples.json").then(function (response) { // Parse and filter data to get sample names let names = response.names; // Add dropdown option for each sample for (i = 0; i < names.length; i+...
Define function that will run on page load
function montMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); }
r = "xy/R mod m"; x,y != r
function limpiarAsignacion() { $('#a_centro').empty(); $('#a_empleadosCentro').empty(); $('#a_todosEmpleados').prop("checked", false); }
! LIMPIAR INPUTS DE ASIGNACION
function listFonts () { asciify.getFonts(function (err, fonts) { if (err) { return console.error(err); } var padSize = ('' + fonts.length).length; fonts.forEach(function (font, index) { console.log(pad(padSize, index+1, '0') + ': ' + font); }); }); }
Write the font list to console
function saveTodos(todoinput){ let todo; if (localStorage.getItem('todo') === null){ todo = []; console.log(todo); } else{ todo = JSON.parse(localStorage.getItem('todo')); } todo.push(todoinput); localStorage.setItem('todo', JSON.stringify(todo)); }
add to localStorage 3
function initRenderer() { renderer = new THREE.WebGLRenderer({ alpha: true, antialias: true }); renderer.setSize( window.innerWidth, window.innerHeight ); document.body.appendChild( renderer.domElement ); renderer.shadowMap.enabled = true; renderer.shadowMap.type = THREE.PCFSoftShadowMap; w...
The renderer needs a size and the actual canvas we draw on needs to be added to the body of the webpage. We also specify that the renderer will be computing soft shadows
function unbiasnet() { var i; var j; for (i = 0; i < netsize; i++) { network[i][0] >>= netbiasshift; network[i][1] >>= netbiasshift; network[i][2] >>= netbiasshift; network[i][3] = i; // record colour no } }
Unbias network to give byte values 0..255 and record position i to prepare for sort
function geoDistanceKm(p1,p2) { var R = 6371; // km var x1 = p2.lat()-p1.lat(); var dLat = x1.toRad(); var x2 = p2.lng()-p1.lng(); var dLon = x2.toRad(); var a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos(p1.lat().toRad()) * Math.cos(p2.lat().toRad()) * Math.sin(dLon/2) * Math.si...
geographic distance courtesy the haversine formula
function IPv4_intA_to_binstrA( strnum ) { var numStr = strnum.toString( 2 ); /* Initialize return value as string */ var numZeros = 32 - numStr.length; /* Calculate no. of zeros */ if (numZeros > 0) { for (var i = 1; i <= numZeros; i++) { numStr = "0" + numStr } } return numStr; }
integer IP to binary string representation
function name_validate(roomParam) { roomParam.child("people/" + $("#input_name").val()).once('value', snapshot => { if (!snapshot.exists()) { let name = $("#input_name").val(); roomParam.child("people/" + name).set(true); //adds username to the database, within the room they are joinin...
checks if the username is unique, if it is, connect them to that activity
function drawDeferred() { var callLength = deferredRenderCalls.length, callIndex; // Draw all pending render calls for (callIndex = 0; callIndex < callLength; callIndex++) { deferredRenderCalls[callIndex](); } // Clear the list deferredRenderCalls = []; }
When downloaded, we are ready to draw deferred charts.
function encodeEntities(value) { return value. replace(/&/g, '&amp;'). replace(NON_ALPHANUMERIC_REGEXP, function(value){ return '&#' + value.charCodeAt(0) + ';'; }). replace(/</g, '&lt;'). replace(/>/g, '&gt;'); }
Escapes all potentially dangerous characters, so that the resulting string can be safely inserted into attribute or element text.
getTableRowsScoped(tableName) { return this.blockchain.getTableRowsScoped(this.accountName, tableName); }
Gets the table rows of the specified table, keyed by scopes
function select_by_weather(recipes) { recipes.forEach(recipe => { recipe['weather'] = false; }); let selectedChoices = findIfFilters("weather"); if (selectedChoices.length === 0) { document.querySelector('#no-filter-chosen').style.display = 'block'; } else { filter("weather",...
Selects the correct recipes for that kind of weather
function AlevelStudent (obj = {name: 'Anatoliy', age: 23, marks:[1, 2, 3, 4, 5]}) { Human.call(this, obj); this.marks = obj.marks; }
let a = new Human(); a.sayHello();
function getType(typeRef) { if (typeRef.kind === _introspection.TypeKind.LIST) { var itemRef = typeRef.ofType; if (!itemRef) { throw new Error('Decorated type deeper than introspection query.'); } return new _definition.GraphQLList(getType(itemRef)); } if (typeRef.kind === _i...
Given a type reference in introspection, return the GraphQLType instance. preferring cached instances before building new instances.
function scoresAverage(someArray) { if (someArray.length === 0) { return 0; } const sumScores = someArray.reduce((acc, eachScore) => { if (!eachScore.score) { return acc } return acc + eachScore.score; },0) let avgScore = sumScores / someArray.length; let roundedScore = M...
Iteration 3: All scores average Get the average of all scores with 2 decimals
function encoder() { let phraseCodee = ''; for (var i = 0; i < phraseAcoder.value.length; i++) { lettre = phraseAcoder.value.charAt(i); position = alphabet.indexOf(lettre); // suppression des ponctuations et espaces if ((lettre == ' ') || (lettre == '!') || (lettre == ',') || (le...
Fontion de codage de la phrase
function checkKeyCodes ( eventKeyCode, key, builtInKeyCode, eventKeyName, builtInKeyName ) { var mappedKeyCode = config.keyCodes[key] || builtInKeyCode; if (builtInKeyName && eventKeyName && !config.keyCodes[key]) { return isKeyNotMatch(builtInKeyName, eventKeyName) } else if (mappedKeyCode) { r...
Runtime helper for checking keyCodes from config. exposed as Vue.prototype._k passing in eventKeyName as last argument separately for backwards compat
function isWithinTimeWindow(starttime, endtime) { //Dummy Record to get current timeof day var dummyConfig = record.create({type: "customrecord_flo_spider_configuration", isDynamic: true}); currenttime = dummyConfig.getValue({fieldId: 'custrecord_flo_conf_current_tod'}) ...
END rescheduleJob Checks whether the current time is within the time window set in config record
play(id) { this.playSound(id); userSequence.push(id); for(i=0; i<userSequence.length; i++){ if(userSequence[i] != gameSequence[i]){ gameOver = true; this.setState({flashIndex: 0}); Alert.alert("Try Again!") this.addAndUp...
play and update data eith the new score
function vpb_IE_detected() { var ua = window.navigator.userAgent; var old_ie = ua.indexOf('MSIE '); var new_ie = ua.indexOf('Trident/'); if ((old_ie > -1) || (new_ie > -1)) { return true; } else { return false; } }
vpb_setcookie('myCookie', 'The value of the cookie', 7) var myCookie = vpb_getcookie('myCookie'); vpb_removecookie('myCookie')
function colorCube() { quad( 1, 0, 3, 2 ); quad( 2, 3, 7, 6 ); quad( 3, 0, 4, 7 ); quad( 6, 5, 1, 2 ); quad( 4, 5, 6, 7 ); quad( 5, 4, 0, 1 ); }
define faces of a cube
async show({ params }) { const evaluation = await Evaluation.findOrFail(params.id); return evaluation; }
Display a single evaluation. GET evaluations/:id
function _flipAlignmentEdge(elementEstimate, target, gap, coverTarget) { var alignmentEdge = elementEstimate.alignmentEdge, targetEdge = elementEstimate.targetEdge, elementRectangle = elementEstimate.elementRectangle; var oppositeEdge = alignmentEdge * -1; var newEstimate = _estimatePosition(elementRectangl...
Flips only the alignment edge of an element rectangle. This is used instead of nudging the alignment edges into position, when alignTargetEdge is specified.
function addTask() { var taskId = "task_" + taskCount++; var task = createTask(taskId, "", ""); taskList[taskId] = task; var domElement = createNewTaskDOMElement(task); taskListDOMElements[taskId] = domElement; showTaskDetail(task); }
Add new Task to list
function setInputValues(dgInputs) { var impTbl = document.getElementById("InputValuesTable"); //impTbl.innerHTML = ""; var keys = dgInputs.keys() var values = dgInputs.values(); var tableData = ""; for (var i = 0; i < keys.length;i++) { if (i % 2 && i != 0) tableData = tableData + "<tr><td>"+ k...
================================================================================= ================================================================================== Sets the iinput array that is the first table in the Data View. ==================================================================================
static async updateDataSource(email, dataSourceID, dataSourceName) { return new Promise((resolve, reject) => { Database.sendQuery('UPDATE datasource SET sourceName=$3 WHERE ( email = $1) AND ( ID = $2) RETURNING *;', [email, dataSourceID, dataSourceName]) .then((result) => { if (result.rows.length > 0) re...
This function is to update a data source
function winOver() { if (player.win === true){ let message = document.createTextNode('You win!'); let messageBtn = document.createTextNode('Play again?') let doc = document, overlay = doc.createElement('div'), winMessageDiv = doc.createElement('div'), winMes...
function to pop up overlay with winning message
function bnMod(a) { var r = nbi(); this.abs().divRemTo(a,null,r); if(this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) a.subTo(r,r); return r; }
(public) this mod a
readLatestMessages(messageNumber){ var entireMessages = this.get('messages'); if (messageNumber > entireMessages.length) messageNumber = entireMessages.length; var begin = Math.abs(messageNumber - entireMessages.length); var end = Math.abs(messageNumber - entireMessages.lengt...
Read the last five messages to the users
function checkWinner() { var win = true; for (var i = 0; i < 4; i++) { for (var j = 0; j < 4; j++) { if (!(cells[i][j].innerHTML == i * 4 + j + 1)) if (!(i == 3 && j == 3)) win = false; } } if (win) { alert("Congratulations! You won...
create function to check if the last move made makes this a win display winning message if it is a winner
function indentLevel(linea) { var level = 0; for ( i in linea ) { if ( linea[i] != ' ' ) { break;} level += 1; } return (level); }
Aux function that retrieves the indentation level of some code line, useful for YAML decoding.
function resize() { var canvas = document.querySelector("canvas"); var parent = document.getElementById('wheel_game'); var windowWidth = parent.offsetWidth; var windowHeight = parent.offsetHeight; var windowRatio = windowWidth / windowHeight; var gameRatio = game.config.width / game.config.heigh...
pure javascript to scale the game
function ajaxHandleResponses( s, jqXHR, responses ) { var firstDataType, ct, finalDataType, type, contents = s.contents, dataTypes = s.dataTypes, responseFields = s.responseFields; // Fill responseXXX fields for ( type in responseFields ) { if ( type in responses ) { jqXHR[ responseFields[type] ] = respo...
Handles responses to an ajax request: sets all responseXXX fields accordingly finds the right dataType (mediates between contenttype and expected dataType) returns the corresponding response
function getMonName(monId) { var female = (monId > 600); if (female) { monId -= 600; } if (WMSkyPoke[monId]) { // (female ? "[F]" : "[M]") + return WMSkyPoke[monId]; } else { return "Unknown"; } }
Returns the monster name for a given monster ID. Requires the sky_monster file to be loaded.
render() { return ( <ThemeContext.Consumer> { value => ( <div style={{ border: `5px solid ${value.color}`, padding: "5px" }}> <div>Header</div> <Title /> </div>...
static contextType = ThemeContext;
function rng_seed_int(x) { rng_pool[rng_pptr++] ^= x & 255; rng_pool[rng_pptr++] ^= (x >> 8) & 255; rng_pool[rng_pptr++] ^= (x >> 16) & 255; rng_pool[rng_pptr++] ^= (x >> 24) & 255; if(rng_pptr >= rng_psize) rng_pptr -= rng_psize; }
Mix in a 32bit integer into the pool
function isDependencyTreeRoot(packageLocator) { if (packageLocator.name === null) return true; for (const dependencyTreeRoot of runtimeState.dependencyTreeRoots) if (dependencyTreeRoot.name === packageLocator.name && dependencyTreeRoot.reference === packageLocator.reference) return true; return false; }
Returns whether the specified locator is a dependency tree root (in which case it's part of the project) or not
function getLongestWord(word1, word2) { return (word1.length > word2.length) ? word1 : word2; }
==================== getLongestWord v2 ====================
function cov( x, y, size){ var sum=0; for(var i=0;i<size;i++){ sum+=x[i]*y[i]; } sum/=size; // var avg1 = avg(x,size); // var avg2 = avg(y,size); // var avgMult = avg1 * avg2; // var total = sum - avgMult; //console.log("cov : " + (sum - avg(x,size)*avg(y,size))) return sum - avg(x,size)*avg(y,s...
returns the covariance of X and Y
function removeProp(obj, propName) { const changedObj = { ...obj }; if (changedObj[propName]) { delete changedObj[propName]; } return changedObj; }
Remove page from object
function totalCells(){ var rows = countRows(); var cols = countColumns(); var size = rows * cols; return size; }
Challenge 4 Awesome job! Other lighthouse operators are jealous of your grid. Just to show off, let's write a new function for the system which will count up how many cells total there are. Given the code you just wrote, this should be pretty easy. Write a new function called totalCells() which will return the total nu...
dequeue(){ if(!this.eQueue.length && !this.dQueue.length) throw Error("Empty Stack"); if(this.dQueue.length === 0){ for(let item of this.eQueue){ this.dQueue.push(item); } } return this.dQueue.pop(); }
move all items into array and then dequeu
update() { let self = this; d3.select('#directoryChart').selectAll('tspan').remove(); // Get info for entities filtered by: // Selected cities, selected category, selected funding type, selected year let fundingType = d3.select('#fundingType').property('value'); let category = d3.select('#categori...
Called when a user clicks on a circle
function chart(selection) { // ********************** // handing new personalized data // ********************** d3.select("#chart svg") .remove(); data.forEach(function(d) { nameLookup[d.name] = d; }); color .range(...
The chart function Selects a div element (selection) and appends an SVG with the horizontal bar chart
function visualLineEndNo(doc, lineN) { if (lineN > doc.lastLine()) { return lineN } var line = getLine(doc, lineN), merged; if (!lineIsHidden(doc, line)) { return lineN } while (merged = collapsedSpanAtEnd(line)) { line = merged.find(1, true).line; } return lineNo(line) + 1 }
Get the line number of the start of the next visual line after the given line.
function UpdateUsuario(req, res){ if (req.usuario.rol === 1 || req.usuario.nombre === req.body.nombre) { const idUsuario = req.params.idUsuario; const usuario = { nombre: req.body.nombre, edad: req.body.edad, email: req.body.email, pass: sha512(req.bod...
===== End of Funcion para agregar usuario ====== /========================================= = Update de usuario = =========================================