language
stringclasses 6
values | original_string
stringlengths 25
887k
| text
stringlengths 25
887k
|
---|---|---|
JavaScript | isAuthenticated(){
if(sessionStorage.getItem('token') != null){
this.authenticated = true;
} else {
this.authenticated = false;
}
return this.authenticated;
} | isAuthenticated(){
if(sessionStorage.getItem('token') != null){
this.authenticated = true;
} else {
this.authenticated = false;
}
return this.authenticated;
} |
JavaScript | validate(email){
return http
.post('/do-validate', {'email': email})
.then(response => {
return response.data;
}, () => {
return false;
});
} | validate(email){
return http
.post('/do-validate', {'email': email})
.then(response => {
return response.data;
}, () => {
return false;
});
} |
JavaScript | changeProfile(nickname, name, date, country, password, image){
const headers = {'headers': {'x-access-token': sessionStorage.getItem('token')}}
if(password.length == 0){
return http
.post('/do-changeProfile/' + nickname + '/' + name + '/' + date + '/' + country + '/' + 'a', {'image': image}, headers)
.then(response => {
return response.data;
}, () => {
return false;
});
} else {
return http
.post('/do-changeProfile/' + nickname + '/' + name + '/' + date + '/' + country + '/' + password, {'image': image}, headers)
.then(response => {
return response.data;
}, () => {
return false;
});
}
} | changeProfile(nickname, name, date, country, password, image){
const headers = {'headers': {'x-access-token': sessionStorage.getItem('token')}}
if(password.length == 0){
return http
.post('/do-changeProfile/' + nickname + '/' + name + '/' + date + '/' + country + '/' + 'a', {'image': image}, headers)
.then(response => {
return response.data;
}, () => {
return false;
});
} else {
return http
.post('/do-changeProfile/' + nickname + '/' + name + '/' + date + '/' + country + '/' + password, {'image': image}, headers)
.then(response => {
return response.data;
}, () => {
return false;
});
}
} |
JavaScript | searchUser(nickname) {
const headers = {'headers': {'x-access-token': sessionStorage.getItem('token')}}
return http
.post('/do-searchUsers/', {'nickname': nickname}, headers)
.then(response => {
return response.data;
}, () => {
return false;
});
} | searchUser(nickname) {
const headers = {'headers': {'x-access-token': sessionStorage.getItem('token')}}
return http
.post('/do-searchUsers/', {'nickname': nickname}, headers)
.then(response => {
return response.data;
}, () => {
return false;
});
} |
JavaScript | rejectRequest(id) {
const headers = {'headers': {'x-access-token': sessionStorage.getItem('token')}}
return http
.post('/do-rejectRequest/', {'id': id}, headers)
.then(response => {
return response.data;
}, () => {
return false;
});
} | rejectRequest(id) {
const headers = {'headers': {'x-access-token': sessionStorage.getItem('token')}}
return http
.post('/do-rejectRequest/', {'id': id}, headers)
.then(response => {
return response.data;
}, () => {
return false;
});
} |
JavaScript | acceptRequest(id) {
const headers = {'headers': {'x-access-token': sessionStorage.getItem('token')}}
return http
.post('/do-acceptRequest/', {'id': id}, headers)
.then(response => {
return response.data;
}, () => {
return false;
});
} | acceptRequest(id) {
const headers = {'headers': {'x-access-token': sessionStorage.getItem('token')}}
return http
.post('/do-acceptRequest/', {'id': id}, headers)
.then(response => {
return response.data;
}, () => {
return false;
});
} |
JavaScript | function collapsibleStreamEventHandler(name, streamName)
{
if(streamName === undefined) streamName = name;
var dataRole = $("#" + name).attr('data-role');
if(dataRole == 'collapsible') {
$("#" + name).collapsible({
collapse: function() {
streamRemove(streamName);
},
expand: function() {
streamAdd(streamName);
}
});
} else if(dataRole == 'panel') {
$("#" + name).panel({
open: function() {
streamAdd(streamName);
},
close: function() {
streamRemove(streamName);
}
});
}
} | function collapsibleStreamEventHandler(name, streamName)
{
if(streamName === undefined) streamName = name;
var dataRole = $("#" + name).attr('data-role');
if(dataRole == 'collapsible') {
$("#" + name).collapsible({
collapse: function() {
streamRemove(streamName);
},
expand: function() {
streamAdd(streamName);
}
});
} else if(dataRole == 'panel') {
$("#" + name).panel({
open: function() {
streamAdd(streamName);
},
close: function() {
streamRemove(streamName);
}
});
}
} |
JavaScript | transferDisplayObjectPropsByName(oldProps, newProps, propsToCheck) {
let displayObject = this._displayObject;
for (var propname in propsToCheck) {
if (typeof newProps[propname] !== 'undefined') {
setPixiValue(displayObject, propname, newProps[propname]);
} else if (typeof oldProps[propname] !== 'undefined' &&
typeof propsToCheck[propname] !== 'undefined') {
// the field we use previously but not any more. reset it to
// some default value (unless the default is undefined)
setPixiValue(displayObject, propname, propsToCheck[propname]);
}
}
// parse Point-like prop values
gPointLikeProps.forEach(function(propname) {
if (typeof newProps[propname] !== 'undefined') {
setPixiValue(displayObject, propname, newProps[propname]);
}
})
} | transferDisplayObjectPropsByName(oldProps, newProps, propsToCheck) {
let displayObject = this._displayObject;
for (var propname in propsToCheck) {
if (typeof newProps[propname] !== 'undefined') {
setPixiValue(displayObject, propname, newProps[propname]);
} else if (typeof oldProps[propname] !== 'undefined' &&
typeof propsToCheck[propname] !== 'undefined') {
// the field we use previously but not any more. reset it to
// some default value (unless the default is undefined)
setPixiValue(displayObject, propname, propsToCheck[propname]);
}
}
// parse Point-like prop values
gPointLikeProps.forEach(function(propname) {
if (typeof newProps[propname] !== 'undefined') {
setPixiValue(displayObject, propname, newProps[propname]);
}
})
} |
JavaScript | function autoSaveCookie(data)
{
var cookieString = '';
jQuery.each(data, function(i, field)
{
cookieString = cookieString + field.name + ':::--FIELDANDVARSPLITTER--:::' + field.value + ':::--FORMSPLITTERFORVARS--:::';
});
// $.cookie(cookie_id, cookieString, { expires: settings['days'] });
if (typeof(Storage) !== "undefined") {
localStorage.setItem(cookie_id, cookieString);
}
else {
$.cookie(cookie_id, cookieString, { expires: settings['days'] });
}
} | function autoSaveCookie(data)
{
var cookieString = '';
jQuery.each(data, function(i, field)
{
cookieString = cookieString + field.name + ':::--FIELDANDVARSPLITTER--:::' + field.value + ':::--FORMSPLITTERFORVARS--:::';
});
// $.cookie(cookie_id, cookieString, { expires: settings['days'] });
if (typeof(Storage) !== "undefined") {
localStorage.setItem(cookie_id, cookieString);
}
else {
$.cookie(cookie_id, cookieString, { expires: settings['days'] });
}
} |
JavaScript | function strpos(haystack, needle, offset)
{
var i = (haystack+'').indexOf(needle, (offset || 0));
return i === -1 ? false : i;
} | function strpos(haystack, needle, offset)
{
var i = (haystack+'').indexOf(needle, (offset || 0));
return i === -1 ? false : i;
} |
JavaScript | _onChange() {
const oldValue = this._currentValue;
const newValue = this._settings.get(this._keyPath);
try {
assert.deepEqual(newValue, oldValue);
} catch (err) {
this._currentValue = newValue;
// Call the watch handler and pass in the new and old values.
this._handler.call(this, newValue, oldValue);
}
} | _onChange() {
const oldValue = this._currentValue;
const newValue = this._settings.get(this._keyPath);
try {
assert.deepEqual(newValue, oldValue);
} catch (err) {
this._currentValue = newValue;
// Call the watch handler and pass in the new and old values.
this._handler.call(this, newValue, oldValue);
}
} |
JavaScript | async function initUserModel(db) {
User.init({
username: {
type: Sequelize.STRING,
allowNull: false,
unique: true,
},
password: {
type: Sequelize.STRING,
},
}, {
sequelize: db,
modelName: 'user',
});
await User.sync();
} | async function initUserModel(db) {
User.init({
username: {
type: Sequelize.STRING,
allowNull: false,
unique: true,
},
password: {
type: Sequelize.STRING,
},
}, {
sequelize: db,
modelName: 'user',
});
await User.sync();
} |
JavaScript | async function check() {
return {
statusCode: 200,
body: JSON.stringify({health: 'ok'}),
};
} | async function check() {
return {
statusCode: 200,
body: JSON.stringify({health: 'ok'}),
};
} |
JavaScript | async function initMessageModel(db) {
await initUserModel(db);
Message.init({
type: {
type: Sequelize.STRING,
allowNull: false,
},
content: {
type: Sequelize.JSON,
allowNull: false,
},
sender: {
type: Sequelize.INTEGER,
allowNull: false,
references: {
model: User,
key: 'id',
},
},
recipient: {
type: Sequelize.INTEGER,
allowNull: false,
references: {
model: User,
key: 'id',
},
},
}, {
sequelize: db,
modelName: 'message',
});
await Message.sync();
} | async function initMessageModel(db) {
await initUserModel(db);
Message.init({
type: {
type: Sequelize.STRING,
allowNull: false,
},
content: {
type: Sequelize.JSON,
allowNull: false,
},
sender: {
type: Sequelize.INTEGER,
allowNull: false,
references: {
model: User,
key: 'id',
},
},
recipient: {
type: Sequelize.INTEGER,
allowNull: false,
references: {
model: User,
key: 'id',
},
},
}, {
sequelize: db,
modelName: 'message',
});
await Message.sync();
} |
JavaScript | isTextFucked(txt) {
if (!txt) return 1
let invalids = 0;
for (let c of txt) {
if (c.charCodeAt(0) >= 30000) invalids += 1;
}
return invalids/txt.length
} | isTextFucked(txt) {
if (!txt) return 1
let invalids = 0;
for (let c of txt) {
if (c.charCodeAt(0) >= 30000) invalids += 1;
}
return invalids/txt.length
} |
JavaScript | cancel() {
if (this.textLayerRenderTask) {
this.textLayerRenderTask.cancel();
this.textLayerRenderTask = null;
}
if (this._onUpdateTextLayerMatches) {
//this.eventBus._off(
//"updatetextlayermatches",
//this._onUpdateTextLayerMatches
//);
this._onUpdateTextLayerMatches = null;
}
} | cancel() {
if (this.textLayerRenderTask) {
this.textLayerRenderTask.cancel();
this.textLayerRenderTask = null;
}
if (this._onUpdateTextLayerMatches) {
//this.eventBus._off(
//"updatetextlayermatches",
//this._onUpdateTextLayerMatches
//);
this._onUpdateTextLayerMatches = null;
}
} |
JavaScript | _bindMouse() {
const div = this.textLayerDiv;
let expandDivsTimer = null;
div.addEventListener("mousedown", evt => {
if (this.enhanceTextSelection && this.textLayerRenderTask) {
this.textLayerRenderTask.expandTextDivs(true);
if (
(typeof PDFJSDev === "undefined" || !PDFJSDev.test("MOZCENTRAL")) &&
expandDivsTimer
) {
clearTimeout(expandDivsTimer);
expandDivsTimer = null;
}
return;
}
const end = div.querySelector(".endOfContent");
if (!end) {
return;
}
if (typeof PDFJSDev === "undefined" || !PDFJSDev.test("MOZCENTRAL")) {
// On non-Firefox browsers, the selection will feel better if the height
// of the `endOfContent` div is adjusted to start at mouse click
// location. This avoids flickering when the selection moves up.
// However it does not work when selection is started on empty space.
let adjustTop = evt.target !== div;
if (typeof PDFJSDev === "undefined" || PDFJSDev.test("GENERIC")) {
adjustTop =
adjustTop &&
window
.getComputedStyle(end)
.getPropertyValue("-moz-user-select") !== "none";
}
if (adjustTop) {
const divBounds = div.getBoundingClientRect();
const r = Math.max(0, (evt.pageY - divBounds.top) / divBounds.height);
end.style.top = (r * 100).toFixed(2) + "%";
}
}
end.classList.add("active");
});
div.addEventListener("mouseup", () => {
if (this.enhanceTextSelection && this.textLayerRenderTask) {
if (typeof PDFJSDev === "undefined" || !PDFJSDev.test("MOZCENTRAL")) {
expandDivsTimer = setTimeout(() => {
if (this.textLayerRenderTask) {
this.textLayerRenderTask.expandTextDivs(false);
}
expandDivsTimer = null;
}, EXPAND_DIVS_TIMEOUT);
} else {
this.textLayerRenderTask.expandTextDivs(false);
}
return;
}
const end = div.querySelector(".endOfContent");
if (!end) {
return;
}
if (typeof PDFJSDev === "undefined" || !PDFJSDev.test("MOZCENTRAL")) {
end.style.top = "";
}
end.classList.remove("active");
});
} | _bindMouse() {
const div = this.textLayerDiv;
let expandDivsTimer = null;
div.addEventListener("mousedown", evt => {
if (this.enhanceTextSelection && this.textLayerRenderTask) {
this.textLayerRenderTask.expandTextDivs(true);
if (
(typeof PDFJSDev === "undefined" || !PDFJSDev.test("MOZCENTRAL")) &&
expandDivsTimer
) {
clearTimeout(expandDivsTimer);
expandDivsTimer = null;
}
return;
}
const end = div.querySelector(".endOfContent");
if (!end) {
return;
}
if (typeof PDFJSDev === "undefined" || !PDFJSDev.test("MOZCENTRAL")) {
// On non-Firefox browsers, the selection will feel better if the height
// of the `endOfContent` div is adjusted to start at mouse click
// location. This avoids flickering when the selection moves up.
// However it does not work when selection is started on empty space.
let adjustTop = evt.target !== div;
if (typeof PDFJSDev === "undefined" || PDFJSDev.test("GENERIC")) {
adjustTop =
adjustTop &&
window
.getComputedStyle(end)
.getPropertyValue("-moz-user-select") !== "none";
}
if (adjustTop) {
const divBounds = div.getBoundingClientRect();
const r = Math.max(0, (evt.pageY - divBounds.top) / divBounds.height);
end.style.top = (r * 100).toFixed(2) + "%";
}
}
end.classList.add("active");
});
div.addEventListener("mouseup", () => {
if (this.enhanceTextSelection && this.textLayerRenderTask) {
if (typeof PDFJSDev === "undefined" || !PDFJSDev.test("MOZCENTRAL")) {
expandDivsTimer = setTimeout(() => {
if (this.textLayerRenderTask) {
this.textLayerRenderTask.expandTextDivs(false);
}
expandDivsTimer = null;
}, EXPAND_DIVS_TIMEOUT);
} else {
this.textLayerRenderTask.expandTextDivs(false);
}
return;
}
const end = div.querySelector(".endOfContent");
if (!end) {
return;
}
if (typeof PDFJSDev === "undefined" || !PDFJSDev.test("MOZCENTRAL")) {
end.style.top = "";
}
end.classList.remove("active");
});
} |
JavaScript | isTextFucked(txt) {
if (!txt) return 1
let invalids = 0
for (let c of txt) {
if (c.charCodeAt(0) >= 30000) invalids += 1
}
return invalids/txt.length
} | isTextFucked(txt) {
if (!txt) return 1
let invalids = 0
for (let c of txt) {
if (c.charCodeAt(0) >= 30000) invalids += 1
}
return invalids/txt.length
} |
JavaScript | function makeWebpackExternalsConfig(moduleNames) {
return moduleNames.reduce((externals, moduleName) => Object.assign(externals, {
[moduleName]: `commonjs ${moduleName}`,
}), {});
} | function makeWebpackExternalsConfig(moduleNames) {
return moduleNames.reduce((externals, moduleName) => Object.assign(externals, {
[moduleName]: `commonjs ${moduleName}`,
}), {});
} |
JavaScript | function createServer(opts) {
opts.webpackConfigPath = path.resolve(process.cwd(), opts.webpackConfigPath);
if (fs.existsSync(opts.webpackConfigPath)) {
opts.webpackConfig = require(path.resolve(process.cwd(), opts.webpackConfigPath));
} else {
throw new Error('Must specify webpackConfigPath or create ./webpack.config.js');
}
delete opts.webpackConfigPath;
const server = new Server(opts);
return server;
} | function createServer(opts) {
opts.webpackConfigPath = path.resolve(process.cwd(), opts.webpackConfigPath);
if (fs.existsSync(opts.webpackConfigPath)) {
opts.webpackConfig = require(path.resolve(process.cwd(), opts.webpackConfigPath));
} else {
throw new Error('Must specify webpackConfigPath or create ./webpack.config.js');
}
delete opts.webpackConfigPath;
const server = new Server(opts);
return server;
} |
JavaScript | function commonOptions(program) {
return program
.option(
'-H, --hostname [hostname]',
'Hostname on which the server will listen. [localhost]',
'localhost'
)
.option(
'-P, --port [port]',
'Port on which the server will listen. [8080]',
8080
)
.option(
'-p, --packagerPort [port]',
'Port on which the react-native packager will listen. [8081]',
8081
)
.option(
'-w, --webpackPort [port]',
'Port on which the webpack dev server will listen. [8082]',
8082
)
.option(
'-c, --webpackConfigPath [path]',
'Path to the webpack configuration file. [webpack.config.js]',
'webpack.config.js'
)
.option(
'--no-android',
'Disable support for Android. [false]',
false
)
.option(
'--no-ios',
'Disable support for iOS. [false]',
false
)
.option(
'-A, --androidEntry [name]',
'Android entry module name. Has no effect if \'--no-android\' is passed. [index.android]',
'index.android'
)
.option(
'-I, --iosEntry [name]',
'iOS entry module name. Has no effect if \'--no-ios\' is passed. [index.ios]',
'index.ios'
)
.option(
'--projectRoots [projectRoots]',
'List of comma-separated paths for the react-native packager to consider as project root directories',
null
)
.option(
'--root [root]',
'List of comma-separated paths for the react-native packager to consider as additional directories. If provided, these paths must include react-native and its dependencies.',
null
)
.option(
'--assetRoots [assetRoots]',
'List of comma-separated paths for the react-native packager to consider as asset root directories',
null
)
.option(
'-r, --resetCache',
'Remove cached react-native packager files [false]',
false
)
.option(
'--hasteExternals',
// React Native 0.23 rewrites `require('HasteModule')` calls to
// `require(42)` where 42 is an internal module id. That breaks
// treating Haste modules simply as commonjs modules and leaving
// the `require()` call in the source. So for now this feature
// only works with React Native <0.23.
'Allow direct import of React Native\'s (<0.23) internal Haste modules [false]',
false
);
} | function commonOptions(program) {
return program
.option(
'-H, --hostname [hostname]',
'Hostname on which the server will listen. [localhost]',
'localhost'
)
.option(
'-P, --port [port]',
'Port on which the server will listen. [8080]',
8080
)
.option(
'-p, --packagerPort [port]',
'Port on which the react-native packager will listen. [8081]',
8081
)
.option(
'-w, --webpackPort [port]',
'Port on which the webpack dev server will listen. [8082]',
8082
)
.option(
'-c, --webpackConfigPath [path]',
'Path to the webpack configuration file. [webpack.config.js]',
'webpack.config.js'
)
.option(
'--no-android',
'Disable support for Android. [false]',
false
)
.option(
'--no-ios',
'Disable support for iOS. [false]',
false
)
.option(
'-A, --androidEntry [name]',
'Android entry module name. Has no effect if \'--no-android\' is passed. [index.android]',
'index.android'
)
.option(
'-I, --iosEntry [name]',
'iOS entry module name. Has no effect if \'--no-ios\' is passed. [index.ios]',
'index.ios'
)
.option(
'--projectRoots [projectRoots]',
'List of comma-separated paths for the react-native packager to consider as project root directories',
null
)
.option(
'--root [root]',
'List of comma-separated paths for the react-native packager to consider as additional directories. If provided, these paths must include react-native and its dependencies.',
null
)
.option(
'--assetRoots [assetRoots]',
'List of comma-separated paths for the react-native packager to consider as asset root directories',
null
)
.option(
'-r, --resetCache',
'Remove cached react-native packager files [false]',
false
)
.option(
'--hasteExternals',
// React Native 0.23 rewrites `require('HasteModule')` calls to
// `require(42)` where 42 is an internal module id. That breaks
// treating Haste modules simply as commonjs modules and leaving
// the `require()` call in the source. So for now this feature
// only works with React Native <0.23.
'Allow direct import of React Native\'s (<0.23) internal Haste modules [false]',
false
);
} |
JavaScript | function renderMediaUploader($, container_media ) {
//'use strict';
var file_frame, image_data, json;
var container_data = container_media.next().next();
//var container_media = $this.parent().next();
/**
* If an instance of file_frame already exists, then we can open it
* rather than creating a new instance.
*/
if ( undefined !== file_frame ) {
file_frame.open();
return;
}
/**
* If we're this far, then an instance does not exist, so we need to
* create our own.
*
* Here, use the wp.media library to define the settings of the Media
* Uploader. We're opting to use the 'post' frame which is a template
* defined in WordPress core and are initializing the file frame
* with the 'insert' state.
*
* We're also not allowing the user to select more than one image.
*/
file_frame = wp.media.frames.file_frame = wp.media({
frame: 'post',
state: 'insert',
multiple: false
});
/**
* Setup an event handler for what to do when an image has been
* selected.
*
* Since we're using the 'view' state when initializing
* the file_frame, we need to make sure that the handler is attached
* to the insert event.
*/
file_frame.on( 'insert', function() {
// Read the JSON data returned from the Media Uploader
json = file_frame.state().get( 'selection' ).first().toJSON();
// First, make sure that we have the URL of an image to display
if ( 0 > $.trim( json.url.length ) ) {
return;
}
var name = json.url.split('/');
name = name[ name.length - 1 ];
// After that, set the properties of the image and display it
container_media
.children( 'p' )
.find('.name')
.text( name )
.parent()
.show()
.parent()
.removeClass( 'hidden' );
container_media
.children( 'img' )
.attr( 'src', json.url )
//.attr( 'alt', json.caption )
//.attr( 'title', json.title )
.show()
.parent()
.removeClass( 'hidden' );
// Next, hide the anchor responsible for allowing the user to select an image
container_media
.prev()
.hide();
// Display the anchor for the removing the featured image
container_media
.next()
.show();
// Store the image's information into the meta data fields
container_data.find('.hd-src').val( json.url );
container_data.find('.hd-title').val( json.title );
// /container_data.find('.hd-alt').val( json.alt );
/*$( '#slider-' + num + '-src' ).val( json.url );
$( '#slider-' + num + '-title' ).val( json.title );
$( '#slider-' + num + '-alt' ).val( json.alt );*/
});
// Now display the actual file_frame
file_frame.open();
} | function renderMediaUploader($, container_media ) {
//'use strict';
var file_frame, image_data, json;
var container_data = container_media.next().next();
//var container_media = $this.parent().next();
/**
* If an instance of file_frame already exists, then we can open it
* rather than creating a new instance.
*/
if ( undefined !== file_frame ) {
file_frame.open();
return;
}
/**
* If we're this far, then an instance does not exist, so we need to
* create our own.
*
* Here, use the wp.media library to define the settings of the Media
* Uploader. We're opting to use the 'post' frame which is a template
* defined in WordPress core and are initializing the file frame
* with the 'insert' state.
*
* We're also not allowing the user to select more than one image.
*/
file_frame = wp.media.frames.file_frame = wp.media({
frame: 'post',
state: 'insert',
multiple: false
});
/**
* Setup an event handler for what to do when an image has been
* selected.
*
* Since we're using the 'view' state when initializing
* the file_frame, we need to make sure that the handler is attached
* to the insert event.
*/
file_frame.on( 'insert', function() {
// Read the JSON data returned from the Media Uploader
json = file_frame.state().get( 'selection' ).first().toJSON();
// First, make sure that we have the URL of an image to display
if ( 0 > $.trim( json.url.length ) ) {
return;
}
var name = json.url.split('/');
name = name[ name.length - 1 ];
// After that, set the properties of the image and display it
container_media
.children( 'p' )
.find('.name')
.text( name )
.parent()
.show()
.parent()
.removeClass( 'hidden' );
container_media
.children( 'img' )
.attr( 'src', json.url )
//.attr( 'alt', json.caption )
//.attr( 'title', json.title )
.show()
.parent()
.removeClass( 'hidden' );
// Next, hide the anchor responsible for allowing the user to select an image
container_media
.prev()
.hide();
// Display the anchor for the removing the featured image
container_media
.next()
.show();
// Store the image's information into the meta data fields
container_data.find('.hd-src').val( json.url );
container_data.find('.hd-title').val( json.title );
// /container_data.find('.hd-alt').val( json.alt );
/*$( '#slider-' + num + '-src' ).val( json.url );
$( '#slider-' + num + '-title' ).val( json.title );
$( '#slider-' + num + '-alt' ).val( json.alt );*/
});
// Now display the actual file_frame
file_frame.open();
} |
JavaScript | function renderFeaturedImage( $ ) {
/* If a thumbnail URL has been associated with this image
* Then we need to display the image and the reset link.
*/
$('.media-info').each(function(){
if ( '' !== $.trim( $(this).find('.hd-src').val()) ) {
$(this).prev().prev().removeClass('hidden');
$(this).prev().prev().prev().hide();
$(this).prev().removeClass('hidden');
}
});
} | function renderFeaturedImage( $ ) {
/* If a thumbnail URL has been associated with this image
* Then we need to display the image and the reset link.
*/
$('.media-info').each(function(){
if ( '' !== $.trim( $(this).find('.hd-src').val()) ) {
$(this).prev().prev().removeClass('hidden');
$(this).prev().prev().prev().hide();
$(this).prev().removeClass('hidden');
}
});
} |
JavaScript | function updateTask(taskId, task) {
return TaskModel.update({
_id: taskId
}, {
name: task.name,
description: task.description,
dueDate: task.dueDate,
completed: task.completed
});
} | function updateTask(taskId, task) {
return TaskModel.update({
_id: taskId
}, {
name: task.name,
description: task.description,
dueDate: task.dueDate,
completed: task.completed
});
} |
JavaScript | function intersect_safe(a, b)
{
var ai=0, bi=0;
var result = [];
while( ai < a.length && bi < b.length )
{
if (a[ai] < b[bi] ){ ai++; }
else if (a[ai] > b[bi] ){ bi++; }
else /* they're equal */
{
result.push(a[ai]);
ai++;
bi++;
}
}
return result;
} | function intersect_safe(a, b)
{
var ai=0, bi=0;
var result = [];
while( ai < a.length && bi < b.length )
{
if (a[ai] < b[bi] ){ ai++; }
else if (a[ai] > b[bi] ){ bi++; }
else /* they're equal */
{
result.push(a[ai]);
ai++;
bi++;
}
}
return result;
} |
JavaScript | function solution(S) {
// write your code in JavaScript (Node.js 8.9.4)
let finalStr = '';
if (S[0] > S[1]) {
finalStr += S[1]
}
else {
finalStr += S[0];
}
for (let i = 1; i < S.length; i++) {
if (S[i-1] <= S[i] && finalStr[0] <= S[i]) {
finalStr += S[i];
}
else {
continue;
}
}
return S.length - finalStr.length;
} | function solution(S) {
// write your code in JavaScript (Node.js 8.9.4)
let finalStr = '';
if (S[0] > S[1]) {
finalStr += S[1]
}
else {
finalStr += S[0];
}
for (let i = 1; i < S.length; i++) {
if (S[i-1] <= S[i] && finalStr[0] <= S[i]) {
finalStr += S[i];
}
else {
continue;
}
}
return S.length - finalStr.length;
} |
JavaScript | function indexerFirstForm() {
// Press the add button
addButton.click();
setTimeout(indexerSecondForm, timeout);
} | function indexerFirstForm() {
// Press the add button
addButton.click();
setTimeout(indexerSecondForm, timeout);
} |
JavaScript | function indexerSecondForm() {
// torznab custom
var customTorznabButton = $(".add-thingy:contains('Torznab')").parent().find(".btn.x-custom");
customTorznabButton.click()
setTimeout(indexerThirdForm, timeout);
} | function indexerSecondForm() {
// torznab custom
var customTorznabButton = $(".add-thingy:contains('Torznab')").parent().find(".btn.x-custom");
customTorznabButton.click()
setTimeout(indexerThirdForm, timeout);
} |
JavaScript | function indexerThirdForm(indexer) {
// Remove next indexer from the array and save it
var indexer = indexers.shift();
var name = indexer[0];
var url = indexer[1];
// Get all form inputs and put the data in them
var formInputs = $(".indexer-modal .form-control");
formInputs[0].value = name;
formInputs[1].value = url;
formInputs[3].value = apikey;
formInputs[4].value = categories;
formInputs[5].value = animeCategories;
// Trigger the change event
$(formInputs).change();
setTimeout(indexerSave, timeout);
} | function indexerThirdForm(indexer) {
// Remove next indexer from the array and save it
var indexer = indexers.shift();
var name = indexer[0];
var url = indexer[1];
// Get all form inputs and put the data in them
var formInputs = $(".indexer-modal .form-control");
formInputs[0].value = name;
formInputs[1].value = url;
formInputs[3].value = apikey;
formInputs[4].value = categories;
formInputs[5].value = animeCategories;
// Trigger the change event
$(formInputs).change();
setTimeout(indexerSave, timeout);
} |
JavaScript | function headerStyle() {
if ($(".main-header").length) {
var windowpos = $(window).scrollTop();
if (windowpos >= 250) {
$(".main-header").addClass("fixed-header");
$(".scroll-to-top").fadeIn(300);
} else {
$(".main-header").removeClass("fixed-header");
$(".scroll-to-top").fadeOut(300);
}
}
} | function headerStyle() {
if ($(".main-header").length) {
var windowpos = $(window).scrollTop();
if (windowpos >= 250) {
$(".main-header").addClass("fixed-header");
$(".scroll-to-top").fadeIn(300);
} else {
$(".main-header").removeClass("fixed-header");
$(".scroll-to-top").fadeOut(300);
}
}
} |
JavaScript | static pingServer(server) {
console.log(`pingServer server: ${server}`);
const status = fetch(server).then(response => {
if (response.ok) { return true; }
}).catch(error => {
console.error('Error while pinging server: ', error);
return false;
});
return status;
} | static pingServer(server) {
console.log(`pingServer server: ${server}`);
const status = fetch(server).then(response => {
if (response.ok) { return true; }
}).catch(error => {
console.error('Error while pinging server: ', error);
return false;
});
return status;
} |
JavaScript | static routeRestaurants(callback) {
DBHelper.getRestaurants()
.then((restaurants) => {
if (restaurants.length) {
console.log('Displaying restaurants from database', restaurants);
if (callback) callback(null, restaurants);
return restaurants;
} else {
console.log('Displaying restaurants from server');
DBHelper.populateRestaurants(callback);
}
});
} | static routeRestaurants(callback) {
DBHelper.getRestaurants()
.then((restaurants) => {
if (restaurants.length) {
console.log('Displaying restaurants from database', restaurants);
if (callback) callback(null, restaurants);
return restaurants;
} else {
console.log('Displaying restaurants from server');
DBHelper.populateRestaurants(callback);
}
});
} |
JavaScript | static populateRestaurants(callback) {
console.log('Opening database within populateRestaurants()');
const dbPromise = DBHelper.openDatabase();
dbPromise.then(function(db) {
DBHelper.serveRestaurants((error, restaurants) => {
const tx = db.transaction('restaurants', 'readwrite');
const restaurantStore = tx.objectStore('restaurants');
return Promise.all(
restaurants.map(function(restaurant) {
console.log('Adding restaurant: ', restaurant);
return restaurantStore.put(restaurant);
}
)).then(function(result) {
console.log('Result from populateRestaurants: ', result);
callback(null, restaurants);
})
.then(function() {
console.log('All restaurants added to database successfully!');
})
.catch(function(error) {
tx.abort();
console.log(error);
});
})
});
} | static populateRestaurants(callback) {
console.log('Opening database within populateRestaurants()');
const dbPromise = DBHelper.openDatabase();
dbPromise.then(function(db) {
DBHelper.serveRestaurants((error, restaurants) => {
const tx = db.transaction('restaurants', 'readwrite');
const restaurantStore = tx.objectStore('restaurants');
return Promise.all(
restaurants.map(function(restaurant) {
console.log('Adding restaurant: ', restaurant);
return restaurantStore.put(restaurant);
}
)).then(function(result) {
console.log('Result from populateRestaurants: ', result);
callback(null, restaurants);
})
.then(function() {
console.log('All restaurants added to database successfully!');
})
.catch(function(error) {
tx.abort();
console.log(error);
});
})
});
} |
JavaScript | static populateReviews(callback, id) {
console.log('Opening database within populateReviews()');
const dbPromise = DBHelper.openDatabase();
dbPromise.then(function(db) {
DBHelper.serveReviews((error, reviews) => {
const tx = db.transaction('reviews', 'readwrite');
const reviewStore = tx.objectStore('reviews');
return Promise.all(
reviews.map(function(review) {
console.log('Adding review: ', review);
return reviewStore.put(review);
}
)).then(function(result) {
console.log('Result from populateReviews: ', result);
callback(null, reviews);
})
.then(function() {
console.log('All reviews added successfully!');
})
.catch(function(error) {
tx.abort();
console.log(error);
});
}, id)
});
} | static populateReviews(callback, id) {
console.log('Opening database within populateReviews()');
const dbPromise = DBHelper.openDatabase();
dbPromise.then(function(db) {
DBHelper.serveReviews((error, reviews) => {
const tx = db.transaction('reviews', 'readwrite');
const reviewStore = tx.objectStore('reviews');
return Promise.all(
reviews.map(function(review) {
console.log('Adding review: ', review);
return reviewStore.put(review);
}
)).then(function(result) {
console.log('Result from populateReviews: ', result);
callback(null, reviews);
})
.then(function() {
console.log('All reviews added successfully!');
})
.catch(function(error) {
tx.abort();
console.log(error);
});
}, id)
});
} |
JavaScript | static postFavorite(restaurant, isFavorite) {
// add favorite to IDB
const dbPromise = DBHelper.openDatabase();
dbPromise.then(function(db) {
const tx = db.transaction('restaurants', 'readwrite');
const restaurantStore = tx.objectStore('restaurants');
restaurant.is_favorite = isFavorite;
restaurant.updatedAt = Date.now();
restaurantStore.put(restaurant);
return tx.complete;
})
.then(() => console.log(`Favorited ${restaurant.name}, id ${restaurant.id}`))
.catch((databaseError) => console.log(`Failed to favorite ${restaurant.name}, id ${restaurant.id} with error ${databaseError}`));
// checks if server online
const isOnline = DBHelper.pingServer(DBHelper.RESTAURANTS_URL);
// if server online, PUT favorite
if (isOnline) {
const init = {
method: 'PUT',
headers: {
"Content-Type": "application/json; charset=utf-8"
},
body: JSON.stringify(restaurant)
};
console.log(`PUT URL: ${DBHelper.RESTAURANTS_URL}/${restaurant.id}/?is_favorite=${isFavorite}`);
return fetch(`${DBHelper.RESTAURANTS_URL}/${restaurant.id}/?is_favorite=${isFavorite}`, init).then(serverResponse => serverResponse.json())
.then(serverResponseJSON => {
console.log(`Response from postFavorite: ${serverResponseJSON}`);
return serverResponseJSON;
}).catch((serverError) => console.log(`Failed to post favorite with error: ${serverError}`));
}
else {
// if server offline, notify user and post when online
console.log('Server connection has been lost. Your post will be submitted when the server comes online.');
}
} | static postFavorite(restaurant, isFavorite) {
// add favorite to IDB
const dbPromise = DBHelper.openDatabase();
dbPromise.then(function(db) {
const tx = db.transaction('restaurants', 'readwrite');
const restaurantStore = tx.objectStore('restaurants');
restaurant.is_favorite = isFavorite;
restaurant.updatedAt = Date.now();
restaurantStore.put(restaurant);
return tx.complete;
})
.then(() => console.log(`Favorited ${restaurant.name}, id ${restaurant.id}`))
.catch((databaseError) => console.log(`Failed to favorite ${restaurant.name}, id ${restaurant.id} with error ${databaseError}`));
// checks if server online
const isOnline = DBHelper.pingServer(DBHelper.RESTAURANTS_URL);
// if server online, PUT favorite
if (isOnline) {
const init = {
method: 'PUT',
headers: {
"Content-Type": "application/json; charset=utf-8"
},
body: JSON.stringify(restaurant)
};
console.log(`PUT URL: ${DBHelper.RESTAURANTS_URL}/${restaurant.id}/?is_favorite=${isFavorite}`);
return fetch(`${DBHelper.RESTAURANTS_URL}/${restaurant.id}/?is_favorite=${isFavorite}`, init).then(serverResponse => serverResponse.json())
.then(serverResponseJSON => {
console.log(`Response from postFavorite: ${serverResponseJSON}`);
return serverResponseJSON;
}).catch((serverError) => console.log(`Failed to post favorite with error: ${serverError}`));
}
else {
// if server offline, notify user and post when online
console.log('Server connection has been lost. Your post will be submitted when the server comes online.');
}
} |
JavaScript | static postReview(review) {
// checks if server online
DBHelper.pingServer(DBHelper.REVIEWS_URL)
.then(isOnline => {
// if server online, PUT favorite
if (isOnline) {
const init = {
method: 'POST',
headers: {
"Content-Type": "application/json; charset=utf-8"
},
body: JSON.stringify(review)
};
console.log(`POST URL: ${DBHelper.REVIEWS_URL}`);
return fetch(`${DBHelper.REVIEWS_URL}`, init)
.then(serverResponse => {
console.log(`Response from postReview: ${serverResponse}`);
return serverResponse;
}).catch(serverError => console.log(`Failed to post review ${review.name} with error: ${serverError}`));
} else {
// if app/server offline, save review to tempReviews object store, **TODO: notify user,** and post when app/server online
console.log('Opening tempReviews database within postReview()');
const dbPromise = DBHelper.openDatabase();
dbPromise.then(function(db) {
const tx = db.transaction('tempReviews', 'readwrite');
const tempReviewsStore = tx.objectStore('tempReviews');
console.log(`Putting review ${review} into tempReviews object store`);
tempReviewsStore.put(review);
console.log(`Have put review ${review} into tempReviews object store`);
console.log('tx.complete:', tx.complete);
return tx.complete;
}).then((review) => console.log(`Saved review ${review} to tempReviews`))
.catch((databaseError) => {
console.log(`Failed to save review ${review} to database with error ${databaseError}`);
alert('The server appears to be offline. Your review will be submitted when the server comes online.');
}
)};
}).catch(pingError => console.log('Failed to ping server with error', pingError));
} | static postReview(review) {
// checks if server online
DBHelper.pingServer(DBHelper.REVIEWS_URL)
.then(isOnline => {
// if server online, PUT favorite
if (isOnline) {
const init = {
method: 'POST',
headers: {
"Content-Type": "application/json; charset=utf-8"
},
body: JSON.stringify(review)
};
console.log(`POST URL: ${DBHelper.REVIEWS_URL}`);
return fetch(`${DBHelper.REVIEWS_URL}`, init)
.then(serverResponse => {
console.log(`Response from postReview: ${serverResponse}`);
return serverResponse;
}).catch(serverError => console.log(`Failed to post review ${review.name} with error: ${serverError}`));
} else {
// if app/server offline, save review to tempReviews object store, **TODO: notify user,** and post when app/server online
console.log('Opening tempReviews database within postReview()');
const dbPromise = DBHelper.openDatabase();
dbPromise.then(function(db) {
const tx = db.transaction('tempReviews', 'readwrite');
const tempReviewsStore = tx.objectStore('tempReviews');
console.log(`Putting review ${review} into tempReviews object store`);
tempReviewsStore.put(review);
console.log(`Have put review ${review} into tempReviews object store`);
console.log('tx.complete:', tx.complete);
return tx.complete;
}).then((review) => console.log(`Saved review ${review} to tempReviews`))
.catch((databaseError) => {
console.log(`Failed to save review ${review} to database with error ${databaseError}`);
alert('The server appears to be offline. Your review will be submitted when the server comes online.');
}
)};
}).catch(pingError => console.log('Failed to ping server with error', pingError));
} |
JavaScript | static postTempReviews() {
DBHelper.pingServer(DBHelper.REVIEWS_URL)
.then(isOnline => {
if (isOnline) {
const dbPromise = DBHelper.openDatabase();
// post temporary reviews to server
return dbPromise.then(function(db) {
const tx = db.transaction('tempReviews', 'readonly');
const tempReviewsStore = tx.objectStore('tempReviews');
return tempReviewsStore.getAll()
.then(reviews => {
console.log('Got reviews from tempReviews: ', reviews);
const init = {
method: 'POST',
headers: {
"Content-Type": "application/json;charset=utf-8"
},
body: JSON.stringify(reviews)
};
console.log(`POST URL for postTempReviews: ${DBHelper.REVIEWS_URL}`);
return fetch(`${DBHelper.REVIEWS_URL}`, init)
.then(serverResponse => {
console.log(`Temp reviews submitted successfully! ${serverResponse}`);
return serverResponse;
}).then(() => {
// clear tempReviews object store
return dbPromise.then(db => {
const tx = db.transaction('tempReviews', 'readwrite');
tx.objectStore('tempReviews').clear();
return tx.complete;
});
}).catch(serverError => console.error(`Error posting temp reviews to server with error ${serverError}`));
}).catch(dbError => console.error(`Error getting temp reviews from tempReviews object store`));
});
} else {
console.log(`The server appears to be offline. Your reviews will be submitted when it comes back online.`);
return;
}
}).catch(pingError => {
console.log(`The server appears to be offline. Your reviews will be submitted when it comes back online.`);
});
} | static postTempReviews() {
DBHelper.pingServer(DBHelper.REVIEWS_URL)
.then(isOnline => {
if (isOnline) {
const dbPromise = DBHelper.openDatabase();
// post temporary reviews to server
return dbPromise.then(function(db) {
const tx = db.transaction('tempReviews', 'readonly');
const tempReviewsStore = tx.objectStore('tempReviews');
return tempReviewsStore.getAll()
.then(reviews => {
console.log('Got reviews from tempReviews: ', reviews);
const init = {
method: 'POST',
headers: {
"Content-Type": "application/json;charset=utf-8"
},
body: JSON.stringify(reviews)
};
console.log(`POST URL for postTempReviews: ${DBHelper.REVIEWS_URL}`);
return fetch(`${DBHelper.REVIEWS_URL}`, init)
.then(serverResponse => {
console.log(`Temp reviews submitted successfully! ${serverResponse}`);
return serverResponse;
}).then(() => {
// clear tempReviews object store
return dbPromise.then(db => {
const tx = db.transaction('tempReviews', 'readwrite');
tx.objectStore('tempReviews').clear();
return tx.complete;
});
}).catch(serverError => console.error(`Error posting temp reviews to server with error ${serverError}`));
}).catch(dbError => console.error(`Error getting temp reviews from tempReviews object store`));
});
} else {
console.log(`The server appears to be offline. Your reviews will be submitted when it comes back online.`);
return;
}
}).catch(pingError => {
console.log(`The server appears to be offline. Your reviews will be submitted when it comes back online.`);
});
} |
JavaScript | static pushFavorites() {
DBHelper.pingServer(DBHelper.RESTAURANTS_URL)
.then(isOnline => {
if (isOnline) {
const dbPromise = DBHelper.openDatabase();
return dbPromise.then(db => {
const tx = db.transaction('restaurants', 'readonly');
const restaurantStore = tx.objectStore('restaurants');
return restaurantStore.getAll()
.then(restaurants => {
console.log(`Restaurants from pushFavorites getAll(): ${restaurants}`);
let updatedRestaurants = restaurants.filter(r => {
console.log(`restaurant id: ${r.id} updated at: ${r.updatedAt} created at: ${r.createdAt}`);
// check createdAt date format; if ISO string, convert to milliseconds and return all restaurants where updatedAt > createdAt
if (typeof r.updatedAt === 'string') {
const updatedAtISO = new Date(r.updatedAt);
const updatedAtMilliseconds = updatedAtISO.getTime();
return updatedAtMilliseconds > r.createdAt;
}
// if createdAt date in milliseconds, return restaurants where updatedAt > createdAt
return r.updatedAt > r.createdAt;
});
console.log(`updatedRestaurants: ${updatedRestaurants}`);
updatedRestaurants.forEach(restaurant => {
const init = {
method: 'PUT',
headers: {
"Content-Type": "application/json;charset=utf-8"
},
body: JSON.stringify(restaurant)
};
return fetch(`${DBHelper.RESTAURANTS_URL}/${restaurant.id}`, init)
.then(serverResponse => {
if (serverResponse.ok) {
console.log(`Offline favorites pushed successfully!`);
} else {
console.log(`Failed to push offline favorites to server with error ${serverResponse}`);
}
}).catch(serverError => console.log(`Failed to PUT offline favorites with error ${serverError}`));
});
}).catch(dbError => console.log(`Failed to getAll() updated restaurants from restaurants object store with error ${dbError}`));
}).catch(dbOpenError => console.log(`Failed to open database within pushFavorites() with error ${dbOpenError}`));
} else {
console.log(`The server appears to be offline. Offline favorites will be submitted when the server comes back online.`);
}
}).catch(pingError => console.log(`Error pinging server within pushFavorites() with error ${pingError}`));
} | static pushFavorites() {
DBHelper.pingServer(DBHelper.RESTAURANTS_URL)
.then(isOnline => {
if (isOnline) {
const dbPromise = DBHelper.openDatabase();
return dbPromise.then(db => {
const tx = db.transaction('restaurants', 'readonly');
const restaurantStore = tx.objectStore('restaurants');
return restaurantStore.getAll()
.then(restaurants => {
console.log(`Restaurants from pushFavorites getAll(): ${restaurants}`);
let updatedRestaurants = restaurants.filter(r => {
console.log(`restaurant id: ${r.id} updated at: ${r.updatedAt} created at: ${r.createdAt}`);
// check createdAt date format; if ISO string, convert to milliseconds and return all restaurants where updatedAt > createdAt
if (typeof r.updatedAt === 'string') {
const updatedAtISO = new Date(r.updatedAt);
const updatedAtMilliseconds = updatedAtISO.getTime();
return updatedAtMilliseconds > r.createdAt;
}
// if createdAt date in milliseconds, return restaurants where updatedAt > createdAt
return r.updatedAt > r.createdAt;
});
console.log(`updatedRestaurants: ${updatedRestaurants}`);
updatedRestaurants.forEach(restaurant => {
const init = {
method: 'PUT',
headers: {
"Content-Type": "application/json;charset=utf-8"
},
body: JSON.stringify(restaurant)
};
return fetch(`${DBHelper.RESTAURANTS_URL}/${restaurant.id}`, init)
.then(serverResponse => {
if (serverResponse.ok) {
console.log(`Offline favorites pushed successfully!`);
} else {
console.log(`Failed to push offline favorites to server with error ${serverResponse}`);
}
}).catch(serverError => console.log(`Failed to PUT offline favorites with error ${serverError}`));
});
}).catch(dbError => console.log(`Failed to getAll() updated restaurants from restaurants object store with error ${dbError}`));
}).catch(dbOpenError => console.log(`Failed to open database within pushFavorites() with error ${dbOpenError}`));
} else {
console.log(`The server appears to be offline. Offline favorites will be submitted when the server comes back online.`);
}
}).catch(pingError => console.log(`Error pinging server within pushFavorites() with error ${pingError}`));
} |
JavaScript | function mapEncoGitToLink(encoder, git_commit) {
if (encoder == "git://git.videolan.org/x264.git")
return "https://git.videolan.org/?p=x264.git;a=commit;h=" + git_commit
if (encoder == "https://chromium.googlesource.com/webm/libvpx")
return encoder + "/+/" + git_commit
return encoder + '/commit/' + git_commit;
} | function mapEncoGitToLink(encoder, git_commit) {
if (encoder == "git://git.videolan.org/x264.git")
return "https://git.videolan.org/?p=x264.git;a=commit;h=" + git_commit
if (encoder == "https://chromium.googlesource.com/webm/libvpx")
return encoder + "/+/" + git_commit
return encoder + '/commit/' + git_commit;
} |
JavaScript | function generateGraph(data) {
//http://stackoverflow.com/questions/9150964/identifying-hovered-point-with-flot
//Create a table of tuple (x,y) for each encoder metric
var xyEncoder = new Object();
var encoderLabel = new Object();
for (var i = 0; i < data.length; i++) {
var entry = data[i];
var date = new Date(entry.date*thousand); //Unix format To standard one;
// Each key creates a new line in the graph
var key = [entry.git_url, entry.git_commit, entry.source];
// Create a corresponding label for this graph line
if (!(key in xyEncoder)) {
xyEncoder[key] = [];
// How the label is displayed
hTitle = $('<td/>', {'class': legendTitleClass})
.text('{0}: '.format(entry.source));
hGitA = $('<a/>', {
'href': mapEncoGitToLink(entry.git_url, entry.git_commit),
'title': entry.git_commit,
}).text(mapEncoder[entry.git_url]);
hInfo = $('<td/>', {'class': legendInfoClass})
.append(hGitA)
.append(' ({0})'.format(formatDate(date)))
encoderLabel[key] = hTitle[0].outerHTML + hInfo[0].outerHTML;
}
// Each point is bitrate-value pair
xyEncoder[key].push([entry.bitrate, entry.value]);
}
// Create the dataset for the plot
var dataset = [];
for (key in xyEncoder) {
var entry = xyEncoder[key];
dataset.push({
"label": encoderLabel[key],
"data": entry.sort(function(a, b){return a[0]-b[0]}),
});
}
var precisionAxis = 3;
//https://github.com/flot/flot/blob/master/API.md
//Plot
var plot = $.plot(placeholderDiv, dataset, {
series: {
lines: {
show: true
},
points: {
show: true
}
},
grid: {
hoverable: true,
},
xaxis: {
tickFormatter: function (v) {
return v.toFixed(precisionAxis) + " kb/s";
}
},
yaxis: {
tickFormatter: function (v) {
return v.toFixed(precisionAxis) + " dB";
}
},
legend: {
container: legendDiv
}
});
//Design of the tooltip
$("<div id=" + tooltip + "></div>").css({
position: "absolute",
display: "none",
border: "4px solid #fdd",
padding: "2px",
color: "#fff",
"background-color": "#000",
opacity: 0.80
}).appendTo("body");
//Event when the mouse go over a point
var mouseover = false;
var timeout;
$(placeholderDiv).bind("plothover", function (event, pos, item) {
//Show information
if (item) {
clearTimeout(timeout);
var x = item.datapoint[0].toFixed(2),
y = item.datapoint[1].toFixed(2);
$(tooltipDiv).html("<p><b>" + item.series.label + "</b></p><p>" + x + "kb/s" + " at " + y + "dB</p>")
.css({
top: item.pageY + 5,
left: item.pageX + 5,
"border-color": item.series.color
})
.fadeIn(200);
} else {
clearTimeout(timeout);
timeout = setTimeout(function () {
$(tooltipDiv).fadeOut(200);
}, 750);
}
});
$(tooltipDiv).bind("mouseenter", function (event) {
clearTimeout(timeout);
});
// Modify position of the legend
$(legendDiv).css("position", "relative");
$(legendDiv).css("top", -$(placeholderDiv).height());
$(legendDiv).css("right", -$(placeholderDiv).width() * 0.97);
$(legendDiv).css("background-color", "rgb(255, 255, 255, 0.85)");
$(graphDiv).hide();
$(graphDiv).toggle("explode");
//$( "#toggle" ).toggle( "explode" );
//$('#placeholder1 > div.legend > div, #placeholder1 > div.legend > table').css("right", -parseInt($('#placeholder1 > div.legend > div').css("width")));
//$('#placeholder1 > div.legend > table').css("background-image", "url(getPhoto.jpg)").css("background-size", "contain");
} | function generateGraph(data) {
//http://stackoverflow.com/questions/9150964/identifying-hovered-point-with-flot
//Create a table of tuple (x,y) for each encoder metric
var xyEncoder = new Object();
var encoderLabel = new Object();
for (var i = 0; i < data.length; i++) {
var entry = data[i];
var date = new Date(entry.date*thousand); //Unix format To standard one;
// Each key creates a new line in the graph
var key = [entry.git_url, entry.git_commit, entry.source];
// Create a corresponding label for this graph line
if (!(key in xyEncoder)) {
xyEncoder[key] = [];
// How the label is displayed
hTitle = $('<td/>', {'class': legendTitleClass})
.text('{0}: '.format(entry.source));
hGitA = $('<a/>', {
'href': mapEncoGitToLink(entry.git_url, entry.git_commit),
'title': entry.git_commit,
}).text(mapEncoder[entry.git_url]);
hInfo = $('<td/>', {'class': legendInfoClass})
.append(hGitA)
.append(' ({0})'.format(formatDate(date)))
encoderLabel[key] = hTitle[0].outerHTML + hInfo[0].outerHTML;
}
// Each point is bitrate-value pair
xyEncoder[key].push([entry.bitrate, entry.value]);
}
// Create the dataset for the plot
var dataset = [];
for (key in xyEncoder) {
var entry = xyEncoder[key];
dataset.push({
"label": encoderLabel[key],
"data": entry.sort(function(a, b){return a[0]-b[0]}),
});
}
var precisionAxis = 3;
//https://github.com/flot/flot/blob/master/API.md
//Plot
var plot = $.plot(placeholderDiv, dataset, {
series: {
lines: {
show: true
},
points: {
show: true
}
},
grid: {
hoverable: true,
},
xaxis: {
tickFormatter: function (v) {
return v.toFixed(precisionAxis) + " kb/s";
}
},
yaxis: {
tickFormatter: function (v) {
return v.toFixed(precisionAxis) + " dB";
}
},
legend: {
container: legendDiv
}
});
//Design of the tooltip
$("<div id=" + tooltip + "></div>").css({
position: "absolute",
display: "none",
border: "4px solid #fdd",
padding: "2px",
color: "#fff",
"background-color": "#000",
opacity: 0.80
}).appendTo("body");
//Event when the mouse go over a point
var mouseover = false;
var timeout;
$(placeholderDiv).bind("plothover", function (event, pos, item) {
//Show information
if (item) {
clearTimeout(timeout);
var x = item.datapoint[0].toFixed(2),
y = item.datapoint[1].toFixed(2);
$(tooltipDiv).html("<p><b>" + item.series.label + "</b></p><p>" + x + "kb/s" + " at " + y + "dB</p>")
.css({
top: item.pageY + 5,
left: item.pageX + 5,
"border-color": item.series.color
})
.fadeIn(200);
} else {
clearTimeout(timeout);
timeout = setTimeout(function () {
$(tooltipDiv).fadeOut(200);
}, 750);
}
});
$(tooltipDiv).bind("mouseenter", function (event) {
clearTimeout(timeout);
});
// Modify position of the legend
$(legendDiv).css("position", "relative");
$(legendDiv).css("top", -$(placeholderDiv).height());
$(legendDiv).css("right", -$(placeholderDiv).width() * 0.97);
$(legendDiv).css("background-color", "rgb(255, 255, 255, 0.85)");
$(graphDiv).hide();
$(graphDiv).toggle("explode");
//$( "#toggle" ).toggle( "explode" );
//$('#placeholder1 > div.legend > div, #placeholder1 > div.legend > table').css("right", -parseInt($('#placeholder1 > div.legend > div').css("width")));
//$('#placeholder1 > div.legend > table').css("background-image", "url(getPhoto.jpg)").css("background-size", "contain");
} |
JavaScript | function p_heartbeat() {
var uri = pushletURI + '?p_event=hb';
p_debug(flag, 'p_heartbeat');
_sendControlURI(uri);
} | function p_heartbeat() {
var uri = pushletURI + '?p_event=hb';
p_debug(flag, 'p_heartbeat');
_sendControlURI(uri);
} |
JavaScript | function p_subscribe(subject, label) {
var uri = pushletURI + '?p_event=subscribe&p_subject=' + subject;
if (label) {
uri = uri + '&p_label=' + label;
}
p_debug(flag, 'p_subscribe', 'subscribe uri=' + uri);
_sendControlURI(uri);
} | function p_subscribe(subject, label) {
var uri = pushletURI + '?p_event=subscribe&p_subject=' + subject;
if (label) {
uri = uri + '&p_label=' + label;
}
p_debug(flag, 'p_subscribe', 'subscribe uri=' + uri);
_sendControlURI(uri);
} |
JavaScript | function Map() {
// Data members
this.index = 0;
this.map = new Array();
// Function members
this.get = MapGet;
this.put = MapPut;
this.toString = MapToString;
this.toTable = MapToTable;
} | function Map() {
// Data members
this.index = 0;
this.map = new Array();
// Function members
this.get = MapGet;
this.put = MapPut;
this.toString = MapToString;
this.toTable = MapToTable;
} |
JavaScript | function PushletEvent(args) {
// Member variable setup; the Map stores the N/V pairs
this.map = new Map();
// Member function setup
this.getSubject = PushletEventGetSubject
this.getEvent = PushletEventGetEvent
this.put = PushletEventPut
this.get = PushletEventGet
this.toString = PushletEventToString
this.toTable = PushletEventToTable
// Put the arguments' name/value pairs in the Map
for (var i = 0; i < args.length; i++) {
this.put(args[i], args[++i]);
}
} | function PushletEvent(args) {
// Member variable setup; the Map stores the N/V pairs
this.map = new Map();
// Member function setup
this.getSubject = PushletEventGetSubject
this.getEvent = PushletEventGetEvent
this.put = PushletEventPut
this.get = PushletEventGet
this.toString = PushletEventToString
this.toTable = PushletEventToTable
// Put the arguments' name/value pairs in the Map
for (var i = 0; i < args.length; i++) {
this.put(args[i], args[++i]);
}
} |
JavaScript | function p_debug(flag, label, value) {
// Only print if the flag is set
if (!flag) {
return;
}
var funcName = "none";
// Fetch JS function name if any
if (p_debug.caller) {
funcName = p_debug.caller.toString()
funcName = funcName.substring(9, funcName.indexOf(")") + 1)
}
// Create message
var msg = "-" + funcName + ": " + label + "=" + value
// Add optional timestamp
var now = new Date()
var elapsed = now - timestamp
if (elapsed < 10000) {
msg += " (" + elapsed + " msec)"
}
timestamp = now
// Show.
if ((debugWindow == null) || debugWindow.closed) {
debugWindow = window.open("", "p_debugWin", "toolbar=no,scrollbars=yes,resizable=yes,width=600,height=400");
}
// Add message to current list
messages[messagesIndex++] = msg
// Write doc header
debugWindow.document.writeln('<html><head><title>Pushlet Debug Window</title></head><body bgcolor=#DDDDDD>');
// Write the messages
for (var i = 0; i < messagesIndex; i++) {
debugWindow.document.writeln('<pre>' + i + ': ' + messages[i] + '</pre>');
}
// Write doc footer and close
debugWindow.document.writeln('</body></html>');
debugWindow.document.close();
debugWindow.focus();
} | function p_debug(flag, label, value) {
// Only print if the flag is set
if (!flag) {
return;
}
var funcName = "none";
// Fetch JS function name if any
if (p_debug.caller) {
funcName = p_debug.caller.toString()
funcName = funcName.substring(9, funcName.indexOf(")") + 1)
}
// Create message
var msg = "-" + funcName + ": " + label + "=" + value
// Add optional timestamp
var now = new Date()
var elapsed = now - timestamp
if (elapsed < 10000) {
msg += " (" + elapsed + " msec)"
}
timestamp = now
// Show.
if ((debugWindow == null) || debugWindow.closed) {
debugWindow = window.open("", "p_debugWin", "toolbar=no,scrollbars=yes,resizable=yes,width=600,height=400");
}
// Add message to current list
messages[messagesIndex++] = msg
// Write doc header
debugWindow.document.writeln('<html><head><title>Pushlet Debug Window</title></head><body bgcolor=#DDDDDD>');
// Write the messages
for (var i = 0; i < messagesIndex; i++) {
debugWindow.document.writeln('<pre>' + i + ': ' + messages[i] + '</pre>');
}
// Write doc footer and close
debugWindow.document.writeln('</body></html>');
debugWindow.document.close();
debugWindow.focus();
} |
JavaScript | function Ok()
{
if ( GetE('txtUrl').value.length == 0 )
{
window.parent.SetSelectedTab( 'Info' ) ;
GetE('txtUrl').focus() ;
alert( oEditor.FCKLang.DlgAlertUrl ) ;
return false ;
}
oEditor.FCKUndo.SaveUndoStep() ;
if ( !oEmbed )
{
oEmbed = FCK.EditorDocument.createElement( cFckMediaElementName ) ;
oFakeImage = null ;
}
UpdateEmbed( oEmbed ) ;
if ( !oFakeImage )
{
oFakeImage = oEditor.FCKDocumentProcessor_CreateFakeImage( 'FCK__Media_'+oEmbed.attributes[cMediaTypeAttrName].value, oEmbed ) ;
oFakeImage.setAttribute( '_fckmedia', 'true', 0 ) ;
oFakeImage = FCK.InsertElement( oFakeImage ) ;
}else {
oFakeImage.className = 'FCK__Media_'+oEmbed.attributes[cMediaTypeAttrName].value;
}
oEditor.FCKMediaProcessor.RefreshView( oFakeImage, oEmbed ) ;
return true ;
} | function Ok()
{
if ( GetE('txtUrl').value.length == 0 )
{
window.parent.SetSelectedTab( 'Info' ) ;
GetE('txtUrl').focus() ;
alert( oEditor.FCKLang.DlgAlertUrl ) ;
return false ;
}
oEditor.FCKUndo.SaveUndoStep() ;
if ( !oEmbed )
{
oEmbed = FCK.EditorDocument.createElement( cFckMediaElementName ) ;
oFakeImage = null ;
}
UpdateEmbed( oEmbed ) ;
if ( !oFakeImage )
{
oFakeImage = oEditor.FCKDocumentProcessor_CreateFakeImage( 'FCK__Media_'+oEmbed.attributes[cMediaTypeAttrName].value, oEmbed ) ;
oFakeImage.setAttribute( '_fckmedia', 'true', 0 ) ;
oFakeImage = FCK.InsertElement( oFakeImage ) ;
}else {
oFakeImage.className = 'FCK__Media_'+oEmbed.attributes[cMediaTypeAttrName].value;
}
oEditor.FCKMediaProcessor.RefreshView( oFakeImage, oEmbed ) ;
return true ;
} |
JavaScript | retrieveTileImage(dc, tile, suppressRedraw){
if (this.currentRetrievals.indexOf(tile.imagePath) < 0) {
if (this.absentResourceList.isResourceAbsent(tile.imagePath)) {
return;
}
const imagePath = tile.imagePath,
cache = dc.gpuResourceCache,
layer = this;
const tileWidth = 256;
const tileHeight = 256;
const result = document.createElement('canvas');
result.height = tileHeight;
result.width = tileWidth;
const ctx = result.getContext('2d');
ctx.rect(0, 0, tileWidth, tileHeight);
ctx.fillStyle = this._color || utils.stringToColours(tile.tileKey, 1, {hue: [20,220], saturation: [35,65], lightness: [40,60]});
ctx.fill();
const texture = layer.createTexture(dc, tile, result);
layer.removeFromCurrentRetrievals(imagePath);
if (texture) {
cache.putResource(imagePath, texture, texture.size);
layer.currentTilesInvalid = true;
layer.absentResourceList.unmarkResourceAbsent(imagePath);
if (!suppressRedraw) {
// Send an event to request a redraw.
const e = document.createEvent('Event');
e.initEvent(WorldWind.REDRAW_EVENT_TYPE, true, true);
window.dispatchEvent(e);
}
}
}
} | retrieveTileImage(dc, tile, suppressRedraw){
if (this.currentRetrievals.indexOf(tile.imagePath) < 0) {
if (this.absentResourceList.isResourceAbsent(tile.imagePath)) {
return;
}
const imagePath = tile.imagePath,
cache = dc.gpuResourceCache,
layer = this;
const tileWidth = 256;
const tileHeight = 256;
const result = document.createElement('canvas');
result.height = tileHeight;
result.width = tileWidth;
const ctx = result.getContext('2d');
ctx.rect(0, 0, tileWidth, tileHeight);
ctx.fillStyle = this._color || utils.stringToColours(tile.tileKey, 1, {hue: [20,220], saturation: [35,65], lightness: [40,60]});
ctx.fill();
const texture = layer.createTexture(dc, tile, result);
layer.removeFromCurrentRetrievals(imagePath);
if (texture) {
cache.putResource(imagePath, texture, texture.size);
layer.currentTilesInvalid = true;
layer.absentResourceList.unmarkResourceAbsent(imagePath);
if (!suppressRedraw) {
// Send an event to request a redraw.
const e = document.createEvent('Event');
e.initEvent(WorldWind.REDRAW_EVENT_TYPE, true, true);
window.dispatchEvent(e);
}
}
}
} |
JavaScript | _renderablesAddCallback() {
this.forEachRenderable((renderable) => {
//collection of functions that will be called after add renderable
const onAddActions = [
this._setFilter.bind(this),
this._setSelected.bind(this),
this._setHover.bind(this),
() => true
];
onAddActions.forEach(a => a(renderable));
return true;
});
} | _renderablesAddCallback() {
this.forEachRenderable((renderable) => {
//collection of functions that will be called after add renderable
const onAddActions = [
this._setFilter.bind(this),
this._setSelected.bind(this),
this._setHover.bind(this),
() => true
];
onAddActions.forEach(a => a(renderable));
return true;
});
} |
JavaScript | forEachRenderable(modificator) {
if(typeof modificator === 'function') {
const styleFunctionExists = typeof this.styleFunction === 'function';
const renderables = this.renderables;
const renderablesCount = this.renderables.length;
for (let i = 0; i < renderablesCount; i++) {
const renderable = renderables[i];
const shouldRerender = modificator(renderable);
if(shouldRerender && styleFunctionExists) {
this.computeAttribution(renderable);
}
}
}
} | forEachRenderable(modificator) {
if(typeof modificator === 'function') {
const styleFunctionExists = typeof this.styleFunction === 'function';
const renderables = this.renderables;
const renderablesCount = this.renderables.length;
for (let i = 0; i < renderablesCount; i++) {
const renderable = renderables[i];
const shouldRerender = modificator(renderable);
if(shouldRerender && styleFunctionExists) {
this.computeAttribution(renderable);
}
}
}
} |
JavaScript | function onCreateNode({node, boundActionCreators, getNode}) {
const { createNodeField } = boundActionCreators;
let slug;
switch (node.internal.type) {
case `MarkdownRemark`:
const fileNode = getNode(node.parent);
const [basePath, name] = fileNode.relativePath.split('/');
slug = `/${basePath}/${name}/`;
break;
}
if (slug) {
createNodeField({node, name: `slug`, value: slug});
}
} | function onCreateNode({node, boundActionCreators, getNode}) {
const { createNodeField } = boundActionCreators;
let slug;
switch (node.internal.type) {
case `MarkdownRemark`:
const fileNode = getNode(node.parent);
const [basePath, name] = fileNode.relativePath.split('/');
slug = `/${basePath}/${name}/`;
break;
}
if (slug) {
createNodeField({node, name: `slug`, value: slug});
}
} |
JavaScript | sendMessage(message, callback) {
const { type } = message;
if (type !== messageType.SYNC && !this.isReady) {
// Do not send a message unless the iFrame is ready to receive.
console.warn("iFrame not initialized to send a message", message);
return;
}
let { messageId } = message;
if (!messageId) {
// Initiating a new message
messageId = IFrameManager.createMessageId(this.instanceId);
if (callback) {
// Keep track of the callback
this.callbacks[messageId] = callback;
}
}
const newMessage = Object.assign({}, message, {
messageId
});
this.logDebugMessage("postMessage", type, message);
this.destinationWindow.postMessage(newMessage, this.destinationHost);
} | sendMessage(message, callback) {
const { type } = message;
if (type !== messageType.SYNC && !this.isReady) {
// Do not send a message unless the iFrame is ready to receive.
console.warn("iFrame not initialized to send a message", message);
return;
}
let { messageId } = message;
if (!messageId) {
// Initiating a new message
messageId = IFrameManager.createMessageId(this.instanceId);
if (callback) {
// Keep track of the callback
this.callbacks[messageId] = callback;
}
}
const newMessage = Object.assign({}, message, {
messageId
});
this.logDebugMessage("postMessage", type, message);
this.destinationWindow.postMessage(newMessage, this.destinationHost);
} |
JavaScript | function Rooms () {
const router = useRouter()
console.log(router.query)
return (
<div className = "h-screen ">
<Navbar/>
<Meetings room={router.query} peerlist={router.query.peerlist}/>
</div>
)
} | function Rooms () {
const router = useRouter()
console.log(router.query)
return (
<div className = "h-screen ">
<Navbar/>
<Meetings room={router.query} peerlist={router.query.peerlist}/>
</div>
)
} |
JavaScript | function Rooms () {
const router = useRouter()
console.log(router.query);
return (
<Frame>
<div className = "h-screen flex items-center justify-center bg-gray-800">
<div className=" p-24 px-40">
<div className="flex flex-col justify-center items-center max-w-7xl mx-auto py-16 text-left px-4 sm:py-24 sm:px-6">
<h2 className="text-4xl font-extrabold text-red-800 sm:text-xl sm:tracking-tight lg:text-6xl">
{router.query.msg}
</h2>
<img className="max-w-2xl p-12" src="https://cdn.pixabay.com/photo/2020/12/25/20/51/bunny-5860131_1280.png"/>
</div>
</div>
</div>
</Frame>
)
} | function Rooms () {
const router = useRouter()
console.log(router.query);
return (
<Frame>
<div className = "h-screen flex items-center justify-center bg-gray-800">
<div className=" p-24 px-40">
<div className="flex flex-col justify-center items-center max-w-7xl mx-auto py-16 text-left px-4 sm:py-24 sm:px-6">
<h2 className="text-4xl font-extrabold text-red-800 sm:text-xl sm:tracking-tight lg:text-6xl">
{router.query.msg}
</h2>
<img className="max-w-2xl p-12" src="https://cdn.pixabay.com/photo/2020/12/25/20/51/bunny-5860131_1280.png"/>
</div>
</div>
</div>
</Frame>
)
} |
JavaScript | function Component() {
const router = useRouter()
const [suggestions, setSuggestions] = useState([]);
const [search, setSearch] = useState("");
const fetcher = url => fetch(url).then(r => r.json())
const { data, error } = useSWR('/api/rooms', fetcher)
const [isOpen, setIsOpen] = useState(false)
const ref = useRef(null);
const clickListener = useCallback(
(e) => {
if (ref.current && !ref.current.contains(event.target)) {
setIsOpen(false)
}
},
[ref.current],
)
useEffect(() => {
// attach the listeners on component mount.
document.addEventListener('click', clickListener)
// detach the listeners on component unmount.
return () => {
document.removeEventListener('click', clickListener)
}
}, [])
const change = (evt) => {
let value = evt.target.value;
setSearch(value);
fetch('http://localhost:3000/api/search?q='+encodeURIComponent(value))
.then(r => {if (r.ok) {return r.json()} }).then(data => {if(data) setSuggestions(data)});
if (value === "1") {
setSuggestions([]);
}
setIsOpen(true);
};
const submit = () => {
setSearch("");
};
const click = (suggestion) => {
setSearch("");
};
return (
<div ref = {ref} className = " max-w-7xl flex items-center lg:w-full justify-center z-50 font-medium text-blue-400 xl:px-6">
<div className = "relative inline-block w-full">
<input onKeyDown={(e)=> {if(e.key==='Enter') router.push(`/course_search_results?q=${search}`)}}
className = "relative w-full truncate border-2 border-gray-300 bg-white h-10 px-5 pr-16 rounded-lg text-sm focus:outline-none"
placeholder = "Search by course code..." value={search} onChange={change} onClick={() => setIsOpen(!isOpen)}
/>
<Transition
show={isOpen}
enter="transition ease-out duration-100"
enterFrom="transform opacity-0 scale-95"
enterTo="transform opacity-100 scale-100"
leave="transition ease-in duration-75"
leaveFrom="transform opacity-100 scale-100"
leaveTo="transform opacity-0 scale-95"
>
{ suggestions===undefined || suggestions.length == 0 ?
<a href = '/course_search_results'>
<p className="w-full absolute bg-white p-2 hover:bg-red-50 truncate text-left border-2 border-grey rounded-md"><u>Explore all courses</u>
</p></a>
:
<div className = "bg-white items-left z-50 absolute w-full overflow-hidden truncate border-2 border-grey rounded-md">
{suggestions.slice(0, 7).map(i =>(
<a key={i.coursecode} href = {`coursepage?course=${i.coursecode}`}>
<p className=" hover:bg-red-100 p-2 truncate text-left">{i.coursecode} {i.coursename}</p>
</a>))}
<a href = '/course_search_results'><p className="p-2 hover:bg-red-50 truncate text-left"><u>Explore all courses</u>
</p></a>
</div> }
</Transition>
</div>
</div>
);
} | function Component() {
const router = useRouter()
const [suggestions, setSuggestions] = useState([]);
const [search, setSearch] = useState("");
const fetcher = url => fetch(url).then(r => r.json())
const { data, error } = useSWR('/api/rooms', fetcher)
const [isOpen, setIsOpen] = useState(false)
const ref = useRef(null);
const clickListener = useCallback(
(e) => {
if (ref.current && !ref.current.contains(event.target)) {
setIsOpen(false)
}
},
[ref.current],
)
useEffect(() => {
// attach the listeners on component mount.
document.addEventListener('click', clickListener)
// detach the listeners on component unmount.
return () => {
document.removeEventListener('click', clickListener)
}
}, [])
const change = (evt) => {
let value = evt.target.value;
setSearch(value);
fetch('http://localhost:3000/api/search?q='+encodeURIComponent(value))
.then(r => {if (r.ok) {return r.json()} }).then(data => {if(data) setSuggestions(data)});
if (value === "1") {
setSuggestions([]);
}
setIsOpen(true);
};
const submit = () => {
setSearch("");
};
const click = (suggestion) => {
setSearch("");
};
return (
<div ref = {ref} className = " max-w-7xl flex items-center lg:w-full justify-center z-50 font-medium text-blue-400 xl:px-6">
<div className = "relative inline-block w-full">
<input onKeyDown={(e)=> {if(e.key==='Enter') router.push(`/course_search_results?q=${search}`)}}
className = "relative w-full truncate border-2 border-gray-300 bg-white h-10 px-5 pr-16 rounded-lg text-sm focus:outline-none"
placeholder = "Search by course code..." value={search} onChange={change} onClick={() => setIsOpen(!isOpen)}
/>
<Transition
show={isOpen}
enter="transition ease-out duration-100"
enterFrom="transform opacity-0 scale-95"
enterTo="transform opacity-100 scale-100"
leave="transition ease-in duration-75"
leaveFrom="transform opacity-100 scale-100"
leaveTo="transform opacity-0 scale-95"
>
{ suggestions===undefined || suggestions.length == 0 ?
<a href = '/course_search_results'>
<p className="w-full absolute bg-white p-2 hover:bg-red-50 truncate text-left border-2 border-grey rounded-md"><u>Explore all courses</u>
</p></a>
:
<div className = "bg-white items-left z-50 absolute w-full overflow-hidden truncate border-2 border-grey rounded-md">
{suggestions.slice(0, 7).map(i =>(
<a key={i.coursecode} href = {`coursepage?course=${i.coursecode}`}>
<p className=" hover:bg-red-100 p-2 truncate text-left">{i.coursecode} {i.coursename}</p>
</a>))}
<a href = '/course_search_results'><p className="p-2 hover:bg-red-50 truncate text-left"><u>Explore all courses</u>
</p></a>
</div> }
</Transition>
</div>
</div>
);
} |
JavaScript | function updateHeight(){
setTimeout(function () {
var bodyHeight = $("#main-content").outerHeight(true);
console.log("body height: " + bodyHeight);
$("#side-bar").css("min-height", bodyHeight);
$("#main-body").css("height", bodyHeight);
console.log("main height: " + bodyHeight);
}, 100);
} | function updateHeight(){
setTimeout(function () {
var bodyHeight = $("#main-content").outerHeight(true);
console.log("body height: " + bodyHeight);
$("#side-bar").css("min-height", bodyHeight);
$("#main-body").css("height", bodyHeight);
console.log("main height: " + bodyHeight);
}, 100);
} |
JavaScript | render() {
let myConfig = {
type: "line",
"globals": {
"font-family": "Roboto",
'background-color': this.props.theme.palette.type === 'dark' ? "#424242" : "white",
'color': this.props.theme.palette.type === 'dark' ? "white" : "#424242",
},
"utc": true,
"title": {
"text": "CPU Usage by Container",
"font-size": "24px",
"adjust-layout": true
},
"plotarea": {
"margin": "dynamic 45 60 dynamic",
'width':'100%',
'height': '100%'
},
'plot': {
'animation': {
'effect': "ANIMATION_SLIDE_LEFT",
'width':'100%',
'height': '100%'
},
},
"legend": {
"layout": "float",
"background-color": "none",
"border-width": 0,
"shadow": 0,
"align": "center",
"adjust-layout": true,
"toggle-action": "remove",
"item": {
"padding": 7,
"marginRight": 17,
"cursor": "hand"
}
},
"scale-x": {
item: {
'font-color': this.props.theme.palette.type === 'dark' ? "white" : "#424242",
},
"min-value": this.findMin(),
"max-value": this.findMax(),
"step": "hour",
"line-color": this.props.theme.palette.type === 'dark' ? "white" : "#424242",
zooming: true,
"shadow": 0,
"transform": {
"type": "date",
"all": "%D, %d %M<br />%h:%i %A",
"guide": {
"visible": false
},
"item": {
"visible": false
}
},
"label": {
"visible": false
},
"minor-ticks": 0
},
"scale-y": {
"line-color": this.props.theme.palette.type === 'dark' ? "white" : "#424242",
"shadow": 0,
"progression": "log",
"log-base": Math.E,
"plotarea": {
"adjust-layout": true,
},
"guide": {
"line-style": "dashed"
},
"item": {
'font-color': this.props.theme.palette.type === 'dark' ? "white": "#424242",
'font-weight': 'normal',
},
"label": {
"text": "CPU Usage",
'font-size': '14px',
"font-color": this.props.theme.palette.type === 'dark' ? "white" : "#424242",
},
"minor-ticks": 0,
"thousands-separator": ","
},
"crosshair-x": {
"line-color": "#efefef",
"plot-label": {
"border-radius": "5px",
"border-width": "1px",
"border-color": this.props.theme.palette.type === 'dark' ? "white" : "#424242",
"padding": "10px",
"font-weight": "bold"
},
"scale-label": {
"font-color": this.props.theme.palette.type === 'dark' ? "white" : "#424242",
"background-color": this.props.theme.palette.type === 'dark' ? "white" : "#424242",
"border-radius": "5px"
}
},
"tooltip": {
"visible": false
},
"plot": {
"highlight": true,
"tooltip-text": "%t views: %v<br>%k",
"shadow": 0,
"line-width": "2px",
"marker": {
"visible":false,
},
"highlight-state": {
"line-width": 3
},
"animation": {
"effect": 1,
"sequence": 2,
"speed": 10,
}
},
"series": this.stateFormat()
}
return (
<div>
<ZingChart data={myConfig} complete={this.chartDone} />
</div>
);
} | render() {
let myConfig = {
type: "line",
"globals": {
"font-family": "Roboto",
'background-color': this.props.theme.palette.type === 'dark' ? "#424242" : "white",
'color': this.props.theme.palette.type === 'dark' ? "white" : "#424242",
},
"utc": true,
"title": {
"text": "CPU Usage by Container",
"font-size": "24px",
"adjust-layout": true
},
"plotarea": {
"margin": "dynamic 45 60 dynamic",
'width':'100%',
'height': '100%'
},
'plot': {
'animation': {
'effect': "ANIMATION_SLIDE_LEFT",
'width':'100%',
'height': '100%'
},
},
"legend": {
"layout": "float",
"background-color": "none",
"border-width": 0,
"shadow": 0,
"align": "center",
"adjust-layout": true,
"toggle-action": "remove",
"item": {
"padding": 7,
"marginRight": 17,
"cursor": "hand"
}
},
"scale-x": {
item: {
'font-color': this.props.theme.palette.type === 'dark' ? "white" : "#424242",
},
"min-value": this.findMin(),
"max-value": this.findMax(),
"step": "hour",
"line-color": this.props.theme.palette.type === 'dark' ? "white" : "#424242",
zooming: true,
"shadow": 0,
"transform": {
"type": "date",
"all": "%D, %d %M<br />%h:%i %A",
"guide": {
"visible": false
},
"item": {
"visible": false
}
},
"label": {
"visible": false
},
"minor-ticks": 0
},
"scale-y": {
"line-color": this.props.theme.palette.type === 'dark' ? "white" : "#424242",
"shadow": 0,
"progression": "log",
"log-base": Math.E,
"plotarea": {
"adjust-layout": true,
},
"guide": {
"line-style": "dashed"
},
"item": {
'font-color': this.props.theme.palette.type === 'dark' ? "white": "#424242",
'font-weight': 'normal',
},
"label": {
"text": "CPU Usage",
'font-size': '14px',
"font-color": this.props.theme.palette.type === 'dark' ? "white" : "#424242",
},
"minor-ticks": 0,
"thousands-separator": ","
},
"crosshair-x": {
"line-color": "#efefef",
"plot-label": {
"border-radius": "5px",
"border-width": "1px",
"border-color": this.props.theme.palette.type === 'dark' ? "white" : "#424242",
"padding": "10px",
"font-weight": "bold"
},
"scale-label": {
"font-color": this.props.theme.palette.type === 'dark' ? "white" : "#424242",
"background-color": this.props.theme.palette.type === 'dark' ? "white" : "#424242",
"border-radius": "5px"
}
},
"tooltip": {
"visible": false
},
"plot": {
"highlight": true,
"tooltip-text": "%t views: %v<br>%k",
"shadow": 0,
"line-width": "2px",
"marker": {
"visible":false,
},
"highlight-state": {
"line-width": 3
},
"animation": {
"effect": 1,
"sequence": 2,
"speed": 10,
}
},
"series": this.stateFormat()
}
return (
<div>
<ZingChart data={myConfig} complete={this.chartDone} />
</div>
);
} |
JavaScript | render() {
let myConfig = {
type: "line",
"globals": {
"font-family": "Roboto",
"background-color": this.props.theme.palette.type === 'dark' ? '#424242': 'white',
"color": this.props.theme.palette.type === 'dark' ? 'white': '#424242',
},
"utc": true,
"title": {
"text": "Kubernetes Node Memory Usage",
"font-size": "24px",
"adjust-layout": true,
},
"plotarea": {
"margin": "dynamic 45 60 dynamic",
'width':'100%',
'height': '100%'
},
"plot": {
"animation": {
"effect": "ANIMATION_SLIDE_LEFT",
'width':'100%',
'height': '100%'
},
},
"legend": {
"layout": "float",
"background-color": "none",
"border-width": 0,
"shadow": 0,
"align": "center",
"adjust-layout": true,
"toggle-action": "remove",
"item": {
"padding": 7,
"marginRight": 17,
"cursor": "hand"
}
},
"scale-x": {
//rendering zingchart with config, change in theme depending on the current theme type
"line-color": this.props.theme.palette.type === 'dark' ? 'white': '#424242',
"item": {
'font-color': this.props.theme.palette.type === 'dark' ? "white": "#424242",
'font-weight': 'normal',
},
"min-value": this.findMin(),
"max-value": this.findMax(),
"step": "hour",
zooming: true,
"shadow": 0,
"transform": {
"type": "date",
"all": "%D, %d %M<br />%h:%i %A",
"guide": {
"visible": false
},
"item": {
"visible": false
}
},
"label": {
"visible": false
},
"minor-ticks": 0
},
"scale-y": {
"line-color": this.props.theme.palette.type === 'dark' ? 'white': '#424242',
"item": {
'font-color': this.props.theme.palette.type === 'dark' ? "white": "#424242",
'font-weight': 'normal',
},
"shadow": 0,
"progression": "log",
"log-base": Math.E,
"plotarea": {
"adjust-layout": true,
},
"guide": {
"line-style": "dashed"
},
"label": {
"text": "Memory Usage",
'font-color': this.props.theme.palette.type === 'dark' ? "white": "#424242",
"font-size": "14px"
},
"minor-ticks": 0,
"thousands-separator": ","
},
"crosshair-x": {
"line-color": this.props.theme.palette.type === 'dark' ? 'white': '#424242',
"plot-label": {
"border-radius": "5px",
"border-width": "1px",
"border-color": this.props.theme.palette.type === 'dark' ? '#white': '#424242',
"padding": "10px",
"font-weight": "bold"
},
"scale-label": {
"font-color": "#000",
"background-color": this.props.theme.palette.type === 'dark' ? '#white': '#424242',
"border-radius": "5px"
}
},
"tooltip": {
"visible": false
},
"plot": {
"highlight": true,
"tooltip-text": "%t views: %v<br>%k",
"shadow": 0,
"line-width": "2px",
"marker": {
"visible": false,
},
"highlight-state": {
"line-width": 3
},
"animation": {
"effect": 1,
"sequence": 2,
"speed": 10,
}
},
"series": this.stateFormat()
}
return (
<div>
<ZingChart data={myConfig} complete={this.chartDone} />
</div>
);
} | render() {
let myConfig = {
type: "line",
"globals": {
"font-family": "Roboto",
"background-color": this.props.theme.palette.type === 'dark' ? '#424242': 'white',
"color": this.props.theme.palette.type === 'dark' ? 'white': '#424242',
},
"utc": true,
"title": {
"text": "Kubernetes Node Memory Usage",
"font-size": "24px",
"adjust-layout": true,
},
"plotarea": {
"margin": "dynamic 45 60 dynamic",
'width':'100%',
'height': '100%'
},
"plot": {
"animation": {
"effect": "ANIMATION_SLIDE_LEFT",
'width':'100%',
'height': '100%'
},
},
"legend": {
"layout": "float",
"background-color": "none",
"border-width": 0,
"shadow": 0,
"align": "center",
"adjust-layout": true,
"toggle-action": "remove",
"item": {
"padding": 7,
"marginRight": 17,
"cursor": "hand"
}
},
"scale-x": {
//rendering zingchart with config, change in theme depending on the current theme type
"line-color": this.props.theme.palette.type === 'dark' ? 'white': '#424242',
"item": {
'font-color': this.props.theme.palette.type === 'dark' ? "white": "#424242",
'font-weight': 'normal',
},
"min-value": this.findMin(),
"max-value": this.findMax(),
"step": "hour",
zooming: true,
"shadow": 0,
"transform": {
"type": "date",
"all": "%D, %d %M<br />%h:%i %A",
"guide": {
"visible": false
},
"item": {
"visible": false
}
},
"label": {
"visible": false
},
"minor-ticks": 0
},
"scale-y": {
"line-color": this.props.theme.palette.type === 'dark' ? 'white': '#424242',
"item": {
'font-color': this.props.theme.palette.type === 'dark' ? "white": "#424242",
'font-weight': 'normal',
},
"shadow": 0,
"progression": "log",
"log-base": Math.E,
"plotarea": {
"adjust-layout": true,
},
"guide": {
"line-style": "dashed"
},
"label": {
"text": "Memory Usage",
'font-color': this.props.theme.palette.type === 'dark' ? "white": "#424242",
"font-size": "14px"
},
"minor-ticks": 0,
"thousands-separator": ","
},
"crosshair-x": {
"line-color": this.props.theme.palette.type === 'dark' ? 'white': '#424242',
"plot-label": {
"border-radius": "5px",
"border-width": "1px",
"border-color": this.props.theme.palette.type === 'dark' ? '#white': '#424242',
"padding": "10px",
"font-weight": "bold"
},
"scale-label": {
"font-color": "#000",
"background-color": this.props.theme.palette.type === 'dark' ? '#white': '#424242',
"border-radius": "5px"
}
},
"tooltip": {
"visible": false
},
"plot": {
"highlight": true,
"tooltip-text": "%t views: %v<br>%k",
"shadow": 0,
"line-width": "2px",
"marker": {
"visible": false,
},
"highlight-state": {
"line-width": 3
},
"animation": {
"effect": 1,
"sequence": 2,
"speed": 10,
}
},
"series": this.stateFormat()
}
return (
<div>
<ZingChart data={myConfig} complete={this.chartDone} />
</div>
);
} |
JavaScript | function closingTagExists(cm, tagName, pos, state, newTag) {
if (!CodeMirror.scanForClosingTag)
return false;
var end = Math.min(cm.lastLine() + 1, pos.line + 500);
var nextClose = CodeMirror.scanForClosingTag(cm, pos, null, end);
if (!nextClose || nextClose.tag != tagName)
return false;
var cx = state.context;
// If the immediate wrapping context contains onCx instances of
// the same tag, a closing tag only exists if there are at least
// that many closing tags of that type following.
for (var onCx = newTag ? 1 : 0; cx && cx.tagName == tagName; cx = cx.prev)
++onCx;
pos = nextClose.to;
for (var i = 1; i < onCx; i++) {
var next = CodeMirror.scanForClosingTag(cm, pos, null, end);
if (!next || next.tag != tagName)
return false;
pos = next.to;
}
return true;
} | function closingTagExists(cm, tagName, pos, state, newTag) {
if (!CodeMirror.scanForClosingTag)
return false;
var end = Math.min(cm.lastLine() + 1, pos.line + 500);
var nextClose = CodeMirror.scanForClosingTag(cm, pos, null, end);
if (!nextClose || nextClose.tag != tagName)
return false;
var cx = state.context;
// If the immediate wrapping context contains onCx instances of
// the same tag, a closing tag only exists if there are at least
// that many closing tags of that type following.
for (var onCx = newTag ? 1 : 0; cx && cx.tagName == tagName; cx = cx.prev)
++onCx;
pos = nextClose.to;
for (var i = 1; i < onCx; i++) {
var next = CodeMirror.scanForClosingTag(cm, pos, null, end);
if (!next || next.tag != tagName)
return false;
pos = next.to;
}
return true;
} |
JavaScript | function generate(answers) {
const projectDir = `${currentDirectory}/${answers.name}`;
// Creating the project dir
console.log(`\nGenerating project in ${chalk.blue(projectDir)}\n`);
fs.mkdirSync(projectDir);
// Getting the templates
const templateRoot = `${__dirname}/../templates`
const templateDir = `${templateRoot}/${answers.tsEnabled ? 'ts' : 'js'}`;
helpers.recurCpTemplates(currentDirectory, templateDir, answers.name);
helpers.recurCpTemplates(currentDirectory, `${templateRoot}/common`, answers.name);
const config = helpers.setOptions(answers);
// Webpack config
console.log('\t* Copying files...');
const webpackTemplateFile = `webpack.${answers.tsEnabled ? 'ts' : 'js'}.${answers.isLibrary ? 'umd' : 'nolib'}`;
helpers.moveFile(`${templateRoot}/other/${webpackTemplateFile}`, `${projectDir}/webpack.config.js`);
// Create tsconfig file
if (answers.tsEnabled) {
helpers.moveFile(`${templateRoot}/other/tsconfig.json`, `${projectDir}/tsconfig.json`);
}
// Create travis file
if (answers.travisEnabled) {
helpers.moveFile(`${templateRoot}/other/.travis.yml`, `${projectDir}/travis.yml`);
}
// Config files for jest
if (answers.testFwk === 'jest') {
if (answers.tsEnabled) {
helpers.moveFile(`${templateRoot}/other/jest.config.js`, `${projectDir}/jest.config.js`);
}
if (answers.isLibrary) {
helpers.moveFile(`${templateRoot}/other/.babelrc`, `${projectDir}/.babelrc`);
}
}
// Replacing user values
console.log('\t* Replacing user values...');
const buildCmd = webpackTemplateFile ? 'webpack --config webpack.config.js' : 'echo \"Error: no build specified\" && exit 1'
const mainFile = answers.tsEnabled ? 'index.ts' : 'index.js';
// Webpack config
rif.sync({
files: `${projectDir}/webpack.config.js`,
from: /project-name-replace/g,
to: answers.name
});
// Package.json
rif.sync({
files: `${projectDir}/package.json`,
from: [
/project-name-replace/g,
/project-desc-replace/g,
/author-replace/g,
/test-command-replace/g,
/build-command-replace/g,
/main-file-replace/g
],
to: [
answers.name,
answers.description,
answers.author,
config.testCmd,
buildCmd,
mainFile
]
});
console.log('\t* Installing dependencies...');
helpers.installDependencies(config.devDependencies, projectDir)
.then(() => {
console.log('\t Dependencies installed');
helpers.quickstart(answers.name);
});
} | function generate(answers) {
const projectDir = `${currentDirectory}/${answers.name}`;
// Creating the project dir
console.log(`\nGenerating project in ${chalk.blue(projectDir)}\n`);
fs.mkdirSync(projectDir);
// Getting the templates
const templateRoot = `${__dirname}/../templates`
const templateDir = `${templateRoot}/${answers.tsEnabled ? 'ts' : 'js'}`;
helpers.recurCpTemplates(currentDirectory, templateDir, answers.name);
helpers.recurCpTemplates(currentDirectory, `${templateRoot}/common`, answers.name);
const config = helpers.setOptions(answers);
// Webpack config
console.log('\t* Copying files...');
const webpackTemplateFile = `webpack.${answers.tsEnabled ? 'ts' : 'js'}.${answers.isLibrary ? 'umd' : 'nolib'}`;
helpers.moveFile(`${templateRoot}/other/${webpackTemplateFile}`, `${projectDir}/webpack.config.js`);
// Create tsconfig file
if (answers.tsEnabled) {
helpers.moveFile(`${templateRoot}/other/tsconfig.json`, `${projectDir}/tsconfig.json`);
}
// Create travis file
if (answers.travisEnabled) {
helpers.moveFile(`${templateRoot}/other/.travis.yml`, `${projectDir}/travis.yml`);
}
// Config files for jest
if (answers.testFwk === 'jest') {
if (answers.tsEnabled) {
helpers.moveFile(`${templateRoot}/other/jest.config.js`, `${projectDir}/jest.config.js`);
}
if (answers.isLibrary) {
helpers.moveFile(`${templateRoot}/other/.babelrc`, `${projectDir}/.babelrc`);
}
}
// Replacing user values
console.log('\t* Replacing user values...');
const buildCmd = webpackTemplateFile ? 'webpack --config webpack.config.js' : 'echo \"Error: no build specified\" && exit 1'
const mainFile = answers.tsEnabled ? 'index.ts' : 'index.js';
// Webpack config
rif.sync({
files: `${projectDir}/webpack.config.js`,
from: /project-name-replace/g,
to: answers.name
});
// Package.json
rif.sync({
files: `${projectDir}/package.json`,
from: [
/project-name-replace/g,
/project-desc-replace/g,
/author-replace/g,
/test-command-replace/g,
/build-command-replace/g,
/main-file-replace/g
],
to: [
answers.name,
answers.description,
answers.author,
config.testCmd,
buildCmd,
mainFile
]
});
console.log('\t* Installing dependencies...');
helpers.installDependencies(config.devDependencies, projectDir)
.then(() => {
console.log('\t Dependencies installed');
helpers.quickstart(answers.name);
});
} |
JavaScript | function run(test) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, runTest_1.default(test.path, test.globalConfig, test.config, exports.getResolver(test.config, test.serializableModuleMap))];
case 1: return [2 /*return*/, _a.sent()];
}
});
});
} | function run(test) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, runTest_1.default(test.path, test.globalConfig, test.config, exports.getResolver(test.config, test.serializableModuleMap))];
case 1: return [2 /*return*/, _a.sent()];
}
});
});
} |
JavaScript | @computed get activeImages () {
const length = this.movies.length;
const current = this.currentIndex;
return [
getBackwardIndex(current, length, 2),
getBackwardIndex(current, length, 1),
current,
getForwardIndex(current, length, 1),
getForwardIndex(current, length, 2)
]
} | @computed get activeImages () {
const length = this.movies.length;
const current = this.currentIndex;
return [
getBackwardIndex(current, length, 2),
getBackwardIndex(current, length, 1),
current,
getForwardIndex(current, length, 1),
getForwardIndex(current, length, 2)
]
} |
JavaScript | @computed get textNavList () {
if ( this.movies.length > 0 ) {
const base = this.basicTextList;
const current = this.currentIndex;
let list = textListMaker (base, current);
return addNavDO (list);
}
return [];
} | @computed get textNavList () {
if ( this.movies.length > 0 ) {
const base = this.basicTextList;
const current = this.currentIndex;
let list = textListMaker (base, current);
return addNavDO (list);
}
return [];
} |
JavaScript | function allXHRsComplete() {
var src;
var xhr;
for (src in currentXHRs) {
xhr = currentXHRs[src];
if (xhr.readyState !== 4) return false;
}
for (src in previousXHRs) {
xhr = currentXHRs[src];
if (xhr.readyState !== 4) return false;
}
if (data.options.show_annotations && annotationsXHR && annotationsXHR.readyState !== 4) return false;
return true;
} | function allXHRsComplete() {
var src;
var xhr;
for (src in currentXHRs) {
xhr = currentXHRs[src];
if (xhr.readyState !== 4) return false;
}
for (src in previousXHRs) {
xhr = currentXHRs[src];
if (xhr.readyState !== 4) return false;
}
if (data.options.show_annotations && annotationsXHR && annotationsXHR.readyState !== 4) return false;
return true;
} |
JavaScript | function anyXHRFailures(xhrObject) {
var xhr;
var src;
for (src in xhrObject) {
xhr = xhrObject[src];
if (xhr.readyState === 4 && xhr.status !== 200) {
return true;
}
}
return false;
} | function anyXHRFailures(xhrObject) {
var xhr;
var src;
for (src in xhrObject) {
xhr = xhrObject[src];
if (xhr.readyState === 4 && xhr.status !== 200) {
return true;
}
}
return false;
} |
JavaScript | function makeNoDataArray(size) {
var arr = [];
for (var i = 0; i < size; i++) {
arr.push(NO_DATA_FOR_TIMESTAMP);
}
return arr;
} | function makeNoDataArray(size) {
var arr = [];
for (var i = 0; i < size; i++) {
arr.push(NO_DATA_FOR_TIMESTAMP);
}
return arr;
} |
JavaScript | function objectToDataList(dataObject) {
var massagedData = [];
for (var t in dataObject) {
massagedData.push({
't': t,
'v': dataObject[t]
});
}
return massagedData;
} | function objectToDataList(dataObject) {
var massagedData = [];
for (var t in dataObject) {
massagedData.push({
't': t,
'v': dataObject[t]
});
}
return massagedData;
} |
JavaScript | function injectButton() {
// Style element to add custom icon
const dashboardButtonIcon = `
<style type='text/css'>
.icon-tdem:before {
content: '\\F400';
}
</style>
`;
// Button to inject to sidebar nav
const dashboardButton = `
<a class='tdem-dashboard-btn js-header-action link-clean cf app-nav-link padding-h--10 with-nav-border-t' data-title='TDEM Dashboard'>
<div class='obj-left margin-l--2'>
<i class='icon icon-tdem icon-medium'></i>
</div>
<div class='nbfc padding-ts hide-condensed txt-size--16'>Extension Manager</div>
</a>
`;
try {
// Inject custom icon style element in head tag
$('head').append(domify(dashboardButtonIcon));
// Inject button at top of sidebar nav footer items
$('nav.app-navigator').prepend(domify(dashboardButton));
// Open dashbord when button is clicked
$('.tdem-dashboard-btn').bind('click', (e) => {
e.preventDefault();
window.open(getExtensionUrl('options/options.html'));
});
} catch (e) {
throw new Error(`⚠️ Error Injecting TDEM | ${e}`);
}
} | function injectButton() {
// Style element to add custom icon
const dashboardButtonIcon = `
<style type='text/css'>
.icon-tdem:before {
content: '\\F400';
}
</style>
`;
// Button to inject to sidebar nav
const dashboardButton = `
<a class='tdem-dashboard-btn js-header-action link-clean cf app-nav-link padding-h--10 with-nav-border-t' data-title='TDEM Dashboard'>
<div class='obj-left margin-l--2'>
<i class='icon icon-tdem icon-medium'></i>
</div>
<div class='nbfc padding-ts hide-condensed txt-size--16'>Extension Manager</div>
</a>
`;
try {
// Inject custom icon style element in head tag
$('head').append(domify(dashboardButtonIcon));
// Inject button at top of sidebar nav footer items
$('nav.app-navigator').prepend(domify(dashboardButton));
// Open dashbord when button is clicked
$('.tdem-dashboard-btn').bind('click', (e) => {
e.preventDefault();
window.open(getExtensionUrl('options/options.html'));
});
} catch (e) {
throw new Error(`⚠️ Error Injecting TDEM | ${e}`);
}
} |
JavaScript | function shoh(id)
{
if (document.getElementById) { // DOM3 = IE5, NS6
if (document.getElementById(id).style.display == "none"){
document.getElementById(id).style.display = 'block';
filter(("img"+id),'imgin');
} else {
filter(("img"+id),'imgout');
document.getElementById(id).style.display = 'none';
}
} else {
if (document.layers) {
if (document.id.display == "none"){
document.id.display = 'block';
filter(("img"+id),'imgin');
} else {
filter(("img"+id),'imgout');
document.id.display = 'none';
}
} else {
if (document.all.id.style.visibility == "none"){
document.all.id.style.display = 'block';
} else {
filter(("img"+id),'imgout');
document.all.id.style.display = 'none';
}
}
}
} | function shoh(id)
{
if (document.getElementById) { // DOM3 = IE5, NS6
if (document.getElementById(id).style.display == "none"){
document.getElementById(id).style.display = 'block';
filter(("img"+id),'imgin');
} else {
filter(("img"+id),'imgout');
document.getElementById(id).style.display = 'none';
}
} else {
if (document.layers) {
if (document.id.display == "none"){
document.id.display = 'block';
filter(("img"+id),'imgin');
} else {
filter(("img"+id),'imgout');
document.id.display = 'none';
}
} else {
if (document.all.id.style.visibility == "none"){
document.all.id.style.display = 'block';
} else {
filter(("img"+id),'imgout');
document.all.id.style.display = 'none';
}
}
}
} |
JavaScript | function numberOfCalls(n)
{
if(n <= 1)
return 1;
return numberOfCalls(n - 1) + n;
} | function numberOfCalls(n)
{
if(n <= 1)
return 1;
return numberOfCalls(n - 1) + n;
} |
JavaScript | function nodeSelected(node, distance)
{
circle = d3.select(node).select("circle")
text = d3.select(node).select("text")
if(distance == 0)
{
circle.style("fill", "red")
text.style("fill", "blue")
}
else if(distance == 1)
{
circle.style("fill", "purple")
text.style("fill", "purple")
}
else
{
circle.style("fill", "blue")
text.style("fill", "blue")
}
} | function nodeSelected(node, distance)
{
circle = d3.select(node).select("circle")
text = d3.select(node).select("text")
if(distance == 0)
{
circle.style("fill", "red")
text.style("fill", "blue")
}
else if(distance == 1)
{
circle.style("fill", "purple")
text.style("fill", "purple")
}
else
{
circle.style("fill", "blue")
text.style("fill", "blue")
}
} |
JavaScript | function init(options) {
options = options || {};
var ghostServer, parentApp;
// ### Initialisation
// The server and its dependencies require a populated config
// It returns a promise that is resolved when the application
// has finished starting up.
// Initialize Internationalization
i18n.init();
return readDirectory(config.getContentPath('apps')).then(function loadThemes(result) {
config.set('paths:availableApps', result);
return api.themes.loadThemes();
}).then(function () {
models.init();
// @TODO: this is temporary, replace migrations with a warning if a DB exists
return db.bootUp();
}).then(function () {
// Populate any missing default settings
return models.Settings.populateDefaults();
}).then(function () {
// Initialize the settings cache
return api.init();
}).then(function () {
// Initialize the permissions actions and objects
// NOTE: Must be done before initDbHashAndFirstRun calls
return permissions.init();
}).then(function () {
return Promise.join(
// Check for or initialise a dbHash.
initDbHashAndFirstRun(),
// Initialize apps
apps.init(),
// Initialize xmrpc ping
xmlrpc.listen(),
// Initialize slack ping
slack.listen()
);
}).then(function () {
// Get reference to an express app instance.
parentApp = express();
// ## Middleware and Routing
middleware(parentApp);
// Log all theme errors and warnings
validateThemes(config.getContentPath('themes'))
.catch(function (result) {
// TODO: change `result` to something better
result.errors.forEach(function (err) {
errors.logError(err.message, err.context, err.help);
});
result.warnings.forEach(function (warn) {
errors.logWarn(warn.message, warn.context, warn.help);
});
});
return auth.init(config.get('auth'))
.then(function (response) {
parentApp.use(response.auth);
});
}).then(function () {
return new GhostServer(parentApp);
}).then(function (_ghostServer) {
ghostServer = _ghostServer;
// scheduling can trigger api requests, that's why we initialize the module after the ghost server creation
// scheduling module can create x schedulers with different adapters
return scheduling.init({
active: config.get('scheduling').active,
apiUrl: utils.url.apiUrl(),
internalPath: config.get('paths').internalSchedulingPath,
contentPath: config.getContentPath('scheduling')
});
}).then(function () {
return ghostServer;
});
} | function init(options) {
options = options || {};
var ghostServer, parentApp;
// ### Initialisation
// The server and its dependencies require a populated config
// It returns a promise that is resolved when the application
// has finished starting up.
// Initialize Internationalization
i18n.init();
return readDirectory(config.getContentPath('apps')).then(function loadThemes(result) {
config.set('paths:availableApps', result);
return api.themes.loadThemes();
}).then(function () {
models.init();
// @TODO: this is temporary, replace migrations with a warning if a DB exists
return db.bootUp();
}).then(function () {
// Populate any missing default settings
return models.Settings.populateDefaults();
}).then(function () {
// Initialize the settings cache
return api.init();
}).then(function () {
// Initialize the permissions actions and objects
// NOTE: Must be done before initDbHashAndFirstRun calls
return permissions.init();
}).then(function () {
return Promise.join(
// Check for or initialise a dbHash.
initDbHashAndFirstRun(),
// Initialize apps
apps.init(),
// Initialize xmrpc ping
xmlrpc.listen(),
// Initialize slack ping
slack.listen()
);
}).then(function () {
// Get reference to an express app instance.
parentApp = express();
// ## Middleware and Routing
middleware(parentApp);
// Log all theme errors and warnings
validateThemes(config.getContentPath('themes'))
.catch(function (result) {
// TODO: change `result` to something better
result.errors.forEach(function (err) {
errors.logError(err.message, err.context, err.help);
});
result.warnings.forEach(function (warn) {
errors.logWarn(warn.message, warn.context, warn.help);
});
});
return auth.init(config.get('auth'))
.then(function (response) {
parentApp.use(response.auth);
});
}).then(function () {
return new GhostServer(parentApp);
}).then(function (_ghostServer) {
ghostServer = _ghostServer;
// scheduling can trigger api requests, that's why we initialize the module after the ghost server creation
// scheduling module can create x schedulers with different adapters
return scheduling.init({
active: config.get('scheduling').active,
apiUrl: utils.url.apiUrl(),
internalPath: config.get('paths').internalSchedulingPath,
contentPath: config.getContentPath('scheduling')
});
}).then(function () {
return ghostServer;
});
} |
JavaScript | function errorHandler(err) {
if (err instanceof errors.DatabaseNotPopulated) {
return populate();
}
return Promise.reject(err);
} | function errorHandler(err) {
if (err instanceof errors.DatabaseNotPopulated) {
return populate();
}
return Promise.reject(err);
} |
JavaScript | function constraintToString(constraint) {
if (Array.isArray(constraint)) {
return constraint.join(', ');
}
return "" + constraint;
} | function constraintToString(constraint) {
if (Array.isArray(constraint)) {
return constraint.join(', ');
}
return "" + constraint;
} |
JavaScript | function Allow(validationOptions) {
return function (object, propertyName) {
var args = {
type: ValidationTypes.WHITELIST,
target: object.constructor,
propertyName: propertyName,
validationOptions: validationOptions,
};
getMetadataStorage().addValidationMetadata(new ValidationMetadata(args));
};
} | function Allow(validationOptions) {
return function (object, propertyName) {
var args = {
type: ValidationTypes.WHITELIST,
target: object.constructor,
propertyName: propertyName,
validationOptions: validationOptions,
};
getMetadataStorage().addValidationMetadata(new ValidationMetadata(args));
};
} |
JavaScript | function registerDecorator(options) {
var constraintCls;
if (options.validator instanceof Function) {
constraintCls = options.validator;
var constraintClasses = getFromContainer(MetadataStorage).getTargetValidatorConstraints(options.validator);
if (constraintClasses.length > 1) {
throw "More than one implementation of ValidatorConstraintInterface found for validator on: " + options.target.name + ":" + options.propertyName;
}
}
else {
var validator_1 = options.validator;
constraintCls = /** @class */ (function () {
function CustomConstraint() {
}
CustomConstraint.prototype.validate = function (value, validationArguments) {
return validator_1.validate(value, validationArguments);
};
CustomConstraint.prototype.defaultMessage = function (validationArguments) {
if (validator_1.defaultMessage) {
return validator_1.defaultMessage(validationArguments);
}
return '';
};
return CustomConstraint;
}());
getMetadataStorage().addConstraintMetadata(new ConstraintMetadata(constraintCls, options.name, options.async));
}
var validationMetadataArgs = {
type: options.name && ValidationTypes.isValid(options.name) ? options.name : ValidationTypes.CUSTOM_VALIDATION,
target: options.target,
propertyName: options.propertyName,
validationOptions: options.options,
constraintCls: constraintCls,
constraints: options.constraints,
};
getMetadataStorage().addValidationMetadata(new ValidationMetadata(validationMetadataArgs));
} | function registerDecorator(options) {
var constraintCls;
if (options.validator instanceof Function) {
constraintCls = options.validator;
var constraintClasses = getFromContainer(MetadataStorage).getTargetValidatorConstraints(options.validator);
if (constraintClasses.length > 1) {
throw "More than one implementation of ValidatorConstraintInterface found for validator on: " + options.target.name + ":" + options.propertyName;
}
}
else {
var validator_1 = options.validator;
constraintCls = /** @class */ (function () {
function CustomConstraint() {
}
CustomConstraint.prototype.validate = function (value, validationArguments) {
return validator_1.validate(value, validationArguments);
};
CustomConstraint.prototype.defaultMessage = function (validationArguments) {
if (validator_1.defaultMessage) {
return validator_1.defaultMessage(validationArguments);
}
return '';
};
return CustomConstraint;
}());
getMetadataStorage().addConstraintMetadata(new ConstraintMetadata(constraintCls, options.name, options.async));
}
var validationMetadataArgs = {
type: options.name && ValidationTypes.isValid(options.name) ? options.name : ValidationTypes.CUSTOM_VALIDATION,
target: options.target,
propertyName: options.propertyName,
validationOptions: options.options,
constraintCls: constraintCls,
constraints: options.constraints,
};
getMetadataStorage().addValidationMetadata(new ValidationMetadata(validationMetadataArgs));
} |
JavaScript | function IsOptional(validationOptions) {
return function (object, propertyName) {
var args = {
type: ValidationTypes.CONDITIONAL_VALIDATION,
target: object.constructor,
propertyName: propertyName,
constraints: [
function (object, value) {
return object[propertyName] !== null && object[propertyName] !== undefined;
},
],
validationOptions: validationOptions,
};
getMetadataStorage().addValidationMetadata(new ValidationMetadata(args));
};
} | function IsOptional(validationOptions) {
return function (object, propertyName) {
var args = {
type: ValidationTypes.CONDITIONAL_VALIDATION,
target: object.constructor,
propertyName: propertyName,
constraints: [
function (object, value) {
return object[propertyName] !== null && object[propertyName] !== undefined;
},
],
validationOptions: validationOptions,
};
getMetadataStorage().addValidationMetadata(new ValidationMetadata(args));
};
} |
JavaScript | function ValidateIf(condition, validationOptions) {
return function (object, propertyName) {
var args = {
type: ValidationTypes.CONDITIONAL_VALIDATION,
target: object.constructor,
propertyName: propertyName,
constraints: [condition],
validationOptions: validationOptions,
};
getMetadataStorage().addValidationMetadata(new ValidationMetadata(args));
};
} | function ValidateIf(condition, validationOptions) {
return function (object, propertyName) {
var args = {
type: ValidationTypes.CONDITIONAL_VALIDATION,
target: object.constructor,
propertyName: propertyName,
constraints: [condition],
validationOptions: validationOptions,
};
getMetadataStorage().addValidationMetadata(new ValidationMetadata(args));
};
} |
JavaScript | function ValidateNested(validationOptions) {
var opts = __assign({}, validationOptions);
var eachPrefix = opts.each ? 'each value in ' : '';
opts.message = opts.message || eachPrefix + 'nested property $property must be either object or array';
return function (object, propertyName) {
var args = {
type: ValidationTypes.NESTED_VALIDATION,
target: object.constructor,
propertyName: propertyName,
validationOptions: opts,
};
getMetadataStorage().addValidationMetadata(new ValidationMetadata(args));
};
} | function ValidateNested(validationOptions) {
var opts = __assign({}, validationOptions);
var eachPrefix = opts.each ? 'each value in ' : '';
opts.message = opts.message || eachPrefix + 'nested property $property must be either object or array';
return function (object, propertyName) {
var args = {
type: ValidationTypes.NESTED_VALIDATION,
target: object.constructor,
propertyName: propertyName,
validationOptions: opts,
};
getMetadataStorage().addValidationMetadata(new ValidationMetadata(args));
};
} |
JavaScript | function IsLatLong(validationOptions) {
return ValidateBy({
name: IS_LATLONG,
validator: {
validate: function (value, args) { return isLatLong(value); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be a latitude,longitude string'; }, validationOptions),
},
}, validationOptions);
} | function IsLatLong(validationOptions) {
return ValidateBy({
name: IS_LATLONG,
validator: {
validate: function (value, args) { return isLatLong(value); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be a latitude,longitude string'; }, validationOptions),
},
}, validationOptions);
} |
JavaScript | function IsLatitude(validationOptions) {
return ValidateBy({
name: IS_LATITUDE,
validator: {
validate: function (value, args) { return isLatitude(value); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be a latitude string or number'; }, validationOptions),
},
}, validationOptions);
} | function IsLatitude(validationOptions) {
return ValidateBy({
name: IS_LATITUDE,
validator: {
validate: function (value, args) { return isLatitude(value); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be a latitude string or number'; }, validationOptions),
},
}, validationOptions);
} |
JavaScript | function IsLongitude(validationOptions) {
return ValidateBy({
name: IS_LONGITUDE,
validator: {
validate: function (value, args) { return isLongitude(value); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be a longitude string or number'; }, validationOptions),
},
}, validationOptions);
} | function IsLongitude(validationOptions) {
return ValidateBy({
name: IS_LONGITUDE,
validator: {
validate: function (value, args) { return isLongitude(value); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be a longitude string or number'; }, validationOptions),
},
}, validationOptions);
} |
JavaScript | function IsIn(values, validationOptions) {
return ValidateBy({
name: IS_IN,
constraints: [values],
validator: {
validate: function (value, args) { return isIn(value, args.constraints[0]); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be one of the following values: $constraint1'; }, validationOptions),
},
}, validationOptions);
} | function IsIn(values, validationOptions) {
return ValidateBy({
name: IS_IN,
constraints: [values],
validator: {
validate: function (value, args) { return isIn(value, args.constraints[0]); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be one of the following values: $constraint1'; }, validationOptions),
},
}, validationOptions);
} |
JavaScript | function IsNotIn(values, validationOptions) {
return ValidateBy({
name: IS_NOT_IN,
constraints: [values],
validator: {
validate: function (value, args) { return isNotIn(value, args.constraints[0]); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property should not be one of the following values: $constraint1'; }, validationOptions),
},
}, validationOptions);
} | function IsNotIn(values, validationOptions) {
return ValidateBy({
name: IS_NOT_IN,
constraints: [values],
validator: {
validate: function (value, args) { return isNotIn(value, args.constraints[0]); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property should not be one of the following values: $constraint1'; }, validationOptions),
},
}, validationOptions);
} |
JavaScript | function IsDivisibleBy(num, validationOptions) {
return ValidateBy({
name: IS_DIVISIBLE_BY,
constraints: [num],
validator: {
validate: function (value, args) { return isDivisibleBy(value, args.constraints[0]); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be divisible by $constraint1'; }, validationOptions),
},
}, validationOptions);
} | function IsDivisibleBy(num, validationOptions) {
return ValidateBy({
name: IS_DIVISIBLE_BY,
constraints: [num],
validator: {
validate: function (value, args) { return isDivisibleBy(value, args.constraints[0]); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be divisible by $constraint1'; }, validationOptions),
},
}, validationOptions);
} |
JavaScript | function IsPositive(validationOptions) {
return ValidateBy({
name: IS_POSITIVE,
validator: {
validate: function (value, args) { return isPositive(value); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be a positive number'; }, validationOptions),
},
}, validationOptions);
} | function IsPositive(validationOptions) {
return ValidateBy({
name: IS_POSITIVE,
validator: {
validate: function (value, args) { return isPositive(value); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be a positive number'; }, validationOptions),
},
}, validationOptions);
} |
JavaScript | function IsNegative(validationOptions) {
return ValidateBy({
name: IS_NEGATIVE,
validator: {
validate: function (value, args) { return isNegative(value); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be a negative number'; }, validationOptions),
},
}, validationOptions);
} | function IsNegative(validationOptions) {
return ValidateBy({
name: IS_NEGATIVE,
validator: {
validate: function (value, args) { return isNegative(value); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be a negative number'; }, validationOptions),
},
}, validationOptions);
} |
JavaScript | function Max(maxValue, validationOptions) {
return ValidateBy({
name: MAX,
constraints: [maxValue],
validator: {
validate: function (value, args) { return max(value, args.constraints[0]); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must not be greater than $constraint1'; }, validationOptions),
},
}, validationOptions);
} | function Max(maxValue, validationOptions) {
return ValidateBy({
name: MAX,
constraints: [maxValue],
validator: {
validate: function (value, args) { return max(value, args.constraints[0]); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must not be greater than $constraint1'; }, validationOptions),
},
}, validationOptions);
} |
JavaScript | function Min(minValue, validationOptions) {
return ValidateBy({
name: MIN,
constraints: [minValue],
validator: {
validate: function (value, args) { return min(value, args.constraints[0]); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must not be less than $constraint1'; }, validationOptions),
},
}, validationOptions);
} | function Min(minValue, validationOptions) {
return ValidateBy({
name: MIN,
constraints: [minValue],
validator: {
validate: function (value, args) { return min(value, args.constraints[0]); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must not be less than $constraint1'; }, validationOptions),
},
}, validationOptions);
} |
JavaScript | function MinDate(date, validationOptions) {
return ValidateBy({
name: MIN_DATE,
constraints: [date],
validator: {
validate: function (value, args) { return minDate(value, args.constraints[0]); },
defaultMessage: buildMessage(function (eachPrefix) { return 'minimal allowed date for ' + eachPrefix + '$property is $constraint1'; }, validationOptions),
},
}, validationOptions);
} | function MinDate(date, validationOptions) {
return ValidateBy({
name: MIN_DATE,
constraints: [date],
validator: {
validate: function (value, args) { return minDate(value, args.constraints[0]); },
defaultMessage: buildMessage(function (eachPrefix) { return 'minimal allowed date for ' + eachPrefix + '$property is $constraint1'; }, validationOptions),
},
}, validationOptions);
} |
JavaScript | function MaxDate(date, validationOptions) {
return ValidateBy({
name: MAX_DATE,
constraints: [date],
validator: {
validate: function (value, args) { return maxDate(value, args.constraints[0]); },
defaultMessage: buildMessage(function (eachPrefix) { return 'maximal allowed date for ' + eachPrefix + '$property is $constraint1'; }, validationOptions),
},
}, validationOptions);
} | function MaxDate(date, validationOptions) {
return ValidateBy({
name: MAX_DATE,
constraints: [date],
validator: {
validate: function (value, args) { return maxDate(value, args.constraints[0]); },
defaultMessage: buildMessage(function (eachPrefix) { return 'maximal allowed date for ' + eachPrefix + '$property is $constraint1'; }, validationOptions),
},
}, validationOptions);
} |
JavaScript | function Contains(seed, validationOptions) {
return ValidateBy({
name: CONTAINS,
constraints: [seed],
validator: {
validate: function (value, args) { return contains(value, args.constraints[0]); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must contain a $constraint1 string'; }, validationOptions),
},
}, validationOptions);
} | function Contains(seed, validationOptions) {
return ValidateBy({
name: CONTAINS,
constraints: [seed],
validator: {
validate: function (value, args) { return contains(value, args.constraints[0]); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must contain a $constraint1 string'; }, validationOptions),
},
}, validationOptions);
} |
JavaScript | function NotContains(seed, validationOptions) {
return ValidateBy({
name: NOT_CONTAINS,
constraints: [seed],
validator: {
validate: function (value, args) { return notContains(value, args.constraints[0]); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property should not contain a $constraint1 string'; }, validationOptions),
},
}, validationOptions);
} | function NotContains(seed, validationOptions) {
return ValidateBy({
name: NOT_CONTAINS,
constraints: [seed],
validator: {
validate: function (value, args) { return notContains(value, args.constraints[0]); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property should not contain a $constraint1 string'; }, validationOptions),
},
}, validationOptions);
} |
JavaScript | function IsAlpha(locale, validationOptions) {
return ValidateBy({
name: IS_ALPHA,
constraints: [locale],
validator: {
validate: function (value, args) { return isAlpha(value, args.constraints[0]); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must contain only letters (a-zA-Z)'; }, validationOptions),
},
}, validationOptions);
} | function IsAlpha(locale, validationOptions) {
return ValidateBy({
name: IS_ALPHA,
constraints: [locale],
validator: {
validate: function (value, args) { return isAlpha(value, args.constraints[0]); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must contain only letters (a-zA-Z)'; }, validationOptions),
},
}, validationOptions);
} |
JavaScript | function IsAlphanumeric(locale, validationOptions) {
return ValidateBy({
name: IS_ALPHANUMERIC,
constraints: [locale],
validator: {
validate: function (value, args) { return isAlphanumeric(value, args.constraints[0]); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must contain only letters and numbers'; }, validationOptions),
},
}, validationOptions);
} | function IsAlphanumeric(locale, validationOptions) {
return ValidateBy({
name: IS_ALPHANUMERIC,
constraints: [locale],
validator: {
validate: function (value, args) { return isAlphanumeric(value, args.constraints[0]); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must contain only letters and numbers'; }, validationOptions),
},
}, validationOptions);
} |
JavaScript | function IsAscii(validationOptions) {
return ValidateBy({
name: IS_ASCII,
validator: {
validate: function (value, args) { return isAscii(value); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must contain only ASCII characters'; }, validationOptions),
},
}, validationOptions);
} | function IsAscii(validationOptions) {
return ValidateBy({
name: IS_ASCII,
validator: {
validate: function (value, args) { return isAscii(value); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must contain only ASCII characters'; }, validationOptions),
},
}, validationOptions);
} |
JavaScript | function IsBase64(validationOptions) {
return ValidateBy({
name: IS_BASE64,
validator: {
validate: function (value, args) { return isBase64(value); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be base64 encoded'; }, validationOptions),
},
}, validationOptions);
} | function IsBase64(validationOptions) {
return ValidateBy({
name: IS_BASE64,
validator: {
validate: function (value, args) { return isBase64(value); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be base64 encoded'; }, validationOptions),
},
}, validationOptions);
} |
JavaScript | function IsByteLength(min, max, validationOptions) {
return ValidateBy({
name: IS_BYTE_LENGTH,
constraints: [min, max],
validator: {
validate: function (value, args) { return isByteLength(value, args.constraints[0], args.constraints[1]); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + "$property's byte length must fall into ($constraint1, $constraint2) range"; }, validationOptions),
},
}, validationOptions);
} | function IsByteLength(min, max, validationOptions) {
return ValidateBy({
name: IS_BYTE_LENGTH,
constraints: [min, max],
validator: {
validate: function (value, args) { return isByteLength(value, args.constraints[0], args.constraints[1]); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + "$property's byte length must fall into ($constraint1, $constraint2) range"; }, validationOptions),
},
}, validationOptions);
} |
JavaScript | function IsCreditCard(validationOptions) {
return ValidateBy({
name: IS_CREDIT_CARD,
validator: {
validate: function (value, args) { return isCreditCard(value); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be a credit card'; }, validationOptions),
},
}, validationOptions);
} | function IsCreditCard(validationOptions) {
return ValidateBy({
name: IS_CREDIT_CARD,
validator: {
validate: function (value, args) { return isCreditCard(value); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be a credit card'; }, validationOptions),
},
}, validationOptions);
} |
JavaScript | function IsCurrency(options, validationOptions) {
return ValidateBy({
name: IS_CURRENCY,
constraints: [options],
validator: {
validate: function (value, args) { return isCurrency(value, args.constraints[0]); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be a currency'; }, validationOptions),
},
}, validationOptions);
} | function IsCurrency(options, validationOptions) {
return ValidateBy({
name: IS_CURRENCY,
constraints: [options],
validator: {
validate: function (value, args) { return isCurrency(value, args.constraints[0]); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be a currency'; }, validationOptions),
},
}, validationOptions);
} |
JavaScript | function IsEmail(options, validationOptions) {
return ValidateBy({
name: IS_EMAIL,
constraints: [options],
validator: {
validate: function (value, args) { return isEmail(value, args.constraints[0]); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be an email'; }, validationOptions),
},
}, validationOptions);
} | function IsEmail(options, validationOptions) {
return ValidateBy({
name: IS_EMAIL,
constraints: [options],
validator: {
validate: function (value, args) { return isEmail(value, args.constraints[0]); },
defaultMessage: buildMessage(function (eachPrefix) { return eachPrefix + '$property must be an email'; }, validationOptions),
},
}, validationOptions);
} |
Subsets and Splits