anchor stringlengths 10 14.3k | positive stringlengths 10 14.9k |
|---|---|
function checkCommentOwnership(req, res, next) {
if (req.isAuthenticated()) {
Comment.findById(req.params.comment_id, function(err, foundComment) {
if (err) {
console.log('Error with edit comment route ', err);
res.redirect('back');
} else {
// does user own the comment
... | middleware to check if a user owns the comment |
function DatePicker( picker, settings ) {
var calendar = this,
elementValue = picker.$node[ 0 ].value,
elementDataValue = picker.$node.data( 'value' ),
valueString = elementDataValue || elementValue,
formatString = elementDataValue ? settings.formatSubmit : settings.format
cale... | The date picker constructor |
function tag(name, attrs, selfclosing) {
if (this.disableTags > 0) {
return;
}
this.buffer += ('<' + name);
if (attrs && attrs.length > 0) {
var i = 0;
var attrib;
while ((attrib = attrs[i]) !== undefined) {
this.buffer += (' ' + attrib[0] + '="' + attrib[1] + '"');
i++;
}
}
... | Helper function to produce an HTML tag. |
function fetch(filename) {
var att = atts[filename];
var path = encodeDocId(doc._id) + '/' + encodeAttachmentId(filename) +
'?rev=' + doc._rev;
return ajaxPromise(opts, {
method: 'GET',
url: genDBUrl(host, path),
binary: true
}).then(function (blob... | we fetch these manually in separate XHRs, because Sync Gateway would normally send it back as multipart/mixed, which we cannot parse. Also, this is more efficient than receiving attachments as base64encoded strings. |
function storeActivity(nsp, activity) {
db.activities.insert(doc, function(err, doc){
if (err) {
console.log("[!] Error storing activity: "+err);
}
else {
nsp.emit('network', {activity: doc});
}
});
} | Store activity for /Network relay |
function attachRefs() {
ReactRef.attachRefs(this, this._currentElement);
} | Helper to call ReactRef.attachRefs with this composite component, split out to avoid allocations in the transaction mountready queue. |
handleKeydownOnHost(event) {
if (event.altKey && event.keyCode === DOWN_ARROW) {
this.dtPicker.open();
event.preventDefault();
}
} | Open the picker when user hold alt + DOWN_ARROW |
function parseHexUtf16(str, start, end) {
var result = '';
while (start < end) {
// UTF-16, so swizzle the bytes
result += String.fromCharCode(
(hexToInt(str.charCodeAt(start + 2)) << 12) |
(hexToInt(str.charCodeAt(start + 3)) << 8) |
(hexToInt(str.charCodeAt(start)) << 4) |
he... | Example: pragma encoding=utf16; select hex('A'); returns '4100' notice that the 00 comes after the 41 (i.e. it's swizzled) |
function greeting (hi, hello,hey,sup){ {
return ('hi', hi)
return ('hello', hello)
return ('hey', hey)
return ('sup', sup)
}
} | spread operator changes the elements into an array as individual separate arguments |
function RSADoPublic(x) {
return x.modPowInt(this.e, this.n);
} | Perform raw public operation on "x": return x^e (mod n) |
static restoreSelectedSwitchesInMainScreen(symbolsArr) {
symbolsArr.forEach(function(symbol) {
$(`#${symbol}`).prop("checked", true);
});
} | After returning to main screen from other screen in the site |
function FieldPath$1() {
var fieldNames = [];
for (var _i = 0; _i < arguments.length; _i++) {
fieldNames[_i] = arguments[_i];
}
validateNamedArrayAtLeastNumberOfElements('FieldPath', fieldNames, 'fieldNames', 1);
for (var i = 0; i < fieldNames.length; ++i) {
... | Creates a FieldPath from the provided field names. If more than one field name is provided, the path will point to a nested field in a document. |
function Guidewire_ExtractSrcFromURL() {
var VarDocumentURL = window.WWHFrame.location;
var TheParametersArray = VarDocumentURL.hash.split("&");
var thisParam;
var FMSourceFile = "UNKNOWN_FRAMEMAKER_SOURCE_FILE";
k = TheParametersArray.length;
for (i= 0 ; i < k; i++) {
thisParam = unescape(TheParametersArray... | extracts the src=myfilename from the URL |
function clearOpponentsHand() {
$('.opponent-hand').empty();
} | clears opponents hand, to be used before refreshing players hand |
function PivotContextMenu(parent){/* eslint-enable */this.parent=parent;this.parent.contextMenuModule=this;} | eslintdisable Constructor for render module |
addContent(name, content) {
//@TODO
let word_map = new Map();
let word_count = new Map();
let map_filename = new Map();
this.words(content);
map3.set(name,content);
let word_offset = [];
let match;
while(match = WORD_REGEX.exec(content)){
if(!this.noise_words.has(match[0])){... | Add document named by string name with specified content to this instance. Update index in this with all nonnoise normalized words in content string. |
function manipulationTarget( elem, content ) {
return jQuery.nodeName( elem, "table" ) &&
jQuery.nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ?
elem.getElementsByTagName("tbody")[0] ||
elem.appendChild( elem.ownerDocument.createElement("tbody") ) :
elem;
} | Support: IE<8 Manipulating tables requires a tbody |
constructor(initList, initIndex){
this.todoList = initList;
this.initList = initList;
this.todoIndex = initIndex;
this.todoItem = this.todoList.items[this.todoIndex];
} | THIS IS THE OBJECT IT WILL MANIPULATE |
function isCrushed() {} | This is a dummy function to check if the function name has been altered by minification. If the function has been minified and NODE_ENV !== 'production', warn the user. |
function mutate(population, mutation_probability) {
for (var i = 0; i < population.length; i++) {
random = Math.random()
if (random < mutation_probability) {
cur_chromosome = population[i]
random = Math.round(Math.random() * (cur_chromosome - 1)) + 0
random_gen = cur_chromosome[Math.round(Ma... | Mutasi population = generate_population(5) mutation_probability = 0.0001 console.log(mutate(population, mutation_probability)) |
preload(scene) {
} | Called when the game preloads assets for later use |
function formatTrim(s) {
out: for (var n = s.length, i = 1, i0 = -1, i1; i < n; ++i) {
switch (s[i]) {
case ".": i0 = i1 = i; break;
case "0": if (i0 === 0) i0 = i; i1 = i; break;
default: if (i0 > 0) { if (!+s[i]) break out; i0 = 0; } break;
}
}
return i0... | Trims insignificant zeros, e.g., replaces 1.2000k with 1.2k. |
function expand(url, params, variables) {
var tmpl = parse(url),
expanded = tmpl.expand(params);
if (variables) {
variables.push.apply(variables, tmpl.vars);
}
return expanded;
} | URL Template v2.0.6 ( |
function resetScore() {
if (lethal) {
score = 0;
lives = 2;
}
else {
return;
}
} | this function stops the player spamming reset until they get favourable wires yet still allows to retain their score pressing reset after picking the correct wire |
function writeOrBuffer(stream, state, chunk, encoding, cb) {
chunk = decodeChunk(state, chunk, encoding);
if (Buffer.isBuffer(chunk))
encoding = 'buffer';
var len = state.objectMode ? 1 : chunk.length;
state.length += len;
var ret = state.length < state.highWaterMark;
// we must ensure that previous n... | if we're already writing something, then just put this in the queue, and wait our turn. Otherwise, call _write If we return false, then we need a drain event, so set that flag. |
function configFromRFC2822(config) {
var match = rfc2822.exec(preprocessRFC2822(config._i));
if (match) {
var parsedArray = extractFromRFC2822Strings(match[4], match[3], match[2], match[5], match[6], match[7]);
if (!checkWeekday(match[1], parsedArray, config)) {
r... | date and time from ref 2822 format |
function crystalsRandomSel() {
var C = Math.floor(Math.random() * 12) + 1;
return C;
} | random numbers selected for the crystals, between range 1 12 |
travelTo(gameObjectTravelling, finalPosition, time, parameters) {
const _from = {
x: gameObjectTravelling.position.x,
y: gameObjectTravelling.position.y,
z: gameObjectTravelling.position.z
};
const _to = {
x: finalPosition.x,
y: finalPosition.y,
z: finalPosition.z
};... | TODO: add tweening register of what objects are travellng TODO: make function parameters an object and use proptypes or alternative to specify mandatory fields and have auto complete. |
async function findByMatricula(matricula){
let estudiante = await db.Estudiante.findAll({
where: {
matricula: matricula
}
});
return estudiante;
} | Busca estudiante por matricula |
function workspaceDisplay(){
console.log("data.workspacesAll: ", data.workspacesAll);
let parking, transit;
let workspaceIndex = [];
//fix array iterations
for (let i = 0; i < displayArray.length; i++) {
if (disp... | Filter and Sort buttons Sort buttons can be done in Switch/Case with querySelectorAll Filter dropdowns needs to search through workspacesAll to populate values Need a submit button? Need to remember filter and sort values Need to display from a display array |
function fixLogo() {
var c = document.getElementsByTagName('td')[1];
// background to ibdof logo
c.className = 'topbkg';
// replace the ibdof logo
c.getElementsByTagName('img')[0].src = 'data:image/gif;base64,R0lGODlhaAFrAPcAAPr7/PT2/PT29PTy9Ozu7OTu9OTm5OTi5Nje5Nzd3NLa3NTT1MDW3MTS1MzO1MzNzMTOzMHO1L/KzMDG... | Prepare the header to receive styling Replace the ibdof logo gif with a background transparent version Note: cell addresses are relative to cell[0] == class 'bodyline' |
function Arrayception(array, depth = 0) {
var depth = 0
var maxdepth = 0
function checkArray(arr) {
for (var i = 0; i < arr.length; i++) {
if (!Array.isArray(arr[i]) && depth === 0) {
depth++;
if (depth > maxdepth) {
maxdepth = depth
... | Given an array of arbitrarily nested arrays, return n, where n is the deepest level that contains a nonarray value. Examples Input Output array: [ [ 5 ], [ [ ] ] ] ==>2 array: [ 10, 20, 30, 40 ] ==>1 array: [ [ 10, 20 ], [ [ 30, [ 40 ] ] ] ] ==>4 array: [ ] ==>0 array: [ [ [ ] ] ] ==>0 |
function addDateStr(messageObj) {
const errMsg = "Unable to parse date stamp in message object";
const months = [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
];
const d = new Date(message... | Add a humanreadable date string to a message object. |
function getStatus(trigger,sampleData) {
switch(trigger.op){
case "less":
if (sampleData < trigger.val){
console.log("alarm trigged at",new Date(),"sampleData",sampleData,"less then trigger",trigger.val);
return true;
}
break;
case "larger":
... | Check if alarms are triggered |
cancel() {
this.state.cancelRender = true;
} | Cancels any currently inprogress render. |
function setWebhook() {
var url = telegramUrl + "/setWebhook?url=" + webAppUrl;
var response = UrlFetchApp.fetch(url);
Logger.log(response.getContentText());
} | Set url to receive incoming Telegram updates to the webAppUrl of the published Google script |
function App() {
const announcementsList = useSelector((state) => state.announcementList.list);
const [cookie, setCookie, removeCookie] = useCookies(['userToken']);
useEffect(()=>{
document.title = "Virtual Notice Board";
}, [])
return (
<div className = 'App'>
<div cla... | Core of the application, specifies all the routes with React Router allowing website to be multi paged |
function createDisposable(request, idx) {
var disposed = false;
return function() {
if (disposed || request._disposed) {
return;
}
disposed = true;
request._callbacks[idx] = null;
request._optimizedPaths[idx] = [];
request._requestedPaths[idx... | Creates a more efficient closure of the things that are needed. So the request and the idx. Also prevents code duplication. |
function valAtIndex (view, index) {
return view.viewAtIndex(index).stringValue()
} | A quick way to get the value of text fields in the alerts |
function yAxis() {
return d3.axisLeft(y)
.tickSize(-width)
.tickFormat("")
} | Gridlines in y axis function |
function checkLine( num ){
if( board.grid[0][num].bool && board.grid[1][num].bool &&board.grid[2][num].bool &&board.grid[3][num].bool &&board.grid[4][num].bool &&board.grid[5][num].bool &&board.grid[6][num].bool &&board.grid[7][num].bool &&board.grid[8][num].bool &&board.grid[9][num].bool ){
board.grid.forEach( f... | sorry I couldn't get forEach or every to work... it was probably because of varriable scoping issues |
function replaceObjectElements(_this, counter) {
var imgType;
var displayType;
var counter = counter;
var newURL;
// get dimensions of current svg
var width = Math.floor(_this.outerWidth());
var height = Math.floor(_this.outerHeight());
var backgroundSiz... | Replace all 'object' elements with images of nick cage. Note this is best done with a background image. |
function setUserInfo(request) {
return {
_id: request._id,
username: request.username,
email: request.email
};
} | We don't want to use the entire user object to sign our JWTs that's a lot of information to eventually store in a cookie. Plus, we don't want to be returning huge blocks of what could be sensitive user information. We need control. Let's create a function to select the user information we want to pass through |
handle () {
console.log(this.creep.memory.role + ' is not valid role for ' + this.creep.name);
} | Main entry into role, called for every creep with that role every tick. Must be overridden by Role subclasses. |
function lineAtHeight(chunk, h) {
var n = chunk.first;
outer: do {
for (var i$1 = 0; i$1 < chunk.children.length; ++i$1) {
var child = chunk.children[i$1], ch = child.height;
if (h < ch) { chunk = child; continue outer }
h -= ch;
n += child.chunkSize();
}
return... | Find the line at the given vertical position, using the height information in the document tree. |
function fetchStarred(login, nextPageUrl) {
return {
login,
[CALL_API]: {
types: [ STARRED_REQUEST, STARRED_SUCCESS, STARRED_FAILURE ],
endpoint: nextPageUrl,
schema: Schemas.REPO_ARRAY
}
}
} | Fetches a page of starred repos by a particular user. Relies on the custom API middleware defined in ../middleware/api.js. |
function cleanDocs(docs) {
for (var i = 0; i < docs.length; i++) {
var doc = docs[i];
if (doc._deleted) {
delete doc._attachments; // ignore atts for deleted docs
} else if (doc._attachments) {
// filter out extraneous keys from _attachments
var atts = Object.keys(doc._attachments... | clean docs given to us by the user |
function changeorder( arr, ordernum ) {
var thisorder = ordernum;
var shufflelocations = new Array();
for (var i=0; i<arr.length; i++) {
shufflelocations.push(i);
}
for (i=arr.length-1; i>=0; --i) {
var loci = shufflelocations[i];
var locj = shufflelocations[thisorder%(i+1)];
thisorder = Math.floo... | We want to be able to alias the order of stimuli to a single number which can be stored and which can easily replicate a given stimulus order. |
function getMapped(state, dispatch, ownProps) {
const Connected = require('./index').default;
expect(mockConnect).toBeCalled();
const [
mapStateToProps,
mapDispatchToProps,
mergeProps,
] = mockConnect.mock.calls[0];
expect(mapStateToProps)
.toBeInstanceOf(Function);
expect(mapDispatchToPro... | sorting order null > 'asc' > 'desc' |
function adjust() {
var height, originalHeight;
if (mirrored !== ta) {
initMirror();
} else {
setWidth();
}
if (!ta.value && options.placeholder) {
// If the textarea is empty, copy the placeholder text into
// the mirror control and use that for sizing so that we
// don't... | Using mainly bare JS in this function because it is going to fire very often while typing, and needs to very efficient. |
function colorgenerator() {
let colours = [],
i;
for (i = 0; i < 372; i++){
colours[i] = 'hsl(' + i + ', 100%, 50%)';
if (i > 359) {
colours[i] = 'hsl(0, 100%, 100%)';
}
}
colours = colours.toString();
//console.log(colours);
root.style.setProperty("--... | Generates all the rainbow colours for the colour slider selector |
function positionFromMove(mv,pos){
"use strict";
var pscp = pos.clone(), nm, i, p = pos.plyr, op, cap, mov;
pscp.sow( [ pos.plyr, mv[0][1] ] );
pscp.plyr = pos.opposite( p );
pscp.possibleMoves = false;
return pscp;
} | return new muskPos by applying given mov to given pos |
function selectHome() {
$("#home").on("click", function () {
$("#scheduleImg").addClass("hidden");
$(".contacts").addClass("hidden");
$(".emails").removeClass("hidden");
$(".nav").removeClass("hidden");
$(".files").addClass("hidden");
$("#search").addClass("hidden");
});
} | Hides and reveals the relevant elements when the home button is clicked |
function clearScene() {
context.save();
context.setTransform(h, 0.0, 0.0, -h, 0.0, h);
context.clearRect(0, 0, w, h);
context.restore();
} | This is Professor Beveridges from the rotating pacman lecture |
getApplication (opportunityId, personId, forceReload) {
var d = $q.defer();
if(!this.loadedOpportunityApplications[`${opportunityId}-${personId}`] || forceReload === true) {
$http.get(`/api/opportunity_applications/${opportunityId}/${personId}`)
.then(response => {
var applicat... | Load opportunity applications from database |
function observerON() {
debug('Turning observer ON');
if (validPointer(mainObserver)) {mainObserver.observe(mainTargetNode, mainConfig);}
} | Functions to log when we connect/disconnect main observer, for debugging |
moons (lib){
for (var i=0;i<7;i++){
let moon = this.madeMoons[i];
var size = moon.s;
lib.moveTo(moon.x, moon.y);
lib.penRGB(moon.r, moon.g, moon.b);
let movingLeft = true;
let behind = false;
if (moon.s < 6) {
... | moons: lib: code.org library Draws all the moons that are larger than or equal to 6 pixels in radius. Then, it moves them to the left before checking if it should change one into a small moon. Written by Keegan Brown |
function d(a,b){if(!(a instanceof b))throw new TypeError("Cannot call a class as a function")} | ! ctxMenu v1.1.1 | (c) Nikolaj Kappler | ! |
function migrateLocalStore(txn, cb) {
var localStore = txn.objectStore(LOCAL_STORE);
var docStore = txn.objectStore(DOC_STORE);
var seqStore = txn.objectStore(BY_SEQ_STORE);
var cursor = docStore.openCursor();
cursor.onsuccess = function (event) {
var cursor = event.target.result;
... | migration to version 3 (part 2) |
function downloadAsSVG(fileName) {
// use default name if not provided
fileName = fileName || "output.svg";
// create a data url of the file
var svgData = project.exportSVG({
asString: true
});
var url = "data:image/svg+xml;utf8," + encodeURIComponent(svgData);
// create a link to the data, and "cli... | a function to download the .svg file |
function refreshhNotifications(){
var html = '';
for(var i = 0;i < currentNotifications.length;i++){
var typeClass = "";
var typeText = "";
if(currentNotifications[i].type == "positive"){
typeClass = "positive-notification";
typeText = "dark-text";
}else if(currentNotifications[i].type == "negative"){... | Refresh notifications Subtracts the cycles (1 second a cycle), if 0 hides the notification. |
function vkXML (text, step) {
const ar = text.replace(/>\s{0,}</g, "><")
.replace(/</g, "~::~<")
.replace(/\s*xmlns\:/g, "~::~xmlns:")
// .replace(/\s*xmlns\=/g,"~::~xmlns=")
.split("~::~");
const len = ar.length;
let inComment = false;
let deep = 0;
let str = "";
const space = (step != null... | vkBeautify Version 0.99.00.beta Copyright (c) 2012 Vadim Kiryukhin |
async initializeChat(conversationData, userInfo, botTranscript) {
var buttonOverrides = new Array(process.env.BUTTON_ID);
var preChatDetails = this.initializePrechatDetails(userInfo, botTranscript);
var chasitorInit = this.initializeSalesForceChatObject(preChatDetails, userInfo, conversationData... | TODO: Pass the Bot transcript to this method for adding to the prechat details. |
function deflate_huff(s, flush) {
var bflush; /* set if current block must be flushed */
for (;;) {
/* Make sure that we have a literal to write. */
if (s.lookahead === 0) {
fill_window(s);
if (s.lookahead === 0) {
if (flush === Z_NO_FLUSH) {
return BS_NEED_MORE;
... | =========================================================================== For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table. (It will be regenerated if this run of deflate switches away from Huffman.) |
function movieList(query, sortBy, order) {
getMovies(query, sortBy, order).then((movies) => {
//console.log('Here are all the movies:');
movies.forEach(({title, rating, id, tvdb, imdb_id, fav}) => {
// console.log(`id#${id} - ${title} - rating: ${rating}`);
let moviePoster = "images... | Creates the primary movie list |
hasWidth(width, opts = { tolerance: 0 }) {
return this._node.__eventually(() => this._node.wait.hasWidth(width, { tolerance: opts.tolerance, timeout: opts.timeout }));
} | Returns true if PageElement's width eventually equals the expected width or if it deviates no more than the specified tolerance from the expected width within a specific timeout. |
function isWithinCollapsedBlock(element) {
/* If the element is not within a collapse block at all, it obviously can't
be within a *currently-collapsed* collapse block.
*/
let collapseParent = element.closest(".collapse");
if (!collapseParent) return false;
/* If the element is within a collapse block a... | Returns true if the given element is within a currentlycollapsed collapse block. |
function retrieveData(key) {
var retrieved = JSON.parse(window.localStorage.getItem(key));
return retrieved;
} | Retrive JSON from local storage |
function loadAddClubEditor(mobile) {
build = "\
<div id='editorContainer'>\
<div id='editor-fields'>\
<input type='text' id='club-name' placeholder='Name of your Club..' />\
<div id='color-picker-container'>\
<label>Color of your Club</label>\
<span id='blue' class='color-box checked' onclick='c... | Load Add Club Editor |
function createSecondPassphrase (selectedAccount) {
var bip39 = require('bip39')
var data = { secondPassphrase: bip39.generateMnemonic() }
if (selectedAccount.secondSignature) {
return formatAndToastError(
gettextCatalog.getString('This account already has a second passphrase: ' + s... | Add a second passphrase to an account |
function onAppReady(obj) {
"use strict";
console.log("init.js: onAppReady");
require(["MainApp", "Router", "Config", "DataService", "handlebars", "templates"], function (MainApp, Router, Config, DataService, handlebars, templates) {
window.app = new MainApp(Config, templates, DataSer... | Handle main application initialization. Prepare main interface by requiring all necessary modules needed for the application to run. |
static get() {
if (this._config) {
return this._config;
} else {
return this.build();
}
} | Get the config object. |
function retablir(txt, id_controle) {
if(document.getElementById(id_controle).value==''){
document.getElementById(id_controle).value=txt;
}
} | fonction qui remet la valeur (tapez votre email, tapez votre mot de passe ...) dans le champ de l'input |
function activeSubmit()
{
$.ajax(
{
url: "../ajax/active-submit.php",
type: "POST",
data: { slug: slug },
cache: false,
success: function(html)
{
$("#contributeA").html(html);
$("#contributeB").ht... | Load contribute buttons Must refresh more frequently, so it is seperate If uploading gets competitive, refresh may need to be upped |
function generateBullets (qtd) {
for (var i=0; i<qtd; i++){
var bullet = $("<a>").html("• ").attr("href","#").data("id",i);
$(".bullets").append(bullet);
}
$(".bullets a").eq(position).addClass("active");
} | criar a bolinha para mudar a foto na tela |
enterSoundName(ctx) {
} | Enter a parse tree produced by MmParsersoundName. |
function map(words, instruction) {
// console.log(words.forEach(instruction));
var result = [];
for (var i = 0; i < words.length; i++) {
result.push(instruction(words[i]));
}
console.log(result);
} | I wanted to implement forEach, but couldn't figure out how to. |
function randomImg() {
imgURL = images[Math.floor(Math.random() * images.length)];
console.log(imgURL);
} | Everything here to the check letter function is my attempt to generate a new photo every time a new word is generated. |
function isCrossing(i, k){
if ( i == k || i == k + 1 || i == k - 1){
return false;
}
var path1 = [pointarray[i].LatLng, pointarray[i + 1].LatLng, pointarray[k].LatLng];
var path2 = [pointarray[i].LatLng, pointarray[i + 1].LatLng, pointarray[k + 1].LatLng];
var path3 = [pointarray[k].LatLng, pointarray[k + ... | return true if (i,i+1) crosses (k,k+1) |
function renderModalEdit(todo) {
var form = $('#form-todo-edit');
var id = todo.attr('data-id'),
title = todo.attr('data-title'),
priority = todo.attr('data-priority'),
details = todo.attr('data-details'),
created = todo.attr('data-created'),
elapsed = parseInt(todo.attr('data-elapsed')),
... | renders todo info on edit modal |
onAddButtonClick(fn) { this.onAddButtonClickFn = fn } | fn(relativePos) Parameters: block (obj) block whose button was clicked relativePos (buttonpos) position of button (14) |
function parseExpressionAt(input, pos, options) {
var p = new Parser(options, input, pos);
p.nextToken();
return p.parseExpression()
} | This function tries to parse a single expression at a given offset in a string. Useful for parsing mixedlanguage formats that embed JavaScript expressions. |
function setup(){
database = firebase.database();
console.log(database);
createCanvas(displayWidth/2, displayHeight/2);
game = new Game();
game.start();
} | this is an array to store players info |
function fetchDocAsynchronously(metadata, row, winningRev) {
var key = metadata.id + "::" + winningRev;
docIdRevIndex.get(key).onsuccess = function onGetDoc(e) {
row.doc = decodeDoc(e.target.result);
if (opts.conflicts) {
row.doc._conflicts = collectConflicts(metadata);
... | if the user specifies include_docs=true, then we don't want to block the main cursor while we're fetching the doc |
function createNewShape() {
agentNewShape = true;
emptyShapeElements();
shape = CreateShape();
nextShape = nextShapeDisplay();
ghostShape = createGhostShape();
sortShapePos(shape);
timeStep = originalTimeStep;
} | clear old shape then load a new one from Shape.js |
function getItemPrefix() {
var prefix;
if(args.tag === "ol") {
prefix = " " + num + ". ";
num = num + 1;
} else {
prefix = " " + bullet + " ";
}
return prefix;
} | Get the item prefix e.g. " 1. " for a numbered list, " " for a bulleted list. |
function setEnabled(element, condition) {
if (condition) element.removeAttribute('disabled');
else element.setAttribute('disabled', '');
} | endregion region Element Toggle Helpers |
function handleLogout(event) {
setUser(false);
NavbarComponents.pop(); // Remove Admin page in Navbar
NavbarComponents.pop(); // Change Log out to Log in in Navbar
NavbarComponents.push(
<li key="login">
<Link to="/login">Giriş Yap</Link>
</li>
);
} | function when user logs out |
function plus1(a,b){
return(a+b);
} | Return method is a function and therefore you can use it as you would a function. To invoke a function, simply call it like this: plus1(); plus2(); Function Declarations |
function set_key(lock, key, callback) {
let str = JSON.stringify({
Action: "SET",
Attribute: "KEY",
Value: key
})
send_command(lock, str)
callback(f.hacker.ingverb())
} | Change the key in the lock |
function addScoreboardAssets(){
manifest.push({src:'assets/scoreboard/bg_scoreboard.png', id:'bgScoreboard'});
manifest.push({src:'assets/scoreboard/icon_replay.png', id:'iconReplay'});
manifest.push({src:'assets/scoreboard/icon_save.png', id:'iconSave'});
manifest.push({src:'assets/scoreboard/icon_scoreboard.png',... | ! SCOREBOARD ASSETS This is the function that runs to add scoreboard assets |
function onFireAction(){
} | functions to activate achievements |
async fetchPages(categories, callback) {
let pages = [];
for (const category of categories) {
const pagesInCategory = await request.get(
`${API_ROOT}/categories/${category}/docs`,
this.httpOptions
);
for (const json of pagesInCategory) {
pages.push(this.fetchPage(json, ... | Fetches all pages of the provided categories, calling the `callback` function for each page loaded. |
getTerminalConfiguration(terminalConfigurationId)
{
return this.dataElement.terminalConfigurations.find(tc => tc.terminalConfigurationId === terminalConfigurationId);
} | get the terminal configuration using the id |
function no_vr_plugin()
{
var errorBox = ID("errorBox");
errorBox.innerHTML = ""+
"<center>"+
"<br>"+
"<h1 style='margin-bottom:0;'>NPVR Browser Plugin required!</h1>"+
"<br>"+
"Get the plugin here and install it:<br>"+
"<br>"+
"<a href='https://github.com/CodingCooky/npvr/#npvr' target='_blank'>https:... | no vr plugin error message |
function updateWater() {
// animate water
for (var i = 0; i < water.length; i++) {
water[i].update();
water[i].draw();
}
// remove water that has gone off screen
if (water[0] && water[0].x < -platformWidth) {
var w = water.splice(0, 1)[0];
w.x = water[water.length-1].x + pla... | Update the water position and draw : object pool water sprites |
function HTML5_SolutionStorage() {
} | SOLUTION SAVING /////////////////////////////////////////// //////////////// html5 storage |
function sumZero(arr){
for(let i = 0; i < arr.lenght; i++){
for(let j = 0; j < arr.lenght; j++){
if(arr[i] + arr[j] === 0){
return [arr[i], arr[j]];
}
}
}
} | the first pair where the sum is 0. Return an array that includes both values that sum to zero or undefined if a pair does not exist. sumZero([3,2,1,0,1,2,3]) => [3,3] sumZero([2,0,1,3]) => undefined sumZero([1,2,3]) => undefined |
function insertAchievements(data)
{
var achievements="";
achievements+='<div class="row achievement" id="'+data.achievementId+'">';
achievements+='<div class="row">';
achievements+='<div class="col-md-6 text-left">';
achievements+='<div style="font-size:18px;color:#008322;"><i class="fa fa-trophy"></i>&n... | CERTIFICATONS ENDS////////////////// / / / / ////////////////////ACHIEVEMENTS STARTS |
async onReady() {
// Init info
await this.initInfoStates();
// store all current (acknowledged) state values
const allStates = await this.getStatesAsync('*');
for (const id in allStates) {
if (allStates[id] && allStates[id].ack) {
this.currentStateValu... | Is called when databases are connected and adapter received configuration. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.