anchor stringlengths 10 14.3k | positive stringlengths 10 14.9k |
|---|---|
function createTodo() {
var titleVal = $todoTitle.value;
var descrpVal = $todoDescrp.value;
// event entered multiple space will be removed because of trim() method
if (titleVal.trim() != "") {
todoList.push({
title: titleVal,
descrp: descrpVal
});
showDOMList();
document.querySel... | the function will create todo and get the data |
function resetComponentStateWhenRemoved(vm) {
const {
state
} = vm;
if (state !== VMState.disconnected) {
const {
oar,
tro
} = vm; // Making sure that any observing record will not trigger the rehydrated on this vm
tro.reset(); // Making sure that any observing acce... | while preventing any attempt to rehydration until after reinsertion. |
function r(o,M){var D=o.split("_");return M%10==1&&M%100!=11?D[0]:M%10>=2&&M%10<=4&&(M%100<10||M%100>=20)?D[1]:D[2]} | ! moment.js locale configuration |
function listenToScroll() {
logTrace('invoking listenToScroll()');
const interval = 1000;
window.clearInterval(checkForItemsInterval);
checkForItemsInterval = window.setInterval(function checkForItems() {
// prevent listening during page load
if (pageLoads === true) {
logVerbose('Stopped checkForI... | Checks for unprocessed items in the directory of the current page and dispatches a scroll event if necessary. |
function highlightCurrentCode() {
// Change the css property by applying a highlighted background color of orange
$("#code_" + registers["rip"]).css('background-color', '#df9857');
} | $ is abbreviated to be: document.querySelect() Find all HTML elements with id:code_numberHere Retrieve the address name from the registers object and tap into the rip property which will retrieve the address of the current function For example, HTML element could have id="code_1000" which refers to the row with address... |
constructor () {
} | WeaponCtrl is a seperate class, used for deciding what type of weapon the player is currently using. It is a body in the level |
function addZone() {
if ($('#location').hasClass("is-valid") && $('#zoneName').hasClass("is-valid")) {
let name = $('#zoneName').val();
let latitude = $('#location').attr("data-latitude");
let longitude = $('#location').attr("data-longitude");
let radius = $('#radius').val() === '' ?... | Build a zone from the values in the form, formatted as YAML. This shouldn't be called unless input has been validated. It will sanity check for the "isvalid" class in the name and coordinates field. |
function monkeyPatch() {
return {
transform: (code, id) => {
const file = path.parse(id).base;
// Only one define call per module is allowed by requirejs so
// we have to remove calls that other libraries make
if (file === 'FileSaver.js') {
code = code.replace(/define !== null\) &... | Monkey patching filesaver and html2canvas |
has(soundName) {
return this._titleCase(soundName) in this.dict;
} | Return whether or not the sound exists in the sound library. |
function attemptSignIn(email,password){
firebase.auth().signInWithEmailAndPassword(email, password).then((user) => {
uid = user.user.uid;
}).catch((error) => {
console.log(error);
});
} | Attempt sign in, used by the form in the sign in menu. |
function Hidden(props) {
var _props$implementation = props.implementation,
implementation = _props$implementation === void 0 ? 'js' : _props$implementation,
_props$lgDown = props.lgDown,
lgDown = _props$lgDown === void 0 ? false : _props$lgDown,
_props$lgUp = props.lgUp,
lgUp = _props$lg... | Responsively hides children based on the selected implementation. |
function load_all_time_slots() {
$.post('gate_man_AJAX/load_all_time_slots.php',{
},function(data){
if (typeof data === 'object'){
parse_data(data);
}else if(data){
create_exception(data ,23,'danger');
}else{
create_exception("Could not connect to the ... | ajax request na ziskanie dat pre gate_man |
voting() {
return __awaiter(this, void 0, void 0, function* () {
const deployed = this.requireDeployed();
return yield deployed.methods.voting().call();
});
} | Return the address of the plcrvoting referenced by this contract instance |
decodeHtml(html) {
const txt = document.createElement('textarea');
txt.innerHTML = html;
return txt.value;
} | href = Thiago Vallin / Rafa Reis |
function tab (stroke, stb){
let table = document.createElement("table");
document.body.append(table)
for(let i = 0; i < stroke; i++){
let tr = document.createElement("tr");
tr.classList.add('box')
for(let i = 0; i < stb; i++){
let td = document.createElement("td");
... | let table = document.createElement("table"); let tr = document.createElement("tr"); let td = document.createElement("td"); console.log(tr) console.log(td) |
async function initializeDatabases() {
// const databases = await Promise.all([connect(uri)]);
const searchbar = await connect(
connectionString,
'searchbar'
);
databases.searchbar = searchbar;
} | Intializes all database connections and adds them to the databases storage object. Allows for database connections to be reused and passed to other files. Needs to be run before the server starts listening for requests. |
function optionEdit(assign_id, optionData) {
var data = optionData.split('|');
var elements = $('opt_mid').getElementsByTagName('option');
for (i=0; i<elements.length; i++) {
elements[i].removeAttribute('selected');
if (data[1] == '0') {
if (elements[i].value == data[0] && elements[i].getAttribute('class'... | End CrossBrowser DHTML Menu / New Options code |
randomVec (length) {
const deg = 2 * Math.PI * Math.random();
return Util.scale([Math.sin(deg), Math.cos(deg)], length);
} | Return a randomly oriented vector with the given length. |
function normalizeProps (options, vm) {
var props = options.props;
if (!props) { return }
var res = {};
var i, val, name;
if (Array.isArray(props)) {
i = props.length;
while (i--) {
val = props[i];
if (typeof val === 'string') {
name = camelize(val);
res[name] = { type: nul... | Ensure all props option syntax are normalized into the Objectbased format. |
function closeWindow(modalId, modalId2) {
var modal = document.getElementById(modalId);
var modal2 = document.getElementById(modalId2);
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
} el... | When the user clicks anywhere outside of the modal, close it |
constructor(socketIoInstance) {
this.rooms = {};
SafeSocket.socketsOn(socketIoInstance, 'connection', (socket) => {
Logger.logInfo('socket ' + socket.id + ' connected');
socket.emit('clientConnectedToServer', {
socketId: socket.id
});
// Default socket.io actions
socket.... | Constructs a new RoomPool and sets listeners and emitters from the given socket.io instance. |
function WishlistManage(id, id_wishlist)
{
$.ajax({
type: 'GET',
async: true,
url: baseDir + 'themes/raindrop/modules/blockwishlist/managewishlist.php',
data: 'id_wishlist=' + id_wishlist + '&refresh=' + false,
cache: false,
success: function(data)
{
$('#' + id).hide();
$('#' + id).html(... | Show wishlist managment page |
function toPartialClassName(param) {
switch (param) {
case 0 :
return "1/2";
case 1 :
return "1/3";
case 2 :
return "2/3";
case 3 :
return "1/4";
case 4 :
return "3/4";
case 5 :
return "1/5";
case 6 :
... | No side effect Generated by BUCKLESCRIPT VERSION 5.0.3, PLEASE EDIT WITH CARE |
function destroyTextures () {
for (var i = 0; i < numTexUnits; ++i) {
gl.activeTexture(GL_TEXTURE0 + i);
gl.bindTexture(GL_TEXTURE_2D, null);
textureUnits[i] = null;
}
values(textureSet).forEach(destroy);
stats.cubeCount = 0;
stats.textureCount = 0;
} | Called when regl is destroyed |
setStart(x, y){
if (this.alive == false){
this.x = x + 130;
this.y = y + 17;
}
} | function for setting the start coordinates for the projectile |
function createEntityNode(entidade, atributo, atributoValor) {
var xml = "<?xml version='1.0' encoding='utf-8'?>" +
"<soap:Envelope xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'" +
" xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'" +
" xmlns:xsd='http://www.w3.org/2001/XMLSchema'>" +
GenerateAuthenti... | Criar Dados em Outra Entidade |
function vary(avg, percentage, min, max) {
var value = avg * (1 + ((percentage / 100) * (2 * Math.random() - 1)));
value = Math.max(value, min);
value = Math.min(value, max);
return value;
} | Simple formula generating a random value around the average in between min and max |
function point_offset(i) {
return 4*i;
} | Get offset for starting at point i |
function normalizeKeyMap(keymap) {
var copy = {};
for (var keyname in keymap) { if (keymap.hasOwnProperty(keyname)) {
var value = keymap[keyname];
if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) { continue }
if (value == "...") { delete keymap[keyname]; continue }
var keys = map(k... | This is a kludge to keep keymaps mostly working as raw objects (backwards compatibility) while at the same time support features like normalization and multistroke key bindings. It compiles a new normalized keymap, and then updates the old object to reflect this. |
function ballReset() {
if (player1Score >= WINNING_SCORE ||
player2Score >= WINNING_SCORE) {
showingWinScreen = true;
}
ballSpeedX = -ballSpeedX;
ballX = canvas.width / 2;
ballY = canvas.height / 2;
} | Restart the ball from the center of the screen |
function precacheNode(inst, node) {
var hostInst = getRenderedHostOrTextFromComponent(inst);
hostInst._hostNode = node;
node[internalInstanceKey] = hostInst;
} | Populate `_hostNode` on the rendered host/text component with the given DOM node. The passed `inst` can be a composite. |
function getIndexFromName(name)
{
var i;
for(i=0; i<svgObjectNames.length; i++)
if(svgObjectNames[i] == name)
return i;
throw new Error("Did not find '" + name + "'.");
} | From module 'name' (e.g. 'density'), find numeric index in the 'svgObjectNames' array. |
function through2 (construct) {
return function (options, transform, flush) {
if (typeof options == 'function') {
flush = transform
transform = options
options = {}
}
if (typeof transform != 'function')
transform = noop
if (typeof flush != 'function')
flush = null... | create a new export function, used by both the main export and the .ctor export, contains common logic for dealing with arguments |
contents_of_input(e){
e.preventDefault();
var val = {text: this.refs.formControl.value, done:false, id: this.state.id }; // retrieve input
const current_array = Array.from(this.state.todos); // copy of current array
current_array.push(val); // pushing value of current array
console.log(current_... | Button Function to actually get the content of what the user has put in the box |
function moveSortVal(pos,mv){
"use strict";
//fill in for larger sizes!
return 0;
} | assign val to move for sorting |
function funescape(_, escaped, escapedWhitespace) {
var high = parseInt(escaped, 16) - 0x10000;
// NaN means non-codepoint
return high !== high || escapedWhitespace
? escaped
: high < 0
? // BMP codepoint
String.fromCharCode(high + 0x10000)
: // Supple... | Unescape function taken from |
function squareDigits(num){
return Number(('' + num).split('').map(function (val) { return val * val;}).join(''));
} | question / Welcome. In this kata, you are asked to square every digit of a number. For example, if we run 9119 through the function, 811181 will come out, because 92 is 81 and 12 is 1. Note: The function accepts an integer and returns an integer answer standard |
function iteratorFor(items) {
var iterator = {
next: function() {
var value = items.shift()
return {done: value === undefined, value: value}
}
}
if (support.iterable) {
iterator[Symbol.iterator] = function() {
return iterator
}
}
return... | Build a destructive iterator for the value list |
_getReleaseTagForDeclaration(declaration) {
let releaseTag = ReleaseTag_1.ReleaseTag.None;
// We don't want to match "bill@example.com". But we do want to match "/**@public*/".
// So for now we require whitespace or a star before/after the string.
const releaseTagRegExp = /(?:\s|\*)@(in... | NOTE: THIS IS A TEMPORARY WORKAROUND. In the near future we will overhaul the AEDoc parser to separate syntactic/semantic analysis, at which point this will be wired up to the same ApiDocumentation layer used for the API Review files |
function movePropDefsToProto(proto) {
var stype = proto.entityType || proto.complexType;
var extra = stype._extra;
var alreadyWrapped = extra.alreadyWrappedProps || {};
stype.getProperties().forEach(function (prop) {
var propName = prop.name;
// we only want to wrap props that haven't alre... | private methods This method is called during Metadata initialization to correctly "wrap" properties. |
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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.