anchor stringlengths 10 14.3k | positive stringlengths 10 14.9k |
|---|---|
Write the font list to console | 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);
});
});
} |
add to localStorage 3 | 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));
} |
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 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... |
Unbias network to give byte values 0..255 and record position i to prepare for sort | 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
}
} |
geographic distance courtesy the haversine formula | 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... |
integer IP to binary string representation | 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;
} |
checks if the username is unique, if it is, connect them to that activity | 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... |
When downloaded, we are ready to draw deferred charts. | function drawDeferred() {
var callLength = deferredRenderCalls.length,
callIndex;
// Draw all pending render calls
for (callIndex = 0; callIndex < callLength; callIndex++) {
deferredRenderCalls[callIndex]();
}
// Clear the list
deferredRenderCalls = [];
} |
Escapes all potentially dangerous characters, so that the resulting string can be safely inserted into attribute or element text. | function encodeEntities(value) {
return value.
replace(/&/g, '&').
replace(NON_ALPHANUMERIC_REGEXP, function(value){
return '&#' + value.charCodeAt(0) + ';';
}).
replace(/</g, '<').
replace(/>/g, '>');
} |
Gets the table rows of the specified table, keyed by scopes | getTableRowsScoped(tableName) {
return this.blockchain.getTableRowsScoped(this.accountName, tableName);
} |
Selects the correct recipes for that kind of weather | 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",... |
let a = new Human(); a.sayHello(); | function AlevelStudent (obj = {name: 'Anatoliy', age: 23, marks:[1, 2, 3, 4, 5]}) {
Human.call(this, obj);
this.marks = obj.marks;
} |
Given a type reference in introspection, return the GraphQLType instance. preferring cached instances before building new instances. | 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... |
Iteration 3: All scores average Get the average of all scores with 2 decimals | 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... |
Fontion de codage de la phrase | 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... |
Runtime helper for checking keyCodes from config. exposed as Vue.prototype._k passing in eventKeyName as last argument separately for backwards compat | 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... |
END rescheduleJob Checks whether the current time is within the time window set in config record | 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'})
... |
play and update data eith the new score | 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... |
vpb_setcookie('myCookie', 'The value of the cookie', 7) var myCookie = vpb_getcookie('myCookie'); vpb_removecookie('myCookie') | 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;
}
} |
define faces of a cube | 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 );
} |
Display a single evaluation. GET evaluations/:id | async show({ params }) {
const evaluation = await Evaluation.findOrFail(params.id);
return evaluation;
} |
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 _flipAlignmentEdge(elementEstimate, target, gap, coverTarget) {
var alignmentEdge = elementEstimate.alignmentEdge, targetEdge = elementEstimate.targetEdge, elementRectangle = elementEstimate.elementRectangle;
var oppositeEdge = alignmentEdge * -1;
var newEstimate = _estimatePosition(elementRectangl... |
Add new Task to list | function addTask() {
var taskId = "task_" + taskCount++;
var task = createTask(taskId, "", "");
taskList[taskId] = task;
var domElement = createNewTaskDOMElement(task);
taskListDOMElements[taskId] = domElement;
showTaskDetail(task);
} |
================================================================================= ================================================================================== Sets the iinput array that is the first table in the Data View. ================================================================================== | 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... |
This function is to update a data source | 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... |
function to pop up overlay with winning message | 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... |
(public) this mod a | 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;
} |
Read the last five messages to the users | 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... |
create function to check if the last move made makes this a win display winning message if it is a winner | 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... |
Aux function that retrieves the indentation level of some code line, useful for YAML decoding. | function indentLevel(linea) {
var level = 0;
for ( i in linea ) {
if ( linea[i] != ' ' ) { break;}
level += 1;
}
return (level);
} |
pure javascript to scale the game | 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... |
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 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... |
Returns the monster name for a given monster ID. Requires the sky_monster file to be loaded. | function getMonName(monId) {
var female = (monId > 600);
if (female) {
monId -= 600;
}
if (WMSkyPoke[monId]) {
// (female ? "[F]" : "[M]") +
return WMSkyPoke[monId];
}
else {
return "Unknown";
}
} |
static contextType = ThemeContext; | render() {
return (
<ThemeContext.Consumer>
{
value => (
<div style={{ border: `5px solid ${value.color}`, padding: "5px" }}>
<div>Header</div>
<Title />
</div>... |
Mix in a 32bit integer into the pool | 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;
} |
Returns whether the specified locator is a dependency tree root (in which case it's part of the project) or not | 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;
} |
==================== getLongestWord v2 ==================== | function getLongestWord(word1, word2) {
return (word1.length > word2.length) ? word1 : word2;
} |
returns the covariance of X and Y | 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... |
Remove page from object | function removeProp(obj, propName) {
const changedObj = { ...obj };
if (changedObj[propName]) {
delete changedObj[propName];
}
return changedObj;
} |
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... | function totalCells(){
var rows = countRows();
var cols = countColumns();
var size = rows * cols;
return size;
} |
move all items into array and then dequeu | 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();
} |
Called when a user clicks on a circle | 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... |
The chart function Selects a div element (selection) and appends an SVG with the horizontal bar chart | function chart(selection) {
// **********************
// handing new personalized data
// **********************
d3.select("#chart svg")
.remove();
data.forEach(function(d) {
nameLookup[d.name] = d;
});
color
.range(... |
Get the line number of the start of the next visual line after the given line. | 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
} |
===== End of Funcion para agregar usuario ====== /========================================= = Update de usuario = ========================================= | 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... |
for listing users for dev testing (excluding passwords) | function getUsers() {
return db('users')
.select('id', 'username')
} |
if strike not already in object, make a new object for the strike THEN add the call or put | function makeNewStrike(line, strikeHorder){
strikeHolder[line.strike] = {};
strikeHolder[line.strike].numberStrike = line.numberStrike;
sortCallsAndPuts(line, [strikeHolder[line.strike]]);
} |
let dom: HTMLElement | null = document.getElementById('root'); console.log(dom.id) | function getStr(str) {
console.log(str.length);
} |
GETTING THE MOVIE WHICH IS SELECTED | 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... |
using this function for both actors array and genre array by passing true or false to isActor | 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(... |
lets you read chars, and optionally reset the cursor to where it was before reading | 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
}
}
} |
Implement the search function | 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 ... |
Return true if |object|.|property| can be called without throwing an error. | function canAccessProperty(object, property) {
try {
const unused = object[property];
return true;
} catch (errors) {
return false;
}
} |
get endDate contract in modal register ticket from comboboxDate | 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;
}
... |
Function for adding new item from form | 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){
... |
practice comparing different values | function compareEquality1(a, b) {
if(a == b) {
return "Equal";
}
return "Not Equal";
} |
this method is called when your extension is deactivated | function deactivate() {} |
Sample Populasi population = generate_population(5) fitnesses = calculate_population_fitness(population) console.log(sample_population(population, fitnesses)) | 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... |
Display the list of Tiles for the current Project. | 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);
} |
Split a data attribute by | and return the trimmed parts | 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;
} |
Submit a password change request to the backend. | 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
... |
Write a function where() that filters for all the values in the properties object. | 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)
... |
evaluate all cells and build new matrix for next generation | 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) {
... |
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 loadTable() {
if (hiddenCmd.dispatch) {
hiddenCmd.dispatch("refresh");
} else {
setTimeout(loadTable, 1000);
}
} |
Toggle expanded / collapsed versions of items' images | 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)... |
Hits API with body of carve | 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... |
vuerouter v3.0.1 (c) 2017 Evan You | function n(t,e){if(!t)throw new Error("[vue-router] "+e)} |
=========================================================================== Send a value on a given number of bits. IN assertion: length <= 16 and value fits in length bits. | 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 += ... |
globals canvasDatagrid: false / this file is for developing in a sandbox on a local machine | 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;
... |
feeds the food array to the renderedList to fix performance | 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);... |
A special extend for ajax options that takes "flat" options (not to be deep extended) Fixes 9887 | 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... |
An agent to draw queues for bfs and dfs | 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... |
Catch the information of each animal | 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... |
Flash error message and redirect the user back | 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... |
Returns information about a package in a safe way (will throw if they cannot be retrieved) | 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... |
This command remove 1 or more Tasks | 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);
}
}
} |
Refactoring, using Multiple Pointers method Time Complexity O(N), Space Complexity O(1) | 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 (... |
removes user by UID returns true if successful, false otherwise | removeUser(userID) {
if(userID in this.users) {
delete this.users[userID];
return true;
}
else {
return false;
}
} |
Renders the AWS CloudFormation properties of an `AWS::ServiceDiscovery::HttpNamespace` resource | function cfnHttpNamespacePropsToCloudFormation(properties) {
if (!cdk.canInspect(properties)) {
return properties;
}
CfnHttpNamespacePropsValidator(properties).assertSuccess();
return {
Name: cdk.stringToCloudFormation(properties.name),
Description: cdk.stringToCloudFormation(pro... |
Read the documentation ( to customize this controller | 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,
});
}
... |
end of doc load | function parseXML(xml){
console.log("in parseXML");
$("h1").html("Final Project Assignment<br>" + "Kody Scharf, Andrew Lee<br>" + "991455754, 991457820<br>");
} |
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. | 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... |
Displays the "empty page" message on the page | function displayEmptyPageMessage() {
$("#emptyPageMessageWrapper").removeClass("hidden");
} |
Leo wrote this given a boolean, sets user's privacy setting | 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)... |
Funcion para poblar los campos | 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));
} |
Method to select/unselect wound from wound list | 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... |
Redirect to the real url | function redirect(url, response) {
console.log('redirect to ' + url);
response.writeHead(301, {Location: 'http://' + url});
response.end();
} |
Returns the current run time | function getCurrentRunTime(startTime, currentTime = undefined) {
if (currentTime === undefined) {
currentTime = new Date().getTime();
}
return currentTime - startTime;
} |
Parse the input string and return an object with department and courseNumber properties filled in. | 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;
} |
Update the cart count in the header nav with the number of items in the Cart | function updateCounter() {
var cartCounter = document.getElementById('itemCount');
cartCounter.textContent = cart.items.length;
} |
Return true if the object passed in implements any of the named methods. | 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... |
vote poll from Albert's codes | 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));
} |
Returns a new createHistory function that may be used to create history objects that know how to handle URL queries. | 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... |
for consuming queuelike objs | consume (key) {
if (_state[key].length > 0)
return _state[key].shift();
return false;
} |
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 | function date(callback) {
console.log(new Date);
setTimeout(function() {
let date = new Date;
callback(date);
},3000)
} |
helper function is used to show the task which was assigned by you to someone | 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... |
TODO publish internal ReactClass displayName transform | 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... |
Assert a compiler is available. | function assertCompiler(name, Compiler) {
if (typeof Compiler !== 'function') {
throw new Error('Cannot `' + name + '` without `Compiler`')
}
} |
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 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) ... |
Keeps the game going until the final question, then it will switch to the final screen. | function wait() {
if ( questionCounter < 7 ) {
questionCounter++;
generateHTML();
counter = 30;
timerWrapper();
} else {
finalScreen();
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.