anchor
stringlengths
10
14.3k
positive
stringlengths
10
14.9k
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 = =========================================
function getUsers() { return db('users') .select('id', 'username') }
for listing users for dev testing (excluding passwords)
function makeNewStrike(line, strikeHorder){ strikeHolder[line.strike] = {}; strikeHolder[line.strike].numberStrike = line.numberStrike; sortCallsAndPuts(line, [strikeHolder[line.strike]]); }
if strike not already in object, make a new object for the strike THEN add the call or put
function getStr(str) { console.log(str.length); }
let dom: HTMLElement | null = document.getElementById('root'); console.log(dom.id)
function getMovie() { //GETTING THE ID FROMSESSION STORAGE let movieId = sessionStorage.getItem("movieId"); axios .get("https://www.omdbapi.com?apikey=af465f0e&i=" + movieId) .then(response => { console.log(response); let movie = response.data; let imdbid = movie.imdbID; // UPDATIN...
GETTING THE MOVIE WHICH IS SELECTED
function checkIfPresent(output, X, isActor){ var set = -1 if(output.length == 0){ return set } output.forEach((element,index,output) => { if(isActor){ if(element.Name === X){ set = index return set } } else{ if(...
using this function for both actors array and genre array by passing true or false to isActor
function createCharReader (nextChar, rewind) { let charsRead = 0 return { nextChar () { charsRead += 1 return nextChar() }, reset () { rewind(charsRead) charsRead = 0 }, rewind (n = 1) { rewind(n) charsRead -= n } } }
lets you read chars, and optionally reset the cursor to where it was before reading
function search() { const text = this.value; if (text === '') { rows.forEach(row => row.style.display = null); return; } const length = names.length; const regex = new RegExp(text, 'gi'); for (let i = 0; i < length; i++) { if (names[i].match(regex)) rows[i].style.display ...
Implement the search function
function canAccessProperty(object, property) { try { const unused = object[property]; return true; } catch (errors) { return false; } }
Return true if |object|.|property| can be called without throwing an error.
function DateRegisterTK(monthExtend) { // body... var date = new Date($('#RegisDateTK').val()); date.setMonth(date.getMonth() + monthExtend); var dd = date.getDate(); var mm = date.getMonth() + 1; //January is 0! var yyyy = date.getFullYear(); if (dd < 10) { dd = '0' + dd; } ...
get endDate contract in modal register ticket from comboboxDate
function addNew(){ var req = new XMLHttpRequest(); var newExercise = document.getElementById("inputNew"); var measurement; if (newExercise.elements.name.value == ""){ alert ("Error: Name is required."); return; } /*Formatting measurement*/ if(newExercise.elements.measurement.checked){ ...
Function for adding new item from form
function compareEquality1(a, b) { if(a == b) { return "Equal"; } return "Not Equal"; }
practice comparing different values
function deactivate() {}
this method is called when your extension is deactivated
function sample_population(population, fitnesses, selection_rate) { num_of_selected_chromosome = parseInt(selection_rate * population.length) mating_population = [] // console.log(num_of_selected_chromosome + " " + population.length) for (var i = 0; i < num_of_selected_chromosome; i++) mating_population.pu...
Sample Populasi population = generate_population(5) fitnesses = calculate_population_fitness(population) console.log(sample_population(population, fitnesses))
function showTiles() { var tiles = getTiles(); var formHTML = "<ul>"; for (var i = 0; i < tiles.length; i++) { formHTML = formHTML + '<li>' + tiles[i].title + '</li>'; } formHTML = formHTML + "</ul>"; $( "div#tilesList" ).html(formHTML); }
Display the list of Tiles for the current Project.
parts(key) { var raw = this.param(key); var parts = raw.split('|'); for (var i = 0; i < parts.length; ++i) { parts[i] = parts[i].trim(); } return parts; }
Split a data attribute by | and return the trimmed parts
function submitPasswordChangeRequest(form) { return new Promise(function (resolve, reject) { // Emulate an API call. Reject a portion of the requests. setTimeout(function () { // reject if password is incorrect if (form.currentPassword !== 'qqQQ11!!') { reject({ code: 401 ...
Submit a password change request to the backend.
function where(list, properties, k) { var names = [] return reduce(list, function(list, v, k) { var names = true for (var k in properties) { if (properties[k] !== v[k]) { names = false } } if (names == true) { list.push(v) ...
Write a function where() that filters for all the values in the properties object.
function nextGeneration () { var changes = false; Life.nextGrid = matrix(Life.HEIGHT, Life.WIDTH, false); for ( var h=0; h < Life.WIDTH; h++ ) { for ( var v=0; v < Life.HEIGHT; v++ ) { // get the number of living neighbors var aliveCount = evaluateNeighbors( h, v ) switch (true) { ...
evaluate all cells and build new matrix for next generation
function loadTable() { if (hiddenCmd.dispatch) { hiddenCmd.dispatch("refresh"); } else { setTimeout(loadTable, 1000); } }
webEdition SDK webEdition CMS $Rev$ $Author$ $Date$ This source is part of the webEdition SDK. The webEdition SDK is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License the Free Software Foundation; either version 3 of the License, or any later version. The G...
function xSwapImg(imgDiv,srcImg,srcAltImg){ /* Update by Christian Vallee <cv@valtechnologie.com> ==> No need to specify absolute URL for images anymore, this feature will find it on its own */ // looking for the images' root URL based on the current image var str = imgDiv.src; var pos = str.search(srcImg)...
Toggle expanded / collapsed versions of items' images
sendMessage() { // Construct the message here const message = { sender: this.state.sender, reciever: this.props.replier, subject: 'RE: ', body: this.state.body, msgType: 'reply', reply: this.props.replyId }; // Post...
Hits API with body of carve
function n(t,e){if(!t)throw new Error("[vue-router] "+e)}
vuerouter v3.0.1 (c) 2017 Evan You
function send_bits(s, value, length) { if (s.bi_valid > (Buf_size - length)) { s.bi_buf |= (value << s.bi_valid) & 0xffff; put_short(s, s.bi_buf); s.bi_buf = value >> (Buf_size - s.bi_valid); s.bi_valid += length - Buf_size; } else { s.bi_buf |= (value << s.bi_valid) & 0xffff; s.bi_valid += ...
=========================================================================== Send a value on a given number of bits. IN assertion: length <= 16 and value fits in length bits.
function g() { 'use strict'; var x, y, grid = canvasDatagrid({ parentNode: document.body, allowFreezingColumns: true, allowFreezingRows: true, debug: false }); grid.style.columnHeaderCellHeight = 40; grid.style.cellHeight = 40; ...
globals canvasDatagrid: false / this file is for developing in a sandbox on a local machine
addToRenderedList() { if (this.state.renderedArray.length <= 5) { let renderedArray = this.state.renderedArray; let foodArray = this.state.foodArray; if (this.state.foodArray.length > 5) { renderedArray = renderedArray.concat(foodArray.slice(0, 5)); foodArray = foodArray.slice(5);...
feeds the food array to the renderedList to fix performance
function ajaxExtend( target, src ) { var deep, key, flatOptions = jQuery.ajaxSettings.flatOptions || {}; for ( key in src ) { if ( src[ key ] !== undefined ) { ( flatOptions[ key ] ? target : ( deep || (deep = {}) ) )[ key ] = src[ key ]; } } if ( deep ) { jQuery.extend( true, target, deep ); } retur...
A special extend for ajax options that takes "flat" options (not to be deep extended) Fixes 9887
function QueueDrawAgent(selector, h, w, problem, options) { this.canvas = document.getElementById(selector); this.canvas.innerHTML = ''; this.two = new Two({ height: h, width: w }).appendTo(this.canvas); this.problem = problem; this.nodeRadius = 25; this.options = options; this.iterate = functi...
An agent to draw queues for bfs and dfs
function received_animals(animals_res, user_input, res){ animals_res.setEncoding("utf8"); let body = ""; animals_res.on("data", function(chunk){ body += chunk; }); animals_res.on("end", function(){ let animals_info = JSON.parse(body);//convert from a JSON string to js obj let animals_array_length = animals_i...
Catch the information of each animal
respondWithRedirect(ctx) { if (!ctx.session) { return ctx.response.status(this.status).send('Invalid credentials'); } ctx.session.flashExcept(['_csrf']); ctx.session.flash('auth', { errors: { uid: this.code === 'E_INVALID_AUTH_UID' ? ['Invalid logi...
Flash error message and redirect the user back
function getPackageInformationSafe(packageLocator) { const packageInformation = getPackageInformation(packageLocator); if (!packageInformation) { throw internalTools_1.makeError(internalTools_1.ErrorCode.INTERNAL, `Couldn't find a matching entry in the dependency tree for the specified parent (this is pr...
Returns information about a package in a safe way (will throw if they cannot be retrieved)
function action(args, env) { // Prompt for tasks if ( args.length === 0 ) { prompt('Task:', _promptFinished); } // Process Tasks else { for ( let i = 0; i < args[0].length; i++ ) { _process(args[0][i], i+1, args[0].length); } } }
This command remove 1 or more Tasks
function newSumZero(arr) { // left = beginning of the array let left = 0; // right = end of array, remember it's zero indexed let right = arr.length - 1; // left < right is our fail safe while (left < right) { let sum = arr[left] + arr[right]; if (sum === 0) { return [arr[left], arr[right]]; } else if (...
Refactoring, using Multiple Pointers method Time Complexity O(N), Space Complexity O(1)
removeUser(userID) { if(userID in this.users) { delete this.users[userID]; return true; } else { return false; } }
removes user by UID returns true if successful, false otherwise
function cfnHttpNamespacePropsToCloudFormation(properties) { if (!cdk.canInspect(properties)) { return properties; } CfnHttpNamespacePropsValidator(properties).assertSuccess(); return { Name: cdk.stringToCloudFormation(properties.name), Description: cdk.stringToCloudFormation(pro...
Renders the AWS CloudFormation properties of an `AWS::ServiceDiscovery::HttpNamespace` resource
async function createIngredientAndUnit(item) { //ingredient let ingredient = await strapi.api.ingredient.services.ingredient.findOne({ name: item.ingredient.name, }); if (!ingredient) { ingredient = await strapi.api.ingredient.services.ingredient.create({ name: item.ingredient.name, }); } ...
Read the documentation ( to customize this controller
function parseXML(xml){ console.log("in parseXML"); $("h1").html("Final Project Assignment<br>" + "Kody Scharf, Andrew Lee<br>" + "991455754, 991457820<br>"); }
end of doc load
animMoveBack(direction) { let anim = this.renderAnimation('moveBack', direction); let board = this.board; let pixi = this.pixi; anim.frames.forEach((frame, frameId) => { let offsetRatio = (frameId + 1) / anim.frames.length; let offset = board.getOffset(-offsetRatio / 2, direction); a...
Moving back and forward is similar to moving. But the offset ratio is cut in half to reflect that the destination is halfatile away. Also, it is a negative ratio, since the offset is behind the unit.
function displayEmptyPageMessage() { $("#emptyPageMessageWrapper").removeClass("hidden"); }
Displays the "empty page" message on the page
async function updatePrivacy(privacy, username) { if(arguments.length != 2 || typeof privacy !== "string") { throw("updatePrivacy: You must have a privacy and a username"); } const usersCollection = await users(); let user = await usersCollection.findOne({userDisplayName: username}); if(user == null)...
Leo wrote this given a boolean, sets user's privacy setting
function addRecord(){ let codigo = document.getElementById('codigo').value; let nombre = document.getElementById('nombre').value; let precio = document.getElementById('precio').value; productos.push(new IngrProducto(codigo,nombre,precio)); }
Funcion para poblar los campos
function frmPatientSummary_checkuncheck(eventobject) { com.healogics.utility.showLoading(); searchPatient_closeSearchList(); //Sandeep offline changes for chart if (isIpad && !isNetworkAvailable()) { var error_label = ERROR_CONSTANTS.NO_NETWORK_CONNECTION; com.healogics.utility.showError...
Method to select/unselect wound from wound list
function redirect(url, response) { console.log('redirect to ' + url); response.writeHead(301, {Location: 'http://' + url}); response.end(); }
Redirect to the real url
function getCurrentRunTime(startTime, currentTime = undefined) { if (currentTime === undefined) { currentTime = new Date().getTime(); } return currentTime - startTime; }
Returns the current run time
function parseInput(str) { var input = {}; var tokens = str.trim().toLowerCase().split(/\s/); var halves = mergeTokens(tokens); if (!validateInput(halves)) return null; input['department'] = halves[0]; input['courseNumber'] = halves[1]; return input; }
Parse the input string and return an object with department and courseNumber properties filled in.
function updateCounter() { var cartCounter = document.getElementById('itemCount'); cartCounter.textContent = cart.items.length; }
Update the cart count in the header nav with the number of items in the Cart
function implementsAnyMethods(obj, methods) { if (typeof obj !== 'object' || obj === null) { return false; } for (var _i = 0, methods_1 = methods; _i < methods_1.length; _i++) { var method = methods_1[_i]; if (method in obj && typeof obj[method] === 'function') { r...
Return true if the object passed in implements any of the named methods.
function remember() { // store our current tweets array in localstorage // but remove last memory of it first localStorage.removeItem('twitter'); // remember tweets array localStorage.setItem('twitter', JSON.stringify(tweets)); }
vote poll from Albert's codes
function useQueries(createHistory) { return function () { var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; var history = createHistory(options); var stringifyQuery = options.stringifyQuery; var parseQueryString = options.parseQueryString; if (typeo...
Returns a new createHistory function that may be used to create history objects that know how to handle URL queries.
consume (key) { if (_state[key].length > 0) return _state[key].shift(); return false; }
for consuming queuelike objs
function date(callback) { console.log(new Date); setTimeout(function() { let date = new Date; callback(date); },3000) }
esto me sirve para poner una funcion dentro de otra funcion y me permite trabajar esto de forma bastante espeficica por lo que entiendo abajo sentencio la funcion date con callback y hace un console log como new Date despues hace un metodo setTimeOut
task_assigned_to(){ var user_id = Session.get('mySession'); Meteor.subscribe('fetch_assigned_task_to', user_id); // var task_assign_by_1 = Session.get('task_assign_to'); // return task_assignment.find({ 'user_id_by' : task_assign_by },{sort: {created_at: -1}}).fetch(); return task_assignment.find...
helper function is used to show the task which was assigned by you to someone
function ReactGridLayout(props, context) { _classCallCheck(this, ReactGridLayout); var _this = _possibleConstructorReturn(this, _React$Component.call(this, props, context)); _initialiseProps.call(_this); (0, _utils.autoBindHandlers)(_this, ['onDragStart', 'onDrag', 'onDragStop', 'onResizeStart', 'onR...
TODO publish internal ReactClass displayName transform
function assertCompiler(name, Compiler) { if (typeof Compiler !== 'function') { throw new Error('Cannot `' + name + '` without `Compiler`') } }
Assert a compiler is available.
function upsertInner(db, docId, diffFun) { return new PouchPromise(function (fulfill, reject) { if (typeof docId !== 'string') { return reject(new Error('doc id is required')); } db.get(docId, function (err, doc) { if (err) { /* istanbul ignore next */ if (err.status !== 404) ...
this is essentially the "update sugar" function from daleharvey/pouchdb1388 the diffFun tells us what delta to apply to the doc. it either returns the doc, or false if it doesn't need to do an update after all
function wait() { if ( questionCounter < 7 ) { questionCounter++; generateHTML(); counter = 30; timerWrapper(); } else { finalScreen(); } }
Keeps the game going until the final question, then it will switch to the final screen.
function bookmarkWhere() { var string = JSON.stringify(where); localStorage.setItem('whereBookmark', string); }
saves the data into local storage
function clickOutside(e) { var container = $("#navList"); if ((!container.is(e.target) && !$("#mobile-nav").is(e.target))) // if the target of the click isn't the container... { container.removeClass("show"); } }
Close navList if click outside div
function goBack() { id('data').innerHTML = ""; id("find-btn").disabled = false; }
Resets the contents and reenable the find buttons;
function add_to_main_windows_list(window_id) { var temp_main_windows_list = get_main_windows_list(); var index = temp_main_windows_list.indexOf(window_id); if (index < 0) { //this windows is not in the list currently temp_main_windows_list.push(window_id); } localStorage.main_windows = temp_main_w...
ADD TO main_windows LIST
function getMedicamentosPaciente(req, res){ console.log('- GET MEDICAMENTOS PACIENTE -'); var query = Paciente.findById(req.params.idPaciente); query.populate({ path: 'medicamentos', model: 'Medicamento' }) .exec(function (err, paciente) { if (err) { ...
Obtengo los medicamentos de un determinado paciente