language
stringclasses 6
values | original_string
stringlengths 25
887k
| text
stringlengths 25
887k
|
---|---|---|
JavaScript | static fields(obj) {
return Object.keys(obj)
.filter(key => Field.looksLike(obj[key]))
.map(key => {
return { key: key, field: Field.parse(obj[key]) };
});
} | static fields(obj) {
return Object.keys(obj)
.filter(key => Field.looksLike(obj[key]))
.map(key => {
return { key: key, field: Field.parse(obj[key]) };
});
} |
JavaScript | static looksLike(obj) {
return isObject(obj) && (
isInstance(obj, Field) ||
isLike(obj, { value: '' }) ||
isLike(obj, { errorMessage: '' })
);
} | static looksLike(obj) {
return isObject(obj) && (
isInstance(obj, Field) ||
isLike(obj, { value: '' }) ||
isLike(obj, { errorMessage: '' })
);
} |
JavaScript | static parse(obj) {
if (!Field.looksLike(obj)) return undefined;
if (isInstance(obj, Field)) return obj;
return new Field(obj.value, obj.errorMessage);
} | static parse(obj) {
if (!Field.looksLike(obj)) return undefined;
if (isInstance(obj, Field)) return obj;
return new Field(obj.value, obj.errorMessage);
} |
JavaScript | function hermes(options) {
var ul = document.createElement('ul');
var types = Object.keys(options.styles);
// If no maxNotifications was given, there is no maximum.
var maxNotifications = options.maxNotifications || Infinity;
var notifications = [];
if (options.listClasses) {
ul.classList.add.apply(ul.classList, options.listClasses);
}
options.container.appendChild(ul);
// Append a notification with the given message and style to a list. Expire oldest
// notification if the list has grown too large.
function appendNotification(style, message) {
var notification = makeNotification(style, message);
notifications.push(notification);
// If we've gone over the max notifications, animate oldest out early.
if (notifications.length > maxNotifications) {
notifications.shift().cancel();
}
notification.start(function notificationComplete() {
var index = notifications.indexOf(notification);
// If this notification animated out naturally, it needs to be removed from the
// notifications array.
if (index !== -1) {
notifications.splice(index, 1);
}
});
var firstLi = ul.children[0];
if (firstLi) {
ul.insertBefore(notification.li, firstLi);
} else {
ul.appendChild(notification.li);
}
}
// Append a new notification type to a notifier object.
function makeType(notifier, type) {
var style = options.styles[type];
notifier[type] = function (message) {
appendNotification(style, message);
};
return notifier;
}
// Populate an object with notification methods and return it.
return types.reduce(makeType, {});
} | function hermes(options) {
var ul = document.createElement('ul');
var types = Object.keys(options.styles);
// If no maxNotifications was given, there is no maximum.
var maxNotifications = options.maxNotifications || Infinity;
var notifications = [];
if (options.listClasses) {
ul.classList.add.apply(ul.classList, options.listClasses);
}
options.container.appendChild(ul);
// Append a notification with the given message and style to a list. Expire oldest
// notification if the list has grown too large.
function appendNotification(style, message) {
var notification = makeNotification(style, message);
notifications.push(notification);
// If we've gone over the max notifications, animate oldest out early.
if (notifications.length > maxNotifications) {
notifications.shift().cancel();
}
notification.start(function notificationComplete() {
var index = notifications.indexOf(notification);
// If this notification animated out naturally, it needs to be removed from the
// notifications array.
if (index !== -1) {
notifications.splice(index, 1);
}
});
var firstLi = ul.children[0];
if (firstLi) {
ul.insertBefore(notification.li, firstLi);
} else {
ul.appendChild(notification.li);
}
}
// Append a new notification type to a notifier object.
function makeType(notifier, type) {
var style = options.styles[type];
notifier[type] = function (message) {
appendNotification(style, message);
};
return notifier;
}
// Populate an object with notification methods and return it.
return types.reduce(makeType, {});
} |
JavaScript | function appendNotification(style, message) {
var notification = makeNotification(style, message);
notifications.push(notification);
// If we've gone over the max notifications, animate oldest out early.
if (notifications.length > maxNotifications) {
notifications.shift().cancel();
}
notification.start(function notificationComplete() {
var index = notifications.indexOf(notification);
// If this notification animated out naturally, it needs to be removed from the
// notifications array.
if (index !== -1) {
notifications.splice(index, 1);
}
});
var firstLi = ul.children[0];
if (firstLi) {
ul.insertBefore(notification.li, firstLi);
} else {
ul.appendChild(notification.li);
}
} | function appendNotification(style, message) {
var notification = makeNotification(style, message);
notifications.push(notification);
// If we've gone over the max notifications, animate oldest out early.
if (notifications.length > maxNotifications) {
notifications.shift().cancel();
}
notification.start(function notificationComplete() {
var index = notifications.indexOf(notification);
// If this notification animated out naturally, it needs to be removed from the
// notifications array.
if (index !== -1) {
notifications.splice(index, 1);
}
});
var firstLi = ul.children[0];
if (firstLi) {
ul.insertBefore(notification.li, firstLi);
} else {
ul.appendChild(notification.li);
}
} |
JavaScript | function makeType(notifier, type) {
var style = options.styles[type];
notifier[type] = function (message) {
appendNotification(style, message);
};
return notifier;
} | function makeType(notifier, type) {
var style = options.styles[type];
notifier[type] = function (message) {
appendNotification(style, message);
};
return notifier;
} |
JavaScript | function dynamicRefreshList(listroot) {
/*
<!-- Items Button Show Button Hidden
0 items Yes
After delete on the screen:
1 show, 0 hidden Yes
2 show, 0 hidden Yes
0 show, > 1 hidden Yes
1 show, > 1 hidden Yes
> 2 items Yes
-->
*/
var c = listroot.getElementsBySelector("div.showmore")[0];
var divs = listroot.getElementsBySelector("div.repeated-chunk[showmore=true]");
if (divs.length > 0 &&c!=null) {
c.style.display = "block";
var hiddenCount = 0;
for (var i = 0;i!=divs.length;i++) {
if (divs[i].style.display ==="none") {
hiddenCount++;
}
}
if (hiddenCount > 0) {
c.style.display = "block";
return ;
} else if ( divs.length > 2) {
c.style.display = "block";
} else if (divs.length < 3 && hiddenCount === 0) {
c.style.display = "none";
}
} else if(divs.length === 0 &&c!=null) {
c.style.display = "none";
}
} | function dynamicRefreshList(listroot) {
/*
<!-- Items Button Show Button Hidden
0 items Yes
After delete on the screen:
1 show, 0 hidden Yes
2 show, 0 hidden Yes
0 show, > 1 hidden Yes
1 show, > 1 hidden Yes
> 2 items Yes
-->
*/
var c = listroot.getElementsBySelector("div.showmore")[0];
var divs = listroot.getElementsBySelector("div.repeated-chunk[showmore=true]");
if (divs.length > 0 &&c!=null) {
c.style.display = "block";
var hiddenCount = 0;
for (var i = 0;i!=divs.length;i++) {
if (divs[i].style.display ==="none") {
hiddenCount++;
}
}
if (hiddenCount > 0) {
c.style.display = "block";
return ;
} else if ( divs.length > 2) {
c.style.display = "block";
} else if (divs.length < 3 && hiddenCount === 0) {
c.style.display = "none";
}
} else if(divs.length === 0 &&c!=null) {
c.style.display = "none";
}
} |
JavaScript | function updateSingleSelectListBox(listBox,url,config) {
config = config || {};
config = object(config);
var originalOnSuccess = config.onSuccess;
config.onSuccess = function(rsp) {
var l = $(listBox);
var currentSelection = l.value;
// clear the contents
while(l.length>0) l.options[0] = null;
var selectionSet = false; // is the selection forced by the server?
var possibleIndex = null; // if there's a new option that matches the current value, remember its index
var opts = eval('('+rsp.responseText+')').values;
for( var i=0; i<opts.length; i++ ) {
l.options[i] = buildSelectOption(opts[i]);
if(opts[i].selected) {
l.selectedIndex = i;
selectionSet = true;
}
if (opts[i].value==currentSelection)
possibleIndex = i;
}
// if no value is explicitly selected by the server, try to select the same value
if (!selectionSet && possibleIndex!=null)
l.selectedIndex = possibleIndex;
rebuildChosenSingleSelect(l);
if (originalOnSuccess!=undefined)
originalOnSuccess(rsp);
},
config.onFailure = function(rsp) {
// deleting values can result in the data loss, so let's not do that
// var l = $(listBox);
// l.options[0] = null;
}
new Ajax.Request(url, config);
} | function updateSingleSelectListBox(listBox,url,config) {
config = config || {};
config = object(config);
var originalOnSuccess = config.onSuccess;
config.onSuccess = function(rsp) {
var l = $(listBox);
var currentSelection = l.value;
// clear the contents
while(l.length>0) l.options[0] = null;
var selectionSet = false; // is the selection forced by the server?
var possibleIndex = null; // if there's a new option that matches the current value, remember its index
var opts = eval('('+rsp.responseText+')').values;
for( var i=0; i<opts.length; i++ ) {
l.options[i] = buildSelectOption(opts[i]);
if(opts[i].selected) {
l.selectedIndex = i;
selectionSet = true;
}
if (opts[i].value==currentSelection)
possibleIndex = i;
}
// if no value is explicitly selected by the server, try to select the same value
if (!selectionSet && possibleIndex!=null)
l.selectedIndex = possibleIndex;
rebuildChosenSingleSelect(l);
if (originalOnSuccess!=undefined)
originalOnSuccess(rsp);
},
config.onFailure = function(rsp) {
// deleting values can result in the data loss, so let's not do that
// var l = $(listBox);
// l.options[0] = null;
}
new Ajax.Request(url, config);
} |
JavaScript | function updateMultiSelectListBox(listBox,url,config) {
config = config || {};
config = object(config);
var originalOnSuccess = config.onSuccess;
config.onSuccess = function(rsp) {
var l = $(listBox);
var currentSelection = [];
for(var j = 0; j < l.selectedOptions.length; j++){
currentSelection.push(l.selectedOptions[j].value);
}
// clear the contents
while(l.childElementCount > 0) l.removeChild(l.firstChild);
var opts = eval('('+rsp.responseText+')').values;
for( var i=0; i<opts.length; i++ ) {
// Is it an option group
if(opts[i].options){
var group = document.createElement("OPTGROUP");
group.label = opts[i].name;
// Build sub items
var subOpts = opts[i].options;
for(var j = 0; j < subOpts.length; j++){
var opt = buildSelectOption(subOpts[j]);
group.appendChild(opt);
if (currentSelection.indexOf(subOpts[j].value) != -1){
opt.selected = true;
}
}
l.appendChild(group);
}else{
var opt = buildSelectOption(opts[i]);
l.appendChild(opt);
if (currentSelection.indexOf(opts[i].value) != -1){
opt.selected = true;
}
}
}
// create chosen style multi-select
rebuildChosenMultiSelect(l);
if (originalOnSuccess!=undefined)
originalOnSuccess(rsp);
},
config.onFailure = function(rsp) {
// deleting values can result in the data loss, so let's not do that
// var l = $(listBox);
// l.options[0] = null;
}
new Ajax.Request(url, config);
} | function updateMultiSelectListBox(listBox,url,config) {
config = config || {};
config = object(config);
var originalOnSuccess = config.onSuccess;
config.onSuccess = function(rsp) {
var l = $(listBox);
var currentSelection = [];
for(var j = 0; j < l.selectedOptions.length; j++){
currentSelection.push(l.selectedOptions[j].value);
}
// clear the contents
while(l.childElementCount > 0) l.removeChild(l.firstChild);
var opts = eval('('+rsp.responseText+')').values;
for( var i=0; i<opts.length; i++ ) {
// Is it an option group
if(opts[i].options){
var group = document.createElement("OPTGROUP");
group.label = opts[i].name;
// Build sub items
var subOpts = opts[i].options;
for(var j = 0; j < subOpts.length; j++){
var opt = buildSelectOption(subOpts[j]);
group.appendChild(opt);
if (currentSelection.indexOf(subOpts[j].value) != -1){
opt.selected = true;
}
}
l.appendChild(group);
}else{
var opt = buildSelectOption(opts[i]);
l.appendChild(opt);
if (currentSelection.indexOf(opts[i].value) != -1){
opt.selected = true;
}
}
}
// create chosen style multi-select
rebuildChosenMultiSelect(l);
if (originalOnSuccess!=undefined)
originalOnSuccess(rsp);
},
config.onFailure = function(rsp) {
// deleting values can result in the data loss, so let's not do that
// var l = $(listBox);
// l.options[0] = null;
}
new Ajax.Request(url, config);
} |
JavaScript | function makeRequireFunction(mod) {
const Module = mod.constructor;
function require(path) {
try {
exports.requireDepth += 1;
return mod.require(path);
} finally {
exports.requireDepth -= 1;
}
}
//有可能在创建模块之前使用到该函数,类似于静态函数
function resolve(request, options) {
if (typeof request !== 'string') {
throw new ERR_INVALID_ARG_TYPE('request', 'string', request);
}
return Module._resolveFilename(request, mod, false, options);
}
require.resolve = resolve;
// Enable support to add extra extension types.
require.extensions = Module._extensions;
require.cache = Module._cache;
return require;
} | function makeRequireFunction(mod) {
const Module = mod.constructor;
function require(path) {
try {
exports.requireDepth += 1;
return mod.require(path);
} finally {
exports.requireDepth -= 1;
}
}
//有可能在创建模块之前使用到该函数,类似于静态函数
function resolve(request, options) {
if (typeof request !== 'string') {
throw new ERR_INVALID_ARG_TYPE('request', 'string', request);
}
return Module._resolveFilename(request, mod, false, options);
}
require.resolve = resolve;
// Enable support to add extra extension types.
require.extensions = Module._extensions;
require.cache = Module._cache;
return require;
} |
JavaScript | handleStatusUpdate(status) {
if (!this._status || status.height > this._status.height) {
this.lastHeightUpdate = Date.now();
this.stuck = false;
}
else if (!this.stuck && Date.now() - this.lastHeightUpdate > 20000) {
this.stuck = true;
this.emit(PeerEvent.NodeStuck);
}
this._status = status;
// Emit the status update
this.emit(PeerEvent.StatusUpdated, status);
} | handleStatusUpdate(status) {
if (!this._status || status.height > this._status.height) {
this.lastHeightUpdate = Date.now();
this.stuck = false;
}
else if (!this.stuck && Date.now() - this.lastHeightUpdate > 20000) {
this.stuck = true;
this.emit(PeerEvent.NodeStuck);
}
this._status = status;
// Emit the status update
this.emit(PeerEvent.StatusUpdated, status);
} |
JavaScript | updateStatus() {
if (this._state !== PeerState.Online) {
return;
}
this.ws
.getStatus()
.then(status => this.handleStatusUpdate(status))
.then(() => this.ws.getPeers())
.then(response => {
this.peers.length = 0;
this.peers.push(...response.peers);
this.emit(PeerEvent.PeersUpdated, response.peers);
})
.catch(err => console.warn(`could not update status of ${this.options.ip}:${this.options.wsPort}: ${err}`));
} | updateStatus() {
if (this._state !== PeerState.Online) {
return;
}
this.ws
.getStatus()
.then(status => this.handleStatusUpdate(status))
.then(() => this.ws.getPeers())
.then(response => {
this.peers.length = 0;
this.peers.push(...response.peers);
this.emit(PeerEvent.PeersUpdated, response.peers);
})
.catch(err => console.warn(`could not update status of ${this.options.ip}:${this.options.wsPort}: ${err}`));
} |
JavaScript | static registerWamp(socket) {
socket.call = (procedure, data) => new Promise((resolve, reject) => {
socket.emit("rpc-request", { type: "/RPCRequest", procedure, data }, (err, result) => {
if (err) {
reject(err);
}
else {
if (result) {
resolve(result.data);
}
else {
resolve();
}
}
});
});
} | static registerWamp(socket) {
socket.call = (procedure, data) => new Promise((resolve, reject) => {
socket.emit("rpc-request", { type: "/RPCRequest", procedure, data }, (err, result) => {
if (err) {
reject(err);
}
else {
if (result) {
resolve(result.data);
}
else {
resolve();
}
}
});
});
} |
JavaScript | normalizePort(val) {
const port = parseInt(val, 10)
if (isNaN(port)) {
// named pipe
return val
}
if (port >= 0) {
// port number
return port
}
return false
} | normalizePort(val) {
const port = parseInt(val, 10)
if (isNaN(port)) {
// named pipe
return val
}
if (port >= 0) {
// port number
return port
}
return false
} |
JavaScript | onError(error) {
if (error.syscall !== 'listen') {
throw error
}
const bind = typeof port === 'string' ? 'Pipe ' + port : 'Port ' + port
// handle specific listen errors with friendly messages
switch (error.code) {
case 'EACCES':
console.error(bind + ' requires elevated privileges')
process.exit(1)
break
case 'EADDRINUSE':
console.error(bind + ' is already in use')
process.exit(1)
break
default:
throw error
}
} | onError(error) {
if (error.syscall !== 'listen') {
throw error
}
const bind = typeof port === 'string' ? 'Pipe ' + port : 'Port ' + port
// handle specific listen errors with friendly messages
switch (error.code) {
case 'EACCES':
console.error(bind + ' requires elevated privileges')
process.exit(1)
break
case 'EADDRINUSE':
console.error(bind + ' is already in use')
process.exit(1)
break
default:
throw error
}
} |
JavaScript | async saveMessages(data) {
const members = data.members;
const messages = data.messages;
return await schema.chats.updateOne({
$or: [{
members: [members[0], members[1]]
}, {
members: [members[1], members[0]]
}]
}, {
$push: {
messages: {
from: messages.from,
message: messages.message
}
}
})
} | async saveMessages(data) {
const members = data.members;
const messages = data.messages;
return await schema.chats.updateOne({
$or: [{
members: [members[0], members[1]]
}, {
members: [members[1], members[0]]
}]
}, {
$push: {
messages: {
from: messages.from,
message: messages.message
}
}
})
} |
JavaScript | retrieveMessages(data) {
return schema.chats.find({
$or: [{
members: [data.friend2, data.friend1]
}, {
members: [data.friend1, data.friend2]
}]
}).populate('messages.from')
} | retrieveMessages(data) {
return schema.chats.find({
$or: [{
members: [data.friend2, data.friend1]
}, {
members: [data.friend1, data.friend2]
}]
}).populate('messages.from')
} |
JavaScript | async addFriend(requester, recipient) {
await this.addFriendToRequester(requester);
await this.addFriendToRecipient(recipient);
return SendResponse.sendResponse(200, "Friends added successfully", []);
} | async addFriend(requester, recipient) {
await this.addFriendToRequester(requester);
await this.addFriendToRecipient(recipient);
return SendResponse.sendResponse(200, "Friends added successfully", []);
} |
JavaScript | async retrieveFriends(userId) {
const response = await User.retrieveFriends(userId);
if (response !== null || response.friends.length > 0) {
const friends = [];
for (let i = 0, len = response.friends.length; i < len; i++) {
const friendsIdData = {
friend1: userId,
friend2: response.friends[i].id
}
const chatResponse = await PrivateChat.retrieveMessages(friendsIdData)
const data = {
friend: response.friends[i],
members: chatResponse[0].members,
messages: chatResponse[0].messages
}
friends.push(data);
}
return SendResponse.sendResponse(200, "Fetched friends successfully", friends);
} else {
return SendResponse.sendResponse(400, "No friends found", response.friends);
}
} | async retrieveFriends(userId) {
const response = await User.retrieveFriends(userId);
if (response !== null || response.friends.length > 0) {
const friends = [];
for (let i = 0, len = response.friends.length; i < len; i++) {
const friendsIdData = {
friend1: userId,
friend2: response.friends[i].id
}
const chatResponse = await PrivateChat.retrieveMessages(friendsIdData)
const data = {
friend: response.friends[i],
members: chatResponse[0].members,
messages: chatResponse[0].messages
}
friends.push(data);
}
return SendResponse.sendResponse(200, "Fetched friends successfully", friends);
} else {
return SendResponse.sendResponse(400, "No friends found", response.friends);
}
} |
JavaScript | async createGroupChat(group) {
await GroupChat.createGroup(group).save();
const groupResponse = await GroupChat.getGroup(group)
return SendResponse.sendResponse(200, 'Group Created Successfully', groupResponse)
} | async createGroupChat(group) {
await GroupChat.createGroup(group).save();
const groupResponse = await GroupChat.getGroup(group)
return SendResponse.sendResponse(200, 'Group Created Successfully', groupResponse)
} |
JavaScript | connect() {
mongoose.connect(`mongodb://${config.mongodb_url}/${config.mongo_dbname}`, {
useNewUrlParser: true,
useFindAndModify: false
}).then(() => {}).catch(err => {
console.error('Connection error : ' + err);
});
} | connect() {
mongoose.connect(`mongodb://${config.mongodb_url}/${config.mongo_dbname}`, {
useNewUrlParser: true,
useFindAndModify: false
}).then(() => {}).catch(err => {
console.error('Connection error : ' + err);
});
} |
JavaScript | createGroup(group) {
return new schema.groupChats({
members: group.members,
name: group.name
});
} | createGroup(group) {
return new schema.groupChats({
members: group.members,
name: group.name
});
} |
JavaScript | retrieveMessages(groupId) {
return schema.groupChats.find({
_id: new mongo.ObjectId(groupId)
}).populate('messages.from')
} | retrieveMessages(groupId) {
return schema.groupChats.find({
_id: new mongo.ObjectId(groupId)
}).populate('messages.from')
} |
JavaScript | async saveMessages(data) {
return await schema.groupChats.updateOne({
_id: new mongo.ObjectId(data.to)
}, {
$push: {
messages: {
from: data.messages.from,
message: data.messages.message
}
}
})
} | async saveMessages(data) {
return await schema.groupChats.updateOne({
_id: new mongo.ObjectId(data.to)
}, {
$push: {
messages: {
from: data.messages.from,
message: data.messages.message
}
}
})
} |
JavaScript | deleteInviteRequest(requestId) {
return schema.invites.deleteOne({
_id: new mongo.ObjectId(requestId),
});
} | deleteInviteRequest(requestId) {
return schema.invites.deleteOne({
_id: new mongo.ObjectId(requestId),
});
} |
JavaScript | checkInviteRequest(to, from, status) {
return schema.invites.findOne({
to: to,
from: from,
status: status
})
} | checkInviteRequest(to, from, status) {
return schema.invites.findOne({
to: to,
from: from,
status: status
})
} |
JavaScript | retrieveInvitations(email) {
return schema.invites.find({
to: email,
status: 'pending'
}).populate('from')
} | retrieveInvitations(email) {
return schema.invites.find({
to: email,
status: 'pending'
}).populate('from')
} |
JavaScript | rejectInviteRequest(requestId) {
return schema.invites.updateOne({
_id: new mongo.ObjectId(requestId),
}, {
$set: {
status: 'rejected'
}
})
} | rejectInviteRequest(requestId) {
return schema.invites.updateOne({
_id: new mongo.ObjectId(requestId),
}, {
$set: {
status: 'rejected'
}
})
} |
JavaScript | async checkUserExistence(toEmail, fromEmail, senderName) {
const userExist = await user.checkUserExistenceByEmail(toEmail);
if (userExist !== null) {
await this.addInviteRequest(toEmail, fromEmail);
return SendResponse.sendResponse(200, "Invitation send successfully", [])
} else {
await this.sendInviteMail(toEmail, fromEmail, senderName);
return SendResponse.sendResponse(200, "Invitation send successfully", [])
}
} | async checkUserExistence(toEmail, fromEmail, senderName) {
const userExist = await user.checkUserExistenceByEmail(toEmail);
if (userExist !== null) {
await this.addInviteRequest(toEmail, fromEmail);
return SendResponse.sendResponse(200, "Invitation send successfully", [])
} else {
await this.sendInviteMail(toEmail, fromEmail, senderName);
return SendResponse.sendResponse(200, "Invitation send successfully", [])
}
} |
JavaScript | configureNodeMailerOptions(toEmail, senderName) {
// create reusable transporter object using the default transport
let transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: '[email protected]',
pass: 'Sanju1703'
}
});
// setup email data with unicode symbols
let mailOptions = {
from: '<[email protected]>', // sender address
to: toEmail, // receiver
subject: 'Invitation', // Subject line
text: 'Invitation', // plain text body
html: `<p>Hello,</p><p><span style='color:#0f9d58'>${senderName}</span> has invited you to have a conversation.</p><p>Please accept the invitation by clicking below <a href='http://localhost:3000' style='color:#0f9d58;font-size:1.3em'>Accept Invitation</a></p>` // html body
};
const options = {
transporter: transporter,
mailOptions: mailOptions
}
return options;
} | configureNodeMailerOptions(toEmail, senderName) {
// create reusable transporter object using the default transport
let transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: '[email protected]',
pass: 'Sanju1703'
}
});
// setup email data with unicode symbols
let mailOptions = {
from: '<[email protected]>', // sender address
to: toEmail, // receiver
subject: 'Invitation', // Subject line
text: 'Invitation', // plain text body
html: `<p>Hello,</p><p><span style='color:#0f9d58'>${senderName}</span> has invited you to have a conversation.</p><p>Please accept the invitation by clicking below <a href='http://localhost:3000' style='color:#0f9d58;font-size:1.3em'>Accept Invitation</a></p>` // html body
};
const options = {
transporter: transporter,
mailOptions: mailOptions
}
return options;
} |
JavaScript | async sendInviteMail(toEmail, fromEmail, senderName) {
const options = this.configureNodeMailerOptions(toEmail, senderName);
// send mail with defined transport object
options.transporter.sendMail(options.mailOptions, async (error, info) => {
if (error) {
return console.log("sendMail error", error);
}
console.log('Message sent: %s', info.messageId);
await this.addInviteRequest(toEmail, fromEmail);
});
} | async sendInviteMail(toEmail, fromEmail, senderName) {
const options = this.configureNodeMailerOptions(toEmail, senderName);
// send mail with defined transport object
options.transporter.sendMail(options.mailOptions, async (error, info) => {
if (error) {
return console.log("sendMail error", error);
}
console.log('Message sent: %s', info.messageId);
await this.addInviteRequest(toEmail, fromEmail);
});
} |
JavaScript | async checkInviteRequest(toEmail, fromEmail, senderName) {
//Check if invite request is rejected
const rejectedRequest = await Invite.checkInviteRequest(toEmail, fromEmail, 'rejected');
if (rejectedRequest == null) {
//Check if invite request is pending
const pendingRequest = await Invite.checkInviteRequest(toEmail, fromEmail, 'pending');
if (pendingRequest !== null) {
//If request is not pending nor rejected, send response
return SendResponse.sendResponse(200, "Your invitation is still pending", [])
} else {
//Check if user exists or not
return await this.checkUserExistence(toEmail, fromEmail, senderName)
}
} else {
//If invitation is rejected, send response of rejection
return SendResponse.sendResponse(400, "You can't send invitation to this user", [])
}
} | async checkInviteRequest(toEmail, fromEmail, senderName) {
//Check if invite request is rejected
const rejectedRequest = await Invite.checkInviteRequest(toEmail, fromEmail, 'rejected');
if (rejectedRequest == null) {
//Check if invite request is pending
const pendingRequest = await Invite.checkInviteRequest(toEmail, fromEmail, 'pending');
if (pendingRequest !== null) {
//If request is not pending nor rejected, send response
return SendResponse.sendResponse(200, "Your invitation is still pending", [])
} else {
//Check if user exists or not
return await this.checkUserExistence(toEmail, fromEmail, senderName)
}
} else {
//If invitation is rejected, send response of rejection
return SendResponse.sendResponse(400, "You can't send invitation to this user", [])
}
} |
JavaScript | async retrieveInvitations(email) {
const invitations = await Invite.retrieveInvitations(email);
if (invitations !== null) {
return SendResponse.sendResponse(200, "Fetched invitations", invitations)
} else {
return SendResponse.sendResponse(400, "No invitations found", [])
}
} | async retrieveInvitations(email) {
const invitations = await Invite.retrieveInvitations(email);
if (invitations !== null) {
return SendResponse.sendResponse(200, "Fetched invitations", invitations)
} else {
return SendResponse.sendResponse(400, "No invitations found", [])
}
} |
JavaScript | async acceptInvitation(requestId) {
try {
const deletedUser = await Invite.deleteInviteRequest(requestId);
if (deletedUser.deletedCount == 1) {
return SendResponse.sendResponse(200, 'Invite Request deleted Successfully', [])
} else {
return SendResponse.sendResponse(400, 'Error deleting invite request', [])
}
} catch (e) {
return SendResponse.sendResponse(400, 'Error deleting invite request', [])
}
} | async acceptInvitation(requestId) {
try {
const deletedUser = await Invite.deleteInviteRequest(requestId);
if (deletedUser.deletedCount == 1) {
return SendResponse.sendResponse(200, 'Invite Request deleted Successfully', [])
} else {
return SendResponse.sendResponse(400, 'Error deleting invite request', [])
}
} catch (e) {
return SendResponse.sendResponse(400, 'Error deleting invite request', [])
}
} |
JavaScript | async rejectInvitation(requestId) {
try {
const rejectInvite = await Invite.rejectInviteRequest(requestId);
if (rejectInvite.ok === 1) {
return SendResponse.sendResponse(200, 'Invite Request rejected', [])
}
} catch (e) {
return SendResponse.sendResponse(200, 'Error rejecting invite request', [])
}
} | async rejectInvitation(requestId) {
try {
const rejectInvite = await Invite.rejectInviteRequest(requestId);
if (rejectInvite.ok === 1) {
return SendResponse.sendResponse(200, 'Invite Request rejected', [])
}
} catch (e) {
return SendResponse.sendResponse(200, 'Error rejecting invite request', [])
}
} |
JavaScript | connected(socket) {
this.socket = socket;
//remove all previously register listeners
this.socket.removeAllListeners();
this.emitPrivateMessages();
this.emitGroupChatMessages();
} | connected(socket) {
this.socket = socket;
//remove all previously register listeners
this.socket.removeAllListeners();
this.emitPrivateMessages();
this.emitGroupChatMessages();
} |
JavaScript | async emitGroupChatMessages() {
this.socket.on('group-message', async (results, err) => {
GroupChat.saveMessages(results);
const emitResult = this.createResultsObject(results, await this.getUser(results.from), 'group')
this.io.sockets.to(results.to).emit('group-message', emitResult);
});
} | async emitGroupChatMessages() {
this.socket.on('group-message', async (results, err) => {
GroupChat.saveMessages(results);
const emitResult = this.createResultsObject(results, await this.getUser(results.from), 'group')
this.io.sockets.to(results.to).emit('group-message', emitResult);
});
} |
JavaScript | async emitPrivateMessages() {
this.socket.on('private-message', async (results, err) => {
await PrivateChat.saveMessages(results);
const emitResult = this.createResultsObject(results, await this.getUser(results.from), 'private')
this.io.sockets.to(results.to).emit('private-message', emitResult);
});
} | async emitPrivateMessages() {
this.socket.on('private-message', async (results, err) => {
await PrivateChat.saveMessages(results);
const emitResult = this.createResultsObject(results, await this.getUser(results.from), 'private')
this.io.sockets.to(results.to).emit('private-message', emitResult);
});
} |
JavaScript | createResultsObject(results, from, type) {
if (type === 'group') {
return {
to: results.to,
messages: {
from: from,
message: results.messages.message
}
}
} else {
return {
messages: {
from: from,
message: results.messages.message
}
}
}
} | createResultsObject(results, from, type) {
if (type === 'group') {
return {
to: results.to,
messages: {
from: from,
message: results.messages.message
}
}
} else {
return {
messages: {
from: from,
message: results.messages.message
}
}
}
} |
JavaScript | async function startTunedCalibration()
{
if (calibratingInProgress) return;
calibratingInProgress = true;
gridHeight = 5;
gridWidth = 5;
cellSize = 110;
startx = 270+55;
starty = 590+55;
calPoints = [];
errorsMade = false;
for (r = 0; r < gridHeight; r++)
{
for( c = 0; c < gridWidth; c++)
{
x = startx + c*cellSize;
y = starty + r*cellSize;
ret = await findExactCalibrationForPoint(x,y);
if (ret.status == 1)
{
p = makePos(ret);
calPoints.push(p);
}
else errorsMade = true;
}
}
if (!errorsMade)
{
cal = robot.getCalibrationData();
//console.log(cal);
cal.pointArray = calPoints;
robot.setCalibrationData(cal);
robot.saveCalibration(cal);
}
calibratingInProgress = false;
} | async function startTunedCalibration()
{
if (calibratingInProgress) return;
calibratingInProgress = true;
gridHeight = 5;
gridWidth = 5;
cellSize = 110;
startx = 270+55;
starty = 590+55;
calPoints = [];
errorsMade = false;
for (r = 0; r < gridHeight; r++)
{
for( c = 0; c < gridWidth; c++)
{
x = startx + c*cellSize;
y = starty + r*cellSize;
ret = await findExactCalibrationForPoint(x,y);
if (ret.status == 1)
{
p = makePos(ret);
calPoints.push(p);
}
else errorsMade = true;
}
}
if (!errorsMade)
{
cal = robot.getCalibrationData();
//console.log(cal);
cal.pointArray = calPoints;
robot.setCalibrationData(cal);
robot.saveCalibration(cal);
}
calibratingInProgress = false;
} |
JavaScript | async function startMultipleCalibration() {
if (calibratingInProgress) return;
var cal = robot.getCalibrationData();
var maxj = 8;
var maxi = 4;
cal.pointArray = [];
startx = -config.calWidth+8;
widthx = config.calWidth*2;
widthy = config.calHeight*2;
starty = -config.calHeight;
x = startx;
y = starty;
z = config.defaultHeight;
calibratingInProgress = true;
touched = false;
console.log('Starting calibration (Fail safe height: '+config.boundary_z.min+')');
for (i = 0; i < maxi; i++)
{
for( j = 0; j < maxj; j++)
{
ret = await lowerAndCheckForContact(x, y, z);
console.log('Calibrated point i='+i+' j='+j +" "+ JSON.stringify(ret));
robot.resetPosition();
if (!ret.status) return;
p = makePos(ret);
cal.pointArray.push(p);
x = startx + i * widthx / (maxi-1);
y = starty + j * widthy / (maxj-1);
z = config.defaultHeight;
touched = false;
await timeout(500);
}
}
console.log('Saving calibration data:' + JSON.stringify(cal))
robot.setCalibrationData(cal);
calibratingInProgress = false;
robot.saveCalibration(cal);
return;
} | async function startMultipleCalibration() {
if (calibratingInProgress) return;
var cal = robot.getCalibrationData();
var maxj = 8;
var maxi = 4;
cal.pointArray = [];
startx = -config.calWidth+8;
widthx = config.calWidth*2;
widthy = config.calHeight*2;
starty = -config.calHeight;
x = startx;
y = starty;
z = config.defaultHeight;
calibratingInProgress = true;
touched = false;
console.log('Starting calibration (Fail safe height: '+config.boundary_z.min+')');
for (i = 0; i < maxi; i++)
{
for( j = 0; j < maxj; j++)
{
ret = await lowerAndCheckForContact(x, y, z);
console.log('Calibrated point i='+i+' j='+j +" "+ JSON.stringify(ret));
robot.resetPosition();
if (!ret.status) return;
p = makePos(ret);
cal.pointArray.push(p);
x = startx + i * widthx / (maxi-1);
y = starty + j * widthy / (maxj-1);
z = config.defaultHeight;
touched = false;
await timeout(500);
}
}
console.log('Saving calibration data:' + JSON.stringify(cal))
robot.setCalibrationData(cal);
calibratingInProgress = false;
robot.saveCalibration(cal);
return;
} |
JavaScript | static async GetFailure(req, res) {
super.Query(req, res, async () => {
res.sendFile("./web_html/404.html", { root: Config.ROOT_DIR })
})
} | static async GetFailure(req, res) {
super.Query(req, res, async () => {
res.sendFile("./web_html/404.html", { root: Config.ROOT_DIR })
})
} |
JavaScript | function chooseColor(depth) {
switch (true) {
case depth < 10:
return "#0dff29";
case depth < 30:
return "#c7ff0d";
case depth < 50:
return "#fbff0d";
case depth < 70:
return "#ffd70d";
case depth < 90:
return "#ff8e0d";
default:
return "#ff1d0d";
}
} | function chooseColor(depth) {
switch (true) {
case depth < 10:
return "#0dff29";
case depth < 30:
return "#c7ff0d";
case depth < 50:
return "#fbff0d";
case depth < 70:
return "#ffd70d";
case depth < 90:
return "#ff8e0d";
default:
return "#ff1d0d";
}
} |
JavaScript | function sendMessageToIndividual(token, message) {
//build the message for Pushy to send
var data = {
"type": "msg",
"message": message,
"chatid": message.chatid
}
// Send push notification via the Send Notifications API
// https://pushy.me/docs/api/send-notifications
pushyAPI.sendPushNotification(data, token, {}, function (err, id) {
// Log errors to console
if (err) {
return console.log('Fatal Error', err);
}
// Log success
console.log('Push sent successfully! (ID: ' + id + ')')
})
} | function sendMessageToIndividual(token, message) {
//build the message for Pushy to send
var data = {
"type": "msg",
"message": message,
"chatid": message.chatid
}
// Send push notification via the Send Notifications API
// https://pushy.me/docs/api/send-notifications
pushyAPI.sendPushNotification(data, token, {}, function (err, id) {
// Log errors to console
if (err) {
return console.log('Fatal Error', err);
}
// Log success
console.log('Push sent successfully! (ID: ' + id + ')')
})
} |
JavaScript | function sendContactRequestToIndividual(token, message) {
var data ={
"type": "contactReq",
"contactid": message
}
// Send push notification via the Send Notifications API
// https://pushy.me/docs/api/send-notifications
pushyAPI.sendPushNotification(data, token, {}, function (err, id) {
// Log errors to console
if (err) {
return console.log('Fatal Error', err);
}
// Log success
console.log('Push sent successfully! (ID: ' + id + ')')
})
} | function sendContactRequestToIndividual(token, message) {
var data ={
"type": "contactReq",
"contactid": message
}
// Send push notification via the Send Notifications API
// https://pushy.me/docs/api/send-notifications
pushyAPI.sendPushNotification(data, token, {}, function (err, id) {
// Log errors to console
if (err) {
return console.log('Fatal Error', err);
}
// Log success
console.log('Push sent successfully! (ID: ' + id + ')')
})
} |
JavaScript | function sendSelfMemberIDToIndividual(token, selfMemberID) {
var data ={
"type": "contactMemberID",
"contactid": selfMemberID
}
// Send push notification via the Send Notifications API
// https://pushy.me/docs/api/send-notifications
pushyAPI.sendPushNotification(data, token, {}, function (err, id) {
// Log errors to console
if (err) {
return console.log('Fatal Error', err);
}
// Log success
console.log('Push sent successfully! (ID: ' + id + ')')
})
} | function sendSelfMemberIDToIndividual(token, selfMemberID) {
var data ={
"type": "contactMemberID",
"contactid": selfMemberID
}
// Send push notification via the Send Notifications API
// https://pushy.me/docs/api/send-notifications
pushyAPI.sendPushNotification(data, token, {}, function (err, id) {
// Log errors to console
if (err) {
return console.log('Fatal Error', err);
}
// Log success
console.log('Push sent successfully! (ID: ' + id + ')')
})
} |
JavaScript | function cleThrottle_select()
{
var cleThrottle_v = document.getElementById("clethrottle_se").value;
if (cleThrottle_v=="cleshowall")
{document.getElementById("clefuelshow").innerHTML=cleFuel_forloopshowall().clefueltext}
else if(cleThrottle_v=="0")
{document.getElementById("clefuelshow").innerHTML=cleFuel_forloopshowindividual().cleFuel_inditext}
else if(cleThrottle_v=="1")
{document.getElementById("clefuelshow").innerHTML=cleFuel_forloopshowindividual().cleFuel_inditext}
else if(cleThrottle_v=="2")
{document.getElementById("clefuelshow").innerHTML=cleFuel_forloopshowindividual().cleFuel_inditext}
else if(cleThrottle_v=="3")
{document.getElementById("clefuelshow").innerHTML=cleFuel_forloopshowindividual().cleFuel_inditext}
else if(cleThrottle_v=="4")
{document.getElementById("clefuelshow").innerHTML=cleFuel_forloopshowindividual().cleFuel_inditext}
else if(cleThrottle_v=="5")
{document.getElementById("clefuelshow").innerHTML=cleFuel_forloopshowindividual().cleFuel_inditext}
else if(cleThrottle_v=="6")
{document.getElementById("clefuelshow").innerHTML=cleFuel_forloopshowindividual().cleFuel_inditext}
else if(cleThrottle_v=="7")
{document.getElementById("clefuelshow").innerHTML=cleFuel_forloopshowindividual().cleFuel_inditext}
else if(cleThrottle_v=="8")
{document.getElementById("clefuelshow").innerHTML=cleFuel_forloopshowindividual().cleFuel_inditext}
else if(cleThrottle_v=="9")
{document.getElementById("clefuelshow").innerHTML=cleFuel_forloopshowindividual().cleFuel_inditext}
} | function cleThrottle_select()
{
var cleThrottle_v = document.getElementById("clethrottle_se").value;
if (cleThrottle_v=="cleshowall")
{document.getElementById("clefuelshow").innerHTML=cleFuel_forloopshowall().clefueltext}
else if(cleThrottle_v=="0")
{document.getElementById("clefuelshow").innerHTML=cleFuel_forloopshowindividual().cleFuel_inditext}
else if(cleThrottle_v=="1")
{document.getElementById("clefuelshow").innerHTML=cleFuel_forloopshowindividual().cleFuel_inditext}
else if(cleThrottle_v=="2")
{document.getElementById("clefuelshow").innerHTML=cleFuel_forloopshowindividual().cleFuel_inditext}
else if(cleThrottle_v=="3")
{document.getElementById("clefuelshow").innerHTML=cleFuel_forloopshowindividual().cleFuel_inditext}
else if(cleThrottle_v=="4")
{document.getElementById("clefuelshow").innerHTML=cleFuel_forloopshowindividual().cleFuel_inditext}
else if(cleThrottle_v=="5")
{document.getElementById("clefuelshow").innerHTML=cleFuel_forloopshowindividual().cleFuel_inditext}
else if(cleThrottle_v=="6")
{document.getElementById("clefuelshow").innerHTML=cleFuel_forloopshowindividual().cleFuel_inditext}
else if(cleThrottle_v=="7")
{document.getElementById("clefuelshow").innerHTML=cleFuel_forloopshowindividual().cleFuel_inditext}
else if(cleThrottle_v=="8")
{document.getElementById("clefuelshow").innerHTML=cleFuel_forloopshowindividual().cleFuel_inditext}
else if(cleThrottle_v=="9")
{document.getElementById("clefuelshow").innerHTML=cleFuel_forloopshowindividual().cleFuel_inditext}
} |
JavaScript | function cleFuel_forloopshowall()
{
var clefueltext ="";
var i;
for (i=0; i< 5925; i=i+592.4)
{
clefueltext +="<br>"+"burn"+" "+i.toFixed(2)+" "+"Ib"+" "+"per hour"; //round to decimal second place
}
document.getElementById("clefuelshow").style.color= "white";
document.getElementById("clefuelshow").innerHTML= clefueltext;
var cle_allpercenttext="";//show all Clean load out throttle percent
var x;
for(x=0; x<110; x=x+10)
{
cle_allpercenttext +="<br>"+"at"+" "+x+" "+"%"+" "+"throttle";
}
document.getElementById("clepercentshow").style.color="white";
document.getElementById("clepercentshow").innerHTML= cle_allpercenttext;
} | function cleFuel_forloopshowall()
{
var clefueltext ="";
var i;
for (i=0; i< 5925; i=i+592.4)
{
clefueltext +="<br>"+"burn"+" "+i.toFixed(2)+" "+"Ib"+" "+"per hour"; //round to decimal second place
}
document.getElementById("clefuelshow").style.color= "white";
document.getElementById("clefuelshow").innerHTML= clefueltext;
var cle_allpercenttext="";//show all Clean load out throttle percent
var x;
for(x=0; x<110; x=x+10)
{
cle_allpercenttext +="<br>"+"at"+" "+x+" "+"%"+" "+"throttle";
}
document.getElementById("clepercentshow").style.color="white";
document.getElementById("clepercentshow").innerHTML= cle_allpercenttext;
} |
JavaScript | function has_unsummarized_children(d) {
if (d.summarized == false) {
return true;
} else {
if (d.children) {
for (var i=0; i<d.children.length; i++) {
return false || has_unsummarized_children(d.children[i]);
}
}
if (d.replace) {
for (var i=0; i<d.replace.length; i++) {
return false || has_unsummarized_children(d.replace[i]);
}
}
return false;
}
} | function has_unsummarized_children(d) {
if (d.summarized == false) {
return true;
} else {
if (d.children) {
for (var i=0; i<d.children.length; i++) {
return false || has_unsummarized_children(d.children[i]);
}
}
if (d.replace) {
for (var i=0; i<d.replace.length; i++) {
return false || has_unsummarized_children(d.replace[i]);
}
}
return false;
}
} |
JavaScript | function startStreaming(token) {
var source = new EventSource(NEST_API_URL + '?auth=' + token);
source.addEventListener('put', function(e) {
console.log('\n' + e.data);
});
source.addEventListener('open', function(e) {
console.log('Connection opened!');
});
source.addEventListener('auth_revoked', function(e) {
console.log('Authentication token was revoked.');
// Re-authenticate your user here.
});
source.addEventListener('error', function(e) {
if (e.readyState == EventSource.CLOSED) {
console.error('Connection was closed! ', e);
} else {
console.error('An unknown error occurred: ', e);
}
}, false);
} | function startStreaming(token) {
var source = new EventSource(NEST_API_URL + '?auth=' + token);
source.addEventListener('put', function(e) {
console.log('\n' + e.data);
});
source.addEventListener('open', function(e) {
console.log('Connection opened!');
});
source.addEventListener('auth_revoked', function(e) {
console.log('Authentication token was revoked.');
// Re-authenticate your user here.
});
source.addEventListener('error', function(e) {
if (e.readyState == EventSource.CLOSED) {
console.error('Connection was closed! ', e);
} else {
console.error('An unknown error occurred: ', e);
}
}, false);
} |
JavaScript | function fixInvalidJSONFloats(obj) {
if (obj instanceof Array) return obj.map(fixInvalidJSONFloats);
if (typeof obj != "object") return obj;
if (obj === null) return null;
if (obj === undefined) return undefined;
if (obj["___INF___"] !== undefined) {
return Infinity * obj["___INF___"];
} else if (obj["___NAN___"] !== undefined) {
return NaN;
}
let value = {};
for (let m in obj) {
value[m] = fixInvalidJSONFloats(obj[m]);
}
return value;
} | function fixInvalidJSONFloats(obj) {
if (obj instanceof Array) return obj.map(fixInvalidJSONFloats);
if (typeof obj != "object") return obj;
if (obj === null) return null;
if (obj === undefined) return undefined;
if (obj["___INF___"] !== undefined) {
return Infinity * obj["___INF___"];
} else if (obj["___NAN___"] !== undefined) {
return NaN;
}
let value = {};
for (let m in obj) {
value[m] = fixInvalidJSONFloats(obj[m]);
}
return value;
} |
JavaScript | function jumlahVolumeKubus(a,b){
var volumeKubusA=a*a*a
var volumeKubusB=b*b*b
var total=a+b
return total
} | function jumlahVolumeKubus(a,b){
var volumeKubusA=a*a*a
var volumeKubusB=b*b*b
var total=a+b
return total
} |
JavaScript | function tambahBuku(){
for(noBuku=1;noBuku<=5;noBuku++){
let tambah=prompt('Masukkan nama buku ke-' + noBuku + ':')
buku.push(tambah); // menambah data inputan ke array "buku"
}
// let jmlSlotRakBuku=5;
// let noBuku=1
// while(noBuku<=5){ // 5 >> jumlah slot rak buku
// let tambah=prompt('Masukkan nama buku ke-' + noBuku + ':')
// buku.push(tambah); // menambah data inputan ke array "buku"
// noBuku++;
// }
} | function tambahBuku(){
for(noBuku=1;noBuku<=5;noBuku++){
let tambah=prompt('Masukkan nama buku ke-' + noBuku + ':')
buku.push(tambah); // menambah data inputan ke array "buku"
}
// let jmlSlotRakBuku=5;
// let noBuku=1
// while(noBuku<=5){ // 5 >> jumlah slot rak buku
// let tambah=prompt('Masukkan nama buku ke-' + noBuku + ':')
// buku.push(tambah); // menambah data inputan ke array "buku"
// noBuku++;
// }
} |
JavaScript | function pinjamBuku(){
let pinjam=parseInt(prompt('Masukkan buku ke berapa yang ingin anda pinjam:'))
if(pinjam>0 && pinjam<=5){
delete bukuTemp[pinjam-1] // untuk menghapus nomor urutan buku sesuai yg diinput, -1 untuk menyamakan dgn indeks
alert("Buku yang anda maksud tersedia untuk dipinjam. Jangan lupa kembalikan ya!")
// untuk memeriksa nilai boolean
// alert("Buku tersedia untuk dipinjam")
}else{
alert("Maaf, di perpustakaan ini hanya ada 5 buku")
}
} | function pinjamBuku(){
let pinjam=parseInt(prompt('Masukkan buku ke berapa yang ingin anda pinjam:'))
if(pinjam>0 && pinjam<=5){
delete bukuTemp[pinjam-1] // untuk menghapus nomor urutan buku sesuai yg diinput, -1 untuk menyamakan dgn indeks
alert("Buku yang anda maksud tersedia untuk dipinjam. Jangan lupa kembalikan ya!")
// untuk memeriksa nilai boolean
// alert("Buku tersedia untuk dipinjam")
}else{
alert("Maaf, di perpustakaan ini hanya ada 5 buku")
}
} |
JavaScript | function click(e) {
if (e.target.textContent === "") {
if (player === "O" && client === "player1") {
socket.emit('addSign', { type: "O", id: e.target.id, player: "X" });
} else if (player === "X" && client === "player2") {
socket.emit('addSign', { type: "X", id: e.target.id, player: "O" });
}
}
} | function click(e) {
if (e.target.textContent === "") {
if (player === "O" && client === "player1") {
socket.emit('addSign', { type: "O", id: e.target.id, player: "X" });
} else if (player === "X" && client === "player2") {
socket.emit('addSign', { type: "X", id: e.target.id, player: "O" });
}
}
} |
JavaScript | function AzureStorage($resource, guidGenerator) {
this.isAvailable = AZURE_MOBILE_SERVICES_KEY && AZURE_MOBILE_SERVICES_ADDRESS;
if (!AZURE_MOBILE_SERVICES_KEY || !AZURE_MOBILE_SERVICES_KEY) {
console.warn("The Azure Mobile Services key and URL are not set up properly. Items will not be stored on Azure.");
}
// Generate the headers to access the Azure Mobile Services table.
var azureMobileServicesInstallationId = guidGenerator.get();
var headers = {
'X-ZUMO-APPLICATION': AZURE_MOBILE_SERVICES_KEY,
'X-ZUMO-INSTALLATION-ID': azureMobileServicesInstallationId,
'X-ZUMO-VERSION': 'ZUMO/1.0 (lang=Web; os=--; os_version=--; arch=--; version=1.0.20218.0)',
'Content-Type': 'application/json'
};
// Url of the Azure Mobile Services table to access.
var azureMobileServicesTableAddress = AZURE_MOBILE_SERVICES_ADDRESS + 'tables/todoitem/:id';
this.toDoItem = $resource(azureMobileServicesTableAddress, { id: '@id' }, {
'query': {
method: 'GET',
params: { $top: '1000' },
isArray: true,
headers: headers
},
'delete': {
method: 'DELETE',
headers: headers
},
'save': {
method: 'POST',
headers: headers
},
'update': {
method: 'PATCH',
headers: headers
}
});
} | function AzureStorage($resource, guidGenerator) {
this.isAvailable = AZURE_MOBILE_SERVICES_KEY && AZURE_MOBILE_SERVICES_ADDRESS;
if (!AZURE_MOBILE_SERVICES_KEY || !AZURE_MOBILE_SERVICES_KEY) {
console.warn("The Azure Mobile Services key and URL are not set up properly. Items will not be stored on Azure.");
}
// Generate the headers to access the Azure Mobile Services table.
var azureMobileServicesInstallationId = guidGenerator.get();
var headers = {
'X-ZUMO-APPLICATION': AZURE_MOBILE_SERVICES_KEY,
'X-ZUMO-INSTALLATION-ID': azureMobileServicesInstallationId,
'X-ZUMO-VERSION': 'ZUMO/1.0 (lang=Web; os=--; os_version=--; arch=--; version=1.0.20218.0)',
'Content-Type': 'application/json'
};
// Url of the Azure Mobile Services table to access.
var azureMobileServicesTableAddress = AZURE_MOBILE_SERVICES_ADDRESS + 'tables/todoitem/:id';
this.toDoItem = $resource(azureMobileServicesTableAddress, { id: '@id' }, {
'query': {
method: 'GET',
params: { $top: '1000' },
isArray: true,
headers: headers
},
'delete': {
method: 'DELETE',
headers: headers
},
'save': {
method: 'POST',
headers: headers
},
'update': {
method: 'PATCH',
headers: headers
}
});
} |
JavaScript | function updateValue ($beautyInput, $valueInput) {
var value;
if ($beautyInput.prop('indeterminate')) {
value = 'None';
} else if ($beautyInput.prop('checked')) {
value = 'True';
} else {
value = 'False';
}
$valueInput.val($valueInput.val().split('=')[0] + '=' + value);
} | function updateValue ($beautyInput, $valueInput) {
var value;
if ($beautyInput.prop('indeterminate')) {
value = 'None';
} else if ($beautyInput.prop('checked')) {
value = 'True';
} else {
value = 'False';
}
$valueInput.val($valueInput.val().split('=')[0] + '=' + value);
} |
JavaScript | function muranoAPI(apiService, toastService) {
var service = {
getPackages: getPackages,
getComponentMeta: getComponentMeta,
editComponentMeta: editComponentMeta,
getEnvironmentMeta: getEnvironmentMeta,
editEnvironmentMeta: editEnvironmentMeta
};
return service;
/**
* @name horizon.app.core.openstack-service-api.murano.getPackages
* @description
* Get a list of packages.
*
* The listing result is an object with property "packages". Each item is
* an packages.
*
* @param {Object} params
* Query parameters. Optional.
*
* @param {boolean} params.paginate
* True to paginate automatically.
*
* @param {string} params.marker
* Specifies the image of the last-seen image.
*
* The typical pattern of limit and marker is to make an
* initial limited request and then to use the last
* image from the response as the marker parameter
* in a subsequent limited request. With paginate, limit
* is automatically set.
*
* @param {string} params.sort_dir
* The sort direction ('asc' or 'desc').
*/
function getPackages(params) {
var config = params ? { "params" : params} : {};
return apiService.get('/api/app-catalog/packages/', config)
.error(function () {
toastService.add('error', gettext('Unable to retrieve the packages.'));
});
}
/**
* @name horizon.app.core.openstack-service-api.murano.getComponentMeta
* @description
* Get metadata attributes associated with a given component
*
* @param {Object} target
* The object identifying the target component
*
* @param {string} target.environment
* The identifier of the environment the component belongs to
*
* @param {string} target.component
* The identifier of the component within the environment
*
* @param {string} target.session
* The identifier of the configuration session for which the data should be
* fetched
*
* @returns {Object} The metadata object
*/
function getComponentMeta(target) {
var params = { params: { session: target.session} };
var url = '/api/app-catalog/environments/' + target.environment +
'/components/' + target.component + '/metadata/';
return apiService.get(url, params)
.error(function () {
toastService.add('error', gettext('Unable to retrieve component metadata.'));
});
}
/**
* @name horizon.app.core.openstack-service-api.murano.editComponentMetadata
* @description
* Update metadata attributes associated with a given component
*
* @param {Object} target
* The object identifying the target component
*
* @param {string} target.environment
* The identifier of the environment the component belongs to
*
* @param {string} target.component
* The identifier of the component within the environment
*
* @param {string} target.session
* The identifier of the configuration session for which the data should be
* updated
*
* @param {object} updated New metadata definitions.
*
* @param {[]} removed Names of removed metadata definitions.
*
* @returns {Object} The result of the API call
*/
function editComponentMeta(target, updated, removed) {
var params = { params: { session: target.session} };
var url = '/api/app-catalog/environments/' + target.environment +
'/components/' + target.component + '/metadata/';
return apiService.post(
url, { updated: updated, removed: removed}, params)
.error(function () {
toastService.add('error', gettext('Unable to edit component metadata.'));
});
}
/**
* @name horizon.app.core.openstack-service-api.murano.getEnvironmentMeta
* @description
* Get metadata attributes associated with a given environment
*
* @param {Object} target
* The object identifying the target environment
*
* @param {string} target.environment
* The identifier of the target environment
*
* @param {string} target.session
* The identifier of the configuration session for which the data should be
* fetched
*
* @returns {Object} The metadata object
*/
function getEnvironmentMeta(target) {
var params = { params: { session: target.session} };
var url = '/api/app-catalog/environments/' + target.environment +
'/metadata/';
return apiService.get(url, params)
.error(function () {
toastService.add('error', gettext('Unable to retrieve environment metadata.'));
});
}
/**
* @name horizon.app.core.openstack-service-api.murano.editEnvironmentMeta
* @description
* Update metadata attributes associated with a given environment
*
* @param {Object} target
* The object identifying the target environment
*
* @param {string} target.environment
* The identifier of the environment the component belongs to
*
* @param {string} target.session
* The identifier of the configuration session for which the data should be
* updated
*
* @param {object} updated New metadata definitions.
*
* @param {[]} removed Names of removed metadata definitions.
*
* @returns {Object} The result of the API call
*/
function editEnvironmentMeta(target, updated, removed) {
var params = { params: { session: target.session} };
var url = '/api/app-catalog/environments/' + target.environment +
'/metadata/';
return apiService.post(
url, { updated: updated, removed: removed}, params)
.error(function () {
toastService.add('error', gettext('Unable to edit environment metadata.'));
});
}
} | function muranoAPI(apiService, toastService) {
var service = {
getPackages: getPackages,
getComponentMeta: getComponentMeta,
editComponentMeta: editComponentMeta,
getEnvironmentMeta: getEnvironmentMeta,
editEnvironmentMeta: editEnvironmentMeta
};
return service;
/**
* @name horizon.app.core.openstack-service-api.murano.getPackages
* @description
* Get a list of packages.
*
* The listing result is an object with property "packages". Each item is
* an packages.
*
* @param {Object} params
* Query parameters. Optional.
*
* @param {boolean} params.paginate
* True to paginate automatically.
*
* @param {string} params.marker
* Specifies the image of the last-seen image.
*
* The typical pattern of limit and marker is to make an
* initial limited request and then to use the last
* image from the response as the marker parameter
* in a subsequent limited request. With paginate, limit
* is automatically set.
*
* @param {string} params.sort_dir
* The sort direction ('asc' or 'desc').
*/
function getPackages(params) {
var config = params ? { "params" : params} : {};
return apiService.get('/api/app-catalog/packages/', config)
.error(function () {
toastService.add('error', gettext('Unable to retrieve the packages.'));
});
}
/**
* @name horizon.app.core.openstack-service-api.murano.getComponentMeta
* @description
* Get metadata attributes associated with a given component
*
* @param {Object} target
* The object identifying the target component
*
* @param {string} target.environment
* The identifier of the environment the component belongs to
*
* @param {string} target.component
* The identifier of the component within the environment
*
* @param {string} target.session
* The identifier of the configuration session for which the data should be
* fetched
*
* @returns {Object} The metadata object
*/
function getComponentMeta(target) {
var params = { params: { session: target.session} };
var url = '/api/app-catalog/environments/' + target.environment +
'/components/' + target.component + '/metadata/';
return apiService.get(url, params)
.error(function () {
toastService.add('error', gettext('Unable to retrieve component metadata.'));
});
}
/**
* @name horizon.app.core.openstack-service-api.murano.editComponentMetadata
* @description
* Update metadata attributes associated with a given component
*
* @param {Object} target
* The object identifying the target component
*
* @param {string} target.environment
* The identifier of the environment the component belongs to
*
* @param {string} target.component
* The identifier of the component within the environment
*
* @param {string} target.session
* The identifier of the configuration session for which the data should be
* updated
*
* @param {object} updated New metadata definitions.
*
* @param {[]} removed Names of removed metadata definitions.
*
* @returns {Object} The result of the API call
*/
function editComponentMeta(target, updated, removed) {
var params = { params: { session: target.session} };
var url = '/api/app-catalog/environments/' + target.environment +
'/components/' + target.component + '/metadata/';
return apiService.post(
url, { updated: updated, removed: removed}, params)
.error(function () {
toastService.add('error', gettext('Unable to edit component metadata.'));
});
}
/**
* @name horizon.app.core.openstack-service-api.murano.getEnvironmentMeta
* @description
* Get metadata attributes associated with a given environment
*
* @param {Object} target
* The object identifying the target environment
*
* @param {string} target.environment
* The identifier of the target environment
*
* @param {string} target.session
* The identifier of the configuration session for which the data should be
* fetched
*
* @returns {Object} The metadata object
*/
function getEnvironmentMeta(target) {
var params = { params: { session: target.session} };
var url = '/api/app-catalog/environments/' + target.environment +
'/metadata/';
return apiService.get(url, params)
.error(function () {
toastService.add('error', gettext('Unable to retrieve environment metadata.'));
});
}
/**
* @name horizon.app.core.openstack-service-api.murano.editEnvironmentMeta
* @description
* Update metadata attributes associated with a given environment
*
* @param {Object} target
* The object identifying the target environment
*
* @param {string} target.environment
* The identifier of the environment the component belongs to
*
* @param {string} target.session
* The identifier of the configuration session for which the data should be
* updated
*
* @param {object} updated New metadata definitions.
*
* @param {[]} removed Names of removed metadata definitions.
*
* @returns {Object} The result of the API call
*/
function editEnvironmentMeta(target, updated, removed) {
var params = { params: { session: target.session} };
var url = '/api/app-catalog/environments/' + target.environment +
'/metadata/';
return apiService.post(
url, { updated: updated, removed: removed}, params)
.error(function () {
toastService.add('error', gettext('Unable to edit environment metadata.'));
});
}
} |
JavaScript | function editComponentMeta(target, updated, removed) {
var params = { params: { session: target.session} };
var url = '/api/app-catalog/environments/' + target.environment +
'/components/' + target.component + '/metadata/';
return apiService.post(
url, { updated: updated, removed: removed}, params)
.error(function () {
toastService.add('error', gettext('Unable to edit component metadata.'));
});
} | function editComponentMeta(target, updated, removed) {
var params = { params: { session: target.session} };
var url = '/api/app-catalog/environments/' + target.environment +
'/components/' + target.component + '/metadata/';
return apiService.post(
url, { updated: updated, removed: removed}, params)
.error(function () {
toastService.add('error', gettext('Unable to edit component metadata.'));
});
} |
JavaScript | function editEnvironmentMeta(target, updated, removed) {
var params = { params: { session: target.session} };
var url = '/api/app-catalog/environments/' + target.environment +
'/metadata/';
return apiService.post(
url, { updated: updated, removed: removed}, params)
.error(function () {
toastService.add('error', gettext('Unable to edit environment metadata.'));
});
} | function editEnvironmentMeta(target, updated, removed) {
var params = { params: { session: target.session} };
var url = '/api/app-catalog/environments/' + target.environment +
'/metadata/';
return apiService.post(
url, { updated: updated, removed: removed}, params)
.error(function () {
toastService.add('error', gettext('Unable to edit environment metadata.'));
});
} |
JavaScript | function isEven(input){
if (input === false){
return false;
}
return (input % 2) === 0;
} | function isEven(input){
if (input === false){
return false;
}
return (input % 2) === 0;
} |
JavaScript | waitForConnection() {
return new Promise((resolve, reject) => {
if (this.con !== null) {
return resolve();
}
this.waiting.push([resolve, reject]);
});
} | waitForConnection() {
return new Promise((resolve, reject) => {
if (this.con !== null) {
return resolve();
}
this.waiting.push([resolve, reject]);
});
} |
JavaScript | removeModRole(role) {
let newRoles = [];
for (let modRole of this.modRoles) {
if (modRole != role)
newRoles.push(modRole);
}
this.modRoles = newRoles;
} | removeModRole(role) {
let newRoles = [];
for (let modRole of this.modRoles) {
if (modRole != role)
newRoles.push(modRole);
}
this.modRoles = newRoles;
} |
JavaScript | static async refreshGuildResponses(guildId) {
const result = await database.queryAll("SELECT * FROM responses WHERE guildid = ? AND global = TRUE", [guildId]);
const newResponses = new Discord.Collection();
for (const res of result) {
const o = new AutoResponse(res.guildid, {
trigger: JSON.parse(res.trigger),
response: res.response,
global: true,
channels: []
}, res.id);
newResponses.set(res.id, o);
}
guildResponses.set(guildId, newResponses);
setTimeout(() => {
guildResponses.delete(guildId);
},cacheDuration);
} | static async refreshGuildResponses(guildId) {
const result = await database.queryAll("SELECT * FROM responses WHERE guildid = ? AND global = TRUE", [guildId]);
const newResponses = new Discord.Collection();
for (const res of result) {
const o = new AutoResponse(res.guildid, {
trigger: JSON.parse(res.trigger),
response: res.response,
global: true,
channels: []
}, res.id);
newResponses.set(res.id, o);
}
guildResponses.set(guildId, newResponses);
setTimeout(() => {
guildResponses.delete(guildId);
},cacheDuration);
} |
JavaScript | static async refreshChannelResponses(channelId) {
const result = await database.queryAll("SELECT * FROM responses WHERE channels LIKE ?", [`%${channelId}%`]);
const newResponses = new Discord.Collection();
for (const res of result) {
newResponses.set(res.id, new AutoResponse(res.guildid, {
trigger: JSON.parse(res.trigger),
response: res.response,
global: false,
channels: res.channels.split(',')
}, res.id));
}
channelResponses.set(channelId, newResponses);
setTimeout(() => {
channelResponses.delete(channelId);
},cacheDuration);
} | static async refreshChannelResponses(channelId) {
const result = await database.queryAll("SELECT * FROM responses WHERE channels LIKE ?", [`%${channelId}%`]);
const newResponses = new Discord.Collection();
for (const res of result) {
newResponses.set(res.id, new AutoResponse(res.guildid, {
trigger: JSON.parse(res.trigger),
response: res.response,
global: false,
channels: res.channels.split(',')
}, res.id));
}
channelResponses.set(channelId, newResponses);
setTimeout(() => {
channelResponses.delete(channelId);
},cacheDuration);
} |
JavaScript | _preBuild() {
const opt = this.options;
// Check if element is selector
if (typeof opt.el === 'string') {
opt.el = document.querySelector(opt.el);
}
// Create element and append it to body to
// prevent initialization errors
this._root = create(opt);
// Check if a custom button is used
if (opt.useAsButton) {
this._root.button = opt.el; // Replace button with customized button
}
document.body.appendChild(this._root.root);
} | _preBuild() {
const opt = this.options;
// Check if element is selector
if (typeof opt.el === 'string') {
opt.el = document.querySelector(opt.el);
}
// Create element and append it to body to
// prevent initialization errors
this._root = create(opt);
// Check if a custom button is used
if (opt.useAsButton) {
this._root.button = opt.el; // Replace button with customized button
}
document.body.appendChild(this._root.root);
} |
JavaScript | function writeToFile(generatePage) {
fs.writeFile(`./dist/index.html`, generatePage, (err) => {
if (err) {
console.error(err);
return;
}
console.log(colors.green("\nFile successfully generated = index.html"));
});
} | function writeToFile(generatePage) {
fs.writeFile(`./dist/index.html`, generatePage, (err) => {
if (err) {
console.error(err);
return;
}
console.log(colors.green("\nFile successfully generated = index.html"));
});
} |
JavaScript | function rmDelete(node) {
if (node.operator != 'delete') {
return node
}
if (node.argument.type != 'Identifier') {
return node
}
return {
type: 'AssignmentExpression',
operator: '=',
left: node.argument,
right: { type: 'Identifier', name: 'undefined' }
}
} | function rmDelete(node) {
if (node.operator != 'delete') {
return node
}
if (node.argument.type != 'Identifier') {
return node
}
return {
type: 'AssignmentExpression',
operator: '=',
left: node.argument,
right: { type: 'Identifier', name: 'undefined' }
}
} |
JavaScript | function stdinArrayHandler(name, nextHandler) {
return (argv, ctx) => {
return getStdin().then(stdin => {
if (stdin) {
argv[name] = stdin.trim().split(/\s+/);
}
return nextHandler(argv, ctx);
});
};
} | function stdinArrayHandler(name, nextHandler) {
return (argv, ctx) => {
return getStdin().then(stdin => {
if (stdin) {
argv[name] = stdin.trim().split(/\s+/);
}
return nextHandler(argv, ctx);
});
};
} |
JavaScript | addPermissionToPackage(permission) {
return new Promise((resolve, reject) => {
const packageJson = this._loadPackageJson();
if (!packageJson) {
reject(new Error(`No package.json found in ${this.context.cwd}`)); // TODO: Define CLI errors...
}
// Add new permission to "permissionSets" if not already there
const found = packageJson.stripes.permissionSets.findIndex(perm => perm.permissionName === permission.permissionName);
if (found > -1) {
resolve(false);
} else {
packageJson.stripes.permissionSets.push(permission);
}
fs.writeFile(`${this.context.cwd}/package.json`, JSON.stringify(packageJson, null, 2), (err) => {
if (err) {
reject(err);
} else {
resolve(packageJson);
}
});
});
} | addPermissionToPackage(permission) {
return new Promise((resolve, reject) => {
const packageJson = this._loadPackageJson();
if (!packageJson) {
reject(new Error(`No package.json found in ${this.context.cwd}`)); // TODO: Define CLI errors...
}
// Add new permission to "permissionSets" if not already there
const found = packageJson.stripes.permissionSets.findIndex(perm => perm.permissionName === permission.permissionName);
if (found > -1) {
resolve(false);
} else {
packageJson.stripes.permissionSets.push(permission);
}
fs.writeFile(`${this.context.cwd}/package.json`, JSON.stringify(packageJson, null, 2), (err) => {
if (err) {
reject(err);
} else {
resolve(packageJson);
}
});
});
} |
JavaScript | function check_session() {
$.ajax({
url: 'check_session.php',
method: 'POST',
success:function(response){
if(response == 'logout') {
alert('Your session has expired, please login');
window.location.replace("logout.php");
return false;
}
}
});
} | function check_session() {
$.ajax({
url: 'check_session.php',
method: 'POST',
success:function(response){
if(response == 'logout') {
alert('Your session has expired, please login');
window.location.replace("logout.php");
return false;
}
}
});
} |
JavaScript | function copyToClipboard(element) {
var $temp = $("<input>");
$("body").append($temp);
var $text = $(element).text();
$text = translatePath($text);
$temp.val($text).select();
document.execCommand("copy");
$temp.remove();
clipboardNotice();
} | function copyToClipboard(element) {
var $temp = $("<input>");
$("body").append($temp);
var $text = $(element).text();
$text = translatePath($text);
$temp.val($text).select();
document.execCommand("copy");
$temp.remove();
clipboardNotice();
} |
JavaScript | function copyToClipboardText(text) {
text = translatePath(text);
var $temp = $("<input>");
$("body").append($temp);
$temp.val(text).select();
document.execCommand("copy");
$temp.remove();
clipboardNotice();
} | function copyToClipboardText(text) {
text = translatePath(text);
var $temp = $("<input>");
$("body").append($temp);
$temp.val(text).select();
document.execCommand("copy");
$temp.remove();
clipboardNotice();
} |
JavaScript | function replaceSearch(name, value) {
var str = location.search;
if (new RegExp("[&?]" + name + "([=&].+)?$").test(str)) {
str = str.replace(new RegExp("(?:[&?])" + name + "[^&]*", "g"), "")
}
str += "&";
str += name + "=" + value;
str = "?" + str.slice(1);
location.assign(location.origin + location.pathname + str + location.hash)
} | function replaceSearch(name, value) {
var str = location.search;
if (new RegExp("[&?]" + name + "([=&].+)?$").test(str)) {
str = str.replace(new RegExp("(?:[&?])" + name + "[^&]*", "g"), "")
}
str += "&";
str += name + "=" + value;
str = "?" + str.slice(1);
location.assign(location.origin + location.pathname + str + location.hash)
} |
JavaScript | function toggleTagButton() {
//check if checkbox is checked
function count() {
var tag_checked = $('input.tagcheck:checked').length;
return tag_checked;
}
if (count() > 0) {
$('#tagbutton').removeAttr('disabled');
} else {
$('#tagbutton').attr('disabled', true);
}
} | function toggleTagButton() {
//check if checkbox is checked
function count() {
var tag_checked = $('input.tagcheck:checked').length;
return tag_checked;
}
if (count() > 0) {
$('#tagbutton').removeAttr('disabled');
} else {
$('#tagbutton').attr('disabled', true);
}
} |
JavaScript | function toggleFileActionButton() {
//check if checkbox is checked
function count() {
var tag_checked = $('input.tagcheck:checked').length;
return tag_checked;
}
if (count() > 0) {
$('#fileactionbutton').removeAttr('disabled');
} else {
$('#fileactionbutton').attr('disabled', true);
}
} | function toggleFileActionButton() {
//check if checkbox is checked
function count() {
var tag_checked = $('input.tagcheck:checked').length;
return tag_checked;
}
if (count() > 0) {
$('#fileactionbutton').removeAttr('disabled');
} else {
$('#fileactionbutton').attr('disabled', true);
}
} |
JavaScript | function jsonError(err) {
let errmsg = 'Json error getting data from diskover index.';
console.error(errmsg);
// set error cookie to expire 1 hour
const d = new Date();
d.setTime(d.getTime() + 3600);
let expires = "expires="+ d.toUTCString();
document.cookie = "error=" + errmsg + ";" + expires + ";path=/";
// redirect to error page
window.location.href = 'error.php';
} | function jsonError(err) {
let errmsg = 'Json error getting data from diskover index.';
console.error(errmsg);
// set error cookie to expire 1 hour
const d = new Date();
d.setTime(d.getTime() + 3600);
let expires = "expires="+ d.toUTCString();
document.cookie = "error=" + errmsg + ";" + expires + ";path=/";
// redirect to error page
window.location.href = 'error.php';
} |
JavaScript | function resetResultsTable() {
// Clear all keys
store.clearAll();
alert('search results table column sizes reset');
} | function resetResultsTable() {
// Clear all keys
store.clearAll();
alert('search results table column sizes reset');
} |
JavaScript | function clipboardNotice() {
$('#clipboardnotice').modal('show');
setTimeout(function() {
$('#clipboardnotice').modal('hide');
}, 1000);
} | function clipboardNotice() {
$('#clipboardnotice').modal('show');
setTimeout(function() {
$('#clipboardnotice').modal('hide');
}, 1000);
} |
JavaScript | eval() {
if (this._cache) {
return this._cache;
}
const lazyErrs = [];
let curr = this;
while (curr && curr[parseErrorTypeKey] === ParseErrorType.LAZY) {
if (curr._cache) {
curr = curr._cache;
} else {
lazyErrs.push(curr);
if (typeof curr._thunk !== "function") {
throw new TypeError("thunk is not a function");
}
curr = curr._thunk.call(undefined);
}
}
if (!(curr && curr[parseErrorTypeKey] === ParseErrorType.STRICT)) {
throw new TypeError("evaluation result is not a StrictParseError obejct");
}
for (const err of lazyErrs) {
err._cache = curr;
}
return curr;
} | eval() {
if (this._cache) {
return this._cache;
}
const lazyErrs = [];
let curr = this;
while (curr && curr[parseErrorTypeKey] === ParseErrorType.LAZY) {
if (curr._cache) {
curr = curr._cache;
} else {
lazyErrs.push(curr);
if (typeof curr._thunk !== "function") {
throw new TypeError("thunk is not a function");
}
curr = curr._thunk.call(undefined);
}
}
if (!(curr && curr[parseErrorTypeKey] === ParseErrorType.STRICT)) {
throw new TypeError("evaluation result is not a StrictParseError obejct");
}
for (const err of lazyErrs) {
err._cache = curr;
}
return curr;
} |
JavaScript | function show(val) {
if (typeof val === "string") {
// optimize performance for singleton case
return val.length === 1 ? `"${escapeChar(val)}"`
: `"${val.replace(/[\u0000-\u001F\\"]/g, escapeChar)}"`;
} else if (Array.isArray(val)) {
return `[${val.map(show).join(", ")}]`;
} else if (typeof val === "object" && val !== null && typeof val.toString !== "function") {
// treatment for objects without `toString` method, such as `Object.create(null)`
return Object.prototype.toString.call(val);
} else {
return String(val);
}
} | function show(val) {
if (typeof val === "string") {
// optimize performance for singleton case
return val.length === 1 ? `"${escapeChar(val)}"`
: `"${val.replace(/[\u0000-\u001F\\"]/g, escapeChar)}"`;
} else if (Array.isArray(val)) {
return `[${val.map(show).join(", ")}]`;
} else if (typeof val === "object" && val !== null && typeof val.toString !== "function") {
// treatment for objects without `toString` method, such as `Object.create(null)`
return Object.prototype.toString.call(val);
} else {
return String(val);
}
} |
JavaScript | addChar(char, tabWidth) {
// For this case,
// - `if` is faster than `switch`
// - comparing strings is faster than character codes
if (char === "") {
return new SourcePos(this.name, this.line, this.column);
} else if (char === "\n") {
return new SourcePos(this.name, this.line + 1, 1);
} else if (char === "\t") {
return new SourcePos(
this.name,
this.line,
this.column + tabWidth - (this.column - 1) % tabWidth
);
} else {
return new SourcePos(this.name, this.line, this.column + 1);
}
} | addChar(char, tabWidth) {
// For this case,
// - `if` is faster than `switch`
// - comparing strings is faster than character codes
if (char === "") {
return new SourcePos(this.name, this.line, this.column);
} else if (char === "\n") {
return new SourcePos(this.name, this.line + 1, 1);
} else if (char === "\t") {
return new SourcePos(
this.name,
this.line,
this.column + tabWidth - (this.column - 1) % tabWidth
);
} else {
return new SourcePos(this.name, this.line, this.column + 1);
}
} |
JavaScript | addString(str, tabWidth, unicode) {
// For this case,
// - `switch` is faster than `if`
// - comparing character codes is faster than strings
let line = this.line;
let column = this.column;
if (unicode) {
for (const char of str) {
switch (char.charCodeAt(0)) {
case LF:
line += 1;
column = 1;
break;
case TAB:
column += tabWidth - (column - 1) % tabWidth;
break;
default:
column += 1;
}
}
} else {
const len = str.length;
for (let i = 0; i < len; i++) {
switch (str.charCodeAt(i)) {
case LF:
line += 1;
column = 1;
break;
case TAB:
column += tabWidth - (column - 1) % tabWidth;
break;
default:
column += 1;
}
}
}
return new SourcePos(this.name, line, column);
} | addString(str, tabWidth, unicode) {
// For this case,
// - `switch` is faster than `if`
// - comparing character codes is faster than strings
let line = this.line;
let column = this.column;
if (unicode) {
for (const char of str) {
switch (char.charCodeAt(0)) {
case LF:
line += 1;
column = 1;
break;
case TAB:
column += tabWidth - (column - 1) % tabWidth;
break;
default:
column += 1;
}
}
} else {
const len = str.length;
for (let i = 0; i < len; i++) {
switch (str.charCodeAt(i)) {
case LF:
line += 1;
column = 1;
break;
case TAB:
column += tabWidth - (column - 1) % tabWidth;
break;
default:
column += 1;
}
}
}
return new SourcePos(this.name, line, column);
} |
JavaScript | eval() {
if (this._cache) {
return this._cache;
}
const lazyParsers = [];
let curr = this;
while (curr && curr[parserTypeKey] === ParserType.LAZY) {
if (curr._cache) {
curr = curr._cache;
} else {
lazyParsers.push(curr);
if (typeof curr._thunk !== "function") {
throw new TypeError("thunk is not a function");
}
curr = curr._thunk.call(undefined);
}
}
if (!(curr && curr[parserTypeKey] === ParserType.STRICT)) {
throw new TypeError("evaluation result is not a StrictParser object");
}
for (const parser of lazyParsers) {
parser._cache = curr;
}
return curr;
} | eval() {
if (this._cache) {
return this._cache;
}
const lazyParsers = [];
let curr = this;
while (curr && curr[parserTypeKey] === ParserType.LAZY) {
if (curr._cache) {
curr = curr._cache;
} else {
lazyParsers.push(curr);
if (typeof curr._thunk !== "function") {
throw new TypeError("thunk is not a function");
}
curr = curr._thunk.call(undefined);
}
}
if (!(curr && curr[parserTypeKey] === ParserType.STRICT)) {
throw new TypeError("evaluation result is not a StrictParser object");
}
for (const parser of lazyParsers) {
parser._cache = curr;
}
return curr;
} |
JavaScript | function OnStart()
{
//Start/connect to our service.
svc = app.CreateService( "this","this" );
//This will cause your service to start at boot.
app.SetAutoBoot( "Service" );
app.SetScreenMode( "Full" );
//Lock screen orientation to Portrait.
app.SetOrientation( "Portrait" );
app.SetMenu( "Exit" );
app.EnableBackKey( false );
//Create the main app layout with objects vertically centered.
layMain = app.CreateLayout( "Linear", "VCenter,FillXY");
web = app.CreateWebView( 1, 1, null,"AutoZoom");
web.SetOnProgress( web_OnProgress );
web.LoadUrl( "main.html" );
layMain.AddChild( web );
//Create a drawer containing a menu list.
CreateDrawer();
//Add main layout and drawer to app.
app.AddLayout( layMain );
app.AddDrawer( drawerScroll, "Left", drawerWidth )
} | function OnStart()
{
//Start/connect to our service.
svc = app.CreateService( "this","this" );
//This will cause your service to start at boot.
app.SetAutoBoot( "Service" );
app.SetScreenMode( "Full" );
//Lock screen orientation to Portrait.
app.SetOrientation( "Portrait" );
app.SetMenu( "Exit" );
app.EnableBackKey( false );
//Create the main app layout with objects vertically centered.
layMain = app.CreateLayout( "Linear", "VCenter,FillXY");
web = app.CreateWebView( 1, 1, null,"AutoZoom");
web.SetOnProgress( web_OnProgress );
web.LoadUrl( "main.html" );
layMain.AddChild( web );
//Create a drawer containing a menu list.
CreateDrawer();
//Add main layout and drawer to app.
app.AddLayout( layMain );
app.AddDrawer( drawerScroll, "Left", drawerWidth )
} |
JavaScript | function BigInteger(n, s, token) {
if (token !== CONSTRUCT) {
if (n instanceof BigInteger) {
return n;
} else if (typeof n === "undefined") {
return ZERO;
}
return BigInteger.parse(n);
}
n = n || []; // Provide the nullary constructor for subclasses.
while (n.length && !n[n.length - 1]) {
--n.length;
}
this._d = n;
this._s = n.length ? (s || 1) : 0;
} | function BigInteger(n, s, token) {
if (token !== CONSTRUCT) {
if (n instanceof BigInteger) {
return n;
} else if (typeof n === "undefined") {
return ZERO;
}
return BigInteger.parse(n);
}
n = n || []; // Provide the nullary constructor for subclasses.
while (n.length && !n[n.length - 1]) {
--n.length;
}
this._d = n;
this._s = n.length ? (s || 1) : 0;
} |
JavaScript | function writeToFile(fileName, htmlString) {
// get path for root output file
let outputPath = path.join(process.cwd(), "./output");
// if folder does not exist - make it
if (!fs.existsSync(outputPath)) {
fs.mkdirSync(outputPath);
}
outputPath = path.join(outputPath, fileName);
// create the html file
fs.writeFileSync(outputPath, htmlString);
return outputPath;
} | function writeToFile(fileName, htmlString) {
// get path for root output file
let outputPath = path.join(process.cwd(), "./output");
// if folder does not exist - make it
if (!fs.existsSync(outputPath)) {
fs.mkdirSync(outputPath);
}
outputPath = path.join(outputPath, fileName);
// create the html file
fs.writeFileSync(outputPath, htmlString);
return outputPath;
} |
JavaScript | function onLoad()
{
parent.widgets.pathField = Dom.get(parent.id + "-pathField");
parent.widgets.documentField = Dom.get(parent.id + "-documentField");
parent.widgets.nodeField = Dom.get(parent.id + "-nodeRef");
parent.widgets.scriptInput = Dom.get(parent.id + "-jsinput");
parent.widgets.scriptOutput = Dom.get(parent.id + "-jsoutput");
parent.widgets.repoInfoOutput = Dom.get(parent.id + "-repoInfo");
parent.widgets.dumpInfoOutput = Dom.get(parent.id + "-dump");
parent.widgets.jsonOutput= Dom.get(parent.id + "-jsonOutput");
parent.widgets.templateInput = Dom.get(parent.id + "-templateinput");
parent.widgets.templateOutputHtml = Dom.get(parent.id + "-templateoutputhtml");
parent.widgets.templateOutputText = Dom.get(parent.id + "-templateoutputtext");
parent.widgets.config = {
runas : Dom.get(parent.id + "-runas"),
transaction : Dom.get(parent.id + "-transactions"),
urlargs : Dom.get(parent.id + "-urlarguments"),
runlikecrazy : Dom.get(parent.id + "-runlikecrazy")
};
// Buttons
parent.widgets.selectDestinationButton = Alfresco.util.createYUIButton(parent, "selectDestination-button", parent.onSelectDestinationClick);
parent.widgets.executeButton = Alfresco.util.createYUIButton(parent, "execute-button", parent.onExecuteClick);
parent.widgets.refreshButton = Alfresco.util.createYUIButton(parent, "refresh-button", parent.onRefreshServerInfoClick);
// Dom.addClass(parent.widgets.refreshButton, 'refresh-button');
Dom.addClass(parent.widgets.refreshButton._button.parentNode.parentNode, 'refresh-button-env');
} | function onLoad()
{
parent.widgets.pathField = Dom.get(parent.id + "-pathField");
parent.widgets.documentField = Dom.get(parent.id + "-documentField");
parent.widgets.nodeField = Dom.get(parent.id + "-nodeRef");
parent.widgets.scriptInput = Dom.get(parent.id + "-jsinput");
parent.widgets.scriptOutput = Dom.get(parent.id + "-jsoutput");
parent.widgets.repoInfoOutput = Dom.get(parent.id + "-repoInfo");
parent.widgets.dumpInfoOutput = Dom.get(parent.id + "-dump");
parent.widgets.jsonOutput= Dom.get(parent.id + "-jsonOutput");
parent.widgets.templateInput = Dom.get(parent.id + "-templateinput");
parent.widgets.templateOutputHtml = Dom.get(parent.id + "-templateoutputhtml");
parent.widgets.templateOutputText = Dom.get(parent.id + "-templateoutputtext");
parent.widgets.config = {
runas : Dom.get(parent.id + "-runas"),
transaction : Dom.get(parent.id + "-transactions"),
urlargs : Dom.get(parent.id + "-urlarguments"),
runlikecrazy : Dom.get(parent.id + "-runlikecrazy")
};
// Buttons
parent.widgets.selectDestinationButton = Alfresco.util.createYUIButton(parent, "selectDestination-button", parent.onSelectDestinationClick);
parent.widgets.executeButton = Alfresco.util.createYUIButton(parent, "execute-button", parent.onExecuteClick);
parent.widgets.refreshButton = Alfresco.util.createYUIButton(parent, "refresh-button", parent.onRefreshServerInfoClick);
// Dom.addClass(parent.widgets.refreshButton, 'refresh-button');
Dom.addClass(parent.widgets.refreshButton._button.parentNode.parentNode, 'refresh-button-env');
} |
JavaScript | function ACJC_createDumpDisplayMenu(){
if(!this.widgets.dumpDisplayMenu){
var displayMenu = new YAHOO.widget.Menu('nowhere');
displayMenu.addItem({text: "Hide equal values",value:"Differences"});
displayMenu.addItem({text: "Hide different values",value:"highlightDifferences"});
displayMenu.addItem({text: "Hide null values", value:"nullValues"});
this.widgets.dumpDisplayMenu = new YAHOO.widget.Button({
type: "split",
label: "Display options",
name: "dumpDisplayButton",
menu: displayMenu,
container: "splitButtonContainer",
disabled: false
});
this.widgets.dumpDisplayMenu.on("appendTo", function () {
menu = this.getMenu();
menu.subscribe("click", function onMenuClick(sType, oArgs) {
var oMenuItem = oArgs[1];
if (oMenuItem) {
dt.showColumn(dt.getColumn(oMenuItem.value));
menu.removeItem(oMenuItem.index);
refreshButton();
}
});
});
}
} | function ACJC_createDumpDisplayMenu(){
if(!this.widgets.dumpDisplayMenu){
var displayMenu = new YAHOO.widget.Menu('nowhere');
displayMenu.addItem({text: "Hide equal values",value:"Differences"});
displayMenu.addItem({text: "Hide different values",value:"highlightDifferences"});
displayMenu.addItem({text: "Hide null values", value:"nullValues"});
this.widgets.dumpDisplayMenu = new YAHOO.widget.Button({
type: "split",
label: "Display options",
name: "dumpDisplayButton",
menu: displayMenu,
container: "splitButtonContainer",
disabled: false
});
this.widgets.dumpDisplayMenu.on("appendTo", function () {
menu = this.getMenu();
menu.subscribe("click", function onMenuClick(sType, oArgs) {
var oMenuItem = oArgs[1];
if (oMenuItem) {
dt.showColumn(dt.getColumn(oMenuItem.value));
menu.removeItem(oMenuItem.index);
refreshButton();
}
});
});
}
} |
JavaScript | function ACJC_onExecuteClick(e, p_obj)
{
// Save any changes done in CodeMirror editor before submitting
this.widgets.codeMirrorScript.save();
this.widgets.codeMirrorTemplate.save();
// If something is selected, only get the selected part of the script
var scriptCode = "";
if (this.widgets.codeMirrorScript.somethingSelected()) {
scriptCode = this.widgets.codeMirrorScript.getSelection();
}
else {
scriptCode = this.widgets.scriptInput.value;
}
templateCode = this.widgets.templateInput.value;
// Build JSON Object to send to the server
var input = {
"script" : scriptCode,
"template" : templateCode,
"spaceNodeRef" : this.widgets.nodeField.value,
"transaction" : this.widgets.config.transaction.value ? this.widgets.config.transaction.value : "readwrite",
"runas" : this.widgets.config.runas.value ? this.widgets.config.runas.value : "admin",
"urlargs" : this.widgets.config.urlargs.value ? this.widgets.config.urlargs.value : "",
"documentNodeRef" : this.options.documentNodeRef
};
// Disable the result textarea
this.widgets.scriptOutput.disabled = true;
this.widgets.executeButton.disabled = true;
this.showLoadingAjaxSpinner(true);
this.executeStartTime = new Date();
input.resultChannel = String(this.executeStartTime.getTime());
Alfresco.util.Ajax.request(
{
url: Alfresco.constants.PROXY_URI + "de/fme/jsconsole/execute",
method: Alfresco.util.Ajax.POST,
dataObj: input,
requestContentType: Alfresco.util.Ajax.JSON,
successCallback:
{
fn: function(res) {
this.fetchResult();
this.fetchResultTimer.cancel();
this.fetchResultTimer = null;
this.showLoadingAjaxSpinner(false);
this.printExecutionStats(res.json);
this.printDumpInfos(res.json.dumpOutput);
this.clearOutput();
this.appendLineArrayToOutput(res.json.printOutput);
this.widgets.templateOutputHtml.innerHTML = res.json.renderedTemplate;
this.widgets.templateOutputText.innerHTML = $html(res.json.renderedTemplate);
this.widgets.codeMirrorJSON.setValue(formatter.formatJson(res.json.renderedTemplate," "));
this.widgets.codeMirrorJSON.focus();
if (res.json.spaceNodeRef) {
this.widgets.nodeField.value = res.json.spaceNodeRef;
this.widgets.pathField.innerHTML = res.json.spacePath;
}
this.widgets.scriptOutput.disabled = false;
this.widgets.templateOutputHtml.disabled = false;
this.widgets.templateOutputText.disabled = false;
this.widgets.executeButton.disabled = false;
this.showResultTable(res.json.result);
Dom.removeClass(this.widgets.scriptOutput, 'jserror');
Dom.addClass(this.widgets.scriptOutput, 'jsgreen');
this.runLikeCrazy();
},
scope: this
},
failureCallback:
{
fn: function(res) {
if (res.serverResponse.status !== 408) {
this.fetchResult();
this.fetchResultTimer.cancel();
this.fetchResultTimer = null;
this.showLoadingAjaxSpinner(false);
this.printExecutionStats();
var result = YAHOO.lang.JSON.parse(res.serverResponse.responseText);
this.markJSError(result);
this.markFreemarkerError(result);
this.clearOutput();
this.setOutputText(result.status.code + " " +
result.status.name + "\nStacktrace-Details:\n"+result.callstack+"\n\n"+
result.status.description + "\n" + result.message);
this.widgets.scriptOutput.disabled = false;
this.widgets.executeButton.disabled = false;
Dom.removeClass(this.widgets.scriptOutput, 'jsgreen');
Dom.addClass(this.widgets.scriptOutput, 'jserror');
this.widgets.outputTabs.selectTab(0); // show console tab
this.runLikeCrazy();
}
},
scope: this
}
});
// remove any marking
Dom.removeClass(this.widgets.scriptOutput, 'jserror');
Dom.removeClass(this.widgets.scriptOutput, 'jsgreen');
// fetch result updates to the print output after a second
this.fetchResultTimer = YAHOO.lang.later(1000, this, this.fetchResult, null, false);
} | function ACJC_onExecuteClick(e, p_obj)
{
// Save any changes done in CodeMirror editor before submitting
this.widgets.codeMirrorScript.save();
this.widgets.codeMirrorTemplate.save();
// If something is selected, only get the selected part of the script
var scriptCode = "";
if (this.widgets.codeMirrorScript.somethingSelected()) {
scriptCode = this.widgets.codeMirrorScript.getSelection();
}
else {
scriptCode = this.widgets.scriptInput.value;
}
templateCode = this.widgets.templateInput.value;
// Build JSON Object to send to the server
var input = {
"script" : scriptCode,
"template" : templateCode,
"spaceNodeRef" : this.widgets.nodeField.value,
"transaction" : this.widgets.config.transaction.value ? this.widgets.config.transaction.value : "readwrite",
"runas" : this.widgets.config.runas.value ? this.widgets.config.runas.value : "admin",
"urlargs" : this.widgets.config.urlargs.value ? this.widgets.config.urlargs.value : "",
"documentNodeRef" : this.options.documentNodeRef
};
// Disable the result textarea
this.widgets.scriptOutput.disabled = true;
this.widgets.executeButton.disabled = true;
this.showLoadingAjaxSpinner(true);
this.executeStartTime = new Date();
input.resultChannel = String(this.executeStartTime.getTime());
Alfresco.util.Ajax.request(
{
url: Alfresco.constants.PROXY_URI + "de/fme/jsconsole/execute",
method: Alfresco.util.Ajax.POST,
dataObj: input,
requestContentType: Alfresco.util.Ajax.JSON,
successCallback:
{
fn: function(res) {
this.fetchResult();
this.fetchResultTimer.cancel();
this.fetchResultTimer = null;
this.showLoadingAjaxSpinner(false);
this.printExecutionStats(res.json);
this.printDumpInfos(res.json.dumpOutput);
this.clearOutput();
this.appendLineArrayToOutput(res.json.printOutput);
this.widgets.templateOutputHtml.innerHTML = res.json.renderedTemplate;
this.widgets.templateOutputText.innerHTML = $html(res.json.renderedTemplate);
this.widgets.codeMirrorJSON.setValue(formatter.formatJson(res.json.renderedTemplate," "));
this.widgets.codeMirrorJSON.focus();
if (res.json.spaceNodeRef) {
this.widgets.nodeField.value = res.json.spaceNodeRef;
this.widgets.pathField.innerHTML = res.json.spacePath;
}
this.widgets.scriptOutput.disabled = false;
this.widgets.templateOutputHtml.disabled = false;
this.widgets.templateOutputText.disabled = false;
this.widgets.executeButton.disabled = false;
this.showResultTable(res.json.result);
Dom.removeClass(this.widgets.scriptOutput, 'jserror');
Dom.addClass(this.widgets.scriptOutput, 'jsgreen');
this.runLikeCrazy();
},
scope: this
},
failureCallback:
{
fn: function(res) {
if (res.serverResponse.status !== 408) {
this.fetchResult();
this.fetchResultTimer.cancel();
this.fetchResultTimer = null;
this.showLoadingAjaxSpinner(false);
this.printExecutionStats();
var result = YAHOO.lang.JSON.parse(res.serverResponse.responseText);
this.markJSError(result);
this.markFreemarkerError(result);
this.clearOutput();
this.setOutputText(result.status.code + " " +
result.status.name + "\nStacktrace-Details:\n"+result.callstack+"\n\n"+
result.status.description + "\n" + result.message);
this.widgets.scriptOutput.disabled = false;
this.widgets.executeButton.disabled = false;
Dom.removeClass(this.widgets.scriptOutput, 'jsgreen');
Dom.addClass(this.widgets.scriptOutput, 'jserror');
this.widgets.outputTabs.selectTab(0); // show console tab
this.runLikeCrazy();
}
},
scope: this
}
});
// remove any marking
Dom.removeClass(this.widgets.scriptOutput, 'jserror');
Dom.removeClass(this.widgets.scriptOutput, 'jsgreen');
// fetch result updates to the print output after a second
this.fetchResultTimer = YAHOO.lang.later(1000, this, this.fetchResult, null, false);
} |
JavaScript | function ACJC_onLoadScriptClick(p_sType, p_aArgs, self) {
var callback = {
success : function(o) {
// set the new editor content
self.widgets.codeMirrorScript.setValue(o.responseText);
},
failure: function(o) {
text: self.msg("error.script.load", filename)
},
scope: this
}
var callbackFreemarker = {
success : function(o) {
// set the new editor content
self.widgets.codeMirrorTemplate.setValue(o.responseText);
},
failure: function(o) {
text: self.msg("error.script.load", filename)
},
scope: this
}
var nodeRef = p_aArgs[1].value;
if (nodeRef == "NEW") {
self.loadDemoScript.call(self);
}
else {
var url = Alfresco.constants.PROXY_URI + "api/node/content/" + nodeRef.replace("://","/");
YAHOO.util.Connect.asyncRequest('GET', url, callback);
var url = Alfresco.constants.PROXY_URI + "api/node/content;jsc:freemarkerScript/" + nodeRef.replace("://","/");
YAHOO.util.Connect.asyncRequest('GET', url, callbackFreemarker);
}
} | function ACJC_onLoadScriptClick(p_sType, p_aArgs, self) {
var callback = {
success : function(o) {
// set the new editor content
self.widgets.codeMirrorScript.setValue(o.responseText);
},
failure: function(o) {
text: self.msg("error.script.load", filename)
},
scope: this
}
var callbackFreemarker = {
success : function(o) {
// set the new editor content
self.widgets.codeMirrorTemplate.setValue(o.responseText);
},
failure: function(o) {
text: self.msg("error.script.load", filename)
},
scope: this
}
var nodeRef = p_aArgs[1].value;
if (nodeRef == "NEW") {
self.loadDemoScript.call(self);
}
else {
var url = Alfresco.constants.PROXY_URI + "api/node/content/" + nodeRef.replace("://","/");
YAHOO.util.Connect.asyncRequest('GET', url, callback);
var url = Alfresco.constants.PROXY_URI + "api/node/content;jsc:freemarkerScript/" + nodeRef.replace("://","/");
YAHOO.util.Connect.asyncRequest('GET', url, callbackFreemarker);
}
} |
JavaScript | function ACJC_onThemeSelection(p_sType, p_aArgs, self) {
var theme = p_aArgs[1].value;
self.widgets.codeMirrorScript.setOption("theme", theme);
self.widgets.codeMirrorTemplate.setOption("theme", theme);
} | function ACJC_onThemeSelection(p_sType, p_aArgs, self) {
var theme = p_aArgs[1].value;
self.widgets.codeMirrorScript.setOption("theme", theme);
self.widgets.codeMirrorTemplate.setOption("theme", theme);
} |
JavaScript | function ACJC_onSaveScriptClick(p_sType, p_aArgs, self) {
self.widgets.codeMirrorScript.save();
var menuItem = p_aArgs[1];
var filename = menuItem.cfg.getProperty("text");
var nodeRef = menuItem.value;
if (nodeRef == "NEW") {
Alfresco.util.PopupManager.getUserInput(
{
title: self.msg("title.save.choose.filename"),
text: self.msg("message.save.choose.filename"),
input: "text",
callback: {
fn: self.saveAsNewScript,
obj: [ ],
scope: self
}
});
} else {
Alfresco.util.PopupManager.displayPrompt
({
title: self.msg("title.confirm.save"),
text: self.msg("message.confirm.save", filename),
buttons: [
{
text: self.msg("button.save"),
handler: function ACJC_onSaveScriptClick_save()
{
this.destroy();
self.saveAsExistingScript(filename, nodeRef);
}
},
{
text: self.msg("button.cancel"),
handler: function ACJC_onSaveScriptClick_cancel()
{
this.destroy();
},
isDefault: true
}]
});
}
} | function ACJC_onSaveScriptClick(p_sType, p_aArgs, self) {
self.widgets.codeMirrorScript.save();
var menuItem = p_aArgs[1];
var filename = menuItem.cfg.getProperty("text");
var nodeRef = menuItem.value;
if (nodeRef == "NEW") {
Alfresco.util.PopupManager.getUserInput(
{
title: self.msg("title.save.choose.filename"),
text: self.msg("message.save.choose.filename"),
input: "text",
callback: {
fn: self.saveAsNewScript,
obj: [ ],
scope: self
}
});
} else {
Alfresco.util.PopupManager.displayPrompt
({
title: self.msg("title.confirm.save"),
text: self.msg("message.confirm.save", filename),
buttons: [
{
text: self.msg("button.save"),
handler: function ACJC_onSaveScriptClick_save()
{
this.destroy();
self.saveAsExistingScript(filename, nodeRef);
}
},
{
text: self.msg("button.cancel"),
handler: function ACJC_onSaveScriptClick_cancel()
{
this.destroy();
},
isDefault: true
}]
});
}
} |
JavaScript | function ACJC_onSelectDestinationClick(e, p_obj)
{
// Set up select destination dialog
if (!this.widgets.destinationDialog)
{
this.widgets.destinationDialog = new Alfresco.module.DoclibGlobalFolder(this.id + "-selectDestination");
var allowedViewModes =
[
Alfresco.module.DoclibGlobalFolder.VIEW_MODE_REPOSITORY
// Alfresco.module.DoclibGlobalFolder.VIEW_MODE_SITE,
// Alfresco.module.DoclibGlobalFolder.VIEW_MODE_USERHOME
];
this.widgets.destinationDialog.setOptions(
{
allowedViewModes: allowedViewModes,
siteId: this.options.siteId,
containerId: this.options.containerId,
title: this.msg("title.destinationDialog"),
nodeRef: "alfresco://company/home"
});
}
// Make sure correct path is expanded
var pathNodeRef = this.widgets.nodeField.value;
this.widgets.destinationDialog.setOptions(
{
pathNodeRef: pathNodeRef ? new Alfresco.util.NodeRef(pathNodeRef) : null
});
// Show dialog
this.widgets.destinationDialog.showDialog();
} | function ACJC_onSelectDestinationClick(e, p_obj)
{
// Set up select destination dialog
if (!this.widgets.destinationDialog)
{
this.widgets.destinationDialog = new Alfresco.module.DoclibGlobalFolder(this.id + "-selectDestination");
var allowedViewModes =
[
Alfresco.module.DoclibGlobalFolder.VIEW_MODE_REPOSITORY
// Alfresco.module.DoclibGlobalFolder.VIEW_MODE_SITE,
// Alfresco.module.DoclibGlobalFolder.VIEW_MODE_USERHOME
];
this.widgets.destinationDialog.setOptions(
{
allowedViewModes: allowedViewModes,
siteId: this.options.siteId,
containerId: this.options.containerId,
title: this.msg("title.destinationDialog"),
nodeRef: "alfresco://company/home"
});
}
// Make sure correct path is expanded
var pathNodeRef = this.widgets.nodeField.value;
this.widgets.destinationDialog.setOptions(
{
pathNodeRef: pathNodeRef ? new Alfresco.util.NodeRef(pathNodeRef) : null
});
// Show dialog
this.widgets.destinationDialog.showDialog();
} |
JavaScript | function highlightAllOccurencesForElement(element,keyword) {
if (element) {
if (element.nodeType == 3) { // Text node
while (true) {
var value = element.nodeValue; // Search for keyword in text node
var indexOfElement = value.toLowerCase().indexOf(keyword);
if (indexOfElement < 0) break; // not found, abort
var span = document.createElement("span");
var text = document.createTextNode(value.substr(indexOfElement,keyword.length));
span.appendChild(text);
span.setAttribute("class","highlightedTag");
span.style.backgroundColor="yellow";
span.style.color="black";
text = document.createTextNode(value.substr(indexOfElement+keyword.length));
element.deleteData(indexOfElement, value.length - indexOfElement);
var next = element.nextSibling;
element.parentNode.insertBefore(span, next);
element.parentNode.insertBefore(text, next);
element = text;
totalResults++; // update the counter
}
} else if (element.nodeType == 1) { // Element node
if (element.style.display != "none" && element.nodeName.toLowerCase() != 'select') {
for (var i=element.childNodes.length-1; i>=0; i--) {
highlightAllOccurencesForElement(element.childNodes[i],keyword);
}
}
}
}
} | function highlightAllOccurencesForElement(element,keyword) {
if (element) {
if (element.nodeType == 3) { // Text node
while (true) {
var value = element.nodeValue; // Search for keyword in text node
var indexOfElement = value.toLowerCase().indexOf(keyword);
if (indexOfElement < 0) break; // not found, abort
var span = document.createElement("span");
var text = document.createTextNode(value.substr(indexOfElement,keyword.length));
span.appendChild(text);
span.setAttribute("class","highlightedTag");
span.style.backgroundColor="yellow";
span.style.color="black";
text = document.createTextNode(value.substr(indexOfElement+keyword.length));
element.deleteData(indexOfElement, value.length - indexOfElement);
var next = element.nextSibling;
element.parentNode.insertBefore(span, next);
element.parentNode.insertBefore(text, next);
element = text;
totalResults++; // update the counter
}
} else if (element.nodeType == 1) { // Element node
if (element.style.display != "none" && element.nodeName.toLowerCase() != 'select') {
for (var i=element.childNodes.length-1; i>=0; i--) {
highlightAllOccurencesForElement(element.childNodes[i],keyword);
}
}
}
}
} |
JavaScript | function removeHighlightsForElement(element) {
if (element) {
if (element.nodeType == 1) {
if (element.getAttribute("class") == "highlightedTag") {
var text = element.removeChild(element.firstChild);
element.parentNode.insertBefore(text,element);
element.parentNode.removeChild(element);
return true;
} else {
var normalize = false;
for (var i=element.childNodes.length-1; i>=0; i--) {
if (removeHighlightsForElement(element.childNodes[i])) {
normalize = true;
}
}
if (normalize) {
element.normalize();
}
}
}
}
return false;
} | function removeHighlightsForElement(element) {
if (element) {
if (element.nodeType == 1) {
if (element.getAttribute("class") == "highlightedTag") {
var text = element.removeChild(element.firstChild);
element.parentNode.insertBefore(text,element);
element.parentNode.removeChild(element);
return true;
} else {
var normalize = false;
for (var i=element.childNodes.length-1; i>=0; i--) {
if (removeHighlightsForElement(element.childNodes[i])) {
normalize = true;
}
}
if (normalize) {
element.normalize();
}
}
}
}
return false;
} |
JavaScript | function removeHighlights() {
totalResults = 0;
currentlySelectedIndex = -1;
removeHighlightsForElement(document.body);
} | function removeHighlights() {
totalResults = 0;
currentlySelectedIndex = -1;
removeHighlightsForElement(document.body);
} |
JavaScript | function gol() {
const dataNew = context.createImageData(canvas.width, canvas.height);
const pixNew = dataNew.data;
for (let y = 0; y < canvas.height; y++) {
for (let x = 0; x < canvas.width; x++) {
//d.innerText = "x:"+x +" y:"+ y;
drawPixel(x, y, isAlive(x, y) ? ALIVE : DEAD, pixNew);
}
}
data = dataNew;
pix = data.data;
context.putImageData(dataNew, 0, 0);
} | function gol() {
const dataNew = context.createImageData(canvas.width, canvas.height);
const pixNew = dataNew.data;
for (let y = 0; y < canvas.height; y++) {
for (let x = 0; x < canvas.width; x++) {
//d.innerText = "x:"+x +" y:"+ y;
drawPixel(x, y, isAlive(x, y) ? ALIVE : DEAD, pixNew);
}
}
data = dataNew;
pix = data.data;
context.putImageData(dataNew, 0, 0);
} |
JavaScript | function calcCrow(lat1, lon1, lat2, lon2) {
// Converts numeric degrees to radians
const toRad = function(Value) {
return (Value * Math.PI) / 180;
}
var R = 6371; // km
var dLat = toRad(lat2 - lat1);
var dLon = toRad(lon2 - lon1);
var lat1 = toRad(lat1);
var lat2 = toRad(lat2);
var a =
Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.sin(dLon / 2) * Math.sin(dLon / 2) * Math.cos(lat1) * Math.cos(lat2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
var d = R * c;
return d;
} | function calcCrow(lat1, lon1, lat2, lon2) {
// Converts numeric degrees to radians
const toRad = function(Value) {
return (Value * Math.PI) / 180;
}
var R = 6371; // km
var dLat = toRad(lat2 - lat1);
var dLon = toRad(lon2 - lon1);
var lat1 = toRad(lat1);
var lat2 = toRad(lat2);
var a =
Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.sin(dLon / 2) * Math.sin(dLon / 2) * Math.cos(lat1) * Math.cos(lat2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
var d = R * c;
return d;
} |
JavaScript | function demo(event) {
const demo = event.currentTarget
if (event.target !== demo && demo.classList.contains("active")) return true; // Ignore clicking on children when expanded
const active = demo.classList.toggle("active")
const query = demo.getElementsByClassName("query").item(0)
query.focus()
const result = demo.getElementsByClassName("result").item(0)
if (active && !result.innerHTML.trim()) {
demoInput({currentTarget: query})
}
} | function demo(event) {
const demo = event.currentTarget
if (event.target !== demo && demo.classList.contains("active")) return true; // Ignore clicking on children when expanded
const active = demo.classList.toggle("active")
const query = demo.getElementsByClassName("query").item(0)
query.focus()
const result = demo.getElementsByClassName("result").item(0)
if (active && !result.innerHTML.trim()) {
demoInput({currentTarget: query})
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.