language
stringclasses 6
values | original_string
stringlengths 25
887k
| text
stringlengths 25
887k
|
---|---|---|
JavaScript | function patchClass(className) {
var OriginalClass = _global[className];
if (!OriginalClass)
return;
// keep original class in global
_global[zoneSymbol(className)] = OriginalClass;
_global[className] = function () {
var a = bindArguments(arguments, className);
switch (a.length) {
case 0:
this[originalInstanceKey] = new OriginalClass();
break;
case 1:
this[originalInstanceKey] = new OriginalClass(a[0]);
break;
case 2:
this[originalInstanceKey] = new OriginalClass(a[0], a[1]);
break;
case 3:
this[originalInstanceKey] = new OriginalClass(a[0], a[1], a[2]);
break;
case 4:
this[originalInstanceKey] = new OriginalClass(a[0], a[1], a[2], a[3]);
break;
default:
throw new Error('Arg list too long.');
}
};
// attach original delegate to patched function
attachOriginToPatched(_global[className], OriginalClass);
var instance = new OriginalClass(function () { });
var prop;
for (prop in instance) {
// https://bugs.webkit.org/show_bug.cgi?id=44721
if (className === 'XMLHttpRequest' && prop === 'responseBlob')
continue;
(function (prop) {
if (typeof instance[prop] === 'function') {
_global[className].prototype[prop] = function () {
return this[originalInstanceKey][prop].apply(this[originalInstanceKey], arguments);
};
}
else {
ObjectDefineProperty(_global[className].prototype, prop, {
set: function (fn) {
if (typeof fn === 'function') {
this[originalInstanceKey][prop] = wrapWithCurrentZone(fn, className + '.' + prop);
// keep callback in wrapped function so we can
// use it in Function.prototype.toString to return
// the native one.
attachOriginToPatched(this[originalInstanceKey][prop], fn);
}
else {
this[originalInstanceKey][prop] = fn;
}
},
get: function () {
return this[originalInstanceKey][prop];
}
});
}
}(prop));
}
for (prop in OriginalClass) {
if (prop !== 'prototype' && OriginalClass.hasOwnProperty(prop)) {
_global[className][prop] = OriginalClass[prop];
}
}
} | function patchClass(className) {
var OriginalClass = _global[className];
if (!OriginalClass)
return;
// keep original class in global
_global[zoneSymbol(className)] = OriginalClass;
_global[className] = function () {
var a = bindArguments(arguments, className);
switch (a.length) {
case 0:
this[originalInstanceKey] = new OriginalClass();
break;
case 1:
this[originalInstanceKey] = new OriginalClass(a[0]);
break;
case 2:
this[originalInstanceKey] = new OriginalClass(a[0], a[1]);
break;
case 3:
this[originalInstanceKey] = new OriginalClass(a[0], a[1], a[2]);
break;
case 4:
this[originalInstanceKey] = new OriginalClass(a[0], a[1], a[2], a[3]);
break;
default:
throw new Error('Arg list too long.');
}
};
// attach original delegate to patched function
attachOriginToPatched(_global[className], OriginalClass);
var instance = new OriginalClass(function () { });
var prop;
for (prop in instance) {
// https://bugs.webkit.org/show_bug.cgi?id=44721
if (className === 'XMLHttpRequest' && prop === 'responseBlob')
continue;
(function (prop) {
if (typeof instance[prop] === 'function') {
_global[className].prototype[prop] = function () {
return this[originalInstanceKey][prop].apply(this[originalInstanceKey], arguments);
};
}
else {
ObjectDefineProperty(_global[className].prototype, prop, {
set: function (fn) {
if (typeof fn === 'function') {
this[originalInstanceKey][prop] = wrapWithCurrentZone(fn, className + '.' + prop);
// keep callback in wrapped function so we can
// use it in Function.prototype.toString to return
// the native one.
attachOriginToPatched(this[originalInstanceKey][prop], fn);
}
else {
this[originalInstanceKey][prop] = fn;
}
},
get: function () {
return this[originalInstanceKey][prop];
}
});
}
}(prop));
}
for (prop in OriginalClass) {
if (prop !== 'prototype' && OriginalClass.hasOwnProperty(prop)) {
_global[className][prop] = OriginalClass[prop];
}
}
} |
JavaScript | function patchMacroTask(obj, funcName, metaCreator) {
var setNative = null;
function scheduleTask(task) {
var data = task.data;
data.args[data.cbIdx] = function () {
task.invoke.apply(this, arguments);
};
setNative.apply(data.target, data.args);
return task;
}
setNative = patchMethod(obj, funcName, function (delegate) { return function (self, args) {
var meta = metaCreator(self, args);
if (meta.cbIdx >= 0 && typeof args[meta.cbIdx] === 'function') {
return scheduleMacroTaskWithCurrentZone(meta.name, args[meta.cbIdx], meta, scheduleTask, null);
}
else {
// cause an error by calling it directly.
return delegate.apply(self, args);
}
}; });
} | function patchMacroTask(obj, funcName, metaCreator) {
var setNative = null;
function scheduleTask(task) {
var data = task.data;
data.args[data.cbIdx] = function () {
task.invoke.apply(this, arguments);
};
setNative.apply(data.target, data.args);
return task;
}
setNative = patchMethod(obj, funcName, function (delegate) { return function (self, args) {
var meta = metaCreator(self, args);
if (meta.cbIdx >= 0 && typeof args[meta.cbIdx] === 'function') {
return scheduleMacroTaskWithCurrentZone(meta.name, args[meta.cbIdx], meta, scheduleTask, null);
}
else {
// cause an error by calling it directly.
return delegate.apply(self, args);
}
}; });
} |
JavaScript | function apply(api, _global) {
var WS = _global.WebSocket;
// On Safari window.EventTarget doesn't exist so need to patch WS add/removeEventListener
// On older Chrome, no need since EventTarget was already patched
if (!_global.EventTarget) {
patchEventTarget(_global, [WS.prototype]);
}
_global.WebSocket = function (x, y) {
var socket = arguments.length > 1 ? new WS(x, y) : new WS(x);
var proxySocket;
var proxySocketProto;
// Safari 7.0 has non-configurable own 'onmessage' and friends properties on the socket instance
var onmessageDesc = ObjectGetOwnPropertyDescriptor(socket, 'onmessage');
if (onmessageDesc && onmessageDesc.configurable === false) {
proxySocket = ObjectCreate(socket);
// socket have own property descriptor 'onopen', 'onmessage', 'onclose', 'onerror'
// but proxySocket not, so we will keep socket as prototype and pass it to
// patchOnProperties method
proxySocketProto = socket;
[ADD_EVENT_LISTENER_STR, REMOVE_EVENT_LISTENER_STR, 'send', 'close'].forEach(function (propName) {
proxySocket[propName] = function () {
var args = ArraySlice.call(arguments);
if (propName === ADD_EVENT_LISTENER_STR || propName === REMOVE_EVENT_LISTENER_STR) {
var eventName = args.length > 0 ? args[0] : undefined;
if (eventName) {
var propertySymbol = Zone.__symbol__('ON_PROPERTY' + eventName);
socket[propertySymbol] = proxySocket[propertySymbol];
}
}
return socket[propName].apply(socket, args);
};
});
}
else {
// we can patch the real socket
proxySocket = socket;
}
patchOnProperties(proxySocket, ['close', 'error', 'message', 'open'], proxySocketProto);
return proxySocket;
};
var globalWebSocket = _global['WebSocket'];
for (var prop in WS) {
globalWebSocket[prop] = WS[prop];
}
} | function apply(api, _global) {
var WS = _global.WebSocket;
// On Safari window.EventTarget doesn't exist so need to patch WS add/removeEventListener
// On older Chrome, no need since EventTarget was already patched
if (!_global.EventTarget) {
patchEventTarget(_global, [WS.prototype]);
}
_global.WebSocket = function (x, y) {
var socket = arguments.length > 1 ? new WS(x, y) : new WS(x);
var proxySocket;
var proxySocketProto;
// Safari 7.0 has non-configurable own 'onmessage' and friends properties on the socket instance
var onmessageDesc = ObjectGetOwnPropertyDescriptor(socket, 'onmessage');
if (onmessageDesc && onmessageDesc.configurable === false) {
proxySocket = ObjectCreate(socket);
// socket have own property descriptor 'onopen', 'onmessage', 'onclose', 'onerror'
// but proxySocket not, so we will keep socket as prototype and pass it to
// patchOnProperties method
proxySocketProto = socket;
[ADD_EVENT_LISTENER_STR, REMOVE_EVENT_LISTENER_STR, 'send', 'close'].forEach(function (propName) {
proxySocket[propName] = function () {
var args = ArraySlice.call(arguments);
if (propName === ADD_EVENT_LISTENER_STR || propName === REMOVE_EVENT_LISTENER_STR) {
var eventName = args.length > 0 ? args[0] : undefined;
if (eventName) {
var propertySymbol = Zone.__symbol__('ON_PROPERTY' + eventName);
socket[propertySymbol] = proxySocket[propertySymbol];
}
}
return socket[propName].apply(socket, args);
};
});
}
else {
// we can patch the real socket
proxySocket = socket;
}
patchOnProperties(proxySocket, ['close', 'error', 'message', 'open'], proxySocketProto);
return proxySocket;
};
var globalWebSocket = _global['WebSocket'];
for (var prop in WS) {
globalWebSocket[prop] = WS[prop];
}
} |
JavaScript | static clearStorage(callback) {
return createPromise(() => {
window.localStorage.clear();
}, callback);
} | static clearStorage(callback) {
return createPromise(() => {
window.localStorage.clear();
}, callback);
} |
JavaScript | acquireToken() {
return new Promise((resolve, reject) => {
this.authenticationContext.acquireToken(
'<azure active directory resource id>',
(error, token) => {
if (error || !token) {
return reject(error)
} else {
return resolve(token)
}
}
)
})
} | acquireToken() {
return new Promise((resolve, reject) => {
this.authenticationContext.acquireToken(
'<azure active directory resource id>',
(error, token) => {
if (error || !token) {
return reject(error)
} else {
return resolve(token)
}
}
)
})
} |
JavaScript | acquireTokenRedirect() {
this.authenticationContext.acquireTokenRedirect(
'<azure active directory resource id>'
)
} | acquireTokenRedirect() {
this.authenticationContext.acquireTokenRedirect(
'<azure active directory resource id>'
)
} |
JavaScript | isAuthenticated() {
// getCachedToken will only return a valid, non-expired token.
if (this.authenticationContext.getCachedToken(this.config.clientId)) {
return true
}
return false
} | isAuthenticated() {
// getCachedToken will only return a valid, non-expired token.
if (this.authenticationContext.getCachedToken(this.config.clientId)) {
return true
}
return false
} |
JavaScript | function runtime (filepath, cb) {
const data = filepath
// eslint-disable-next-line no-unused-vars
let converted = ''
let linebyline = data.split('\n')
for (let PC = 0; PC < linebyline.length; PC++) {
const line = linebyline[PC].split('=>')[0]
const lineArr = line.split('<')
const cmd = lineArr[0] ? lineArr[0].trim().toLowerCase() : ''
const arg0 = lineArr[1] ? lineArr[1].trim() : ''
switch (cmd) {
case 'modl':
if (fs.existsSync(arg0)) {
fs.readFile(arg0, (moErr, moData) => {
if (moErr) cb(moData)
moData = moData.toString('utf-8')
linebyline[PC] = ''
linebyline = moData.split('\n').concat(linebyline)
PC = (-1)
})
}
break
case 'con':
converted += '$msg.channel.send(' + arg0 + ')'
break
case 'con.err':
converted += '$msg.channel.send(\'Error: \' + ' + arg0 + ')'
break
case 'con.dir':
converted += '$msg.channel.send(JSON.stringify(' + arg0 + '))'
break
case 'exit':
converted += '$msg.channel.send(\'Returns: \'' + arg0 + ')'
break
case 'if':
converted += 'if (' + arg0 + ') {'
break
default:
if (cmd && arg0) {
converted += 'let ' + cmd + ' = ' + arg0
}
break
}
if (line.endsWith('->')) converted += '}'
converted += '\n'
}
// eslint-disable-next-line no-new-func
converted = new Function('$msg', converted)
cb(null, converted)
} | function runtime (filepath, cb) {
const data = filepath
// eslint-disable-next-line no-unused-vars
let converted = ''
let linebyline = data.split('\n')
for (let PC = 0; PC < linebyline.length; PC++) {
const line = linebyline[PC].split('=>')[0]
const lineArr = line.split('<')
const cmd = lineArr[0] ? lineArr[0].trim().toLowerCase() : ''
const arg0 = lineArr[1] ? lineArr[1].trim() : ''
switch (cmd) {
case 'modl':
if (fs.existsSync(arg0)) {
fs.readFile(arg0, (moErr, moData) => {
if (moErr) cb(moData)
moData = moData.toString('utf-8')
linebyline[PC] = ''
linebyline = moData.split('\n').concat(linebyline)
PC = (-1)
})
}
break
case 'con':
converted += '$msg.channel.send(' + arg0 + ')'
break
case 'con.err':
converted += '$msg.channel.send(\'Error: \' + ' + arg0 + ')'
break
case 'con.dir':
converted += '$msg.channel.send(JSON.stringify(' + arg0 + '))'
break
case 'exit':
converted += '$msg.channel.send(\'Returns: \'' + arg0 + ')'
break
case 'if':
converted += 'if (' + arg0 + ') {'
break
default:
if (cmd && arg0) {
converted += 'let ' + cmd + ' = ' + arg0
}
break
}
if (line.endsWith('->')) converted += '}'
converted += '\n'
}
// eslint-disable-next-line no-new-func
converted = new Function('$msg', converted)
cb(null, converted)
} |
JavaScript | function toClass(impl) {
var prop,
clazz = impl[init] || function () {};
for (prop in impl)
if (impl.hasOwnProperty(prop) && prop !== init)
clazz.prototype[prop] = impl[prop];
return clazz;
} | function toClass(impl) {
var prop,
clazz = impl[init] || function () {};
for (prop in impl)
if (impl.hasOwnProperty(prop) && prop !== init)
clazz.prototype[prop] = impl[prop];
return clazz;
} |
JavaScript | function extending(childImpl, baseImpl) {
var prop;
for (prop in baseImpl)
if (!childImpl.hasOwnProperty(prop) && prop !== init)
childImpl[prop] = baseImpl[prop];
} | function extending(childImpl, baseImpl) {
var prop;
for (prop in baseImpl)
if (!childImpl.hasOwnProperty(prop) && prop !== init)
childImpl[prop] = baseImpl[prop];
} |
JavaScript | unauthenticatedUser() {
return [
<li className="navbar-item" key={1}>
<NavLink to="/singin">Sign In</NavLink>
</li>,
<li className="navbar-item" key={2}>
<NavLink to="/signup">Sign Up</NavLink>
</li>
]
} | unauthenticatedUser() {
return [
<li className="navbar-item" key={1}>
<NavLink to="/singin">Sign In</NavLink>
</li>,
<li className="navbar-item" key={2}>
<NavLink to="/signup">Sign Up</NavLink>
</li>
]
} |
JavaScript | function testTableData(){
console.log("\n************\n" + tableData[0].name);
} | function testTableData(){
console.log("\n************\n" + tableData[0].name);
} |
JavaScript | add(file) {
this._spriter.debug('Added "%s" to processing queue', path.basename(file.path));
this._files.push(file);
this.emit('add');
} | add(file) {
this._spriter.debug('Added "%s" to processing queue', path.basename(file.path));
this._files.push(file);
this.emit('add');
} |
JavaScript | process() {
if (this._files.length && this.active < this._spriter._limit) {
++this.active;
const file = this._files.shift();
let shape;
let spriter;
// Instantiate the shape
try {
shape = new Shape(file, this._spriter);
spriter = this._spriter;
// In case of errors: Skip the file
} catch (error) {
this._spriter.error('Skipping "%s" (%s)', path.basename(file.path), error.message);
this.emit(--this.active ? 'remove' : 'empty');
return;
}
// Subsequently run through all optimization and compilation tasks
async.waterfall([
// Transform the shape
_cb => {
spriter._transformShape(shape, _cb);
},
// Complement the shape
_cb => {
shape.complement(_cb);
}
], this.remove.bind(this));
}
} | process() {
if (this._files.length && this.active < this._spriter._limit) {
++this.active;
const file = this._files.shift();
let shape;
let spriter;
// Instantiate the shape
try {
shape = new Shape(file, this._spriter);
spriter = this._spriter;
// In case of errors: Skip the file
} catch (error) {
this._spriter.error('Skipping "%s" (%s)', path.basename(file.path), error.message);
this.emit(--this.active ? 'remove' : 'empty');
return;
}
// Subsequently run through all optimization and compilation tasks
async.waterfall([
// Transform the shape
_cb => {
spriter._transformShape(shape, _cb);
},
// Complement the shape
_cb => {
shape.complement(_cb);
}
], this.remove.bind(this));
}
} |
JavaScript | function position(dot) {
dot .attr("cx", function(d) { return xScale(x(d)); })
.attr("cy", function(d) { return yScale(y(d)); })
.style("fill", function(d) {
return campus_color_map[d['campus']];
})
.style("stroke", function(d) {
return campus_color_map[d['campus']];
})
.attr("r", function(d) {
if (size_dimension.metric === 'same') {
return radiusScale(size_dimension.domain[1]);
}
return radiusScale(Math.abs(radius(d)));
});
} | function position(dot) {
dot .attr("cx", function(d) { return xScale(x(d)); })
.attr("cy", function(d) { return yScale(y(d)); })
.style("fill", function(d) {
return campus_color_map[d['campus']];
})
.style("stroke", function(d) {
return campus_color_map[d['campus']];
})
.attr("r", function(d) {
if (size_dimension.metric === 'same') {
return radiusScale(size_dimension.domain[1]);
}
return radiusScale(Math.abs(radius(d)));
});
} |
JavaScript | function displayYear(year) {
dot.data(interpolateData(year), key).call(position).sort(order);
label.text(Math.round(year));
$("#slider").val(Math.round(year));
$(".tooltip_title").text(Math.round(year));
} | function displayYear(year) {
dot.data(interpolateData(year), key).call(position).sort(order);
label.text(Math.round(year));
$("#slider").val(Math.round(year));
$(".tooltip_title").text(Math.round(year));
} |
JavaScript | function interpolateData(year) {
return data.map(function(d) {
return {
campus: d.campus,
pell: interpolateValues(d.pell, year),
gradrate: interpolateValues(d.gradrate, year),
gap: interpolateValues(d.gap, year),
total: interpolateValues(d.total, year),
};
});
} | function interpolateData(year) {
return data.map(function(d) {
return {
campus: d.campus,
pell: interpolateValues(d.pell, year),
gradrate: interpolateValues(d.gradrate, year),
gap: interpolateValues(d.gap, year),
total: interpolateValues(d.total, year),
};
});
} |
JavaScript | function interpolateValues(values, year) {
var i = bisect.left(values, year, 0, values.length - 1),
a = values[i];
if (i > 0) {
var b = values[i - 1],
t = (year - a[0]) / (b[0] - a[0]);
return a[1] * (1 - t) + b[1] * t;
}
return a[1];
} | function interpolateValues(values, year) {
var i = bisect.left(values, year, 0, values.length - 1),
a = values[i];
if (i > 0) {
var b = values[i - 1],
t = (year - a[0]) / (b[0] - a[0]);
return a[1] * (1 - t) + b[1] * t;
}
return a[1];
} |
JavaScript | function* loginUser(action) {
try {
// clear any existing error on the login page
yield put({ type: 'CLEAR_LOGIN_ERROR' });
const config = {
headers: { 'Content-Type': 'application/json' },
withCredentials: true,
};
// send the action.payload as the body
// the config includes credentials which
// allow the server session to recognize the user
yield axios.post('/api/user/login', action.payload, config);
// after the user has logged in
// get the user information from the server
yield put({type: 'FETCH_USER'});
} catch (error) {
console.log('Error with user login:', error);
if (error.response.status === 401) {
// The 401 is the error status sent from passport
// if user isn't in the database or
// if the username and password don't match in the database
yield put({ type: 'LOGIN_FAILED' });
} else {
// Got an error that wasn't a 401
// Could be anything, but most common cause is the server is not started
yield put({ type: 'LOGIN_FAILED_NO_CODE' });
}
}
} | function* loginUser(action) {
try {
// clear any existing error on the login page
yield put({ type: 'CLEAR_LOGIN_ERROR' });
const config = {
headers: { 'Content-Type': 'application/json' },
withCredentials: true,
};
// send the action.payload as the body
// the config includes credentials which
// allow the server session to recognize the user
yield axios.post('/api/user/login', action.payload, config);
// after the user has logged in
// get the user information from the server
yield put({type: 'FETCH_USER'});
} catch (error) {
console.log('Error with user login:', error);
if (error.response.status === 401) {
// The 401 is the error status sent from passport
// if user isn't in the database or
// if the username and password don't match in the database
yield put({ type: 'LOGIN_FAILED' });
} else {
// Got an error that wasn't a 401
// Could be anything, but most common cause is the server is not started
yield put({ type: 'LOGIN_FAILED_NO_CODE' });
}
}
} |
JavaScript | function* logoutUser(action) {
try {
const config = {
headers: { 'Content-Type': 'application/json' },
withCredentials: true,
};
// the config includes credentials which
// allow the server session to recognize the user
// when the server recognizes the user session
// it will end the session
yield axios.post('/api/user/logout', config);
// now that the session has ended on the server
// remove the client-side user object to let
// the client-side code know the user is logged out
yield put({ type: 'UNSET_USER' });
} catch (error) {
console.log('Error with user logout:', error);
}
} | function* logoutUser(action) {
try {
const config = {
headers: { 'Content-Type': 'application/json' },
withCredentials: true,
};
// the config includes credentials which
// allow the server session to recognize the user
// when the server recognizes the user session
// it will end the session
yield axios.post('/api/user/logout', config);
// now that the session has ended on the server
// remove the client-side user object to let
// the client-side code know the user is logged out
yield put({ type: 'UNSET_USER' });
} catch (error) {
console.log('Error with user logout:', error);
}
} |
JavaScript | function* rootSaga() {
yield all([
loginSaga(),
registrationSaga(),
userSaga(),
recipeSaga(),
grocerySaga(),
unitSaga(),
categorySaga(),
IngredientSaga(),
]);
} | function* rootSaga() {
yield all([
loginSaga(),
registrationSaga(),
userSaga(),
recipeSaga(),
grocerySaga(),
unitSaga(),
categorySaga(),
IngredientSaga(),
]);
} |
JavaScript | function galSlider(elem) {
this.self = elem;
this.children = [];
this.iteration = 0;
this.transition = "fade"; // fade, slide-up, slide-down, slide-left, slide-right, random
this.transition_values = [ "fade", "slide-up", "slide-down", "slide-left", "slide-right", "random"];
this.time_interval = 4000;
this.lock_on_hover = false;
this.is_hovered = false;
this.timeout = undefined;
this.autoplay = true;
this.arrowsActive = false;
elem.addEventListener("mouseover", galSlider.onMouseOver);
elem.addEventListener("mouseout", galSlider.onMouseOut);
this.self.classList.add("galSlider");
if (this.self.getAttribute("galSlider-width") !== undefined)
this.self.style.width = this.self.getAttribute("galSlider-width")+"px";
else
this.self.style.width = 700 + "px";
if (this.self.getAttribute("galSlider-height") !== undefined)
this.self.style.height = this.self.getAttribute("galSlider-height")+"px";
else
this.self.style.height = 200 + "px";
if (this.self.getAttribute("galSlider-time-interval") !== undefined)
this.time_interval = parseInt(this.self.getAttribute("galSlider-time-interval"));
if (this.transition_values.indexOf(this.self.getAttribute("galSlider-transition")) > -1)
this.transition = this.self.getAttribute("galSlider-transition");
if (this.self.getAttribute("galSlider-lock-onhover") !== undefined)
this.lock_on_hover = (this.self.getAttribute("galSlider-lock-onhover") == "true");
if (this.self.getAttribute("galSlider-autoplay") !== undefined)
this.autoplay = (this.self.getAttribute("galSlider-autoplay") == "true");
var arrowsActive = false;
if (this.self.getAttribute("galSlider-show-arrows") !== undefined)
arrowsActive = (this.self.getAttribute("galSlider-show-arrows") == "true");
var b = this.self.getElementsByClassName("galSlider-content");
for (var i = 0; i < b.length; i++) {
this.append(b[i]);
}
if (arrowsActive)
this.showArrows();
if (this.autoplay)
this.start();
} | function galSlider(elem) {
this.self = elem;
this.children = [];
this.iteration = 0;
this.transition = "fade"; // fade, slide-up, slide-down, slide-left, slide-right, random
this.transition_values = [ "fade", "slide-up", "slide-down", "slide-left", "slide-right", "random"];
this.time_interval = 4000;
this.lock_on_hover = false;
this.is_hovered = false;
this.timeout = undefined;
this.autoplay = true;
this.arrowsActive = false;
elem.addEventListener("mouseover", galSlider.onMouseOver);
elem.addEventListener("mouseout", galSlider.onMouseOut);
this.self.classList.add("galSlider");
if (this.self.getAttribute("galSlider-width") !== undefined)
this.self.style.width = this.self.getAttribute("galSlider-width")+"px";
else
this.self.style.width = 700 + "px";
if (this.self.getAttribute("galSlider-height") !== undefined)
this.self.style.height = this.self.getAttribute("galSlider-height")+"px";
else
this.self.style.height = 200 + "px";
if (this.self.getAttribute("galSlider-time-interval") !== undefined)
this.time_interval = parseInt(this.self.getAttribute("galSlider-time-interval"));
if (this.transition_values.indexOf(this.self.getAttribute("galSlider-transition")) > -1)
this.transition = this.self.getAttribute("galSlider-transition");
if (this.self.getAttribute("galSlider-lock-onhover") !== undefined)
this.lock_on_hover = (this.self.getAttribute("galSlider-lock-onhover") == "true");
if (this.self.getAttribute("galSlider-autoplay") !== undefined)
this.autoplay = (this.self.getAttribute("galSlider-autoplay") == "true");
var arrowsActive = false;
if (this.self.getAttribute("galSlider-show-arrows") !== undefined)
arrowsActive = (this.self.getAttribute("galSlider-show-arrows") == "true");
var b = this.self.getElementsByClassName("galSlider-content");
for (var i = 0; i < b.length; i++) {
this.append(b[i]);
}
if (arrowsActive)
this.showArrows();
if (this.autoplay)
this.start();
} |
JavaScript | function search() {
var source = document.getElementById("entry-template").innerHTML;
var template = Handlebars.compile(source);
var query = $('.address-input').val();
if (query.length >= 4) {
$.ajax({
url: 'https://api.tomtom.com/search/2/geocode/' + query + '.json?typeahead=true&limit=3&key=jmSHc4P5sMLTeiGeWWoRL81YcCxYxqGp',
method: 'GET',
success: function (data) {
var results = data.results;
for (var i = 0; i < data.results.length; i++) {
var context = {
address: results[i].address.freeformAddress,
latitude: results[i].position.lat,
longitude: results[i].position.lon,
};
var html = template(context);
$(".results").append(html);
}
},
error: function (request, state, errors) {}
});
}
} | function search() {
var source = document.getElementById("entry-template").innerHTML;
var template = Handlebars.compile(source);
var query = $('.address-input').val();
if (query.length >= 4) {
$.ajax({
url: 'https://api.tomtom.com/search/2/geocode/' + query + '.json?typeahead=true&limit=3&key=jmSHc4P5sMLTeiGeWWoRL81YcCxYxqGp',
method: 'GET',
success: function (data) {
var results = data.results;
for (var i = 0; i < data.results.length; i++) {
var context = {
address: results[i].address.freeformAddress,
latitude: results[i].position.lat,
longitude: results[i].position.lon,
};
var html = template(context);
$(".results").append(html);
}
},
error: function (request, state, errors) {}
});
}
} |
JavaScript | function latLonSearch(latitude, longitude, distance) {
var source = document.getElementById("search-template").innerHTML;
var template = Handlebars.compile(source);
$.ajax({
url: 'http://127.0.0.1:8000/api/filter',
method: 'GET',
data: {
'latitude': latitude,
'longitude': longitude,
'distance': distance
},
success: function (data) {
var results = JSON.parse(data);
for (var i = 0; i < results.length; i++) {
var context = {
address: results[i].address,
bathroom: results[i].bathroom,
bed: results[i].bed,
img_path: results[i].img_path,
id: results[i].id,
mq: results[i].mq,
room_number: results[i].room_number,
};
for (var x = 0; x < results[i].extras.length; x++) {
if (context.hasOwnProperty('extras'))
context.extras += results[i].extras[x].name + ' ';
else {
context.extras = results[i].extras[x].name + ' ';
}
}
var html = template(context);
$(".house-results").append(html);
}
},
error: function (request, state, errors) {}
});
} | function latLonSearch(latitude, longitude, distance) {
var source = document.getElementById("search-template").innerHTML;
var template = Handlebars.compile(source);
$.ajax({
url: 'http://127.0.0.1:8000/api/filter',
method: 'GET',
data: {
'latitude': latitude,
'longitude': longitude,
'distance': distance
},
success: function (data) {
var results = JSON.parse(data);
for (var i = 0; i < results.length; i++) {
var context = {
address: results[i].address,
bathroom: results[i].bathroom,
bed: results[i].bed,
img_path: results[i].img_path,
id: results[i].id,
mq: results[i].mq,
room_number: results[i].room_number,
};
for (var x = 0; x < results[i].extras.length; x++) {
if (context.hasOwnProperty('extras'))
context.extras += results[i].extras[x].name + ' ';
else {
context.extras = results[i].extras[x].name + ' ';
}
}
var html = template(context);
$(".house-results").append(html);
}
},
error: function (request, state, errors) {}
});
} |
JavaScript | async function request(url, options) {
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
},
credentials: 'include',
...options
});
checkStatus(response);
const data = await response.json();
return parseErrorMessage(data, url);
} | async function request(url, options) {
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
},
credentials: 'include',
...options
});
checkStatus(response);
const data = await response.json();
return parseErrorMessage(data, url);
} |
JavaScript | function putMostRecentEvents(divId) {
var divEl = document.getElementById(divId);
if (!divEl) {
console.log("load_events.js/putMostRecentEvents > Invalid div: " +
divId);
return;
}
var xhr = new XMLHttpRequest();
xhr.open("GET", "/eventi", true);
xhr.onload = function (e) {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
divEl.innerHTML = xhr.responseText;
} else {
console.error(xhr.statusText);
}
}
};
xhr.onerror = function (e) {console.error(xhr.statusText);};
xhr.send(null);
} | function putMostRecentEvents(divId) {
var divEl = document.getElementById(divId);
if (!divEl) {
console.log("load_events.js/putMostRecentEvents > Invalid div: " +
divId);
return;
}
var xhr = new XMLHttpRequest();
xhr.open("GET", "/eventi", true);
xhr.onload = function (e) {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
divEl.innerHTML = xhr.responseText;
} else {
console.error(xhr.statusText);
}
}
};
xhr.onerror = function (e) {console.error(xhr.statusText);};
xhr.send(null);
} |
JavaScript | function putAllEvents(divId) {
var divEl = document.getElementById(divId);
if (!divEl) {
console.log("load_events.js/putAllEvents > Invalid div: " + divId);
return;
}
var xhr = new XMLHttpRequest();
xhr.open("GET", "/eventi/all", true);
xhr.onload = function (e) {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
divEl.innerHTML = xhr.responseText;
} else {
console.error(xhr.statusText);
}
}
};
xhr.onerror = function (e) {console.error(xhr.statusText);};
xhr.send(null);
} | function putAllEvents(divId) {
var divEl = document.getElementById(divId);
if (!divEl) {
console.log("load_events.js/putAllEvents > Invalid div: " + divId);
return;
}
var xhr = new XMLHttpRequest();
xhr.open("GET", "/eventi/all", true);
xhr.onload = function (e) {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
divEl.innerHTML = xhr.responseText;
} else {
console.error(xhr.statusText);
}
}
};
xhr.onerror = function (e) {console.error(xhr.statusText);};
xhr.send(null);
} |
JavaScript | help() {
const pre = '```';
let message = `\`@mmm cod [引数] [文字列]\` でcodicで命名検索しますよ ${this.emoji.smile}\n`;
message += '・引数\n' + pre;
message += '-c\tcamelCase\n';
message += '-C\tCamelCase\n';
message += '-s\tsnake_case\n';
message += '-S\tSNAKE_CASE\n';
message += '-help\tshow help\n' + pre;
return message;
} | help() {
const pre = '```';
let message = `\`@mmm cod [引数] [文字列]\` でcodicで命名検索しますよ ${this.emoji.smile}\n`;
message += '・引数\n' + pre;
message += '-c\tcamelCase\n';
message += '-C\tCamelCase\n';
message += '-s\tsnake_case\n';
message += '-S\tSNAKE_CASE\n';
message += '-help\tshow help\n' + pre;
return message;
} |
JavaScript | function imageLoaded() {
imagesLoaded++;
if(imagesLoaded === totalImages) {
ready = true;
loader.hidden = true;
count = 30;
}
} | function imageLoaded() {
imagesLoaded++;
if(imagesLoaded === totalImages) {
ready = true;
loader.hidden = true;
count = 30;
}
} |
JavaScript | function displayPhotos () {
imagesLoaded=0;
totalImages = photosArray.length;
// run function for each for each object in photosArray
photosArray.forEach((photo) => {
// create <a> to link to unsplash
const item = document.createElement('a');
// item.setAttribute('href', photo.links.html)
// item.setAttribute('target', '_blank');
setAttributes(item, {
href: photo.links.html,
target: '_blank'
})
// create <img> for photo
const img = document.createElement('img');
// img.setAttribute('src', photo.urls.regular);
// img.setAttribute('alt', photo.alt_description);
// img.setAttribute('title', photo.alt_description);
setAttributes(img, {
src : photo.urls.regular,
alt: photo.alt_description,
title: photo.alt_description
})
// add eventlistener, check when each load is finished
img.addEventListener('load', imageLoaded);
// put <img> inside <a> and put both inside of imageContainer
item.appendChild(img);
imageContainer.appendChild(item);
})
} | function displayPhotos () {
imagesLoaded=0;
totalImages = photosArray.length;
// run function for each for each object in photosArray
photosArray.forEach((photo) => {
// create <a> to link to unsplash
const item = document.createElement('a');
// item.setAttribute('href', photo.links.html)
// item.setAttribute('target', '_blank');
setAttributes(item, {
href: photo.links.html,
target: '_blank'
})
// create <img> for photo
const img = document.createElement('img');
// img.setAttribute('src', photo.urls.regular);
// img.setAttribute('alt', photo.alt_description);
// img.setAttribute('title', photo.alt_description);
setAttributes(img, {
src : photo.urls.regular,
alt: photo.alt_description,
title: photo.alt_description
})
// add eventlistener, check when each load is finished
img.addEventListener('load', imageLoaded);
// put <img> inside <a> and put both inside of imageContainer
item.appendChild(img);
imageContainer.appendChild(item);
})
} |
JavaScript | async function toDests(chess) {
console.log('getting dests for', await toColor(chess));
const dests = new Map();
let moves = await chess.get_moves();
//console.log(moves);
for (let i = 0; i < moves.length; i += 2) {
if (dests.has(moves[i])) {
dests.set(moves[i], dests.get(moves[i]).concat(moves[i + 1]));
} else {
dests.set(moves[i], [moves[i + 1]]);
}
}
return dests;
} | async function toDests(chess) {
console.log('getting dests for', await toColor(chess));
const dests = new Map();
let moves = await chess.get_moves();
//console.log(moves);
for (let i = 0; i < moves.length; i += 2) {
if (dests.has(moves[i])) {
dests.set(moves[i], dests.get(moves[i]).concat(moves[i + 1]));
} else {
dests.set(moves[i], [moves[i + 1]]);
}
}
return dests;
} |
JavaScript | function playOtherSide(ground, chess) {
return async (from, to) => {
let promotion = checkPromotion(ground, to); // returns false if no promote else q,r,n,b
from = algebraicToIndex(from);
to = algebraicToIndex(to);
if (promotion) {
console.log(promotion);
await chess.make_move(
from,
to,
true,
promotion.toLowerCase().charCodeAt(0),
);
} else {
await chess.make_move(from, to, false, 1);
}
//ground.toggleOrientation();
ground.set({
turnColor: await toColor(chess),
check: await chess.in_check(),
movable: {
color: await toColor(chess),
dests: await toDests(chess),
},
});
};
} | function playOtherSide(ground, chess) {
return async (from, to) => {
let promotion = checkPromotion(ground, to); // returns false if no promote else q,r,n,b
from = algebraicToIndex(from);
to = algebraicToIndex(to);
if (promotion) {
console.log(promotion);
await chess.make_move(
from,
to,
true,
promotion.toLowerCase().charCodeAt(0),
);
} else {
await chess.make_move(from, to, false, 1);
}
//ground.toggleOrientation();
ground.set({
turnColor: await toColor(chess),
check: await chess.in_check(),
movable: {
color: await toColor(chess),
dests: await toDests(chess),
},
});
};
} |
JavaScript | function checkConfig(config, node) {
if (!config) {
// TODO: have to think further if it makes sense to separate these out, it isn't clear what the user can do if they encounter this besides use the explicit error to more clearly debug the code
node.error(RED._("ui_led.error.no-config"));
return false;
}
if (!config.hasOwnProperty("group")) {
node.error(RED._("ui_led.error.no-group"));
return false;
}
return true;
} | function checkConfig(config, node) {
if (!config) {
// TODO: have to think further if it makes sense to separate these out, it isn't clear what the user can do if they encounter this besides use the explicit error to more clearly debug the code
node.error(RED._("ui_led.error.no-config"));
return false;
}
if (!config.hasOwnProperty("group")) {
node.error(RED._("ui_led.error.no-group"));
return false;
}
return true;
} |
JavaScript | function WebSocketStreamServer(config) {
var _this = _super.call(this) || this;
node_core_logger_1.default.log('Web Socket stream server started listening on 8080');
if (!config.stream)
throw new Error('Incorrect Stream Config');
_this.config = config;
_this.streamSessions = new Map();
_this.wsServer = new ws_1.default.Server({ port: 8080 });
// Check media root directory
try {
mkdirp_1.default.sync(config.stream.mediaroot);
fs_1.default.accessSync(config.stream.mediaroot, fs_1.default.constants.W_OK);
}
catch (error) {
node_core_logger_1.default.error("Node Media Stream Server startup failed. MediaRoot:" + config.stream.mediaroot + " cannot be written.");
return _this;
}
// Check for ffmpeg
try {
fs_1.default.accessSync(config.stream.ffmpeg, fs_1.default.constants.X_OK);
}
catch (error) {
node_core_logger_1.default.error("Node Media Stream Server startup failed. ffmpeg:" + config.stream.ffmpeg + " cannot be executed.");
return _this;
}
// // add event listeners
// const serverEventsMap = new Map<string, (...args: any[]) => void>([
// ['connection', this.connection],
// ['error', this.error],
// ['headers', this.headers],
// ['close', this.close]
// ])
// Object.keys(serverEventsMap).forEach(key =>
// this.wsServer.on(key, serverEventsMap.get(key) as (...args: any[]) => void)
// )
_this.connection = _this.connection.bind(_this);
_this.error = _this.error.bind(_this);
_this.headers = _this.headers.bind(_this);
_this.listening = _this.listening.bind(_this);
_this.wsServer.on('connection', _this.connection);
_this.wsServer.on('error', _this.error);
_this.wsServer.on('headers', _this.headers);
_this.wsServer.on('listening', _this.listening);
return _this;
} | function WebSocketStreamServer(config) {
var _this = _super.call(this) || this;
node_core_logger_1.default.log('Web Socket stream server started listening on 8080');
if (!config.stream)
throw new Error('Incorrect Stream Config');
_this.config = config;
_this.streamSessions = new Map();
_this.wsServer = new ws_1.default.Server({ port: 8080 });
// Check media root directory
try {
mkdirp_1.default.sync(config.stream.mediaroot);
fs_1.default.accessSync(config.stream.mediaroot, fs_1.default.constants.W_OK);
}
catch (error) {
node_core_logger_1.default.error("Node Media Stream Server startup failed. MediaRoot:" + config.stream.mediaroot + " cannot be written.");
return _this;
}
// Check for ffmpeg
try {
fs_1.default.accessSync(config.stream.ffmpeg, fs_1.default.constants.X_OK);
}
catch (error) {
node_core_logger_1.default.error("Node Media Stream Server startup failed. ffmpeg:" + config.stream.ffmpeg + " cannot be executed.");
return _this;
}
// // add event listeners
// const serverEventsMap = new Map<string, (...args: any[]) => void>([
// ['connection', this.connection],
// ['error', this.error],
// ['headers', this.headers],
// ['close', this.close]
// ])
// Object.keys(serverEventsMap).forEach(key =>
// this.wsServer.on(key, serverEventsMap.get(key) as (...args: any[]) => void)
// )
_this.connection = _this.connection.bind(_this);
_this.error = _this.error.bind(_this);
_this.headers = _this.headers.bind(_this);
_this.listening = _this.listening.bind(_this);
_this.wsServer.on('connection', _this.connection);
_this.wsServer.on('error', _this.error);
_this.wsServer.on('headers', _this.headers);
_this.wsServer.on('listening', _this.listening);
return _this;
} |
JavaScript | function openForm() {
document.getElementById("myForm").style.display = "block";
//When form has popped up turn open-button white
if(display = "block") {
blurOpenButton.setAttribute("style", "background-color: white; color: white; box-shadow: white;");
}
} | function openForm() {
document.getElementById("myForm").style.display = "block";
//When form has popped up turn open-button white
if(display = "block") {
blurOpenButton.setAttribute("style", "background-color: white; color: white; box-shadow: white;");
}
} |
JavaScript | function closeForm() {
document.getElementById("myForm").style.display = "none";
// when form is closed regular styles return
if(display = "block") {
blurOpenButton.setAttribute("style", "");
}
} | function closeForm() {
document.getElementById("myForm").style.display = "none";
// when form is closed regular styles return
if(display = "block") {
blurOpenButton.setAttribute("style", "");
}
} |
JavaScript | function displayNumberCharactersInSpan(){
// identify slider value
const passwordLength = inputNumberCharacters.value;
//change text content of number of characters in span to match
displayNumberCharacters.textContent = passwordLength;
} | function displayNumberCharactersInSpan(){
// identify slider value
const passwordLength = inputNumberCharacters.value;
//change text content of number of characters in span to match
displayNumberCharacters.textContent = passwordLength;
} |
JavaScript | willSendResponse(requestContext) {
logger.log({
level: 'info',
message: `${get(requestContext, 'request.operationName')}:End`,
queryId,
})
} | willSendResponse(requestContext) {
logger.log({
level: 'info',
message: `${get(requestContext, 'request.operationName')}:End`,
queryId,
})
} |
JavaScript | function addNoteScreen() {
var elString = "";
// Animate the plus new note button to turn into an X with the twist class
document.querySelector("#add-note-btn").classList.add("twist");
// Assigning Button (Html for new notes sections)
elString += '<div id="add-note-screen">';
elString += '<h1>Add New Note</h1>';
elString += '<textarea id="new-note-content" autofocus></textarea>';
elString += '<button id="insert-gymtraining">Gym Exercises</button>';
elString += '<button id="insert-glossarylist">Glossary List</button>';
elString += '<button id="submit-new-note">Add Note</button>';
elString += '</div>';
// Add the element string created above to the document
document.querySelector("body").innerHTML += elString;
document.querySelector("#add-note-screen").classList.add("note-screen-in");
// Adding and removing button
document.querySelector("#add-note-btn").removeEventListener("click", addNoteScreen);
document.querySelector("#add-note-btn").addEventListener("click", removeNoteScreen, false);
// Event listener for Space and ? adding
document.querySelector("#insert-gymtraining").addEventListener("click", function(){
typeInTextarea(document.querySelector("textarea"), "Gym Exercises : ")
}, false);
document.querySelector("#insert-glossarylist").addEventListener("click", function(){
typeInTextarea(document.querySelector("textarea"), "Glossary list : ")
}, false);
// Eventlistner for Submit new note button and remove buttons
document.querySelector("#submit-new-note").addEventListener("click", addNoteToList, false);
} | function addNoteScreen() {
var elString = "";
// Animate the plus new note button to turn into an X with the twist class
document.querySelector("#add-note-btn").classList.add("twist");
// Assigning Button (Html for new notes sections)
elString += '<div id="add-note-screen">';
elString += '<h1>Add New Note</h1>';
elString += '<textarea id="new-note-content" autofocus></textarea>';
elString += '<button id="insert-gymtraining">Gym Exercises</button>';
elString += '<button id="insert-glossarylist">Glossary List</button>';
elString += '<button id="submit-new-note">Add Note</button>';
elString += '</div>';
// Add the element string created above to the document
document.querySelector("body").innerHTML += elString;
document.querySelector("#add-note-screen").classList.add("note-screen-in");
// Adding and removing button
document.querySelector("#add-note-btn").removeEventListener("click", addNoteScreen);
document.querySelector("#add-note-btn").addEventListener("click", removeNoteScreen, false);
// Event listener for Space and ? adding
document.querySelector("#insert-gymtraining").addEventListener("click", function(){
typeInTextarea(document.querySelector("textarea"), "Gym Exercises : ")
}, false);
document.querySelector("#insert-glossarylist").addEventListener("click", function(){
typeInTextarea(document.querySelector("textarea"), "Glossary list : ")
}, false);
// Eventlistner for Submit new note button and remove buttons
document.querySelector("#submit-new-note").addEventListener("click", addNoteToList, false);
} |
JavaScript | function removeNoteScreen() {
// Turns the X back into a plus by removing the twist class
document.querySelector("#add-note-btn").classList.remove("twist");
// Add class with animation to add-note-screen so animates out
document.querySelector("#add-note-screen").classList.add("note-screen-out");
// Wait half a second to remove the add-note-screen so animation can play
setTimeout(function(){
// removes the add-note-screen from the document
document.querySelector("body").removeChild(document.querySelector("#add-note-screen"));
}, 500);
// This switches and event listener attached to the add-note-btn to create the note dialog instead of closing it
document.querySelector("#add-note-btn").removeEventListener("click", removeNoteScreen);
document.querySelector("#add-note-btn").addEventListener("click", addNoteScreen, false);
delNoteBtns();
} | function removeNoteScreen() {
// Turns the X back into a plus by removing the twist class
document.querySelector("#add-note-btn").classList.remove("twist");
// Add class with animation to add-note-screen so animates out
document.querySelector("#add-note-screen").classList.add("note-screen-out");
// Wait half a second to remove the add-note-screen so animation can play
setTimeout(function(){
// removes the add-note-screen from the document
document.querySelector("body").removeChild(document.querySelector("#add-note-screen"));
}, 500);
// This switches and event listener attached to the add-note-btn to create the note dialog instead of closing it
document.querySelector("#add-note-btn").removeEventListener("click", removeNoteScreen);
document.querySelector("#add-note-btn").addEventListener("click", addNoteScreen, false);
delNoteBtns();
} |
JavaScript | function addNoteToList() {
var noteText = document.querySelector("#new-note-content").value;
if(noteText === "" || noteText === " "){
return false;
}
// Inserting new contrainer div for the note
var container = document.createElement('div');
container.className = "note fade-in";
var closeBtn = document.createElement('button');
closeBtn.textContent = "X";
closeBtn.className = "del-note";
container.textContent = noteText;
container.appendChild(closeBtn);
document.querySelector("body").appendChild(container);
removeNoteScreen();
saveNoteTxt();
} | function addNoteToList() {
var noteText = document.querySelector("#new-note-content").value;
if(noteText === "" || noteText === " "){
return false;
}
// Inserting new contrainer div for the note
var container = document.createElement('div');
container.className = "note fade-in";
var closeBtn = document.createElement('button');
closeBtn.textContent = "X";
closeBtn.className = "del-note";
container.textContent = noteText;
container.appendChild(closeBtn);
document.querySelector("body").appendChild(container);
removeNoteScreen();
saveNoteTxt();
} |
JavaScript | function saveNoteTxt(){
var notes = document.querySelectorAll(".note");
var noteObj = {};
for(var x = 0; x < notes.length; x++) {
noteObj[x] = notes[x].innerHTML;
}
localStorage.setItem('noteAppStorageObj', JSON.stringify(noteObj));
} | function saveNoteTxt(){
var notes = document.querySelectorAll(".note");
var noteObj = {};
for(var x = 0; x < notes.length; x++) {
noteObj[x] = notes[x].innerHTML;
}
localStorage.setItem('noteAppStorageObj', JSON.stringify(noteObj));
} |
JavaScript | function delNoteBtns(){
var els = document.querySelectorAll(".note");
for(var x = 0; x < els.length; x++){
els[x].addEventListener("click", function(e){
if(e.target.className === "del-note"){
this.parentElement.removeChild(this);
saveNoteTxt();
}
}, false);
}
} | function delNoteBtns(){
var els = document.querySelectorAll(".note");
for(var x = 0; x < els.length; x++){
els[x].addEventListener("click", function(e){
if(e.target.className === "del-note"){
this.parentElement.removeChild(this);
saveNoteTxt();
}
}, false);
}
} |
JavaScript | function typeInTextarea(el, newText) {
var start = el.selectionStart;
var end = el.selectionEnd;
var text = el.value;
// Gets the contents of the textarea before and after the position of the selection/cursor and stores it
var before = text.substring(0, start);
var after = text.substring(end, text.length);
// Combines the old text with the added content
el.value = (before + newText + after);
el.selectionStart = el.selectionEnd = start + newText.length;
// Focus cursor on textarea again
el.focus();
} | function typeInTextarea(el, newText) {
var start = el.selectionStart;
var end = el.selectionEnd;
var text = el.value;
// Gets the contents of the textarea before and after the position of the selection/cursor and stores it
var before = text.substring(0, start);
var after = text.substring(end, text.length);
// Combines the old text with the added content
el.value = (before + newText + after);
el.selectionStart = el.selectionEnd = start + newText.length;
// Focus cursor on textarea again
el.focus();
} |
JavaScript | function openGroupChat(team, users) {
// Opens the group chat
return got.post('https://slack.com/api/mpim.open', {
json: true,
form: true,
timeout: 5000,
body: {
token: team.botAccessToken,
users: users.map(user => user.id).join(',')
}
})
.then(res => res.body)
.then(response => {
if (response.warning) {
util.log('warn', new Error(response.warning))
}
if (!response.ok) {
throw new Error(response.error)
}
// Post the explaination message into the group chat
return got.post('https://slack.com/api/chat.postMessage', {
json: true,
form: true,
timeout: 5000,
body: {
token: team.botAccessToken,
channel: response.group.id,
text: copy.groupChatMessageText
}
})
})
.then(res => res.body)
.then(response => {
if (response.warning) {
util.log('warn', new Error(response.warning))
}
if (!response.ok) {
throw new Error(response.error)
}
})
.catch(err => util.log('error', err))
} | function openGroupChat(team, users) {
// Opens the group chat
return got.post('https://slack.com/api/mpim.open', {
json: true,
form: true,
timeout: 5000,
body: {
token: team.botAccessToken,
users: users.map(user => user.id).join(',')
}
})
.then(res => res.body)
.then(response => {
if (response.warning) {
util.log('warn', new Error(response.warning))
}
if (!response.ok) {
throw new Error(response.error)
}
// Post the explaination message into the group chat
return got.post('https://slack.com/api/chat.postMessage', {
json: true,
form: true,
timeout: 5000,
body: {
token: team.botAccessToken,
channel: response.group.id,
text: copy.groupChatMessageText
}
})
})
.then(res => res.body)
.then(response => {
if (response.warning) {
util.log('warn', new Error(response.warning))
}
if (!response.ok) {
throw new Error(response.error)
}
})
.catch(err => util.log('error', err))
} |
JavaScript | function finishShuffle(teamId, channelId, responseUrl) {
Promise.all([
Team.findById(teamId).exec(),
Shuffle.findOne({teamId, channelId, active: true}).exec()
]).then(values => {
const team = values[0]
const shuffle = values[1]
if (!team) {
util.respond(responseUrl, {text: copy.notSetup})
return
}
if (!shuffle) {
util.respond(responseUrl, {text: copy.noShuffleActiveInChannel})
return
}
// You can only open a group chat with 2 people or more!
if (shuffle.people.length > 1) {
const groups = util.generateRandomGroups(shuffle.people)
// Open a private chat for each group
for (const group of groups) {
openGroupChat(team, group)
// Keep a record of the generated groups for debugging purposes
shuffle.groups.push(group.map(person => person.name).join(','))
}
}
// Close off the shuffle
shuffle.active = false
shuffle.save()
// Remove the join message and interactive buttons from the shuffle message
util.updateShuffleMessage(team, shuffle)
})
} | function finishShuffle(teamId, channelId, responseUrl) {
Promise.all([
Team.findById(teamId).exec(),
Shuffle.findOne({teamId, channelId, active: true}).exec()
]).then(values => {
const team = values[0]
const shuffle = values[1]
if (!team) {
util.respond(responseUrl, {text: copy.notSetup})
return
}
if (!shuffle) {
util.respond(responseUrl, {text: copy.noShuffleActiveInChannel})
return
}
// You can only open a group chat with 2 people or more!
if (shuffle.people.length > 1) {
const groups = util.generateRandomGroups(shuffle.people)
// Open a private chat for each group
for (const group of groups) {
openGroupChat(team, group)
// Keep a record of the generated groups for debugging purposes
shuffle.groups.push(group.map(person => person.name).join(','))
}
}
// Close off the shuffle
shuffle.active = false
shuffle.save()
// Remove the join message and interactive buttons from the shuffle message
util.updateShuffleMessage(team, shuffle)
})
} |
JavaScript | async function route(ctx) {
// Verify the request actually came from Slack
if (ctx.request.body.token !== config.get('slack:verification')) {
ctx.response.status = 401
return
}
const subcommand = ctx.request.body.text
const teamId = ctx.request.body.team_id
const channelId = ctx.request.body.channel_id
const responseUrl = ctx.request.body.response_url
if (subcommand === 'start') {
ctx.body = ''
startShuffle(teamId, channelId, responseUrl)
} else if (subcommand === 'finish') {
ctx.body = ''
finishShuffle(teamId, channelId, responseUrl)
} else if (subcommand === 'cancel') {
ctx.body = ''
cancelShuffle(teamId, channelId, responseUrl)
} else {
ctx.body = copy.invalidSubcommand
}
} | async function route(ctx) {
// Verify the request actually came from Slack
if (ctx.request.body.token !== config.get('slack:verification')) {
ctx.response.status = 401
return
}
const subcommand = ctx.request.body.text
const teamId = ctx.request.body.team_id
const channelId = ctx.request.body.channel_id
const responseUrl = ctx.request.body.response_url
if (subcommand === 'start') {
ctx.body = ''
startShuffle(teamId, channelId, responseUrl)
} else if (subcommand === 'finish') {
ctx.body = ''
finishShuffle(teamId, channelId, responseUrl)
} else if (subcommand === 'cancel') {
ctx.body = ''
cancelShuffle(teamId, channelId, responseUrl)
} else {
ctx.body = copy.invalidSubcommand
}
} |
JavaScript | function generateKey() {
return new Promise((resolve, reject) => {
crypto.randomBytes(20, (error, buffer) => {
if (error) {
return reject(error)
}
return resolve(buffer.toString('hex'))
})
})
} | function generateKey() {
return new Promise((resolve, reject) => {
crypto.randomBytes(20, (error, buffer) => {
if (error) {
return reject(error)
}
return resolve(buffer.toString('hex'))
})
})
} |
JavaScript | async function login(state, session, password) {
// Check against hard coded password 😆
if (password === config.get('password')) {
session.loggedIn = true
}
// Generate a key for validating the Slack oauth response
if (session.loggedIn && !session.oauthKey) {
session.oauthKey = await generateKey()
}
state.loggedIn = session.loggedIn
state.oauthKey = session.oauthKey
state.slackId = config.get('slack:id')
} | async function login(state, session, password) {
// Check against hard coded password 😆
if (password === config.get('password')) {
session.loggedIn = true
}
// Generate a key for validating the Slack oauth response
if (session.loggedIn && !session.oauthKey) {
session.oauthKey = await generateKey()
}
state.loggedIn = session.loggedIn
state.oauthKey = session.oauthKey
state.slackId = config.get('slack:id')
} |
JavaScript | function respond(responseUrl, message) {
return got.post(responseUrl, {
timeout: 5000,
// For some reason sending a `application/x-www-form-urlencoded` body to a response_url casues a 500 error in Slack
body: JSON.stringify(message)
})
.then(res => res.body)
.then(response => {
if (response !== 'ok') {
log('error', response)
}
}, error => log('error', error))
} | function respond(responseUrl, message) {
return got.post(responseUrl, {
timeout: 5000,
// For some reason sending a `application/x-www-form-urlencoded` body to a response_url casues a 500 error in Slack
body: JSON.stringify(message)
})
.then(res => res.body)
.then(response => {
if (response !== 'ok') {
log('error', response)
}
}, error => log('error', error))
} |
JavaScript | function updateShuffleMessage(team, shuffle) {
let text = copy.startMessageText
if (shuffle.cancelled) {
text = copy.cancelledMessageText
} else if (shuffle.people.length > 0) {
// List the people that have joined the shuffle
let names = shuffle.people.map(person => `@${person.name}`)
// Add 'and' between the last two names
if (names.length > 1) {
const last = names.pop()
const secondToLast = names.pop()
const lastTwo = `${secondToLast} and ${last}`
names.push(lastTwo)
}
names = names.join(', ')
if (shuffle.active) {
text = `${copy.startMessageText} ${names} ${pluralize('has', shuffle.people.length)} already joined!`
} else {
text = `${names} shuffled!`
}
}
// Remove the interactive buttons when the shuffle has finished
const attachments = shuffle.active ? null : JSON.stringify(copy.startMessageAttachments)
// Update the message
got.post('https://slack.com/api/chat.update', {
json: true,
form: true,
timeout: 5000,
body: {
token: team.botAccessToken,
ts: shuffle.messageTimestamp,
channel: shuffle.channelId,
parse: 'full',
link_names: 1, // eslint-disable-line camelcase
text,
attachments
}
})
.then(res => res.body)
.then(response => {
if (response.warning) {
log('warn', response.warning)
}
if (!response.ok) {
log('error', response.error)
}
}, error => log('error', error))
} | function updateShuffleMessage(team, shuffle) {
let text = copy.startMessageText
if (shuffle.cancelled) {
text = copy.cancelledMessageText
} else if (shuffle.people.length > 0) {
// List the people that have joined the shuffle
let names = shuffle.people.map(person => `@${person.name}`)
// Add 'and' between the last two names
if (names.length > 1) {
const last = names.pop()
const secondToLast = names.pop()
const lastTwo = `${secondToLast} and ${last}`
names.push(lastTwo)
}
names = names.join(', ')
if (shuffle.active) {
text = `${copy.startMessageText} ${names} ${pluralize('has', shuffle.people.length)} already joined!`
} else {
text = `${names} shuffled!`
}
}
// Remove the interactive buttons when the shuffle has finished
const attachments = shuffle.active ? null : JSON.stringify(copy.startMessageAttachments)
// Update the message
got.post('https://slack.com/api/chat.update', {
json: true,
form: true,
timeout: 5000,
body: {
token: team.botAccessToken,
ts: shuffle.messageTimestamp,
channel: shuffle.channelId,
parse: 'full',
link_names: 1, // eslint-disable-line camelcase
text,
attachments
}
})
.then(res => res.body)
.then(response => {
if (response.warning) {
log('warn', response.warning)
}
if (!response.ok) {
log('error', response.error)
}
}, error => log('error', error))
} |
JavaScript | function generateRandomGroups(items) {
const TARGET = config.get('groupsize:target')
const MINIMUM = config.get('groupsize:minimum')
// Randomise the array
const randomItems = lodashShuffle(items)
// Remove the remainders to create even groups
const remaindersNum = randomItems.length % TARGET
const remainders = randomItems.splice(0, remaindersNum)
// Create groups
const groups = lodashChunk(randomItems, TARGET)
if (remaindersNum > 0) {
// If there's less remainders than the minimum and there's at least 1 group,
// spread the remainders evenly across the groups
if (remaindersNum < MINIMUM && groups.length > 0) {
let groupIndex = 0
while (remainders.length > 0) {
groups[groupIndex].push(remainders.pop())
if (groupIndex < groups.length - 1) {
groupIndex += 1
} else {
groupIndex = 0
}
}
// Else just create a new group from the remainders
} else {
groups.push(remainders)
}
}
return groups
} | function generateRandomGroups(items) {
const TARGET = config.get('groupsize:target')
const MINIMUM = config.get('groupsize:minimum')
// Randomise the array
const randomItems = lodashShuffle(items)
// Remove the remainders to create even groups
const remaindersNum = randomItems.length % TARGET
const remainders = randomItems.splice(0, remaindersNum)
// Create groups
const groups = lodashChunk(randomItems, TARGET)
if (remaindersNum > 0) {
// If there's less remainders than the minimum and there's at least 1 group,
// spread the remainders evenly across the groups
if (remaindersNum < MINIMUM && groups.length > 0) {
let groupIndex = 0
while (remainders.length > 0) {
groups[groupIndex].push(remainders.pop())
if (groupIndex < groups.length - 1) {
groupIndex += 1
} else {
groupIndex = 0
}
}
// Else just create a new group from the remainders
} else {
groups.push(remainders)
}
}
return groups
} |
JavaScript | function shutdown(exitCode) {
util.log('info', 'Server stopping...')
server.close(() => {
mongoose.disconnect(() => {
util.log('info', 'Server stopped')
})
})
process.exitCode = exitCode
} | function shutdown(exitCode) {
util.log('info', 'Server stopping...')
server.close(() => {
mongoose.disconnect(() => {
util.log('info', 'Server stopped')
})
})
process.exitCode = exitCode
} |
JavaScript | function validateUser(user_id, password)
{
let validated_user = all_users.find(user => user.id === user_id);
if ( typeof validated_user === 'undefined' || validated_user.password !== password )
{
console.log('Wrong ID and/or password, please try again.');
return null;
}
// Validation succeed, return the user object
return validated_user;
} | function validateUser(user_id, password)
{
let validated_user = all_users.find(user => user.id === user_id);
if ( typeof validated_user === 'undefined' || validated_user.password !== password )
{
console.log('Wrong ID and/or password, please try again.');
return null;
}
// Validation succeed, return the user object
return validated_user;
} |
JavaScript | function addRules(current, definition, byFilter) {
var newFilters = definition.filters,
newRules = definition.rules,
updatedFilters, clone, previous;
// The current definition might have been split up into
// multiple definitions already.
for (var k = 0; k < current.length; k++) {
updatedFilters = current[k].filters.cloneWith(newFilters);
if (updatedFilters) {
previous = byFilter[updatedFilters];
if (previous) {
// There's already a definition with those exact
// filters. Add the current definitions' rules
// and stop processing it as the existing rule
// has already gone down the inheritance chain.
previous.addRules(newRules);
} else {
clone = current[k].clone(updatedFilters);
// Make sure that we're only maintaining the clone
// when we did actually add rules. If not, there's
// no need to keep the clone around.
if (clone.addRules(newRules)) {
// We inserted an element before this one, so we need
// to make sure that in the next loop iteration, we're
// not performing the same task for this element again,
// hence the k++.
byFilter[updatedFilters] = clone;
current.splice(k, 0, clone);
k++;
}
}
} else if (updatedFilters === null) {
// if updatedFilters is null, then adding the filters doesn't
// invalidate or split the selector, so we addRules to the
// combined selector
// Filters can be added, but they don't change the
// filters. This means we don't have to split the
// definition.
//
// this is cloned here because of shared classes, see
// sharedclass.mss
current[k] = current[k].clone();
current[k].addRules(newRules);
}
// if updatedFeatures is false, then the filters split the rule,
// so they aren't the same inheritance chain
}
return current;
} | function addRules(current, definition, byFilter) {
var newFilters = definition.filters,
newRules = definition.rules,
updatedFilters, clone, previous;
// The current definition might have been split up into
// multiple definitions already.
for (var k = 0; k < current.length; k++) {
updatedFilters = current[k].filters.cloneWith(newFilters);
if (updatedFilters) {
previous = byFilter[updatedFilters];
if (previous) {
// There's already a definition with those exact
// filters. Add the current definitions' rules
// and stop processing it as the existing rule
// has already gone down the inheritance chain.
previous.addRules(newRules);
} else {
clone = current[k].clone(updatedFilters);
// Make sure that we're only maintaining the clone
// when we did actually add rules. If not, there's
// no need to keep the clone around.
if (clone.addRules(newRules)) {
// We inserted an element before this one, so we need
// to make sure that in the next loop iteration, we're
// not performing the same task for this element again,
// hence the k++.
byFilter[updatedFilters] = clone;
current.splice(k, 0, clone);
k++;
}
}
} else if (updatedFilters === null) {
// if updatedFilters is null, then adding the filters doesn't
// invalidate or split the selector, so we addRules to the
// combined selector
// Filters can be added, but they don't change the
// filters. This means we don't have to split the
// definition.
//
// this is cloned here because of shared classes, see
// sharedclass.mss
current[k] = current[k].clone();
current[k].addRules(newRules);
}
// if updatedFeatures is false, then the filters split the rule,
// so they aren't the same inheritance chain
}
return current;
} |
JavaScript | function inheritDefinitions(definitions, env) {
var inheritTime = +new Date();
// definitions are ordered by specificity,
// high (index 0) to low
var byAttachment = {},
byFilter = {};
var result = [];
var current, attachment;
// Evaluate the filters specified by each definition with the given
// environment to correctly resolve variable references
definitions.forEach(function(d) {
d.filters.ev(env);
});
for (var i = 0; i < definitions.length; i++) {
attachment = definitions[i].attachment;
current = [definitions[i]];
if (!byAttachment[attachment]) {
byAttachment[attachment] = [];
byAttachment[attachment].attachment = attachment;
byFilter[attachment] = {};
result.push(byAttachment[attachment]);
}
// Iterate over all subsequent rules.
for (var j = i + 1; j < definitions.length; j++) {
if (definitions[j].attachment === attachment) {
// Only inherit rules from the same attachment.
current = addRules(current, definitions[j], byFilter[attachment]);
}
}
for (var k = 0; k < current.length; k++) {
byFilter[attachment][current[k].filters] = current[k];
byAttachment[attachment].push(current[k]);
}
}
if (env.benchmark) console.warn('Inheritance time: ' + ((new Date() - inheritTime)) + 'ms');
return result;
} | function inheritDefinitions(definitions, env) {
var inheritTime = +new Date();
// definitions are ordered by specificity,
// high (index 0) to low
var byAttachment = {},
byFilter = {};
var result = [];
var current, attachment;
// Evaluate the filters specified by each definition with the given
// environment to correctly resolve variable references
definitions.forEach(function(d) {
d.filters.ev(env);
});
for (var i = 0; i < definitions.length; i++) {
attachment = definitions[i].attachment;
current = [definitions[i]];
if (!byAttachment[attachment]) {
byAttachment[attachment] = [];
byAttachment[attachment].attachment = attachment;
byFilter[attachment] = {};
result.push(byAttachment[attachment]);
}
// Iterate over all subsequent rules.
for (var j = i + 1; j < definitions.length; j++) {
if (definitions[j].attachment === attachment) {
// Only inherit rules from the same attachment.
current = addRules(current, definitions[j], byFilter[attachment]);
}
}
for (var k = 0; k < current.length; k++) {
byFilter[attachment][current[k].filters] = current[k];
byAttachment[attachment].push(current[k]);
}
}
if (env.benchmark) console.warn('Inheritance time: ' + ((new Date() - inheritTime)) + 'ms');
return result;
} |
JavaScript | function foldStyle(style) {
for (var i = 0; i < style.length; i++) {
for (var j = style.length - 1; j > i; j--) {
if (style[j].filters.cloneWith(style[i].filters) === null) {
style.splice(j, 1);
}
}
}
return style;
} | function foldStyle(style) {
for (var i = 0; i < style.length; i++) {
for (var j = style.length - 1; j > i; j--) {
if (style[j].filters.cloneWith(style[i].filters) === null) {
style.splice(j, 1);
}
}
}
return style;
} |
JavaScript | function on (state, eventName, handler) {
state.emitter.on(eventName, handler)
return this
} | function on (state, eventName, handler) {
state.emitter.on(eventName, handler)
return this
} |
JavaScript | function one (state, eventName, handler) {
state.emitter.once(eventName, handler)
return this
} | function one (state, eventName, handler) {
state.emitter.once(eventName, handler)
return this
} |
JavaScript | function off (state, eventName, handler) {
state.emitter.removeListener(eventName, handler)
return this
} | function off (state, eventName, handler) {
state.emitter.removeListener(eventName, handler)
return this
} |
JavaScript | function isV1(wlansd) {
if ( wlansd.length == undefined || wlansd.length == 0 ) {
// List is empty so the card version is not detectable. Assumes as V2.
return false;
} else if ( wlansd[0].length !== undefined ) {
// Each row in the list is array. V1.
return true;
} else {
// Otherwise V2.
return false;
}
} | function isV1(wlansd) {
if ( wlansd.length == undefined || wlansd.length == 0 ) {
// List is empty so the card version is not detectable. Assumes as V2.
return false;
} else if ( wlansd[0].length !== undefined ) {
// Each row in the list is array. V1.
return true;
} else {
// Otherwise V2.
return false;
}
} |
JavaScript | function convertFileList() {
for (var i = 0; i < wlansd.length; i++) {
var elements = wlansd[i].split(",");
wlansd[i] = new Array();
wlansd[i]["r_uri"] = elements[0];
wlansd[i]["fname"] = elements[1];
wlansd[i]["fsize"] = Number(elements[2]);
wlansd[i]["attr"] = Number(elements[3]);
wlansd[i]["fdate"] = Number(elements[4]);
wlansd[i]["ftime"] = Number(elements[5]);
}
} | function convertFileList() {
for (var i = 0; i < wlansd.length; i++) {
var elements = wlansd[i].split(",");
wlansd[i] = new Array();
wlansd[i]["r_uri"] = elements[0];
wlansd[i]["fname"] = elements[1];
wlansd[i]["fsize"] = Number(elements[2]);
wlansd[i]["attr"] = Number(elements[3]);
wlansd[i]["fdate"] = Number(elements[4]);
wlansd[i]["ftime"] = Number(elements[5]);
}
} |
JavaScript | function markerstyle(feature) {
return {
opacity: 1,
fillOpacity: 1,
color: "#98ee00",
fillColor: chooseColor(feature.geometry.coordinates[2]),
radius: feature.properties.mag * 3,
weight: 1
};
} | function markerstyle(feature) {
return {
opacity: 1,
fillOpacity: 1,
color: "#98ee00",
fillColor: chooseColor(feature.geometry.coordinates[2]),
radius: feature.properties.mag * 3,
weight: 1
};
} |
JavaScript | function checkWinner() {
if (npc1XPosition >= winningX) {
alert("1 wins!");
if (currentBet == 1) {
changeMoney(2);
}
resetPositions();
}
if (npc2XPosition >= winningX) {
alert("2 wins!");
if (currentBet == 2) {
changeMoney(2);
}
resetPositions();
}
if (npc3XPosition >= winningX) {
alert("3 wins!");
if (currentBet == 3) {
changeMoney(2);
}
resetPositions();
}
} | function checkWinner() {
if (npc1XPosition >= winningX) {
alert("1 wins!");
if (currentBet == 1) {
changeMoney(2);
}
resetPositions();
}
if (npc2XPosition >= winningX) {
alert("2 wins!");
if (currentBet == 2) {
changeMoney(2);
}
resetPositions();
}
if (npc3XPosition >= winningX) {
alert("3 wins!");
if (currentBet == 3) {
changeMoney(2);
}
resetPositions();
}
} |
JavaScript | function drawInvaders() {
context.drawImage(npcImage, npc1XPosition, npcYPosition);
context.drawImage(npcImage, npc2XPosition, npcYPosition + 100);
context.drawImage(npcImage, npc3XPosition, npcYPosition + 200);
} | function drawInvaders() {
context.drawImage(npcImage, npc1XPosition, npcYPosition);
context.drawImage(npcImage, npc2XPosition, npcYPosition + 100);
context.drawImage(npcImage, npc3XPosition, npcYPosition + 200);
} |
JavaScript | function preventCheating() {
if (npc1XPosition >= winningX / 2) {
activateButtons(false);
}
if (npc2XPosition >= winningX / 2) {
activateButtons(false);
}
if (npc3XPosition >= winningX / 2) {
activateButtons(false);
}
} | function preventCheating() {
if (npc1XPosition >= winningX / 2) {
activateButtons(false);
}
if (npc2XPosition >= winningX / 2) {
activateButtons(false);
}
if (npc3XPosition >= winningX / 2) {
activateButtons(false);
}
} |
JavaScript | function displayAlert(status) {
var alertArea = $("#alert-area");
//clear the alert if theres one already there
clearTimeout(alertTimeout);
alertArea.fadeIn("fast");
if (status) {
alertArea.html("<div class='alert alert-success w-75 mx-auto' role='alert'> <strong>Correct!</strong> +10 points!</div>");
} else {
alertArea.html("<div class='alert alert-danger w-75 mx-auto' role='alert'> <strong>Wrong!</strong> -10 seconds.</div>");
}
alertTimeout = setTimeout(function () { alertArea.fadeOut("slow"); }, 1000);
} | function displayAlert(status) {
var alertArea = $("#alert-area");
//clear the alert if theres one already there
clearTimeout(alertTimeout);
alertArea.fadeIn("fast");
if (status) {
alertArea.html("<div class='alert alert-success w-75 mx-auto' role='alert'> <strong>Correct!</strong> +10 points!</div>");
} else {
alertArea.html("<div class='alert alert-danger w-75 mx-auto' role='alert'> <strong>Wrong!</strong> -10 seconds.</div>");
}
alertTimeout = setTimeout(function () { alertArea.fadeOut("slow"); }, 1000);
} |
JavaScript | function renderQuestion() {
if (questions[questionIndex]) {
//Update the question text
document.querySelector("#question").textContent = questions[questionIndex].question;
//Clear the previous answers, if any
answerArea.innerHTML = "";
//Add each potential answer button
for (var i = 0; i < questions[questionIndex].answers.length; i++) {
var answerOption = document.createElement("button");
answerOption.textContent = questions[questionIndex].answers[i];
answerOption.setAttribute("class", "btn btn-primary my-2 quiz-answer");
answerOption.style.display = "block";
answerArea.appendChild(answerOption);
}
} else {
// If out of questions, end game
endGame();
}
} | function renderQuestion() {
if (questions[questionIndex]) {
//Update the question text
document.querySelector("#question").textContent = questions[questionIndex].question;
//Clear the previous answers, if any
answerArea.innerHTML = "";
//Add each potential answer button
for (var i = 0; i < questions[questionIndex].answers.length; i++) {
var answerOption = document.createElement("button");
answerOption.textContent = questions[questionIndex].answers[i];
answerOption.setAttribute("class", "btn btn-primary my-2 quiz-answer");
answerOption.style.display = "block";
answerArea.appendChild(answerOption);
}
} else {
// If out of questions, end game
endGame();
}
} |
JavaScript | addSerializers(serializers) {
if (!this.serializers) {
this.serializers = {};
}
Object.keys(serializers).forEach(field => {
const serializer = serializers[field];
if (typeof (serializer) !== 'function') {
throw new TypeError(format('invalid serializer for "%s" field: must be a function', field));
}
this.serializers[field] = serializer;
});
} | addSerializers(serializers) {
if (!this.serializers) {
this.serializers = {};
}
Object.keys(serializers).forEach(field => {
const serializer = serializers[field];
if (typeof (serializer) !== 'function') {
throw new TypeError(format('invalid serializer for "%s" field: must be a function', field));
}
this.serializers[field] = serializer;
});
} |
JavaScript | _applySerializers(fields, excludeFields) {
// Check each serializer against these (presuming number of serializers
// is typically less than number of fields).
Object.keys(this.serializers).forEach(name => {
if (fields[name] === undefined || (excludeFields && excludeFields[name])) {
return;
}
try {
fields[name] = this.serializers[name](fields[name]);
} catch (err) {
_warn(format('bunyan: ERROR: Exception thrown from the "%s" ' +
'Bunyan serializer. This should never happen. This is a bug' +
'in that serializer function.\n%s',
name, err.stack || err));
fields[name] = format('(Error in Bunyan log "%s" serializer broke field. See stderr for details.)', name);
}
});
} | _applySerializers(fields, excludeFields) {
// Check each serializer against these (presuming number of serializers
// is typically less than number of fields).
Object.keys(this.serializers).forEach(name => {
if (fields[name] === undefined || (excludeFields && excludeFields[name])) {
return;
}
try {
fields[name] = this.serializers[name](fields[name]);
} catch (err) {
_warn(format('bunyan: ERROR: Exception thrown from the "%s" ' +
'Bunyan serializer. This should never happen. This is a bug' +
'in that serializer function.\n%s',
name, err.stack || err));
fields[name] = format('(Error in Bunyan log "%s" serializer broke field. See stderr for details.)', name);
}
});
} |
JavaScript | function mkLogEmitter(minLevel) {
return function () {
const log = this;
function mkRecord(args) {
let excludeFields;
if (args[0] instanceof Error) {
// `log.<level>(err, ...)`
fields = {
// Use this Logger's err serializer, if defined.
err: (log.serializers && log.serializers.err ? log.serializers.err(args[0]) : stdSerializers.err(args[0])),
};
excludeFields = {err: true};
if (args.length === 1) {
msgArgs = [fields.err.message];
} else {
msgArgs = Array.prototype.slice.call(args, 1);
}
} else if (typeof (args[0]) !== 'object' && args[0] !== null || Array.isArray(args[0])) {
// `log.<level>(msg, ...)`
fields = null;
msgArgs = Array.prototype.slice.call(args);
} else {
// `log.<level>(fields, msg, ...)`
fields = args[0];
if (args.length === 1 && fields.err && fields.err instanceof Error) {
msgArgs = [fields.err.message];
} else {
msgArgs = Array.prototype.slice.call(args, 1);
}
}
// Build up the record object.
const rec = objCopy(log.fields);
rec.level = minLevel;
const recFields = (fields ? objCopy(fields) : null);
if (recFields) {
if (log.serializers) {
log._applySerializers(recFields, excludeFields);
}
Object.keys(recFields).forEach(k => {
rec[k] = recFields[k];
});
}
rec.levelName = nameFromLevel[minLevel];
rec.msg = msgArgs.length ? format.apply(log, msgArgs) : '';
if (!rec.time) {
rec.time = (new Date());
}
// Get call source info
if (log.src && !rec.src) {
try {
//need to throw the error so there is a stack in IE
throw new Error(CALL_STACK_ERROR);
} catch (err) {
// in Safari there is missing stack trace sometimes
const src = err.stack ? extractSrcFromStacktrace(err.stack, 2) : '';
if (!src && !_haveWarned('src')) {
_warn('Unable to determine src line info', 'src');
}
rec.src = src || '';
}
}
rec.v = LOG_VERSION;
return rec;
}
let fields = null;
let msgArgs = arguments;
let rec = null;
if (arguments.length === 0) { // `log.<level>()`
return (this._level <= minLevel);
} else if (this._level > minLevel) {
/* pass through */
} else {
rec = mkRecord(msgArgs);
this._emit(rec);
}
};
} | function mkLogEmitter(minLevel) {
return function () {
const log = this;
function mkRecord(args) {
let excludeFields;
if (args[0] instanceof Error) {
// `log.<level>(err, ...)`
fields = {
// Use this Logger's err serializer, if defined.
err: (log.serializers && log.serializers.err ? log.serializers.err(args[0]) : stdSerializers.err(args[0])),
};
excludeFields = {err: true};
if (args.length === 1) {
msgArgs = [fields.err.message];
} else {
msgArgs = Array.prototype.slice.call(args, 1);
}
} else if (typeof (args[0]) !== 'object' && args[0] !== null || Array.isArray(args[0])) {
// `log.<level>(msg, ...)`
fields = null;
msgArgs = Array.prototype.slice.call(args);
} else {
// `log.<level>(fields, msg, ...)`
fields = args[0];
if (args.length === 1 && fields.err && fields.err instanceof Error) {
msgArgs = [fields.err.message];
} else {
msgArgs = Array.prototype.slice.call(args, 1);
}
}
// Build up the record object.
const rec = objCopy(log.fields);
rec.level = minLevel;
const recFields = (fields ? objCopy(fields) : null);
if (recFields) {
if (log.serializers) {
log._applySerializers(recFields, excludeFields);
}
Object.keys(recFields).forEach(k => {
rec[k] = recFields[k];
});
}
rec.levelName = nameFromLevel[minLevel];
rec.msg = msgArgs.length ? format.apply(log, msgArgs) : '';
if (!rec.time) {
rec.time = (new Date());
}
// Get call source info
if (log.src && !rec.src) {
try {
//need to throw the error so there is a stack in IE
throw new Error(CALL_STACK_ERROR);
} catch (err) {
// in Safari there is missing stack trace sometimes
const src = err.stack ? extractSrcFromStacktrace(err.stack, 2) : '';
if (!src && !_haveWarned('src')) {
_warn('Unable to determine src line info', 'src');
}
rec.src = src || '';
}
}
rec.v = LOG_VERSION;
return rec;
}
let fields = null;
let msgArgs = arguments;
let rec = null;
if (arguments.length === 0) { // `log.<level>()`
return (this._level <= minLevel);
} else if (this._level > minLevel) {
/* pass through */
} else {
rec = mkRecord(msgArgs);
this._emit(rec);
}
};
} |
JavaScript | function playHtml5Video( containerId, src, width, height ) {
var videoId = "video_inside_" + containerId;
var cnt = document.getElementById(containerId);
var elt = document.getElementById(videoId);
if( elt == null ) {
cnt.innerHTML = "<video id='"+videoId+"' src='"+src+"' controls width='"+width+"' height='"+height+"' webkit-playsinline></video>";
elt = document.getElementById(videoId);
} else {
}
elt.src = src;
elt.width = width;
elt.height = height;
elt.load();
elt.play();
} | function playHtml5Video( containerId, src, width, height ) {
var videoId = "video_inside_" + containerId;
var cnt = document.getElementById(containerId);
var elt = document.getElementById(videoId);
if( elt == null ) {
cnt.innerHTML = "<video id='"+videoId+"' src='"+src+"' controls width='"+width+"' height='"+height+"' webkit-playsinline></video>";
elt = document.getElementById(videoId);
} else {
}
elt.src = src;
elt.width = width;
elt.height = height;
elt.load();
elt.play();
} |
JavaScript | function playFlashVideo( containerId, src, width, height ) {
// create a container inside the container to be able to kill flash by
// resetting the child container to an empty string
var objectId = "object_inside_" + containerId;
var cnt = document.getElementById(containerId);
var elt = document.getElementById(objectId);
if( elt == null ) {
cnt.innerHTML = "<object id='" + objectId + "' />";
elt = document.getElementById(objectId);
}
// Create a StrobeMediaPlayback configuration
var parameters =
{ src: src
,autoPlay: true
,controlBarPosition: "none",
wmode: "transparent"
};
// Embed the player SWF:
swfobject.embedSWF
("js/swplayer/StrobeMediaPlaybackDis.swf"
, objectId
, width
, height
, "10.1.0"
, {}
, parameters
, { allowFullScreen: "true"}
, { name: objectId }
);
} | function playFlashVideo( containerId, src, width, height ) {
// create a container inside the container to be able to kill flash by
// resetting the child container to an empty string
var objectId = "object_inside_" + containerId;
var cnt = document.getElementById(containerId);
var elt = document.getElementById(objectId);
if( elt == null ) {
cnt.innerHTML = "<object id='" + objectId + "' />";
elt = document.getElementById(objectId);
}
// Create a StrobeMediaPlayback configuration
var parameters =
{ src: src
,autoPlay: true
,controlBarPosition: "none",
wmode: "transparent"
};
// Embed the player SWF:
swfobject.embedSWF
("js/swplayer/StrobeMediaPlaybackDis.swf"
, objectId
, width
, height
, "10.1.0"
, {}
, parameters
, { allowFullScreen: "true"}
, { name: objectId }
);
} |
JavaScript | function onSilverlightError(sender, args) {
var appSource = "";
if (sender != null && sender != 0) {
appSource = sender.getHost().Source;
}
var errorType = args.ErrorType;
var iErrorCode = args.ErrorCode;
if (errorType == "ImageError" || errorType == "MediaError") {
return;
}
var errMsg = "Unhandled Error in Silverlight Application " + appSource + "\n" ;
errMsg += "Code: "+ iErrorCode + " \n";
errMsg += "Category: " + errorType + " \n";
errMsg += "Message: " + args.ErrorMessage + " \n";
if (errorType == "ParserError") {
errMsg += "File: " + args.xamlFile + " \n";
errMsg += "Line: " + args.lineNumber + " \n";
errMsg += "Position: " + args.charPosition + " \n";
}
else if (errorType == "RuntimeError") {
if (args.lineNumber != 0) {
errMsg += "Line: " + args.lineNumber + " \n";
errMsg += "Position: " + args.charPosition + " \n";
}
errMsg += "MethodName: " + args.methodName + " \n";
}
throw new Error(errMsg);
} | function onSilverlightError(sender, args) {
var appSource = "";
if (sender != null && sender != 0) {
appSource = sender.getHost().Source;
}
var errorType = args.ErrorType;
var iErrorCode = args.ErrorCode;
if (errorType == "ImageError" || errorType == "MediaError") {
return;
}
var errMsg = "Unhandled Error in Silverlight Application " + appSource + "\n" ;
errMsg += "Code: "+ iErrorCode + " \n";
errMsg += "Category: " + errorType + " \n";
errMsg += "Message: " + args.ErrorMessage + " \n";
if (errorType == "ParserError") {
errMsg += "File: " + args.xamlFile + " \n";
errMsg += "Line: " + args.lineNumber + " \n";
errMsg += "Position: " + args.charPosition + " \n";
}
else if (errorType == "RuntimeError") {
if (args.lineNumber != 0) {
errMsg += "Line: " + args.lineNumber + " \n";
errMsg += "Position: " + args.charPosition + " \n";
}
errMsg += "MethodName: " + args.methodName + " \n";
}
throw new Error(errMsg);
} |
JavaScript | function playSilverVideo( containerId, src, width, height ) {
var objectId = "object_inside_" + containerId;
var cnt = document.getElementById(containerId);
var elt = document.getElementById(objectId);
if( elt == null ) {
cnt.innerHTML =
"<object data='data:application/x-silverlight-2,' type='application/x-silverlight-2' width='"+width + "' height='" + height + "'>\n" +
" <param name='source' value='SmoothStreamingPlayer_lite.xap'/>\n"+
" <param name='onError' value='onSilverlightError' />\n" +
" <param name='background' value='white' />\n" +
" <param name='minRuntimeVersion' value='4.0.50401.0' />\n" +
" <param name='autoUpgrade' value='true' />\n"+
" <param name='InitParams' value='mediaurl=" + src + "' />\n" +
" <a href='http://go.microsoft.com/fwlink/?LinkID=149156&v=4.0.50401.0' style='text-decoration:none'>\n" +
" <img src='http://go.microsoft.com/fwlink/?LinkId=161376' alt='Get Microsoft Silverlight' style='border-style:none'/>\n" +
" </a>\n"+
"</object>\n";
elt = document.getElementById(objectId);
} else {
}
// XXX. This could be good to use a javascript api to control the silver player (play/pause ..)
} | function playSilverVideo( containerId, src, width, height ) {
var objectId = "object_inside_" + containerId;
var cnt = document.getElementById(containerId);
var elt = document.getElementById(objectId);
if( elt == null ) {
cnt.innerHTML =
"<object data='data:application/x-silverlight-2,' type='application/x-silverlight-2' width='"+width + "' height='" + height + "'>\n" +
" <param name='source' value='SmoothStreamingPlayer_lite.xap'/>\n"+
" <param name='onError' value='onSilverlightError' />\n" +
" <param name='background' value='white' />\n" +
" <param name='minRuntimeVersion' value='4.0.50401.0' />\n" +
" <param name='autoUpgrade' value='true' />\n"+
" <param name='InitParams' value='mediaurl=" + src + "' />\n" +
" <a href='http://go.microsoft.com/fwlink/?LinkID=149156&v=4.0.50401.0' style='text-decoration:none'>\n" +
" <img src='http://go.microsoft.com/fwlink/?LinkId=161376' alt='Get Microsoft Silverlight' style='border-style:none'/>\n" +
" </a>\n"+
"</object>\n";
elt = document.getElementById(objectId);
} else {
}
// XXX. This could be good to use a javascript api to control the silver player (play/pause ..)
} |
JavaScript | function playHlsFlashIosVideo( containerId, src, width, height ) {
// Same as flash: Container inside the container to kill it
var objectId = "object_inside_" + containerId;
var cnt = document.getElementById(containerId);
var elt = document.getElementById(objectId);
if( elt == null ) {
cnt.innerHTML = "<object id='" + objectId + "' />";
elt = document.getElementById(objectId);
}
jwplayer(objectId).setup({
height: height,
width: width,
// plugins: { 'assets/qualitymonitor.swf':{} },
modes: [
{ type: "flash",
src: "jwplayer.swf",
config: {
provider:"jwadaptiveProvider.swf",
file: src
}
},
{ type: "html5",
config: {
file: src
}
},
{ type: "download" }
]
});
// XXX: sometimes the jwplayer is hidden
var elt = document.getElementById(objectId);
if( elt != null ) {
elt.style.visibility = "visible";
}
jwplayer(objectId).play();
} | function playHlsFlashIosVideo( containerId, src, width, height ) {
// Same as flash: Container inside the container to kill it
var objectId = "object_inside_" + containerId;
var cnt = document.getElementById(containerId);
var elt = document.getElementById(objectId);
if( elt == null ) {
cnt.innerHTML = "<object id='" + objectId + "' />";
elt = document.getElementById(objectId);
}
jwplayer(objectId).setup({
height: height,
width: width,
// plugins: { 'assets/qualitymonitor.swf':{} },
modes: [
{ type: "flash",
src: "jwplayer.swf",
config: {
provider:"jwadaptiveProvider.swf",
file: src
}
},
{ type: "html5",
config: {
file: src
}
},
{ type: "download" }
]
});
// XXX: sometimes the jwplayer is hidden
var elt = document.getElementById(objectId);
if( elt != null ) {
elt.style.visibility = "visible";
}
jwplayer(objectId).play();
} |
JavaScript | function formatSrc( srcPath, srcFile, srcExt, options) {
var ret = srcPath;
if( ! srcPath.endsWith("/") ) {
ret = ret + "/";
}
ret = ret + srcFile;
if( srcExt != "" ) {
if( ! srcExt.startsWith( ".") ) {
ret = ret + ".";
}
ret = ret + srcExt;
}
if ( options ) {
ret = ret + options;
}
return ret;
} | function formatSrc( srcPath, srcFile, srcExt, options) {
var ret = srcPath;
if( ! srcPath.endsWith("/") ) {
ret = ret + "/";
}
ret = ret + srcFile;
if( srcExt != "" ) {
if( ! srcExt.startsWith( ".") ) {
ret = ret + ".";
}
ret = ret + srcExt;
}
if ( options ) {
ret = ret + options;
}
return ret;
} |
JavaScript | sendScreenState() {
const body = JSON.stringify(this.screenMonitorEvents)
this.screenMonitorEvents = []
if (this.detection.fetch()) {
fetch(this.apiEndpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body
})
}
} | sendScreenState() {
const body = JSON.stringify(this.screenMonitorEvents)
this.screenMonitorEvents = []
if (this.detection.fetch()) {
fetch(this.apiEndpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body
})
}
} |
JavaScript | function restore_options() {
// Use default value enable = true and block_60fps = false
chrome.storage.local.get({
enable: true,
block_60fps: false
}, function(options) {
document.getElementById('enable').checked = options.enable;
document.getElementById('block_60fps').checked = options.block_60fps;
});
} | function restore_options() {
// Use default value enable = true and block_60fps = false
chrome.storage.local.get({
enable: true,
block_60fps: false
}, function(options) {
document.getElementById('enable').checked = options.enable;
document.getElementById('block_60fps').checked = options.block_60fps;
});
} |
JavaScript | function makeModifiedTypeChecker(origChecker) {
// Check if a video type is allowed
return function (type) {
if (type === undefined) return '';
var disallowed_types = ['webm', 'vp8', 'vp9'];
// If video type is in disallowed_types, say we don't support them
for (var i = 0; i < disallowed_types.length; i++) {
if (type.indexOf(disallowed_types[i]) !== -1) return '';
}
if (localStorage['h264ify+-block_60fps'] === 'true') {
var match = /framerate=(\d+)/.exec(type);
if (match && match[1] > 30) return '';
}
// Otherwise, ask the browser
return origChecker(type);
};
} | function makeModifiedTypeChecker(origChecker) {
// Check if a video type is allowed
return function (type) {
if (type === undefined) return '';
var disallowed_types = ['webm', 'vp8', 'vp9'];
// If video type is in disallowed_types, say we don't support them
for (var i = 0; i < disallowed_types.length; i++) {
if (type.indexOf(disallowed_types[i]) !== -1) return '';
}
if (localStorage['h264ify+-block_60fps'] === 'true') {
var match = /framerate=(\d+)/.exec(type);
if (match && match[1] > 30) return '';
}
// Otherwise, ask the browser
return origChecker(type);
};
} |
JavaScript | function GameObject()
{
/** Display depth order. A smaller zOrder means the element is rendered first, and therefor
in the background.
@type Number
*/
this.zOrder = 0;
/**
The position on the X axis
@type Number
*/
this.x = 0;
/**
The position on the Y axis
@type Number
*/
this.y = 0;
/**
Initialises the object, and adds it to the list of objects held by the GameObjectManager.
@param x The position on the X axis
@param y The position on the Y axis
@param z The z order of the element (elements in the background have a lower z value)
*/
this.startupGameObject = function(/**Number*/ x, /**Number*/ y, /**Number*/ z)
{
this.zOrder = z;
this.x = x;
this.y = y;
g_GameObjectManager.addGameObject(this);
return this;
}
/**
Cleans up the object, and removes it from the list of objects held by the GameObjectManager.
*/
this.shutdownGameObject = function()
{
g_GameObjectManager.removeGameObject(this);
}
} | function GameObject()
{
/** Display depth order. A smaller zOrder means the element is rendered first, and therefor
in the background.
@type Number
*/
this.zOrder = 0;
/**
The position on the X axis
@type Number
*/
this.x = 0;
/**
The position on the Y axis
@type Number
*/
this.y = 0;
/**
Initialises the object, and adds it to the list of objects held by the GameObjectManager.
@param x The position on the X axis
@param y The position on the Y axis
@param z The z order of the element (elements in the background have a lower z value)
*/
this.startupGameObject = function(/**Number*/ x, /**Number*/ y, /**Number*/ z)
{
this.zOrder = z;
this.x = x;
this.y = y;
g_GameObjectManager.addGameObject(this);
return this;
}
/**
Cleans up the object, and removes it from the list of objects held by the GameObjectManager.
*/
this.shutdownGameObject = function()
{
g_GameObjectManager.removeGameObject(this);
}
} |
JavaScript | function RepeatingGameObject()
{
/** The width that the final image will take up
@type Number
*/
this.width = 0;
/** The height that the final image will take up
@type Number
*/
this.height = 0;
/** How much of the scrollX and scrollY to apply when drawing
@type Number
*/
this.scrollFactor = 1;
/**
Initialises this object
@return A reference to the initialised object
*/
this.startupRepeatingGameObject = function(image, x, y, z, width, height, scrollFactor)
{
this.startupVisualGameObject(image, x, y, z);
this.width = width;
this.height = height;
this.scrollFactor = scrollFactor;
return this;
}
/**
Clean this object up
*/
this.shutdownstartupRepeatingGameObject = function()
{
this.shutdownVisualGameObject();
}
/**
Draws this element to the back buffer
@param dt Time in seconds since the last frame
@param context The context to draw to
@param xScroll The global scrolling value of the x axis
@param yScroll The global scrolling value of the y axis
*/
this.draw = function(dt, canvas, xScroll, yScroll)
{
var areaDrawn = [0, 0];
for (var y = 0; y < this.height; y += areaDrawn[1])
{
for (var x = 0; x < this.width; x += areaDrawn[0])
{
// the top left corner to start drawing the next tile from
var newPosition = [this.x + x, this.y + y];
// the amount of space left in which to draw
var newFillArea = [this.width - x, this.height - y];
// the first time around you have to start drawing from the middle of the image
// subsequent tiles alwyas get drawn from the top or left
var newScrollPosition = [0, 0];
if (x==0) newScrollPosition[0] = xScroll * this.scrollFactor;
if (y==0) newScrollPosition[1] = yScroll * this.scrollFactor;
areaDrawn = this.drawRepeat(canvas, newPosition, newFillArea, newScrollPosition);
}
}
}
this.drawRepeat = function(canvas, newPosition, newFillArea, newScrollPosition)
{
// find where in our repeating texture to start drawing (the top left corner)
var xOffset = Math.abs(newScrollPosition[0]) % this.image.width;
var yOffset = Math.abs(newScrollPosition[1]) % this.image.height;
var left = newScrollPosition[0]<0?this.image.width-xOffset:xOffset;
var top = newScrollPosition[1]<0?this.image.height-yOffset:yOffset;
var width = newFillArea[0] < this.image.width-left?newFillArea[0]:this.image.width-left;
var height = newFillArea[1] < this.image.height-top?newFillArea[1]:this.image.height-top;
// draw the image
canvas.drawImage(this.image, left, top, width, height, newPosition[0], newPosition[1], width, height);
return [width, height];
}
} | function RepeatingGameObject()
{
/** The width that the final image will take up
@type Number
*/
this.width = 0;
/** The height that the final image will take up
@type Number
*/
this.height = 0;
/** How much of the scrollX and scrollY to apply when drawing
@type Number
*/
this.scrollFactor = 1;
/**
Initialises this object
@return A reference to the initialised object
*/
this.startupRepeatingGameObject = function(image, x, y, z, width, height, scrollFactor)
{
this.startupVisualGameObject(image, x, y, z);
this.width = width;
this.height = height;
this.scrollFactor = scrollFactor;
return this;
}
/**
Clean this object up
*/
this.shutdownstartupRepeatingGameObject = function()
{
this.shutdownVisualGameObject();
}
/**
Draws this element to the back buffer
@param dt Time in seconds since the last frame
@param context The context to draw to
@param xScroll The global scrolling value of the x axis
@param yScroll The global scrolling value of the y axis
*/
this.draw = function(dt, canvas, xScroll, yScroll)
{
var areaDrawn = [0, 0];
for (var y = 0; y < this.height; y += areaDrawn[1])
{
for (var x = 0; x < this.width; x += areaDrawn[0])
{
// the top left corner to start drawing the next tile from
var newPosition = [this.x + x, this.y + y];
// the amount of space left in which to draw
var newFillArea = [this.width - x, this.height - y];
// the first time around you have to start drawing from the middle of the image
// subsequent tiles alwyas get drawn from the top or left
var newScrollPosition = [0, 0];
if (x==0) newScrollPosition[0] = xScroll * this.scrollFactor;
if (y==0) newScrollPosition[1] = yScroll * this.scrollFactor;
areaDrawn = this.drawRepeat(canvas, newPosition, newFillArea, newScrollPosition);
}
}
}
this.drawRepeat = function(canvas, newPosition, newFillArea, newScrollPosition)
{
// find where in our repeating texture to start drawing (the top left corner)
var xOffset = Math.abs(newScrollPosition[0]) % this.image.width;
var yOffset = Math.abs(newScrollPosition[1]) % this.image.height;
var left = newScrollPosition[0]<0?this.image.width-xOffset:xOffset;
var top = newScrollPosition[1]<0?this.image.height-yOffset:yOffset;
var width = newFillArea[0] < this.image.width-left?newFillArea[0]:this.image.width-left;
var height = newFillArea[1] < this.image.height-top?newFillArea[1]:this.image.height-top;
// draw the image
canvas.drawImage(this.image, left, top, width, height, newPosition[0], newPosition[1], width, height);
return [width, height];
}
} |
JavaScript | function ApplicationManager()
{
/**
Initialises this object
@return A reference to the initialised object
*/
this.startupApplicationManager = function()
{
this.runner = new AnimatedGameObject().startupAnimatedGameObject(g_run, 0, 0, 1, cTotalFrames, FPS);
return this;
}
} | function ApplicationManager()
{
/**
Initialises this object
@return A reference to the initialised object
*/
this.startupApplicationManager = function()
{
this.runner = new AnimatedGameObject().startupAnimatedGameObject(g_run, 0, 0, 1, cTotalFrames, FPS);
return this;
}
} |
JavaScript | async function downloadAndCopyBinaries(config) {
info('Downloading dependencies...')
const {
transactionManager, cakeshop, generateKeys, quorumVersion, consensus,
} = config.network
const downloads = []
if (isIstanbul(consensus)) {
downloads.push(downloadIfMissing('istanbul', LATEST_ISTANBUL_TOOLS))
}
if (generateKeys) {
downloads.push(downloadIfMissing('bootnode', LATEST_BOOTNODE))
}
if (quorumVersion !== 'PATH') {
downloads.push(downloadIfMissing('quorum', quorumVersion))
}
const tesseraVersion = transactionManager
if (tesseraVersion !== 'PATH' && isTessera(tesseraVersion)) {
downloads.push(downloadIfMissing('tessera', tesseraVersion))
}
if (cakeshop !== 'none') {
downloads.push(downloadIfMissing('cakeshop', cakeshop))
}
await Promise.all(downloads)
} | async function downloadAndCopyBinaries(config) {
info('Downloading dependencies...')
const {
transactionManager, cakeshop, generateKeys, quorumVersion, consensus,
} = config.network
const downloads = []
if (isIstanbul(consensus)) {
downloads.push(downloadIfMissing('istanbul', LATEST_ISTANBUL_TOOLS))
}
if (generateKeys) {
downloads.push(downloadIfMissing('bootnode', LATEST_BOOTNODE))
}
if (quorumVersion !== 'PATH') {
downloads.push(downloadIfMissing('quorum', quorumVersion))
}
const tesseraVersion = transactionManager
if (tesseraVersion !== 'PATH' && isTessera(tesseraVersion)) {
downloads.push(downloadIfMissing('tessera', tesseraVersion))
}
if (cakeshop !== 'none') {
downloads.push(downloadIfMissing('cakeshop', cakeshop))
}
await Promise.all(downloads)
} |
JavaScript | isDayTime(target) {
let highTime = this.getTwentyFourHourTime("6:00 pm");
let lowTime = this.getTwentyFourHourTime("6:00 am");
//assume time will always go faster
//thus, we would assume that 6:00 pm and after 6:00pm
// will be night time. because everyone mintue is very fast.
//if it does not fall in interval of
// 6:am(6) <= target < (18)6:00pm
//just in case there is a digit more than 24 hours.
return (lowTime <= target) && (target < highTime);
} | isDayTime(target) {
let highTime = this.getTwentyFourHourTime("6:00 pm");
let lowTime = this.getTwentyFourHourTime("6:00 am");
//assume time will always go faster
//thus, we would assume that 6:00 pm and after 6:00pm
// will be night time. because everyone mintue is very fast.
//if it does not fall in interval of
// 6:am(6) <= target < (18)6:00pm
//just in case there is a digit more than 24 hours.
return (lowTime <= target) && (target < highTime);
} |
JavaScript | function ensureLocalizationDirectory() {
var locDir = common_1.getLocalizationDirectoryPath(true);
if (!fse.existsSync(locDir))
common_1.log("created '" + common_1.chalk.cyanBright(locDir) + "' directory");
fse.ensureDirSync(locDir);
if (!fse.existsSync(locDir))
throw new Error(common_1.terminalPrefix + " cannot create '" + common_1.chalk.cyanBright(_1.Lingualizer.DefaulLocalizationDirName) + "' directory at '" + common_1.chalk.red(locDir) + "'");
return locDir;
} | function ensureLocalizationDirectory() {
var locDir = common_1.getLocalizationDirectoryPath(true);
if (!fse.existsSync(locDir))
common_1.log("created '" + common_1.chalk.cyanBright(locDir) + "' directory");
fse.ensureDirSync(locDir);
if (!fse.existsSync(locDir))
throw new Error(common_1.terminalPrefix + " cannot create '" + common_1.chalk.cyanBright(_1.Lingualizer.DefaulLocalizationDirName) + "' directory at '" + common_1.chalk.red(locDir) + "'");
return locDir;
} |
JavaScript | function ensureKey(obj, key) {
if (!key)
return;
var tokens = key.split('.');
var nestedObj = obj;
for (var i = 0; i < tokens.length; i++) {
var token = tokens[i];
if (typeof nestedObj[token] == 'undefined') {
nestedObj[token] = {};
}
if ((tokens.length - 1) !== i && typeof nestedObj[token] !== 'object')
// its not the last one so ensure we have a object not a string
nestedObj[token] = {};
nestedObj = nestedObj[token];
}
} | function ensureKey(obj, key) {
if (!key)
return;
var tokens = key.split('.');
var nestedObj = obj;
for (var i = 0; i < tokens.length; i++) {
var token = tokens[i];
if (typeof nestedObj[token] == 'undefined') {
nestedObj[token] = {};
}
if ((tokens.length - 1) !== i && typeof nestedObj[token] !== 'object')
// its not the last one so ensure we have a object not a string
nestedObj[token] = {};
nestedObj = nestedObj[token];
}
} |
JavaScript | function changeActiveTab() {
for (var j = 0; j < tabs.length; ++j) {
tabs[j].className = "tabButton";
if(tabs[j] == this) {
this.className += " activeTab";
$(tabs[j]).attr("aria-selected", true);
$('#loginIdPanel').attr("aria-labelledby", $(tabs[j]).attr('id'));
} else {
$(tabs[j]).attr("aria-selected", false);
}
}
if ($('.login').length) {
//hide error message after a tab click
if ($("#casMsg").length > 0){
document.getElementById("casErrorDiv").style.display="none";
}
document.getElementById('loginIdLabel').innerHTML = loginTypesAndLabels[this.childNodes[1].innerHTML][0];
document.getElementById('PINLabel').innerHTML = loginTypesAndLabels[this.childNodes[1].innerHTML][1];
// document.getElementById('compositeAuthenticationSourceType').value = loginTypesAndLabels[this.childNodes[1].innerHTML][2];
document.getElementById('authenticationSourceType').value = loginTypesAndLabels[this.childNodes[1].innerHTML][2];
if(loginTypesAndLabels[this.childNodes[1].innerHTML][2]=="HarvardKey") {
document.getElementById('username').setAttribute('placeholder', '[email protected]');
}
else {
document.getElementById('username').setAttribute('placeholder', '');
}
}
} | function changeActiveTab() {
for (var j = 0; j < tabs.length; ++j) {
tabs[j].className = "tabButton";
if(tabs[j] == this) {
this.className += " activeTab";
$(tabs[j]).attr("aria-selected", true);
$('#loginIdPanel').attr("aria-labelledby", $(tabs[j]).attr('id'));
} else {
$(tabs[j]).attr("aria-selected", false);
}
}
if ($('.login').length) {
//hide error message after a tab click
if ($("#casMsg").length > 0){
document.getElementById("casErrorDiv").style.display="none";
}
document.getElementById('loginIdLabel').innerHTML = loginTypesAndLabels[this.childNodes[1].innerHTML][0];
document.getElementById('PINLabel').innerHTML = loginTypesAndLabels[this.childNodes[1].innerHTML][1];
// document.getElementById('compositeAuthenticationSourceType').value = loginTypesAndLabels[this.childNodes[1].innerHTML][2];
document.getElementById('authenticationSourceType').value = loginTypesAndLabels[this.childNodes[1].innerHTML][2];
if(loginTypesAndLabels[this.childNodes[1].innerHTML][2]=="HarvardKey") {
document.getElementById('username').setAttribute('placeholder', '[email protected]');
}
else {
document.getElementById('username').setAttribute('placeholder', '');
}
}
} |
JavaScript | function categoryMenuToggle() {
var screenSize = windows.width();
if (screenSize <= 991) {
categoryMenu.slideUp();
} else {
categoryMenu.slideDown();
}
} | function categoryMenuToggle() {
var screenSize = windows.width();
if (screenSize <= 991) {
categoryMenu.slideUp();
} else {
categoryMenu.slideDown();
}
} |
JavaScript | function range(start = 0, stop, step = 1) {
if (arguments.length <= 1) {
stop = start; // eslint-disable-line
}
const length = Math.max(Math.ceil((stop - start) / step), 0);
let idx = 0;
const arr = new Array(length);
while (idx < length) {
arr[idx++] = start; // eslint-disable-line
start += step; // eslint-disable-line
}
return arr;
} | function range(start = 0, stop, step = 1) {
if (arguments.length <= 1) {
stop = start; // eslint-disable-line
}
const length = Math.max(Math.ceil((stop - start) / step), 0);
let idx = 0;
const arr = new Array(length);
while (idx < length) {
arr[idx++] = start; // eslint-disable-line
start += step; // eslint-disable-line
}
return arr;
} |
JavaScript | function generateHtml(employees) {
return `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Team Profile</title>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.1/css/all.css"
integrity="sha384-50oBUHEmvpQ+1lW4y57PTFmhCaXp0ML5d60M1M7uH2+nqUivzIebhndOJK28anvf" crossorigin="anonymous" />
<link rel="stylesheet" href="./develop/dist/style.css">
</head>
<body>
<h1>My Team</h1>
${employees.map(employee => {
return cardGenerator(employee);
}).join('')
}
</body>
</html>`
} | function generateHtml(employees) {
return `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Team Profile</title>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.1/css/all.css"
integrity="sha384-50oBUHEmvpQ+1lW4y57PTFmhCaXp0ML5d60M1M7uH2+nqUivzIebhndOJK28anvf" crossorigin="anonymous" />
<link rel="stylesheet" href="./develop/dist/style.css">
</head>
<body>
<h1>My Team</h1>
${employees.map(employee => {
return cardGenerator(employee);
}).join('')
}
</body>
</html>`
} |
JavaScript | function prepare(source) {
var structure = source
.replace(/\bextends\s+([^;]+?)(?:\s+from\s+([^;]+?))?\s*\{/g, function(match, selector, module){
return '{ inherits: ' + (module ? '.' + module : '@this') + ' ' + selector + ';';
}).replace(/\bextends\s+([^;]+?)(?:\s+from\s+([^;]+?))?\s*;/g, function(match, selector, module){
return 'inherits: ' + (module ? '.' + module : '@this') + ' ' + selector + ';';
}).replace(/@import\s+([^;]+?)\s+from\s+([^;]+)\s*;/g, function(match, selector, module){
return selector + ' { inherits: .' + module + ' ' + selector + '; }';
}).replace(/\bimport\s+([^;]+?)\s+from\s+([^;]+)\s*;/g, function(match, selector, module){
return 'import: .' + module + ' ' + selector + ';';
}).split(/@module\s+(\w+);/);
var global = structure.shift();
var name, modules = {};
while (structure.length) {
name = structure.shift();
modules[name] = rework(structure.shift())
.use(function(css, rework){
css.rules.forEach(function(rule){
if (rule.type != 'rule') return;
for (var i = 0; i < rule.selectors.length; i++) {
if (rule.selectors[i].indexOf('@this') !== -1) continue;
rule.selectors[i] = '@this ' + rule.selectors[i];
}
});
return css;
}).toString();
}
for (name in modules) {
global += modules[name].replace(/@this/g, '.'+name) + '\n';
}
return global;
} | function prepare(source) {
var structure = source
.replace(/\bextends\s+([^;]+?)(?:\s+from\s+([^;]+?))?\s*\{/g, function(match, selector, module){
return '{ inherits: ' + (module ? '.' + module : '@this') + ' ' + selector + ';';
}).replace(/\bextends\s+([^;]+?)(?:\s+from\s+([^;]+?))?\s*;/g, function(match, selector, module){
return 'inherits: ' + (module ? '.' + module : '@this') + ' ' + selector + ';';
}).replace(/@import\s+([^;]+?)\s+from\s+([^;]+)\s*;/g, function(match, selector, module){
return selector + ' { inherits: .' + module + ' ' + selector + '; }';
}).replace(/\bimport\s+([^;]+?)\s+from\s+([^;]+)\s*;/g, function(match, selector, module){
return 'import: .' + module + ' ' + selector + ';';
}).split(/@module\s+(\w+);/);
var global = structure.shift();
var name, modules = {};
while (structure.length) {
name = structure.shift();
modules[name] = rework(structure.shift())
.use(function(css, rework){
css.rules.forEach(function(rule){
if (rule.type != 'rule') return;
for (var i = 0; i < rule.selectors.length; i++) {
if (rule.selectors[i].indexOf('@this') !== -1) continue;
rule.selectors[i] = '@this ' + rule.selectors[i];
}
});
return css;
}).toString();
}
for (name in modules) {
global += modules[name].replace(/@this/g, '.'+name) + '\n';
}
return global;
} |
JavaScript | function MOOCSS(source, options) {
return rework(prepare(source), options)
.use(imprt({ transform: prepare }))
.use(function(css, rework){
var inserts = [];
var sum = 1;
css.rules.forEach(function(rule, idx){
if (rule.type != 'rule') return;
rule.declarations = rule.declarations.filter(function(declaration){
if (declaration.property === 'import') {
var match = declaration.value.match(/^(\.\w+)\s+(.+)/);
var selectors = rule.selectors.map(function(selector){
return selector + ' ' + match[2];
});
inserts.push({
index: idx,
rule: {
type: 'rule',
selectors: selectors,
declarations: [{
type: 'declaration',
property: 'inherits',
value: declaration.value
}]
}
});
return false;
}
return true;
});
});
inserts.forEach(function(insert){
css.rules.splice(insert.index + (sum++), 0, insert.rule);
});
return css;
})
.use(inherit());
} | function MOOCSS(source, options) {
return rework(prepare(source), options)
.use(imprt({ transform: prepare }))
.use(function(css, rework){
var inserts = [];
var sum = 1;
css.rules.forEach(function(rule, idx){
if (rule.type != 'rule') return;
rule.declarations = rule.declarations.filter(function(declaration){
if (declaration.property === 'import') {
var match = declaration.value.match(/^(\.\w+)\s+(.+)/);
var selectors = rule.selectors.map(function(selector){
return selector + ' ' + match[2];
});
inserts.push({
index: idx,
rule: {
type: 'rule',
selectors: selectors,
declarations: [{
type: 'declaration',
property: 'inherits',
value: declaration.value
}]
}
});
return false;
}
return true;
});
});
inserts.forEach(function(insert){
css.rules.splice(insert.index + (sum++), 0, insert.rule);
});
return css;
})
.use(inherit());
} |
JavaScript | function createBoard() {
var grid = document.querySelector('.container');
grid.innerHTML = '';
for (var row = 0; row < rowsize; row++) {
for (var col = 0; col < colsize; col++) {
let weight = Math.round(getRandomArbitrary(5));
let temp = createNode(row, col, weight);
grid.appendChild(temp);
}
}
} | function createBoard() {
var grid = document.querySelector('.container');
grid.innerHTML = '';
for (var row = 0; row < rowsize; row++) {
for (var col = 0; col < colsize; col++) {
let weight = Math.round(getRandomArbitrary(5));
let temp = createNode(row, col, weight);
grid.appendChild(temp);
}
}
} |
JavaScript | function from(pulses) {
let list = [];
let byteBuffer = "";
for (var i = 4; i < pulses.length; i++) {
if (i % 2) {
// Enjoy the silence
} else {
if (pulses[i] >= 700) {
byteBuffer += 1;
} else {
byteBuffer += 0;
}
if (!(current.length % 8)) {
list.push(byteBuffer);
byteBuffer = "";
}
}
}
} | function from(pulses) {
let list = [];
let byteBuffer = "";
for (var i = 4; i < pulses.length; i++) {
if (i % 2) {
// Enjoy the silence
} else {
if (pulses[i] >= 700) {
byteBuffer += 1;
} else {
byteBuffer += 0;
}
if (!(current.length % 8)) {
list.push(byteBuffer);
byteBuffer = "";
}
}
}
} |
JavaScript | replaceConfirmSendingOfDraft(myEmail) {
let text = this.messageList.alertConfirmSendingOfDraft;
let placeholderValues = [
{
regexp: '{{myEmail}}',
value: myEmail,
},
];
text = this.replacePlaceholders_(text, placeholderValues);
return text;
} | replaceConfirmSendingOfDraft(myEmail) {
let text = this.messageList.alertConfirmSendingOfDraft;
let placeholderValues = [
{
regexp: '{{myEmail}}',
value: myEmail,
},
];
text = this.replacePlaceholders_(text, placeholderValues);
return text;
} |
JavaScript | replaceConfirmAccount(draftMode, myEmail) {
let text = draftMode
? this.messageList.alertConfirmAccountCreateDraft
: this.messageList.alertConfirmAccountSendEmail;
let placeholderValues = [
{
regexp: '{{myEmail}}',
value: myEmail,
},
];
text = this.replacePlaceholders_(text, placeholderValues);
return text;
} | replaceConfirmAccount(draftMode, myEmail) {
let text = draftMode
? this.messageList.alertConfirmAccountCreateDraft
: this.messageList.alertConfirmAccountSendEmail;
let placeholderValues = [
{
regexp: '{{myEmail}}',
value: myEmail,
},
];
text = this.replacePlaceholders_(text, placeholderValues);
return text;
} |
JavaScript | replaceCompleteMessage(draftMode, messageCount) {
let text = draftMode
? this.messageList.alertCompleteAllDraftsCreated
: this.messageList.alertCompleteAllMailsSent;
let placeholderValues = [
{
regexp: '{{messageCount}}',
value: messageCount,
},
];
text = this.replacePlaceholders_(text, placeholderValues);
return text;
} | replaceCompleteMessage(draftMode, messageCount) {
let text = draftMode
? this.messageList.alertCompleteAllDraftsCreated
: this.messageList.alertCompleteAllMailsSent;
let placeholderValues = [
{
regexp: '{{messageCount}}',
value: messageCount,
},
];
text = this.replacePlaceholders_(text, placeholderValues);
return text;
} |
JavaScript | function randomUpdate() {
let totalProb = 0;
runProbabilities.forEach(function(runProb) {
let choiceWeight = Math.random() * totalProbabilitySum;
runProbabilities.some(function(item) {
choiceWeight -= item.weight;
if (choiceWeight <= 0.0)
{
item.action();
return true;
}
});
});
} | function randomUpdate() {
let totalProb = 0;
runProbabilities.forEach(function(runProb) {
let choiceWeight = Math.random() * totalProbabilitySum;
runProbabilities.some(function(item) {
choiceWeight -= item.weight;
if (choiceWeight <= 0.0)
{
item.action();
return true;
}
});
});
} |
JavaScript | function updateRotation() {
currentRotation.x += velocity.x;
currentRotation.y += velocity.y;
currentRotation.z += velocity.z;
rotateX(currentRotation.x);
rotateY(currentRotation.y);
rotateZ(currentRotation.z);
} | function updateRotation() {
currentRotation.x += velocity.x;
currentRotation.y += velocity.y;
currentRotation.z += velocity.z;
rotateX(currentRotation.x);
rotateY(currentRotation.y);
rotateZ(currentRotation.z);
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.