language
stringclasses 6
values | original_string
stringlengths 25
887k
| text
stringlengths 25
887k
|
---|---|---|
JavaScript | function isHex (str) {
isString(str)
let hexStr = remove0x(str)
assert(hexStr && /^[0-9a-fA-F]+$/.test(hexStr), 'Must pass in hex string')
} | function isHex (str) {
isString(str)
let hexStr = remove0x(str)
assert(hexStr && /^[0-9a-fA-F]+$/.test(hexStr), 'Must pass in hex string')
} |
JavaScript | createBranch(angle) {
push();
let newBranch = new Branch(this.end, this.len * random(0.4, 0.9), this.angle - angle, this.gen + 1, this.weight - 0.4);
this.branches.push(newBranch);
newBranch.draw();
pop();
} | createBranch(angle) {
push();
let newBranch = new Branch(this.end, this.len * random(0.4, 0.9), this.angle - angle, this.gen + 1, this.weight - 0.4);
this.branches.push(newBranch);
newBranch.draw();
pop();
} |
JavaScript | draw() {
translate(this.begin.x, this.begin.y);
strokeWeight(this.weight);
line(0, 0, this.end.x - this.begin.x, this.end.y - this.begin.y);
} | draw() {
translate(this.begin.x, this.begin.y);
strokeWeight(this.weight);
line(0, 0, this.end.x - this.begin.x, this.end.y - this.begin.y);
} |
JavaScript | componentWillUnmount() {
super.componentWillUnmount();
document.body.classList.remove("welcome-page");
} | componentWillUnmount() {
super.componentWillUnmount();
document.body.classList.remove("welcome-page");
} |
JavaScript | _doRenderInsecureRoomNameWarning() {
return (
<div className="insecure-room-name-warning">
<Icon src={IconWarning} />
<span>{this.props.t("security.insecureRoomNameWarning")}</span>
</div>
);
} | _doRenderInsecureRoomNameWarning() {
return (
<div className="insecure-room-name-warning">
<Icon src={IconWarning} />
<span>{this.props.t("security.insecureRoomNameWarning")}</span>
</div>
);
} |
JavaScript | _onFormSubmit(event) {
event.preventDefault();
if (!this._roomInputRef || this._roomInputRef.reportValidity()) {
this._onJoin();
}
} | _onFormSubmit(event) {
event.preventDefault();
if (!this._roomInputRef || this._roomInputRef.reportValidity()) {
this._onJoin();
}
} |
JavaScript | _renderTabs() {
if (isMobileBrowser()) {
return null;
}
const { _calendarEnabled, _recentListEnabled, t } = this.props;
const tabs = [];
if (_calendarEnabled) {
tabs.push({
label: t("welcomepage.calendar"),
content: <CalendarList />
});
}
if (_recentListEnabled) {
tabs.push({
label: t("welcomepage.recentList"),
content: <RecentList />
});
}
if (tabs.length === 0) {
return null;
}
return (
<Tabs
onSelect={this._onTabSelected}
selected={this.state.selectedTab}
tabs={tabs}
/>
);
} | _renderTabs() {
if (isMobileBrowser()) {
return null;
}
const { _calendarEnabled, _recentListEnabled, t } = this.props;
const tabs = [];
if (_calendarEnabled) {
tabs.push({
label: t("welcomepage.calendar"),
content: <CalendarList />
});
}
if (_recentListEnabled) {
tabs.push({
label: t("welcomepage.recentList"),
content: <RecentList />
});
}
if (tabs.length === 0) {
return null;
}
return (
<Tabs
onSelect={this._onTabSelected}
selected={this.state.selectedTab}
tabs={tabs}
/>
);
} |
JavaScript | _shouldShowAdditionalCard() {
return (
interfaceConfig.DISPLAY_WELCOME_PAGE_ADDITIONAL_CARD &&
this._additionalCardTemplate &&
this._additionalCardTemplate.content &&
this._additionalCardTemplate.innerHTML.trim()
);
} | _shouldShowAdditionalCard() {
return (
interfaceConfig.DISPLAY_WELCOME_PAGE_ADDITIONAL_CARD &&
this._additionalCardTemplate &&
this._additionalCardTemplate.content &&
this._additionalCardTemplate.innerHTML.trim()
);
} |
JavaScript | _shouldShowAdditionalContent() {
return (
interfaceConfig.DISPLAY_WELCOME_PAGE_CONTENT &&
this._additionalContentTemplate &&
this._additionalContentTemplate.content &&
this._additionalContentTemplate.innerHTML.trim()
);
} | _shouldShowAdditionalContent() {
return (
interfaceConfig.DISPLAY_WELCOME_PAGE_CONTENT &&
this._additionalContentTemplate &&
this._additionalContentTemplate.content &&
this._additionalContentTemplate.innerHTML.trim()
);
} |
JavaScript | _shouldShowAdditionalToolbarContent() {
return (
interfaceConfig.DISPLAY_WELCOME_PAGE_TOOLBAR_ADDITIONAL_CONTENT &&
this._additionalToolbarContentTemplate &&
this._additionalToolbarContentTemplate.content &&
this._additionalToolbarContentTemplate.innerHTML.trim()
);
} | _shouldShowAdditionalToolbarContent() {
return (
interfaceConfig.DISPLAY_WELCOME_PAGE_TOOLBAR_ADDITIONAL_CONTENT &&
this._additionalToolbarContentTemplate &&
this._additionalToolbarContentTemplate.content &&
this._additionalToolbarContentTemplate.innerHTML.trim()
);
} |
JavaScript | _renderJitsiWatermark() {
const {
_logoLink,
_logoUrl,
_showJitsiWatermark,
} = this.props;
const videoAPIURL = getVideoAPIURL();
const { apiID } = getAPIInfo();
window.tenantURL = window.tenantURL || {};
if (!window.tenantURL[apiID]) {
window.tenantURL[apiID] = '-';
fetch(`${videoAPIURL}/api/tenant/url/${apiID}`).then(data => {
if (data.status === 200) {
data.text().then(text => {
const linkJSON = JSON.parse(text);
if (linkJSON.Data) {
window.tenantURL[apiID] = linkJSON.Data;
this.setState({ link: linkJSON.Data });
}
});
} else {
throw 'try-again-later';
}
})
.catch(() => {
setTimeout(() => {
delete window.tenantURL;
}, 5000);
});
}
let reactElement = null;
const logoUrl = `${videoAPIURL}/api/tenant/logo/${apiID}`;
const style = {
backgroundImage: `url(${logoUrl})`,
maxWidth: 140,
maxHeight: 70
};
reactElement = (<div
className = 'watermark leftwatermark'
style = { style } />);
if (this.state.link) {
reactElement = (
<a
href = { this.state.link }
target = '_new'>
{ reactElement }
</a>
);
}
return reactElement;
} | _renderJitsiWatermark() {
const {
_logoLink,
_logoUrl,
_showJitsiWatermark,
} = this.props;
const videoAPIURL = getVideoAPIURL();
const { apiID } = getAPIInfo();
window.tenantURL = window.tenantURL || {};
if (!window.tenantURL[apiID]) {
window.tenantURL[apiID] = '-';
fetch(`${videoAPIURL}/api/tenant/url/${apiID}`).then(data => {
if (data.status === 200) {
data.text().then(text => {
const linkJSON = JSON.parse(text);
if (linkJSON.Data) {
window.tenantURL[apiID] = linkJSON.Data;
this.setState({ link: linkJSON.Data });
}
});
} else {
throw 'try-again-later';
}
})
.catch(() => {
setTimeout(() => {
delete window.tenantURL;
}, 5000);
});
}
let reactElement = null;
const logoUrl = `${videoAPIURL}/api/tenant/logo/${apiID}`;
const style = {
backgroundImage: `url(${logoUrl})`,
maxWidth: 140,
maxHeight: 70
};
reactElement = (<div
className = 'watermark leftwatermark'
style = { style } />);
if (this.state.link) {
reactElement = (
<a
href = { this.state.link }
target = '_new'>
{ reactElement }
</a>
);
}
return reactElement;
} |
JavaScript | async _initScreenshotCapture() {
const imageBitmap = await this._imageCapture.grabFrame();
this._currentCanvasContext.drawImage(imageBitmap, 0, 0, this._streamWidth, this._streamHeight);
const imageData = this._currentCanvasContext.getImageData(0, 0, this._streamWidth, this._streamHeight);
this._storedImageData = imageData;
this._streamWorker.postMessage({
id: SET_INTERVAL,
timeMs: POLL_INTERVAL
});
} | async _initScreenshotCapture() {
const imageBitmap = await this._imageCapture.grabFrame();
this._currentCanvasContext.drawImage(imageBitmap, 0, 0, this._streamWidth, this._streamHeight);
const imageData = this._currentCanvasContext.getImageData(0, 0, this._streamWidth, this._streamHeight);
this._storedImageData = imageData;
this._streamWorker.postMessage({
id: SET_INTERVAL,
timeMs: POLL_INTERVAL
});
} |
JavaScript | function ceLeapYear(y) {
if (y % 100 == 0) {
if (y % 400 == 0) {
return true;
}
} else if (y % 4 == 0) {
return true;
}
return false;
} | function ceLeapYear(y) {
if (y % 100 == 0) {
if (y % 400 == 0) {
return true;
}
} else if (y % 4 == 0) {
return true;
}
return false;
} |
JavaScript | function julLeapYear(y) {
if (y < 0) {
y = (((y + 1) % 700) + 700) % 700;
}
if (y % 4 == 0) {
return true;
}
return false;
} | function julLeapYear(y) {
if (y < 0) {
y = (((y + 1) % 700) + 700) % 700;
}
if (y % 4 == 0) {
return true;
}
return false;
} |
JavaScript | function isLeapYear(year, cal_type) {
if (cal_type == 'GREGORIAN') {
new_year = year;
if (year < 0) {
new_year = (((year + 1) % 400) + 400) % 400;
return ceLeapYear(new_year);
}
} else if (cal_type == 'CE') {
return ceLeapYear(year);
} else if (cal_type == 'JULIAN') {
return julLeapYear(year);
} else if (cal_type == 'ENGLISH') {
if (year >= 1800) {
return ceLeapYear(year);
} else {
return julLeapYear(year);
}
} else if (cal_type == 'ROMAN') {
if (year >= 1700) {
return ceLeapYear(year);
} else {
return julLeapYear(year);
}
}
} | function isLeapYear(year, cal_type) {
if (cal_type == 'GREGORIAN') {
new_year = year;
if (year < 0) {
new_year = (((year + 1) % 400) + 400) % 400;
return ceLeapYear(new_year);
}
} else if (cal_type == 'CE') {
return ceLeapYear(year);
} else if (cal_type == 'JULIAN') {
return julLeapYear(year);
} else if (cal_type == 'ENGLISH') {
if (year >= 1800) {
return ceLeapYear(year);
} else {
return julLeapYear(year);
}
} else if (cal_type == 'ROMAN') {
if (year >= 1700) {
return ceLeapYear(year);
} else {
return julLeapYear(year);
}
}
} |
JavaScript | function checkInt(value) {
if (value === parseInt(value, 10)) {
return true;
}
return false;
} | function checkInt(value) {
if (value === parseInt(value, 10)) {
return true;
}
return false;
} |
JavaScript | function addxxYY(year, cal_type) {
new_year = ((year % 100) + 100) % 100;
if (cal_type != 'CE' && year < 0) {
new_year = (((year + 1) % 100) + 100) % 100;
}
return (((((Math.floor(new_year / 12) + (((new_year % 12) + 12) % 12) +
Math.floor((((new_year % 12) + 12) % 12) / 4)) % 7) + 7) % 7));
} | function addxxYY(year, cal_type) {
new_year = ((year % 100) + 100) % 100;
if (cal_type != 'CE' && year < 0) {
new_year = (((year + 1) % 100) + 100) % 100;
}
return (((((Math.floor(new_year / 12) + (((new_year % 12) + 12) % 12) +
Math.floor((((new_year % 12) + 12) % 12) / 4)) % 7) + 7) % 7));
} |
JavaScript | function addYYxx(year, month, date, cal_type) {
var new_year = 0;
if (cal_type == 'GREGORIAN') {
new_year = year;
if (year < 0) {
new_year = (((year + 1) % 400) + 400) % 400;
}
new_year = ((new_year % 400) + 400) % 400;
return ceAddYYxx(new_year);
} else if (cal_type == 'CE') {
new_year = ((year % 400) + 400) % 400;
return ceAddYYxx(new_year);
} else if (cal_type == 'JULIAN') {
new_year = year;
if (year < 0) {
new_year = (((year + 1) % 700) + 700) % 700;
}
new_year = ((new_year % 700) + 700) % 700;
return julAddYYxx(new_year);
} else if (cal_type == 'ENGLISH') {
if (year >= 1752) {
if (year == 1752) {
if (month >= 9 && month <= 12) {
if (month == 9) {
if (date >= 14) {
return 0;
} else {
return 4;
}
} else {
return 0;
}
} else {
return 4;
}
} else {
new_year = ((year % 400) + 400) % 400;
return ceAddYYxx(new_year);
}
} else {
new_year = year;
if (year < 0) {
new_year = (((year + 1) % 700) + 700) % 700;
}
new_year = ((new_year % 700) + 700) % 700;
return julAddYYxx(new_year);
}
} else if (cal_type == 'ROMAN') {
if (year >= 1582) {
if (year == 1582) {
if (month >= 10 && month <= 12) {
if (month == 10) {
if (date >= 15) {
return 3;
} else {
return 6;
}
} else {
return 3;
}
} else {
return 6;
}
} else {
new_year = ((year % 400) + 400) % 400;
return ceAddYYxx(new_year);
}
} else {
new_year = year;
if (year < 0) {
new_year = (((year + 1) % 700) + 700) % 700;
}
new_year = ((new_year % 700) + 700) % 700;
return julAddYYxx(new_year);
}
}
} | function addYYxx(year, month, date, cal_type) {
var new_year = 0;
if (cal_type == 'GREGORIAN') {
new_year = year;
if (year < 0) {
new_year = (((year + 1) % 400) + 400) % 400;
}
new_year = ((new_year % 400) + 400) % 400;
return ceAddYYxx(new_year);
} else if (cal_type == 'CE') {
new_year = ((year % 400) + 400) % 400;
return ceAddYYxx(new_year);
} else if (cal_type == 'JULIAN') {
new_year = year;
if (year < 0) {
new_year = (((year + 1) % 700) + 700) % 700;
}
new_year = ((new_year % 700) + 700) % 700;
return julAddYYxx(new_year);
} else if (cal_type == 'ENGLISH') {
if (year >= 1752) {
if (year == 1752) {
if (month >= 9 && month <= 12) {
if (month == 9) {
if (date >= 14) {
return 0;
} else {
return 4;
}
} else {
return 0;
}
} else {
return 4;
}
} else {
new_year = ((year % 400) + 400) % 400;
return ceAddYYxx(new_year);
}
} else {
new_year = year;
if (year < 0) {
new_year = (((year + 1) % 700) + 700) % 700;
}
new_year = ((new_year % 700) + 700) % 700;
return julAddYYxx(new_year);
}
} else if (cal_type == 'ROMAN') {
if (year >= 1582) {
if (year == 1582) {
if (month >= 10 && month <= 12) {
if (month == 10) {
if (date >= 15) {
return 3;
} else {
return 6;
}
} else {
return 3;
}
} else {
return 6;
}
} else {
new_year = ((year % 400) + 400) % 400;
return ceAddYYxx(new_year);
}
} else {
new_year = year;
if (year < 0) {
new_year = (((year + 1) % 700) + 700) % 700;
}
new_year = ((new_year % 700) + 700) % 700;
return julAddYYxx(new_year);
}
}
} |
JavaScript | function addMonth(year, month, cal_type) {
if (isLeapYear(year, cal_type) && MONTH_OFFSET[month - 1].length > 1) {
return window.MONTH_OFFSET[month - 1][1];
}
return window.MONTH_OFFSET[month - 1][0];
} | function addMonth(year, month, cal_type) {
if (isLeapYear(year, cal_type) && MONTH_OFFSET[month - 1].length > 1) {
return window.MONTH_OFFSET[month - 1][1];
}
return window.MONTH_OFFSET[month - 1][0];
} |
JavaScript | function dateCalc(year, month, date, cal_type) {
cal_type = typeof cal_type !== 'undefined' ? cal_type : 'ENGLISH';
cal_type = cal_type.toUpperCase();
if (isRealDate(year, month, date, cal_type)) {
var total = ((addYear(year, month, date, cal_type) +
addMonth(year, month, cal_type) + date) % 7)
return window.DAYS[total];
}
return '';
} | function dateCalc(year, month, date, cal_type) {
cal_type = typeof cal_type !== 'undefined' ? cal_type : 'ENGLISH';
cal_type = cal_type.toUpperCase();
if (isRealDate(year, month, date, cal_type)) {
var total = ((addYear(year, month, date, cal_type) +
addMonth(year, month, cal_type) + date) % 7)
return window.DAYS[total];
}
return '';
} |
JavaScript | function Session(editor) {
this.editor = editor;
this.path = editor.document.file.fullPath;
this.ternHints = [];
this.ternGuesses = null;
this.fnType = null;
this.builtins = null;
} | function Session(editor) {
this.editor = editor;
this.path = editor.document.file.fullPath;
this.ternHints = [];
this.ternGuesses = null;
this.fnType = null;
this.builtins = null;
} |
JavaScript | function isOnFunctionIdentifier() {
// Check if we might be on function identifier of the function call.
var type = token.type,
nextToken,
localLexical,
localCursor = {line: cursor.line, ch: token.end};
if (type === "variable-2" || type === "variable" || type === "property") {
nextToken = self.getNextToken(localCursor, true);
if (nextToken && nextToken.string === "(") {
localLexical = getLexicalState(nextToken);
return localLexical;
}
}
return null;
} | function isOnFunctionIdentifier() {
// Check if we might be on function identifier of the function call.
var type = token.type,
nextToken,
localLexical,
localCursor = {line: cursor.line, ch: token.end};
if (type === "variable-2" || type === "variable" || type === "property") {
nextToken = self.getNextToken(localCursor, true);
if (nextToken && nextToken.string === "(") {
localLexical = getLexicalState(nextToken);
return localLexical;
}
}
return null;
} |
JavaScript | function filterWithQueryAndMatcher(hints, matcher) {
var matchResults = $.map(hints, function (hint) {
var searchResult = matcher.match(hint.value, query);
if (searchResult) {
searchResult.value = hint.value;
searchResult.guess = hint.guess;
searchResult.type = hint.type;
if (hint.keyword !== undefined) {
searchResult.keyword = hint.keyword;
}
if (hint.literal !== undefined) {
searchResult.literal = hint.literal;
}
if (hint.depth !== undefined) {
searchResult.depth = hint.depth;
}
if (hint.doc) {
searchResult.doc = hint.doc;
}
if (hint.url) {
searchResult.url = hint.url;
}
if (!type.property && !type.showFunctionType && hint.origin &&
isBuiltin(hint.origin)) {
searchResult.builtin = 1;
} else {
searchResult.builtin = 0;
}
}
return searchResult;
});
return matchResults;
} | function filterWithQueryAndMatcher(hints, matcher) {
var matchResults = $.map(hints, function (hint) {
var searchResult = matcher.match(hint.value, query);
if (searchResult) {
searchResult.value = hint.value;
searchResult.guess = hint.guess;
searchResult.type = hint.type;
if (hint.keyword !== undefined) {
searchResult.keyword = hint.keyword;
}
if (hint.literal !== undefined) {
searchResult.literal = hint.literal;
}
if (hint.depth !== undefined) {
searchResult.depth = hint.depth;
}
if (hint.doc) {
searchResult.doc = hint.doc;
}
if (hint.url) {
searchResult.url = hint.url;
}
if (!type.property && !type.showFunctionType && hint.origin &&
isBuiltin(hint.origin)) {
searchResult.builtin = 1;
} else {
searchResult.builtin = 0;
}
}
return searchResult;
});
return matchResults;
} |
JavaScript | function initTernServer(env, files) {
ternOptions = {
defs: env,
async: true,
getFile: getFile,
plugins: {requirejs: {}, doc_comment: true, node: true, es_modules: true},
ecmaVersion: 9
};
// If a server is already created just reset the analysis data before marking it for GC
if (ternServer) {
ternServer.reset();
Infer.resetGuessing();
}
ternServer = new Tern.Server(ternOptions);
files.forEach(function (file) {
ternServer.addFile(file);
});
} | function initTernServer(env, files) {
ternOptions = {
defs: env,
async: true,
getFile: getFile,
plugins: {requirejs: {}, doc_comment: true, node: true, es_modules: true},
ecmaVersion: 9
};
// If a server is already created just reset the analysis data before marking it for GC
if (ternServer) {
ternServer.reset();
Infer.resetGuessing();
}
ternServer = new Tern.Server(ternOptions);
files.forEach(function (file) {
ternServer.addFile(file);
});
} |
JavaScript | function generateReadMe(answers) {
return `
${answers.title}
## Table of Contents
${answers.tableOfContents}
- [Description](#Description)
- [Installation](#Installation)
- [Usage](#Usage)
- [License](#License)
- [Contributors](#Contributors)
- [Tests](#Tests)
- [Questions](#Questions)
- [GitHub Username](#gitHubUsername)
## Description
${answers.description}
### Installation
${answers.installation}
### Usage
${answers.usage}
### License
${answers.license}
### Contributors
${answers.contributing}
### Tests
${answers.tests}
### Questions
${answers.questions}
### GitHub Username
${answers.gitHubUsername}
### Badges

Copyright 2020 ©
`;
} | function generateReadMe(answers) {
return `
${answers.title}
## Table of Contents
${answers.tableOfContents}
- [Description](#Description)
- [Installation](#Installation)
- [Usage](#Usage)
- [License](#License)
- [Contributors](#Contributors)
- [Tests](#Tests)
- [Questions](#Questions)
- [GitHub Username](#gitHubUsername)
## Description
${answers.description}
### Installation
${answers.installation}
### Usage
${answers.usage}
### License
${answers.license}
### Contributors
${answers.contributing}
### Tests
${answers.tests}
### Questions
${answers.questions}
### GitHub Username
${answers.gitHubUsername}
### Badges

Copyright 2020 ©
`;
} |
JavaScript | function GetUser(callback) {
var user = JSON.parse(localStorage.getItem('user'));
var userRequest = new UserRequest();
if (user !== null) {
userRequest.setId(user.id);
client.getUser(userRequest, {}, callback);
}
} | function GetUser(callback) {
var user = JSON.parse(localStorage.getItem('user'));
var userRequest = new UserRequest();
if (user !== null) {
userRequest.setId(user.id);
client.getUser(userRequest, {}, callback);
}
} |
JavaScript | function SignupUser(user, callback) {
var request = new BaseRequest();
if (!user) {
callback({message: "Cannot use a empty user in signup"});
}
request.setName(user.name);
request.setEmail(user.email);
request.setPassword(user.password);
client.createUser(request, {}, callback);
} | function SignupUser(user, callback) {
var request = new BaseRequest();
if (!user) {
callback({message: "Cannot use a empty user in signup"});
}
request.setName(user.name);
request.setEmail(user.email);
request.setPassword(user.password);
client.createUser(request, {}, callback);
} |
JavaScript | function LoginUser(user, callback) {
var request = new BaseRequest();
if (!user) {
callback({message: "Cannot use a emtpy user in login"});
}
request.setName(user.name);
request.setPassword(user.password);
client.login(request, {}, callback);
} | function LoginUser(user, callback) {
var request = new BaseRequest();
if (!user) {
callback({message: "Cannot use a emtpy user in login"});
}
request.setName(user.name);
request.setPassword(user.password);
client.login(request, {}, callback);
} |
JavaScript | function createHTML(logString) {
var content = document.getElementById("toast-content");
content.textContent = logString;
tau.openPopup("#toast");
} | function createHTML(logString) {
var content = document.getElementById("toast-content");
content.textContent = logString;
tau.openPopup("#toast");
} |
JavaScript | function isLoggedIn(req, res, next) {
console.log("checking to see if they are authenticated!");
// if user is authenticated in the session, carry on
res.locals.loggedIn = false;
if (req.isAuthenticated()) {
console.log("user has been Authenticated");
res.locals.loggedIn = true;
return next();
} else {
console.log("user has not been authenticated...");
return next();
}
} | function isLoggedIn(req, res, next) {
console.log("checking to see if they are authenticated!");
// if user is authenticated in the session, carry on
res.locals.loggedIn = false;
if (req.isAuthenticated()) {
console.log("user has been Authenticated");
res.locals.loggedIn = true;
return next();
} else {
console.log("user has not been authenticated...");
return next();
}
} |
JavaScript | function SimpleOfflineCache(cacheName, options, missPolicy) {
this.cacheName = cacheName || DEFAULT_CACHE_NAME;
this.options = options || DEFAULT_MATCH_OPTIONS;
this.missPolicy = missPolicy || DEFAULT_MISS_POLICY;
if (MISS_POLICIES.indexOf(this.missPolicy) === -1) {
console.warn("Policy " + missPolicy + " not supported");
this.missPolicy = DEFAULT_MISS_POLICY;
}
} | function SimpleOfflineCache(cacheName, options, missPolicy) {
this.cacheName = cacheName || DEFAULT_CACHE_NAME;
this.options = options || DEFAULT_MATCH_OPTIONS;
this.missPolicy = missPolicy || DEFAULT_MISS_POLICY;
if (MISS_POLICIES.indexOf(this.missPolicy) === -1) {
console.warn("Policy " + missPolicy + " not supported");
this.missPolicy = DEFAULT_MISS_POLICY;
}
} |
JavaScript | function* fileRequires(file, options) {
try {
const requires = detective(file.contents.toString('utf8'));
for (let n=0; n<requires.length; n++) {
if (options.debugVcjd) debug(`Found require for: ${requires[n]} in ${file.path}.`);
yield requires[n];
}
} catch(err) {
}
} | function* fileRequires(file, options) {
try {
const requires = detective(file.contents.toString('utf8'));
for (let n=0; n<requires.length; n++) {
if (options.debugVcjd) debug(`Found require for: ${requires[n]} in ${file.path}.`);
yield requires[n];
}
} catch(err) {
}
} |
JavaScript | function srcFilePusher(options) {
return through.obj(function(file, encoding, done) {
getAllFiles(file, options).then(files=>{
files.forEach(file=>this.push(file));
done();
}, err=>{});
})
} | function srcFilePusher(options) {
return through.obj(function(file, encoding, done) {
getAllFiles(file, options).then(files=>{
files.forEach(file=>this.push(file));
done();
}, err=>{});
})
} |
JavaScript | function createResolver(options) {
return (moduleId, base)=>new Promise((resolve, reject)=>{
const resolver = new Resolver(options.resolver?options.resolver:{});
resolver.resolve(moduleId, base, (err, absolutePath)=>{
if (err) {
if (options.debugVcjd) debug(`Could not resolve path to module: ${moduleId}\n\tfrom base: ${base}`);
return reject(err);
}
if (options.debugVcjd) debug(`Resolved module: ${moduleId}:\n\tfrom base: ${base}\n\t:is: ${base}`);
return resolve(absolutePath);
});
})
} | function createResolver(options) {
return (moduleId, base)=>new Promise((resolve, reject)=>{
const resolver = new Resolver(options.resolver?options.resolver:{});
resolver.resolve(moduleId, base, (err, absolutePath)=>{
if (err) {
if (options.debugVcjd) debug(`Could not resolve path to module: ${moduleId}\n\tfrom base: ${base}`);
return reject(err);
}
if (options.debugVcjd) debug(`Resolved module: ${moduleId}:\n\tfrom base: ${base}\n\t:is: ${base}`);
return resolve(absolutePath);
});
})
} |
JavaScript | function showCourseofstudy(faculty_id, studytype_id, courseofstudy_id) {
$.ajax({
url: "/moderator/faculties/" + faculty_id + "/assoziations/" + studytype_id + "/dropdown",
type: "GET",
success: showCouseofstudies,
dataType: "json"
});
function showCouseofstudies(courseofstudies) {
var content = $('#js-courseofstudies');
content.empty();
var html = '<div class="form-group" id="js-courseofstudies">' +
'<label class="control-label col-lg-2" for="assoziation_courseofstudy_id">' +
'Courseofstudy</label><div class="col-lg-10">' +
'<select name="assoziation[courseofstudy_id]" id="assoziation_courseofstudy_id" ' +
'remote="true" class="form-control"><option value="">Please select</option>';
for(i = 0; i < courseofstudies.length; i++) {
if(courseofstudy_id == courseofstudies[i].id) {
html += '<option selected value="' + courseofstudies[i].id+ '">' + courseofstudies[i].name + '</option>';
} else {
html += '<option value="' + courseofstudies[i].id+ '">' + courseofstudies[i].name + '</option>';
}
}
html += '</select></div></div>';
content.append(html);
}
} | function showCourseofstudy(faculty_id, studytype_id, courseofstudy_id) {
$.ajax({
url: "/moderator/faculties/" + faculty_id + "/assoziations/" + studytype_id + "/dropdown",
type: "GET",
success: showCouseofstudies,
dataType: "json"
});
function showCouseofstudies(courseofstudies) {
var content = $('#js-courseofstudies');
content.empty();
var html = '<div class="form-group" id="js-courseofstudies">' +
'<label class="control-label col-lg-2" for="assoziation_courseofstudy_id">' +
'Courseofstudy</label><div class="col-lg-10">' +
'<select name="assoziation[courseofstudy_id]" id="assoziation_courseofstudy_id" ' +
'remote="true" class="form-control"><option value="">Please select</option>';
for(i = 0; i < courseofstudies.length; i++) {
if(courseofstudy_id == courseofstudies[i].id) {
html += '<option selected value="' + courseofstudies[i].id+ '">' + courseofstudies[i].name + '</option>';
} else {
html += '<option value="' + courseofstudies[i].id+ '">' + courseofstudies[i].name + '</option>';
}
}
html += '</select></div></div>';
content.append(html);
}
} |
JavaScript | function createNameFieldContent() {
var content = $('#connection_name');
var lecture_name = $('#connection_lecture_id > option:selected').text();
var section_name = $('#connection_section_id > option:selected').text();
content.val(lecture_name + " <> " + section_name);
} | function createNameFieldContent() {
var content = $('#connection_name');
var lecture_name = $('#connection_lecture_id > option:selected').text();
var section_name = $('#connection_section_id > option:selected').text();
content.val(lecture_name + " <> " + section_name);
} |
JavaScript | formatCalendarHeader(datesForWeek, calendarHeaderFormat) {
if (!datesForWeek || datesForWeek.length === 0) {
return "";
}
let firstDay = datesForWeek[0];
let lastDay = datesForWeek[datesForWeek.length - 1];
let monthFormatting = "";
//Parsing the month part of the user defined formating
if ((calendarHeaderFormat.match(/Mo/g) || []).length > 0) {
monthFormatting = "Mo";
} else {
if ((calendarHeaderFormat.match(/M/g) || []).length > 0) {
for (
let i = (calendarHeaderFormat.match(/M/g) || []).length;
i > 0;
i--
) {
monthFormatting += "M";
}
}
}
if (firstDay.month() === lastDay.month()) {
return firstDay.format(calendarHeaderFormat);
} else if (firstDay.year() !== lastDay.year()) {
return `${firstDay.format(calendarHeaderFormat)} / ${lastDay.format(
calendarHeaderFormat
)}`;
}
return `${
monthFormatting.length > 1 ? firstDay.format(monthFormatting) : ""
} ${monthFormatting.length > 1 ? "/" : ""} ${lastDay.format(
calendarHeaderFormat
)}`;
} | formatCalendarHeader(datesForWeek, calendarHeaderFormat) {
if (!datesForWeek || datesForWeek.length === 0) {
return "";
}
let firstDay = datesForWeek[0];
let lastDay = datesForWeek[datesForWeek.length - 1];
let monthFormatting = "";
//Parsing the month part of the user defined formating
if ((calendarHeaderFormat.match(/Mo/g) || []).length > 0) {
monthFormatting = "Mo";
} else {
if ((calendarHeaderFormat.match(/M/g) || []).length > 0) {
for (
let i = (calendarHeaderFormat.match(/M/g) || []).length;
i > 0;
i--
) {
monthFormatting += "M";
}
}
}
if (firstDay.month() === lastDay.month()) {
return firstDay.format(calendarHeaderFormat);
} else if (firstDay.year() !== lastDay.year()) {
return `${firstDay.format(calendarHeaderFormat)} / ${lastDay.format(
calendarHeaderFormat
)}`;
}
return `${
monthFormatting.length > 1 ? firstDay.format(monthFormatting) : ""
} ${monthFormatting.length > 1 ? "/" : ""} ${lastDay.format(
calendarHeaderFormat
)}`;
} |
JavaScript | addReaction(req, res) {
// adds reaction to thought's reaction array
Thought.findOneAndUpdate(
{ _id: req.params.thoughtId },
{ $addToSet: { reactions: req.body } },
{ runValidators: true, new: true }
)
.then((reaction) =>
!reaction
? res.status(404).json({ message: "No reaction with this id!" })
: res.json(reaction)
)
.catch((err) => res.status(500).json(err));
} | addReaction(req, res) {
// adds reaction to thought's reaction array
Thought.findOneAndUpdate(
{ _id: req.params.thoughtId },
{ $addToSet: { reactions: req.body } },
{ runValidators: true, new: true }
)
.then((reaction) =>
!reaction
? res.status(404).json({ message: "No reaction with this id!" })
: res.json(reaction)
)
.catch((err) => res.status(500).json(err));
} |
JavaScript | function ConfirmPassword() {
var password = document.getElementById("password").value;
var confirmPassword = document.getElementById("secondpassword").value;
if (password === confirmPassword) {
return true
}
$('#error-confirmpassword').html('*Passwords must match')
$('#secondpassword').css('border', '1px solid red')
return false
} | function ConfirmPassword() {
var password = document.getElementById("password").value;
var confirmPassword = document.getElementById("secondpassword").value;
if (password === confirmPassword) {
return true
}
$('#error-confirmpassword').html('*Passwords must match')
$('#secondpassword').css('border', '1px solid red')
return false
} |
JavaScript | function ValidateField(name, val) {
if (!regx_patts[name][0].test(val)) {
form_is_good_to_post = false
if (name==='first_name') {
$('#'+name).css('margin-bottom', '0px')
}
$('#'+name).css('border', '1px solid red')
$('#error-'+name).html(regx_patts[name][1])
}
} | function ValidateField(name, val) {
if (!regx_patts[name][0].test(val)) {
form_is_good_to_post = false
if (name==='first_name') {
$('#'+name).css('margin-bottom', '0px')
}
$('#'+name).css('border', '1px solid red')
$('#error-'+name).html(regx_patts[name][1])
}
} |
JavaScript | function renderLicenseBadge(license) {
switch (license) {
case "Apache2":
return "https://img.shields.io/badge/license-Apache2-blue.svg";
case "GPLv3":
return "https://img.shields.io/badge/license-GPLv3-blue.svg";
case "ISC":
return "https://img.shields.io/badge/license-ISC-green.svg";
case "MIT":
return "https://img.shields.io/badge/license-MIT-green.svg";
default:
return "";
}
} | function renderLicenseBadge(license) {
switch (license) {
case "Apache2":
return "https://img.shields.io/badge/license-Apache2-blue.svg";
case "GPLv3":
return "https://img.shields.io/badge/license-GPLv3-blue.svg";
case "ISC":
return "https://img.shields.io/badge/license-ISC-green.svg";
case "MIT":
return "https://img.shields.io/badge/license-MIT-green.svg";
default:
return "";
}
} |
JavaScript | function renderLicenseLink(license) {
switch (license) {
case "Apache2":
return "https://www.apache.org/licenses/LICENSE-2.0";
case "GPLv3":
return "https://www.gnu.org/licenses/gpl-3.0.en.html";
case "ISC":
return "https://opensource.org/licenses/ISC";
case "MIT":
return "https://opensource.org/licenses/MIT";
default:
return "";
}
} | function renderLicenseLink(license) {
switch (license) {
case "Apache2":
return "https://www.apache.org/licenses/LICENSE-2.0";
case "GPLv3":
return "https://www.gnu.org/licenses/gpl-3.0.en.html";
case "ISC":
return "https://opensource.org/licenses/ISC";
case "MIT":
return "https://opensource.org/licenses/MIT";
default:
return "";
}
} |
JavaScript | function renderLicenseSection(license) {
return `}) This project is covered by ${renderLicenseLink(license)} license.`;
} | function renderLicenseSection(license) {
return `}) This project is covered by ${renderLicenseLink(license)} license.`;
} |
JavaScript | function generateMarkdown(data) {
return `# 09 Node.js Homework: ${data.projectTitle}
## License
${renderLicenseSection(data.license)}
## Description
${data.projectDescription}
## Table of Contents
- [License](#license)
- [Description](#description)
- [Installation Instructions](#installation-instructions)
- [Usage](#usage)
- [Contributing Guidelines](#contributing-guidelines)
- [Testing](#testing)
- [Questions](#questions)
## Installation Instructions
${data.installationInstructions}
## Usage
${data.usage}
## Contributing Guidelines
${data.contributingGuidelines}
## Testing
${data.testInstructions}
## Questions
You may find me on GitHub via my username: ${data.username}
\n
You may also contact me via my email address: ${data.email}
`;
} | function generateMarkdown(data) {
return `# 09 Node.js Homework: ${data.projectTitle}
## License
${renderLicenseSection(data.license)}
## Description
${data.projectDescription}
## Table of Contents
- [License](#license)
- [Description](#description)
- [Installation Instructions](#installation-instructions)
- [Usage](#usage)
- [Contributing Guidelines](#contributing-guidelines)
- [Testing](#testing)
- [Questions](#questions)
## Installation Instructions
${data.installationInstructions}
## Usage
${data.usage}
## Contributing Guidelines
${data.contributingGuidelines}
## Testing
${data.testInstructions}
## Questions
You may find me on GitHub via my username: ${data.username}
\n
You may also contact me via my email address: ${data.email}
`;
} |
JavaScript | function writeToFile(fileName, answers) {
fs.writeFile(filename, gM(answers), (err) => {
if (err) throw err;
console.log("success, the file has been created!");
});
} | function writeToFile(fileName, answers) {
fs.writeFile(filename, gM(answers), (err) => {
if (err) throw err;
console.log("success, the file has been created!");
});
} |
JavaScript | function init() {
inquirer
.prompt(questions)
.then((answers) => {
writeToFile(filename, answers);
})
.catch((error) => {
if (error.isTtyError) {
// Prompt couldn't be rendered in the current environment
console.log("error if: " + error.isTtyError);
} else {
// Something else went wrong
console.log("error else: " + error);
}
});
} | function init() {
inquirer
.prompt(questions)
.then((answers) => {
writeToFile(filename, answers);
})
.catch((error) => {
if (error.isTtyError) {
// Prompt couldn't be rendered in the current environment
console.log("error if: " + error.isTtyError);
} else {
// Something else went wrong
console.log("error else: " + error);
}
});
} |
JavaScript | function mostrarDatos(resultSet) {
var items;
items = [];
//Iterar sobre los registros: while(resultSet.isValidRow())
//Añadimos cada registro como item: items.push(prepararItem(registro))
while (resultSet.isValidRow()) {
items.push(prepararItem(resultSet));
resultSet.next();
}
//Cerramos resultSet
resultSet.close();
//Mostramos elementos en la lista
$.section.setItems(items);
} | function mostrarDatos(resultSet) {
var items;
items = [];
//Iterar sobre los registros: while(resultSet.isValidRow())
//Añadimos cada registro como item: items.push(prepararItem(registro))
while (resultSet.isValidRow()) {
items.push(prepararItem(resultSet));
resultSet.next();
}
//Cerramos resultSet
resultSet.close();
//Mostramos elementos en la lista
$.section.setItems(items);
} |
JavaScript | function prepararItem(registro) {
var pelicula = {
id : registro.fieldByName("id"),
titulo : registro.fieldByName("titulo"),
genero : registro.fieldByName("genero"),
año : registro.fieldByName("año"),
sinopsis : registro.fieldByName("sinopsis")
};
//Preparar objeto pelicula obteniendo la información
//para cada item del registro
return {
properties : {
width : Ti.UI.FILL,
height : 48,
title : pelicula.titulo,
color : "black",
accessoryType : Titanium.UI.LIST_ACCESSORY_TYPE_DISCLOSURE,
pelicula : pelicula
}
};
} | function prepararItem(registro) {
var pelicula = {
id : registro.fieldByName("id"),
titulo : registro.fieldByName("titulo"),
genero : registro.fieldByName("genero"),
año : registro.fieldByName("año"),
sinopsis : registro.fieldByName("sinopsis")
};
//Preparar objeto pelicula obteniendo la información
//para cada item del registro
return {
properties : {
width : Ti.UI.FILL,
height : 48,
title : pelicula.titulo,
color : "black",
accessoryType : Titanium.UI.LIST_ACCESSORY_TYPE_DISCLOSURE,
pelicula : pelicula
}
};
} |
JavaScript | function editarItem(e) {
//Obtener item de lista
var pelicula = e.section.getItemAt(e.itemIndex).properties.pelicula;
//Guardar ID en idEnEdicion
idEnEdicion = pelicula.id;
//Rellenar el formulario
$.titulo.setValue(pelicula.titulo);
$.genero.setValue(pelicula.genero);
$.año.setValue(pelicula.año);
$.sinopsis.setValue(pelicula.sinopsis);
//Establecemos modo de edición y mostramos formulario
modoEditor = MODO_EDICION;
$.editor.show();
} | function editarItem(e) {
//Obtener item de lista
var pelicula = e.section.getItemAt(e.itemIndex).properties.pelicula;
//Guardar ID en idEnEdicion
idEnEdicion = pelicula.id;
//Rellenar el formulario
$.titulo.setValue(pelicula.titulo);
$.genero.setValue(pelicula.genero);
$.año.setValue(pelicula.año);
$.sinopsis.setValue(pelicula.sinopsis);
//Establecemos modo de edición y mostramos formulario
modoEditor = MODO_EDICION;
$.editor.show();
} |
JavaScript | function guardarPelicula(e) {
if (modoEditor == MODO_NUEVO) {
insertarPelicula();
} else if (modoEditor == MODO_EDICION) {
actualizarPelicula();
}
//Cerramos editor
cerrarEditor();
//Refrescamos lista
actualizarLista();
} | function guardarPelicula(e) {
if (modoEditor == MODO_NUEVO) {
insertarPelicula();
} else if (modoEditor == MODO_EDICION) {
actualizarPelicula();
}
//Cerramos editor
cerrarEditor();
//Refrescamos lista
actualizarLista();
} |
JavaScript | function insertarPelicula() {
var query,
titulo,
genero,
año,
sinopsis;
//Solo insertamos si todos los campos tienen valores
if (esFormularioValido()) {
//Obtenemos datos del formulario
titulo = $.titulo.getValue();
genero = $.genero.getValue();
año = $.año.getValue();
sinopsis = $.sinopsis.getValue();
//Preparamos query
query = "INSERT INTO PELICULAS (TITULO, GENERO, AÑO, SINOPSIS) VALUES (?, ?, ?, ?);";
//Insertamos en la base de datos
db.execute(query, titulo, genero, año, sinopsis);
}
} | function insertarPelicula() {
var query,
titulo,
genero,
año,
sinopsis;
//Solo insertamos si todos los campos tienen valores
if (esFormularioValido()) {
//Obtenemos datos del formulario
titulo = $.titulo.getValue();
genero = $.genero.getValue();
año = $.año.getValue();
sinopsis = $.sinopsis.getValue();
//Preparamos query
query = "INSERT INTO PELICULAS (TITULO, GENERO, AÑO, SINOPSIS) VALUES (?, ?, ?, ?);";
//Insertamos en la base de datos
db.execute(query, titulo, genero, año, sinopsis);
}
} |
JavaScript | function actualizarPelicula() {
var query,
titulo,
genero,
año,
sinopsis;
//Solo actualizamos si todos los campos tienen valores
if (esFormularioValido()) {
//Obtenemos datos del formulario
titulo = $.titulo.getValue();
genero = $.genero.getValue();
año = $.año.getValue();
sinopsis = $.sinopsis.getValue();
//Preparamos query
query = "UPDATE PELICULAS SET TITULO=?, GENERO=?, AÑO=?, SINOPSIS=? WHERE ID=?;";
//Actualizamos la base de datos
db.execute(query, titulo, genero, año, sinopsis, idEnEdicion);
}
} | function actualizarPelicula() {
var query,
titulo,
genero,
año,
sinopsis;
//Solo actualizamos si todos los campos tienen valores
if (esFormularioValido()) {
//Obtenemos datos del formulario
titulo = $.titulo.getValue();
genero = $.genero.getValue();
año = $.año.getValue();
sinopsis = $.sinopsis.getValue();
//Preparamos query
query = "UPDATE PELICULAS SET TITULO=?, GENERO=?, AÑO=?, SINOPSIS=? WHERE ID=?;";
//Actualizamos la base de datos
db.execute(query, titulo, genero, año, sinopsis, idEnEdicion);
}
} |
JavaScript | function borrarPelicula() {
var query;
if (modoEditor == MODO_EDICION) {
//Preparamos query con idEnEdicion
query = "DELETE FROM PELICULAS WHERE ID=?;";
//Eliminamos registro
db.execute(query, idEnEdicion);
//Actualizamos la lista
actualizarLista();
cerrarEditor();
}
} | function borrarPelicula() {
var query;
if (modoEditor == MODO_EDICION) {
//Preparamos query con idEnEdicion
query = "DELETE FROM PELICULAS WHERE ID=?;";
//Eliminamos registro
db.execute(query, idEnEdicion);
//Actualizamos la lista
actualizarLista();
cerrarEditor();
}
} |
JavaScript | function cerrarEditor(e) {
//Reset idEnEdicion y editor
idEnEdicion = null;
modoEditor = null;
//Reset formulario
$.titulo.setValue("");
$.genero.setValue("");
$.año.setValue("");
$.sinopsis.setValue("");
//Ocultamos editor
$.editor.hide();
} | function cerrarEditor(e) {
//Reset idEnEdicion y editor
idEnEdicion = null;
modoEditor = null;
//Reset formulario
$.titulo.setValue("");
$.genero.setValue("");
$.año.setValue("");
$.sinopsis.setValue("");
//Ocultamos editor
$.editor.hide();
} |
JavaScript | function esFormularioValido() {
return ["titulo", "genero", "año", "sinopsis"].every(function(campo) {
return $[campo].hasText();
});
} | function esFormularioValido() {
return ["titulo", "genero", "año", "sinopsis"].every(function(campo) {
return $[campo].hasText();
});
} |
JavaScript | function leerFichero(e) {
var file,
text;
//Obtenemos manejador de fichero
//Utilizamos directorio privado de aplicación
//Nombre de fichero: miFichero.txt
file = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, "miFichero.txt");
//Si no existe mostramos un mensaje indicando que no existe el fichero
text = "No existe el fichero";
//Si fichero existe lo leemos y volcamos contenido sobre etiqueta #fileContent
if (file.exists()) {
text = file.read().text;
}
//Establecemos con tenido de fichero en Label
$.fileContent.setText(text);
} | function leerFichero(e) {
var file,
text;
//Obtenemos manejador de fichero
//Utilizamos directorio privado de aplicación
//Nombre de fichero: miFichero.txt
file = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, "miFichero.txt");
//Si no existe mostramos un mensaje indicando que no existe el fichero
text = "No existe el fichero";
//Si fichero existe lo leemos y volcamos contenido sobre etiqueta #fileContent
if (file.exists()) {
text = file.read().text;
}
//Establecemos con tenido de fichero en Label
$.fileContent.setText(text);
} |
JavaScript | function escribirFichero(e) {
var text;
text = $.textArea.getValue();
//Solo escribimos si hay contenido en el área de texto #textArea
if (text.length) {
//Obtenemos manejador de fichero
//Utilizamos directorio privado de aplicación
//Nombre de fichero: miFichero.txt
Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, "miFichero.txt").write(text);
//Si escritura exitosa mostramos mensaje de alerta indicando el éxito
Alloy.Globals.dialog("Alerta", "Fichero texto.txt guardado.");
} else {
Alloy.Globals.dialog("Alerta", "Text Area vacío. No guardamos el fichero");
}
} | function escribirFichero(e) {
var text;
text = $.textArea.getValue();
//Solo escribimos si hay contenido en el área de texto #textArea
if (text.length) {
//Obtenemos manejador de fichero
//Utilizamos directorio privado de aplicación
//Nombre de fichero: miFichero.txt
Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, "miFichero.txt").write(text);
//Si escritura exitosa mostramos mensaje de alerta indicando el éxito
Alloy.Globals.dialog("Alerta", "Fichero texto.txt guardado.");
} else {
Alloy.Globals.dialog("Alerta", "Text Area vacío. No guardamos el fichero");
}
} |
JavaScript | function clickEnMenu(e) {
//Implementar función que asigna una clase activa al menú pulsado
//Y deja el resto como inactivas
var resetItems,
label;
switch(e.source.id) {
case "inicio":
$.addClass($.inicio, "menuItemActivo");
resetItems = ["fotos", "mensajes", "perfil"];
label = "Inicio";
break;
case "fotos":
$.addClass($.fotos, "menuItemActivo");
resetItems = ["inicio", "mensajes", "perfil"];
label = "Fotos";
break;
case "mensajes":
$.addClass($.mensajes, "menuItemActivo");
resetItems = ["inicio", "fotos", "perfil"];
label = "Mensajes";
break;
case "perfil":
$.addClass($.perfil, "menuItemActivo");
resetItems = ["inicio", "fotos", "mensajes"];
label = "Perfil";
break;
default:
break;
}
if (resetItems) {
resetItems.forEach(function(item) {
$.resetClass($[item], item);
});
}
//Añadir contenido a vista contenedor.
if (label) {
//Si ya hay una vista en el contenedor
//debemos eliminarla antes para añadir la nueva
$.container.removeAllChildren();
$.container.add(Ti.UI.createLabel({
text : label,
color : Alloy.CFG.negro,
font: {
fontSize: 18,
fontWeight: "bold"
}
}));
}
} | function clickEnMenu(e) {
//Implementar función que asigna una clase activa al menú pulsado
//Y deja el resto como inactivas
var resetItems,
label;
switch(e.source.id) {
case "inicio":
$.addClass($.inicio, "menuItemActivo");
resetItems = ["fotos", "mensajes", "perfil"];
label = "Inicio";
break;
case "fotos":
$.addClass($.fotos, "menuItemActivo");
resetItems = ["inicio", "mensajes", "perfil"];
label = "Fotos";
break;
case "mensajes":
$.addClass($.mensajes, "menuItemActivo");
resetItems = ["inicio", "fotos", "perfil"];
label = "Mensajes";
break;
case "perfil":
$.addClass($.perfil, "menuItemActivo");
resetItems = ["inicio", "fotos", "mensajes"];
label = "Perfil";
break;
default:
break;
}
if (resetItems) {
resetItems.forEach(function(item) {
$.resetClass($[item], item);
});
}
//Añadir contenido a vista contenedor.
if (label) {
//Si ya hay una vista en el contenedor
//debemos eliminarla antes para añadir la nueva
$.container.removeAllChildren();
$.container.add(Ti.UI.createLabel({
text : label,
color : Alloy.CFG.negro,
font: {
fontSize: 18,
fontWeight: "bold"
}
}));
}
} |
JavaScript | onUploadResponse(text) {
const em = this.config.em;
const config = this.config;
const target = this.target;
const json = JSON.parse(text);
em && em.trigger('asset:upload:response', json);
if (config.autoAdd && target) {
target.add(json.data);
}
this.onUploadEnd(text);
} | onUploadResponse(text) {
const em = this.config.em;
const config = this.config;
const target = this.target;
const json = JSON.parse(text);
em && em.trigger('asset:upload:response', json);
if (config.autoAdd && target) {
target.add(json.data);
}
this.onUploadEnd(text);
} |
JavaScript | updateDimensions() {
this.setState({
width: window.innerWidth,
height: window.innerHeight
});
} | updateDimensions() {
this.setState({
width: window.innerWidth,
height: window.innerHeight
});
} |
JavaScript | function humanReadable(totalSeconds) {
const hours = Math.floor(totalSeconds / 3600);
const remainder = totalSeconds % 3600;
const minutes = Math.floor(remainder / 60);
const seconds = remainder % 60;
return [hours, minutes, seconds].map(num => String(num).padStart(2, '0')).join(':');
} | function humanReadable(totalSeconds) {
const hours = Math.floor(totalSeconds / 3600);
const remainder = totalSeconds % 3600;
const minutes = Math.floor(remainder / 60);
const seconds = remainder % 60;
return [hours, minutes, seconds].map(num => String(num).padStart(2, '0')).join(':');
} |
JavaScript | function lyricSegment(n) {
return _.chain([])
.push(`${n} ${n > 1 ? 'bottles' : 'bottle'} of beer on the wall`)
.push(`${n} ${n > 1 ? 'bottles' : 'bottle'} of beer`)
.push('Take one down and pass it around')
.tap((lyrics) => {
if (n > 1) {
lyrics.push(`${n - 1} ${n - 1 > 1 ? 'bottles' : 'bottle'} of beer on the wall`);
} else {
lyrics.push('No more bottles of beer on the wall');
}
})
.value();
} | function lyricSegment(n) {
return _.chain([])
.push(`${n} ${n > 1 ? 'bottles' : 'bottle'} of beer on the wall`)
.push(`${n} ${n > 1 ? 'bottles' : 'bottle'} of beer`)
.push('Take one down and pass it around')
.tap((lyrics) => {
if (n > 1) {
lyrics.push(`${n - 1} ${n - 1 > 1 ? 'bottles' : 'bottle'} of beer on the wall`);
} else {
lyrics.push('No more bottles of beer on the wall');
}
})
.value();
} |
JavaScript | function uniqueString1(count) {
// Generate a random number
// Convert it to a base-36 string
// Skip the first two characters ('0x')
return Math.random().toString(36).substr(2, count);
} | function uniqueString1(count) {
// Generate a random number
// Convert it to a base-36 string
// Skip the first two characters ('0x')
return Math.random().toString(36).substr(2, count);
} |
JavaScript | function complement(pred) {
return function(/* arguments */) {
return !pred.apply(null, _.toArray(arguments));
}
} | function complement(pred) {
return function(/* arguments */) {
return !pred.apply(null, _.toArray(arguments));
}
} |
JavaScript | function parseGetParameters(parameter) {
var fullURL = window.location.search.substring(1);
var parametersArray = fullURL.split('&');
for (var i = 0; i < parametersArray.length; i++) {
var currentParameter = parametersArray[i].split('=');
if (currentParameter[0] == parameter)
return currentParameter[1];
}
} | function parseGetParameters(parameter) {
var fullURL = window.location.search.substring(1);
var parametersArray = fullURL.split('&');
for (var i = 0; i < parametersArray.length; i++) {
var currentParameter = parametersArray[i].split('=');
if (currentParameter[0] == parameter)
return currentParameter[1];
}
} |
JavaScript | function catPathToString(string) {
var the_arr = window.location.href.split('/');
the_arr.pop();
return(the_arr.join('/') + '/' + string);
} | function catPathToString(string) {
var the_arr = window.location.href.split('/');
the_arr.pop();
return(the_arr.join('/') + '/' + string);
} |
JavaScript | function openModal(returnArr, formModal) {
if (returnArr['usernameSpecCharFound'] == 1) {
document.getElementById('modalHeader').innerHTML = 'Double-check form';
document.getElementById('modalText').innerHTML = 'Username contains special characters.';
formModal.style.display = 'flex';
}
if (returnArr['usernameNotRegistered'] == 1) {
document.getElementById('modalHeader').innerHTML = 'Double-check form';
document.getElementById('modalText').innerHTML = 'Username is invalid.';
formModal.style.display = 'flex';
}
if (returnArr['forgotPasswordEmailSent'] == 1) {
document.getElementById('modalHeader').innerHTML = 'Password reset email sent';
document.getElementById('modalText').innerHTML = 'We\'ve sent you an email to reset your password, please follow the instructions carefully.';
formModal.style.display = 'flex';
}
} | function openModal(returnArr, formModal) {
if (returnArr['usernameSpecCharFound'] == 1) {
document.getElementById('modalHeader').innerHTML = 'Double-check form';
document.getElementById('modalText').innerHTML = 'Username contains special characters.';
formModal.style.display = 'flex';
}
if (returnArr['usernameNotRegistered'] == 1) {
document.getElementById('modalHeader').innerHTML = 'Double-check form';
document.getElementById('modalText').innerHTML = 'Username is invalid.';
formModal.style.display = 'flex';
}
if (returnArr['forgotPasswordEmailSent'] == 1) {
document.getElementById('modalHeader').innerHTML = 'Password reset email sent';
document.getElementById('modalText').innerHTML = 'We\'ve sent you an email to reset your password, please follow the instructions carefully.';
formModal.style.display = 'flex';
}
} |
JavaScript | function addCommentToPic(event, pictureID) {
event.preventDefault();
var commentBoxValue = document.getElementById('commentBox').value;
var xhr = new XMLHttpRequest();
xhr.open('POST', 'processComments.php', true);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.onload = function() {
var returnArr = JSON.parse(this.responseText);
if (returnArr['updateComments'] == 1)
increaseComments(returnArr['username'], commentBoxValue);
if (returnArr['noPicID'] == 1) {
document.getElementById('modalHeader').innerHTML = 'Picture doesn\'t exist';
document.getElementById('modalText').innerHTML = 'The related picture does not exist.';
formModal.style.display = 'flex';
}
}
xhr.send('commentBoxValue=' + commentBoxValue + '&' + 'pictureID=' + pictureID);
document.getElementById('commentBox').value = '';
} | function addCommentToPic(event, pictureID) {
event.preventDefault();
var commentBoxValue = document.getElementById('commentBox').value;
var xhr = new XMLHttpRequest();
xhr.open('POST', 'processComments.php', true);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.onload = function() {
var returnArr = JSON.parse(this.responseText);
if (returnArr['updateComments'] == 1)
increaseComments(returnArr['username'], commentBoxValue);
if (returnArr['noPicID'] == 1) {
document.getElementById('modalHeader').innerHTML = 'Picture doesn\'t exist';
document.getElementById('modalText').innerHTML = 'The related picture does not exist.';
formModal.style.display = 'flex';
}
}
xhr.send('commentBoxValue=' + commentBoxValue + '&' + 'pictureID=' + pictureID);
document.getElementById('commentBox').value = '';
} |
JavaScript | function escapeHTML(string) {
return string
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
} | function escapeHTML(string) {
return string
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
} |
JavaScript | function openModal(returnArr, formModal) {
// Logic - Modal - Username.
if (returnArr['usernameTooLong'] == 1) {
document.getElementById('modalText').innerHTML = 'Username too long, maximum 32 characters.';
formModal.style.display = 'flex';
}
if (returnArr['usernameTooShort'] == 1) {
document.getElementById('modalText').innerHTML = 'Username too short, minimum 4 characters.';
formModal.style.display = 'flex';
}
if (returnArr['usernameSpecCharFound'] == 1) {
document.getElementById('modalText').innerHTML = 'Username contains special characters.';
formModal.style.display = 'flex';
}
if (returnArr['usernameMultipleWords'] == 1) {
document.getElementById('modalText').innerHTML = 'Username contains multiple words.';
formModal.style.display = 'flex';
}
if (returnArr['usernameTaken'] == 1) {
document.getElementById('modalText').innerHTML = 'Username taken, try another username.';
formModal.style.display = 'flex';
}
// Logic - Modal - Passwords.
if (returnArr['passwordTooShort'] == 1) {
document.getElementById('modalText').innerHTML = 'Password(s) too short, minimum 7 characters.';
formModal.style.display = 'flex';
}
if (returnArr['passwordNoMix'] == 1) {
document.getElementById('modalText').innerHTML = 'Password(s) not mixed case.';
formModal.style.display = 'flex';
}
if (returnArr['passwordMatch'] == 0) {
document.getElementById('modalText').innerHTML = 'Passwords do not match.';
formModal.style.display = 'flex';
}
// Logic - Modal - Email.
if (returnArr['emailTooLong'] == 1) {
document.getElementById('modalText').innerHTML = 'Email address too long, maximum 32 characters.';
formModal.style.display = 'flex';
}
if (returnArr['emailNotValid'] == 1) {
document.getElementById('modalText').innerHTML = 'Email address is not valid';
formModal.style.display = 'flex';
}
if (returnArr['emailTaken'] == 1) {
document.getElementById('modalText').innerHTML = 'Email address taken, try another email address.';
formModal.style.display = 'flex';
}
// Logic - Modal - Account created.
if (returnArr['accountCreated'] == 1) {
document.getElementById('modalHeader').innerHTML = 'Account created';
document.getElementById('modalText').innerHTML = 'To verify your account, follow the instructions in the message sent your email address.';
formModal.style.display = 'flex';
}
} | function openModal(returnArr, formModal) {
// Logic - Modal - Username.
if (returnArr['usernameTooLong'] == 1) {
document.getElementById('modalText').innerHTML = 'Username too long, maximum 32 characters.';
formModal.style.display = 'flex';
}
if (returnArr['usernameTooShort'] == 1) {
document.getElementById('modalText').innerHTML = 'Username too short, minimum 4 characters.';
formModal.style.display = 'flex';
}
if (returnArr['usernameSpecCharFound'] == 1) {
document.getElementById('modalText').innerHTML = 'Username contains special characters.';
formModal.style.display = 'flex';
}
if (returnArr['usernameMultipleWords'] == 1) {
document.getElementById('modalText').innerHTML = 'Username contains multiple words.';
formModal.style.display = 'flex';
}
if (returnArr['usernameTaken'] == 1) {
document.getElementById('modalText').innerHTML = 'Username taken, try another username.';
formModal.style.display = 'flex';
}
// Logic - Modal - Passwords.
if (returnArr['passwordTooShort'] == 1) {
document.getElementById('modalText').innerHTML = 'Password(s) too short, minimum 7 characters.';
formModal.style.display = 'flex';
}
if (returnArr['passwordNoMix'] == 1) {
document.getElementById('modalText').innerHTML = 'Password(s) not mixed case.';
formModal.style.display = 'flex';
}
if (returnArr['passwordMatch'] == 0) {
document.getElementById('modalText').innerHTML = 'Passwords do not match.';
formModal.style.display = 'flex';
}
// Logic - Modal - Email.
if (returnArr['emailTooLong'] == 1) {
document.getElementById('modalText').innerHTML = 'Email address too long, maximum 32 characters.';
formModal.style.display = 'flex';
}
if (returnArr['emailNotValid'] == 1) {
document.getElementById('modalText').innerHTML = 'Email address is not valid';
formModal.style.display = 'flex';
}
if (returnArr['emailTaken'] == 1) {
document.getElementById('modalText').innerHTML = 'Email address taken, try another email address.';
formModal.style.display = 'flex';
}
// Logic - Modal - Account created.
if (returnArr['accountCreated'] == 1) {
document.getElementById('modalHeader').innerHTML = 'Account created';
document.getElementById('modalText').innerHTML = 'To verify your account, follow the instructions in the message sent your email address.';
formModal.style.display = 'flex';
}
} |
JavaScript | function clearPicture(mode) {
takePicButtonClicks = 0;
uploadChange = 0;
uploadButton.value = '';
for (var cntr = 1; cntr <= 8; cntr++) {
let stickerTag = document.getElementById('sticker' + cntr);
if (stickerTag !== null)
stickerTag.remove();
}
stickerChangeCount = 0;
stickerChangeImageId = 0;
sticker2Path = undefined;
sticker4Path = undefined;
sticker6Path = undefined;
sticker8Path = undefined;
if (mode == 0)
return;
document.getElementById('videoDiv').style.display = "flex";
document.getElementById('canvasDiv').style.display = "none";
} | function clearPicture(mode) {
takePicButtonClicks = 0;
uploadChange = 0;
uploadButton.value = '';
for (var cntr = 1; cntr <= 8; cntr++) {
let stickerTag = document.getElementById('sticker' + cntr);
if (stickerTag !== null)
stickerTag.remove();
}
stickerChangeCount = 0;
stickerChangeImageId = 0;
sticker2Path = undefined;
sticker4Path = undefined;
sticker6Path = undefined;
sticker8Path = undefined;
if (mode == 0)
return;
document.getElementById('videoDiv').style.display = "flex";
document.getElementById('canvasDiv').style.display = "none";
} |
JavaScript | function updateUserGallery() {
var xhr = new XMLHttpRequest();
xhr.open('POST', 'processUpdateUserGallery.php', true);
xhr.onload = function() {
var returnArr = JSON.parse(this.responseText);
if (returnArr['updateUserGalleryFail'] == 1) {
document.getElementById('modalHeader').innerHTML = 'Notice';
document.getElementById('modalText').innerHTML = 'Async update to user gallery failed.';
formModal.style.display = 'flex';
}
if (returnArr['gotNewestPic'] == 1) {
let newUserPicture = document.createElement('img');
newUserPicture.setAttribute('src', returnArr['encodedPicture']);
newUserPicture.setAttribute('class', 'userPicture');
newUserPicture.setAttribute('id', 'userPic' + returnArr['pictureID']);
newUserPicture.setAttribute('onclick', 'delUserPic(this)');
document.getElementById('userPictureGallery1').appendChild(newUserPicture);
}
}
xhr.send();
} | function updateUserGallery() {
var xhr = new XMLHttpRequest();
xhr.open('POST', 'processUpdateUserGallery.php', true);
xhr.onload = function() {
var returnArr = JSON.parse(this.responseText);
if (returnArr['updateUserGalleryFail'] == 1) {
document.getElementById('modalHeader').innerHTML = 'Notice';
document.getElementById('modalText').innerHTML = 'Async update to user gallery failed.';
formModal.style.display = 'flex';
}
if (returnArr['gotNewestPic'] == 1) {
let newUserPicture = document.createElement('img');
newUserPicture.setAttribute('src', returnArr['encodedPicture']);
newUserPicture.setAttribute('class', 'userPicture');
newUserPicture.setAttribute('id', 'userPic' + returnArr['pictureID']);
newUserPicture.setAttribute('onclick', 'delUserPic(this)');
document.getElementById('userPictureGallery1').appendChild(newUserPicture);
}
}
xhr.send();
} |
JavaScript | function delUserPic(element) {
var string = element.id;
var arr = string.split('userPic');
var pictureID = arr[1];
var xhr = new XMLHttpRequest();
xhr.open('POST', 'processUpdateUserGalleryRem.php', true);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.onload = function() {
var returnArr = JSON.parse(this.responseText);
if (returnArr['updateUserGalleryRemFail'] == 1) {
document.getElementById('modalHeader').innerHTML = 'Notice';
document.getElementById('modalText').innerHTML = 'Async update to user gallery failed.';
formModal.style.display = 'flex';
}
if (returnArr['deletedPicture'] == 1)
element.parentNode.removeChild(element);
}
xhr.send('pictureID=' + pictureID);
} | function delUserPic(element) {
var string = element.id;
var arr = string.split('userPic');
var pictureID = arr[1];
var xhr = new XMLHttpRequest();
xhr.open('POST', 'processUpdateUserGalleryRem.php', true);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.onload = function() {
var returnArr = JSON.parse(this.responseText);
if (returnArr['updateUserGalleryRemFail'] == 1) {
document.getElementById('modalHeader').innerHTML = 'Notice';
document.getElementById('modalText').innerHTML = 'Async update to user gallery failed.';
formModal.style.display = 'flex';
}
if (returnArr['deletedPicture'] == 1)
element.parentNode.removeChild(element);
}
xhr.send('pictureID=' + pictureID);
} |
JavaScript | function openModal(returnArr, formModal) {
// Logic - Modal - Username.
if (returnArr['usernameTooLong'] == 1) {
document.getElementById('modalText').innerHTML = 'Username too long, maximum 32 characters.';
formModal.style.display = 'flex';
}
if (returnArr['usernameTooShort'] == 1) {
document.getElementById('modalText').innerHTML = 'Username too short, minimum 4 characters.';
formModal.style.display = 'flex';
}
if (returnArr['usernameSpecCharFound'] == 1) {
document.getElementById('modalText').innerHTML = 'Username contains special characters.';
formModal.style.display = 'flex';
}
if (returnArr['usernameMultipleWords'] == 1) {
document.getElementById('modalText').innerHTML = 'Username contains multiple words.';
formModal.style.display = 'flex';
}
if (returnArr['usernameTaken'] == 1) {
document.getElementById('modalText').innerHTML = 'Username taken, try another username.';
formModal.style.display = 'flex';
}
// Logic - Modal - Passwords.
if (returnArr['passwordTooShort'] == 1) {
document.getElementById('modalText').innerHTML = 'Password too short, minimum 7 characters.';
formModal.style.display = 'flex';
}
if (returnArr['passwordNoMix'] == 1) {
document.getElementById('modalText').innerHTML = 'Password(s) not mixed case.';
formModal.style.display = 'flex';
}
if (returnArr['passwordMatch'] == 0) {
document.getElementById('modalText').innerHTML = 'Passwords do not match.';
formModal.style.display = 'flex';
}
// Logic - Modal - Email.
if (returnArr['emailTooLong'] == 1) {
document.getElementById('modalText').innerHTML = 'Email address too long, maximum 32 characters.';
formModal.style.display = 'flex';
}
if (returnArr['emailNotValid'] == 1) {
document.getElementById('modalText').innerHTML = 'Email address is not valid';
formModal.style.display = 'flex';
}
if (returnArr['emailTaken'] == 1) {
document.getElementById('modalText').innerHTML = 'Email address taken, try another email address.';
formModal.style.display = 'flex';
}
// Logic - Modal - Profile edited.
if (returnArr['editedProfile'] == 1) {
document.getElementById('modalHeader').innerHTML = 'Edited profile';
document.getElementById('modalText').innerHTML = 'You have successfully edited your profile, make sure to keep your details safe.';
formModal.style.display = 'flex';
}
} | function openModal(returnArr, formModal) {
// Logic - Modal - Username.
if (returnArr['usernameTooLong'] == 1) {
document.getElementById('modalText').innerHTML = 'Username too long, maximum 32 characters.';
formModal.style.display = 'flex';
}
if (returnArr['usernameTooShort'] == 1) {
document.getElementById('modalText').innerHTML = 'Username too short, minimum 4 characters.';
formModal.style.display = 'flex';
}
if (returnArr['usernameSpecCharFound'] == 1) {
document.getElementById('modalText').innerHTML = 'Username contains special characters.';
formModal.style.display = 'flex';
}
if (returnArr['usernameMultipleWords'] == 1) {
document.getElementById('modalText').innerHTML = 'Username contains multiple words.';
formModal.style.display = 'flex';
}
if (returnArr['usernameTaken'] == 1) {
document.getElementById('modalText').innerHTML = 'Username taken, try another username.';
formModal.style.display = 'flex';
}
// Logic - Modal - Passwords.
if (returnArr['passwordTooShort'] == 1) {
document.getElementById('modalText').innerHTML = 'Password too short, minimum 7 characters.';
formModal.style.display = 'flex';
}
if (returnArr['passwordNoMix'] == 1) {
document.getElementById('modalText').innerHTML = 'Password(s) not mixed case.';
formModal.style.display = 'flex';
}
if (returnArr['passwordMatch'] == 0) {
document.getElementById('modalText').innerHTML = 'Passwords do not match.';
formModal.style.display = 'flex';
}
// Logic - Modal - Email.
if (returnArr['emailTooLong'] == 1) {
document.getElementById('modalText').innerHTML = 'Email address too long, maximum 32 characters.';
formModal.style.display = 'flex';
}
if (returnArr['emailNotValid'] == 1) {
document.getElementById('modalText').innerHTML = 'Email address is not valid';
formModal.style.display = 'flex';
}
if (returnArr['emailTaken'] == 1) {
document.getElementById('modalText').innerHTML = 'Email address taken, try another email address.';
formModal.style.display = 'flex';
}
// Logic - Modal - Profile edited.
if (returnArr['editedProfile'] == 1) {
document.getElementById('modalHeader').innerHTML = 'Edited profile';
document.getElementById('modalText').innerHTML = 'You have successfully edited your profile, make sure to keep your details safe.';
formModal.style.display = 'flex';
}
} |
JavaScript | function openModal(returnArr, formModal) {
// Logic - Modal - Username.
if (returnArr['usernameInvalid'] == 1) {
document.getElementById('modalHeader').innerHTML = 'Double-check form';
document.getElementById('modalText').innerHTML = 'Username invalid.';
formModal.style.display = 'flex';
}
// Logic - Modal - Passwords.
if (returnArr['passwordInvalid'] == 1) {
document.getElementById('modalHeader').innerHTML = 'Double-check form';
document.getElementById('modalText').innerHTML = 'Password invalid.';
formModal.style.display = 'flex';
}
// Logic - Modal - Account verification.
if (returnArr['accountNotVerified'] == 1) {
document.getElementById('modalHeader').innerHTML = 'Verify account';
document.getElementById('modalText').innerHTML = 'Your account needs to be verified before you can sign in.';
formModal.style.display = 'flex';
}
// Logic - Modal - Sign in.
if (returnArr['successfulSignin'] == 1) {
var username = returnArr['username'];
window.location = catPathToString('index.php?signin=success&username=') + username;
}
} | function openModal(returnArr, formModal) {
// Logic - Modal - Username.
if (returnArr['usernameInvalid'] == 1) {
document.getElementById('modalHeader').innerHTML = 'Double-check form';
document.getElementById('modalText').innerHTML = 'Username invalid.';
formModal.style.display = 'flex';
}
// Logic - Modal - Passwords.
if (returnArr['passwordInvalid'] == 1) {
document.getElementById('modalHeader').innerHTML = 'Double-check form';
document.getElementById('modalText').innerHTML = 'Password invalid.';
formModal.style.display = 'flex';
}
// Logic - Modal - Account verification.
if (returnArr['accountNotVerified'] == 1) {
document.getElementById('modalHeader').innerHTML = 'Verify account';
document.getElementById('modalText').innerHTML = 'Your account needs to be verified before you can sign in.';
formModal.style.display = 'flex';
}
// Logic - Modal - Sign in.
if (returnArr['successfulSignin'] == 1) {
var username = returnArr['username'];
window.location = catPathToString('index.php?signin=success&username=') + username;
}
} |
JavaScript | function ipinfoLocToGeoJSON(ipinfoLocString) {
let numArr = ipinfoLocString.split(',');
let longitude = parseFloat(numArr[1]);
let latitude = parseFloat(numArr[0]);
return ({ type: "Point", coordinates: [longitude, latitude] });
} | function ipinfoLocToGeoJSON(ipinfoLocString) {
let numArr = ipinfoLocString.split(',');
let longitude = parseFloat(numArr[1]);
let latitude = parseFloat(numArr[0]);
return ({ type: "Point", coordinates: [longitude, latitude] });
} |
JavaScript | function escapeSpecChars(string) {
return string
// .replace(/&/g, "&")
// .replace(/</g, "<")
// .replace(/>/g, ">")
// .replace(/"/g, """)
// .replace(/'/g, "'");
} | function escapeSpecChars(string) {
return string
// .replace(/&/g, "&")
// .replace(/</g, "<")
// .replace(/>/g, ">")
// .replace(/"/g, """)
// .replace(/'/g, "'");
} |
JavaScript | function registerUserInfoValid(req, res, signalObj) {
let fillMsg = "Please fill in all input fields.";
let invalidTypeMsg = "Your input types are incorrect.";
let firstNameTooLong = "First name is too long.";
let firstNameTooShort = "First name is too short.";
let lastNameTooLong = "Last name is too long.";
let lastNameTooShort = "Last name is too short.";
let usernameTooLong = "Username is too long.";
let usernameTooShort = "Username is too short.";
let usernameNotMixed = "Username must contain digits.";
let correctAgeMsg = "You need to be older than 18 to register.";
let invalidGenderMsg = "Invalid gender.";
let invalidSexuality = "Invalid sexuality.";
let incorrectLocFormat = "ipinfoLocString isn\'t formatted correctly.";
let incorrectLocSplit = "ipinfoLocString doesn\'t split correctly.";
let emailTooLong = "Entered email is too long";
let incorrectEmail = "Entered email is incorrect.";
let passwordTooLong = "Entered password is too long";
let passwordTooShort = "Entered password is too short";
let passwordWeak = "Entered password is weak, try mixing cases, digits and special characters.";
// Check if all fields filled in.
if (hasAllRegisterProperties(req) == false)
return res.json({ success: false, msg: fillMsg });
// Check types.
if (
typeof req.body.firstName != 'string' ||
typeof req.body.lastName != 'string' ||
typeof req.body.username != 'string' ||
typeof req.body.age != 'number' ||
typeof req.body.gender != 'string' ||
typeof req.body.sexuality != 'string' ||
typeof req.body.ipinfoLoc != 'string' ||
typeof req.body.email != 'string' ||
typeof req.body.password != 'string')
return res.json({ success: false, msg: invalidTypeMsg });
let firstNameLength = req.body.firstName.length;
let lastNameLength = req.body.lastName.length;
let usernameLength = req.body.username.length;
// Check firstName, lastName and username.
if (firstNameLength > 32)
return res.json({ success: false, msg: firstNameTooLong });
if (firstNameLength < 2)
return res.json({ success: false, msg: firstNameTooShort });
if (lastNameLength > 32)
return res.json({ success: false, msg: lastNameTooLong });
if (lastNameLength < 2)
return res.json({ success: false, msg: lastNameTooShort });
if (usernameLength > 32)
return res.json({ success: false, msg: usernameTooLong });
if (usernameLength < 2)
return res.json({ success: false, msg: usernameTooShort });
if (/\d/.test(req.body.username) == false)
return res.json({ success: false, msg: usernameNotMixed });
// Check age.
if (req.body.age < 18)
return res.json({ success: false, msg: correctAgeMsg });
// Check gender.
if (
req.body.gender != 'Male' &&
req.body.gender != 'Female' &&
req.body.gender != 'Other')
return res.json({ success: false, msg: invalidGenderMsg });
// Check sexuality.
if (
req.body.sexuality != 'Heterosexual' &&
req.body.sexuality != 'Homosexual' &&
req.body.sexuality != 'Bisexual')
return res.json({ success: false, msg: invalidSexuality });
// Check ipinfoLoc
if (req.body.ipinfoLoc.includes(',') == false)
return res.json({ success: false, msg: incorrectLocFormat });
let numArr = req.body.ipinfoLoc.split(',');
if (numArr.length != 2)
return res.json({ success: false, msg: incorrectLocSplit });
// Check valid email.
if (req.body.email.length > 64)
return res.json({ success: false, msg: emailTooLong });
let re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
// console.log(re.test(req.body.email.toLowerCase()));
if (re.test(req.body.email.toLowerCase()) == false)
return res.json({ success: false, msg: incorrectEmail });
// Check password strength.
let passwordLength = req.body.password.length;
if (passwordLength > 1024) // For buffer overflow?
return res.json({ success: false, msg: passwordTooLong });
if (passwordLength < 7)
return res.json({ success: false, msg: passwordTooShort });
if (
/[a-z]+/.test(req.body.password) == false ||
/[A-Z]+/.test(req.body.password) == false ||
/[0-9]+/.test(req.body.password) == false ||
/[^\[\]${*}()\\+|?<>!@`#,%.&*-]+/.test(req.body.password) == false)
return res.json({ success: false, msg: passwordWeak });
// Signalling that input passed.
signalObj.passedInputValidation = true;
} | function registerUserInfoValid(req, res, signalObj) {
let fillMsg = "Please fill in all input fields.";
let invalidTypeMsg = "Your input types are incorrect.";
let firstNameTooLong = "First name is too long.";
let firstNameTooShort = "First name is too short.";
let lastNameTooLong = "Last name is too long.";
let lastNameTooShort = "Last name is too short.";
let usernameTooLong = "Username is too long.";
let usernameTooShort = "Username is too short.";
let usernameNotMixed = "Username must contain digits.";
let correctAgeMsg = "You need to be older than 18 to register.";
let invalidGenderMsg = "Invalid gender.";
let invalidSexuality = "Invalid sexuality.";
let incorrectLocFormat = "ipinfoLocString isn\'t formatted correctly.";
let incorrectLocSplit = "ipinfoLocString doesn\'t split correctly.";
let emailTooLong = "Entered email is too long";
let incorrectEmail = "Entered email is incorrect.";
let passwordTooLong = "Entered password is too long";
let passwordTooShort = "Entered password is too short";
let passwordWeak = "Entered password is weak, try mixing cases, digits and special characters.";
// Check if all fields filled in.
if (hasAllRegisterProperties(req) == false)
return res.json({ success: false, msg: fillMsg });
// Check types.
if (
typeof req.body.firstName != 'string' ||
typeof req.body.lastName != 'string' ||
typeof req.body.username != 'string' ||
typeof req.body.age != 'number' ||
typeof req.body.gender != 'string' ||
typeof req.body.sexuality != 'string' ||
typeof req.body.ipinfoLoc != 'string' ||
typeof req.body.email != 'string' ||
typeof req.body.password != 'string')
return res.json({ success: false, msg: invalidTypeMsg });
let firstNameLength = req.body.firstName.length;
let lastNameLength = req.body.lastName.length;
let usernameLength = req.body.username.length;
// Check firstName, lastName and username.
if (firstNameLength > 32)
return res.json({ success: false, msg: firstNameTooLong });
if (firstNameLength < 2)
return res.json({ success: false, msg: firstNameTooShort });
if (lastNameLength > 32)
return res.json({ success: false, msg: lastNameTooLong });
if (lastNameLength < 2)
return res.json({ success: false, msg: lastNameTooShort });
if (usernameLength > 32)
return res.json({ success: false, msg: usernameTooLong });
if (usernameLength < 2)
return res.json({ success: false, msg: usernameTooShort });
if (/\d/.test(req.body.username) == false)
return res.json({ success: false, msg: usernameNotMixed });
// Check age.
if (req.body.age < 18)
return res.json({ success: false, msg: correctAgeMsg });
// Check gender.
if (
req.body.gender != 'Male' &&
req.body.gender != 'Female' &&
req.body.gender != 'Other')
return res.json({ success: false, msg: invalidGenderMsg });
// Check sexuality.
if (
req.body.sexuality != 'Heterosexual' &&
req.body.sexuality != 'Homosexual' &&
req.body.sexuality != 'Bisexual')
return res.json({ success: false, msg: invalidSexuality });
// Check ipinfoLoc
if (req.body.ipinfoLoc.includes(',') == false)
return res.json({ success: false, msg: incorrectLocFormat });
let numArr = req.body.ipinfoLoc.split(',');
if (numArr.length != 2)
return res.json({ success: false, msg: incorrectLocSplit });
// Check valid email.
if (req.body.email.length > 64)
return res.json({ success: false, msg: emailTooLong });
let re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
// console.log(re.test(req.body.email.toLowerCase()));
if (re.test(req.body.email.toLowerCase()) == false)
return res.json({ success: false, msg: incorrectEmail });
// Check password strength.
let passwordLength = req.body.password.length;
if (passwordLength > 1024) // For buffer overflow?
return res.json({ success: false, msg: passwordTooLong });
if (passwordLength < 7)
return res.json({ success: false, msg: passwordTooShort });
if (
/[a-z]+/.test(req.body.password) == false ||
/[A-Z]+/.test(req.body.password) == false ||
/[0-9]+/.test(req.body.password) == false ||
/[^\[\]${*}()\\+|?<>!@`#,%.&*-]+/.test(req.body.password) == false)
return res.json({ success: false, msg: passwordWeak });
// Signalling that input passed.
signalObj.passedInputValidation = true;
} |
JavaScript | function hasAllUpdateProperties(updatedUser) {
if (
updatedUser.firstName == null || updatedUser.lastName == null ||
updatedUser.username == null || updatedUser.age == null ||
updatedUser.gender == null || updatedUser.sexualPreference == null ||
updatedUser.ipinfoLoc == null ||
updatedUser.email == null || updatedUser.password == null ||
updatedUser.firstName == '' || updatedUser.lastName == '' ||
updatedUser.username == '' || updatedUser.age == '' ||
updatedUser.gender == ''|| updatedUser.sexualPreference == '' ||
updatedUser.ipinfoLoc == '' ||
updatedUser.email == '' || updatedUser.password == '')
return false;
return true;
} | function hasAllUpdateProperties(updatedUser) {
if (
updatedUser.firstName == null || updatedUser.lastName == null ||
updatedUser.username == null || updatedUser.age == null ||
updatedUser.gender == null || updatedUser.sexualPreference == null ||
updatedUser.ipinfoLoc == null ||
updatedUser.email == null || updatedUser.password == null ||
updatedUser.firstName == '' || updatedUser.lastName == '' ||
updatedUser.username == '' || updatedUser.age == '' ||
updatedUser.gender == ''|| updatedUser.sexualPreference == '' ||
updatedUser.ipinfoLoc == '' ||
updatedUser.email == '' || updatedUser.password == '')
return false;
return true;
} |
JavaScript | function updatedUserInfoValid(updatedUser, res, signalObj) {
let fillMsg = "Please fill in all input fields.";
let firstNameTooLong = "First name is too long.";
let firstNameTooShort = "First name is too short.";
let lastNameTooLong = "Last name is too long.";
let lastNameTooShort = "Last name is too short.";
let emailTooLong = "Entered email is too long";
let incorrectEmail = "Entered email is incorrect.";
let invalidGenderMsg = "Invalid gender.";
let invalidSexuality = "Invalid sexuality.";
let biographyTooLong = "Your biography is too long";
// Checking if all fields present.
if (hasAllUpdateProperties(updatedUser) == false)
return res.json({ success: false, msg: fillMsg });
let firstNameLength = updatedUser.firstName.length;
let lastNameLength = updatedUser.lastName.length;
// Check firstName, lastName and username.
if (firstNameLength > 32)
return res.json({ success: false, msg: firstNameTooLong });
if (firstNameLength < 2)
return res.json({ success: false, msg: firstNameTooShort });
if (lastNameLength > 32)
return res.json({ success: false, msg: lastNameTooLong });
if (lastNameLength < 2)
return res.json({ success: false, msg: lastNameTooShort });
// Check valid email.
if (updatedUser.email.length > 64)
return res.json({ success: false, msg: emailTooLong });
let re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (re.test(updatedUser.email.toLowerCase()) == false)
return res.json({ success: false, msg: incorrectEmail });
// Check gender.
if (
updatedUser.gender != 'Male' &&
updatedUser.gender != 'Female' &&
updatedUser.gender != 'Other')
return res.json({ success: false, msg: invalidGenderMsg });
// Check sexuality.
if (
updatedUser.sexualPreference != 'Heterosexual' &&
updatedUser.sexualPreference != 'Homosexual' &&
updatedUser.sexualPreference != 'Bisexual')
return res.json({ success: false, msg: invalidSexuality });
// Check biography.
if (updatedUser.biography.length > 1024)
return res.json({ success: false, msg: biographyTooLong });
signalObj.passedInputValidation = true;
} | function updatedUserInfoValid(updatedUser, res, signalObj) {
let fillMsg = "Please fill in all input fields.";
let firstNameTooLong = "First name is too long.";
let firstNameTooShort = "First name is too short.";
let lastNameTooLong = "Last name is too long.";
let lastNameTooShort = "Last name is too short.";
let emailTooLong = "Entered email is too long";
let incorrectEmail = "Entered email is incorrect.";
let invalidGenderMsg = "Invalid gender.";
let invalidSexuality = "Invalid sexuality.";
let biographyTooLong = "Your biography is too long";
// Checking if all fields present.
if (hasAllUpdateProperties(updatedUser) == false)
return res.json({ success: false, msg: fillMsg });
let firstNameLength = updatedUser.firstName.length;
let lastNameLength = updatedUser.lastName.length;
// Check firstName, lastName and username.
if (firstNameLength > 32)
return res.json({ success: false, msg: firstNameTooLong });
if (firstNameLength < 2)
return res.json({ success: false, msg: firstNameTooShort });
if (lastNameLength > 32)
return res.json({ success: false, msg: lastNameTooLong });
if (lastNameLength < 2)
return res.json({ success: false, msg: lastNameTooShort });
// Check valid email.
if (updatedUser.email.length > 64)
return res.json({ success: false, msg: emailTooLong });
let re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (re.test(updatedUser.email.toLowerCase()) == false)
return res.json({ success: false, msg: incorrectEmail });
// Check gender.
if (
updatedUser.gender != 'Male' &&
updatedUser.gender != 'Female' &&
updatedUser.gender != 'Other')
return res.json({ success: false, msg: invalidGenderMsg });
// Check sexuality.
if (
updatedUser.sexualPreference != 'Heterosexual' &&
updatedUser.sexualPreference != 'Homosexual' &&
updatedUser.sexualPreference != 'Bisexual')
return res.json({ success: false, msg: invalidSexuality });
// Check biography.
if (updatedUser.biography.length > 1024)
return res.json({ success: false, msg: biographyTooLong });
signalObj.passedInputValidation = true;
} |
JavaScript | function openModal(returnArr, formModal) {
// Logic - Modal - Username.
if (returnArr['usernameSpecCharFound'] == 1) {
document.getElementById('modalHeader').innerHTML = 'Double-check form';
document.getElementById('modalText').innerHTML = 'Username contains special characters.';
formModal.style.display = 'flex';
}
if (returnArr['usernameNotRegistered'] == 1) {
document.getElementById('modalHeader').innerHTML = 'Double-check form';
document.getElementById('modalText').innerHTML = 'Username is invalid.';
formModal.style.display = 'flex';
}
// Logic - Modal - Passwords.
if (returnArr['passwordTooShort'] == 1) {
document.getElementById('modalHeader').innerHTML = 'Double-check form';
document.getElementById('modalText').innerHTML = 'Password too short, minimum 7 characters.';
formModal.style.display = 'flex';
}
if (returnArr['passwordNoMix'] == 1) {
document.getElementById('modalHeader').innerHTML = 'Double-check form';
document.getElementById('modalText').innerHTML = 'Password(s) not mixed case.';
formModal.style.display = 'flex';
}
if (returnArr['passwordMatch'] == 0) {
document.getElementById('modalHeader').innerHTML = 'Double-check form';
document.getElementById('modalText').innerHTML = 'Passwords do not match.';
formModal.style.display = 'flex';
}
// Logic - Modal - Token.
if (returnArr['tokenInvalid'] == 1) {
document.getElementById('modalHeader').innerHTML = 'Double-check form';
document.getElementById('modalText').innerHTML = 'The token you entered is invalid';
formModal.style.display = 'flex';
}
// Logic - Modal - Password reset successful.
if (returnArr['passResetSuccessful'] == 1) {
document.getElementById('modalHeader').innerHTML = 'Password reset successful';
document.getElementById('modalText').innerHTML = 'Your password has been reset successfully. You may now sign in.';
formModal.style.display = 'flex';
}
} | function openModal(returnArr, formModal) {
// Logic - Modal - Username.
if (returnArr['usernameSpecCharFound'] == 1) {
document.getElementById('modalHeader').innerHTML = 'Double-check form';
document.getElementById('modalText').innerHTML = 'Username contains special characters.';
formModal.style.display = 'flex';
}
if (returnArr['usernameNotRegistered'] == 1) {
document.getElementById('modalHeader').innerHTML = 'Double-check form';
document.getElementById('modalText').innerHTML = 'Username is invalid.';
formModal.style.display = 'flex';
}
// Logic - Modal - Passwords.
if (returnArr['passwordTooShort'] == 1) {
document.getElementById('modalHeader').innerHTML = 'Double-check form';
document.getElementById('modalText').innerHTML = 'Password too short, minimum 7 characters.';
formModal.style.display = 'flex';
}
if (returnArr['passwordNoMix'] == 1) {
document.getElementById('modalHeader').innerHTML = 'Double-check form';
document.getElementById('modalText').innerHTML = 'Password(s) not mixed case.';
formModal.style.display = 'flex';
}
if (returnArr['passwordMatch'] == 0) {
document.getElementById('modalHeader').innerHTML = 'Double-check form';
document.getElementById('modalText').innerHTML = 'Passwords do not match.';
formModal.style.display = 'flex';
}
// Logic - Modal - Token.
if (returnArr['tokenInvalid'] == 1) {
document.getElementById('modalHeader').innerHTML = 'Double-check form';
document.getElementById('modalText').innerHTML = 'The token you entered is invalid';
formModal.style.display = 'flex';
}
// Logic - Modal - Password reset successful.
if (returnArr['passResetSuccessful'] == 1) {
document.getElementById('modalHeader').innerHTML = 'Password reset successful';
document.getElementById('modalText').innerHTML = 'Your password has been reset successfully. You may now sign in.';
formModal.style.display = 'flex';
}
} |
JavaScript | function sammenlignKrig(spiller, comp){
if ((spiller % 13)>(comp % 13)){
spillerHaand.push(spillerHaand, krigArray);
spillerHaand.push(comp);
spillerHaand.push(spiller);
spillerHaand.shift();
compHaand.shift();
krigArray.length = 0;
oppdater();
sjekkVinn();
} if ((spiller % 13)<(comp % 13)){
compHaand.push(compHaand, krigArray);
compHaand.push(comp);
compHaand.push(spiller);
spillerHaand.shift();
compHaand.shift();
krigArray.length = 0;
oppdater();
sjekkVinn();
}else if ((spiller % 13) === (comp % 13)) {
krig();
}
} | function sammenlignKrig(spiller, comp){
if ((spiller % 13)>(comp % 13)){
spillerHaand.push(spillerHaand, krigArray);
spillerHaand.push(comp);
spillerHaand.push(spiller);
spillerHaand.shift();
compHaand.shift();
krigArray.length = 0;
oppdater();
sjekkVinn();
} if ((spiller % 13)<(comp % 13)){
compHaand.push(compHaand, krigArray);
compHaand.push(comp);
compHaand.push(spiller);
spillerHaand.shift();
compHaand.shift();
krigArray.length = 0;
oppdater();
sjekkVinn();
}else if ((spiller % 13) === (comp % 13)) {
krig();
}
} |
JavaScript | function sjekkVinn(){
if (spillerHaand == 0) {
console.log("Datamaskin vant!");
} else if (compHaand == 0) {
console.log("Spiller vant!");
}
} | function sjekkVinn(){
if (spillerHaand == 0) {
console.log("Datamaskin vant!");
} else if (compHaand == 0) {
console.log("Spiller vant!");
}
} |
JavaScript | function addDomainPermissionToggle(options) {
if (globalOptions) {
throw new Error('webext-domain-permission-toggle can only be initialized once');
}
const { name } = chrome.runtime.getManifest();
globalOptions = {
title: `Enable ${name} on this domain`,
reloadOnSuccess: `Do you want to reload this page to apply ${name}?`, ...options
};
chrome.contextMenus.onClicked.addListener(handleClick);
chrome.tabs.onActivated.addListener(updateItem);
chrome.tabs.onUpdated.addListener((tabId, { status }) => {
if (currentTabId === tabId && status === 'complete') {
updateItem({ tabId });
}
});
createMenu();
} | function addDomainPermissionToggle(options) {
if (globalOptions) {
throw new Error('webext-domain-permission-toggle can only be initialized once');
}
const { name } = chrome.runtime.getManifest();
globalOptions = {
title: `Enable ${name} on this domain`,
reloadOnSuccess: `Do you want to reload this page to apply ${name}?`, ...options
};
chrome.contextMenus.onClicked.addListener(handleClick);
chrome.tabs.onActivated.addListener(updateItem);
chrome.tabs.onUpdated.addListener((tabId, { status }) => {
if (currentTabId === tabId && status === 'complete') {
updateItem({ tabId });
}
});
createMenu();
} |
JavaScript | async register(contentScriptOptions, callback) {
const {
js = [],
css = [],
allFrames,
matchAboutBlank,
matches,
runAt
} = contentScriptOptions;
// Injectable code; it sets a `true` property on `document` with the hash of the files as key.
const loadCheck = `document[${JSON.stringify(JSON.stringify({ js, css }))}]`;
const matchesRegex = patternToRegex(...matches);
const listener = async (tabId, { status }) => {
if (status !== 'loading') {
return;
}
const { url } = await p_(chrome.tabs.get, tabId);
if (
!url || // No URL = no permission;
!matchesRegex.test(url) || // Manual `matches` glob matching
!await isOriginPermitted(url) || // Permissions check
await wasPreviouslyLoaded(tabId, loadCheck) // Double-injection avoidance
) {
return;
}
for (const file of css) {
chrome.tabs.insertCSS(tabId, {
...file,
matchAboutBlank,
allFrames,
runAt: runAt ?? 'document_start' // CSS should prefer `document_start` when unspecified
});
}
for (const file of js) {
chrome.tabs.executeScript(tabId, {
...file,
matchAboutBlank,
allFrames,
runAt
});
}
// Mark as loaded
chrome.tabs.executeScript(tabId, {
code: `${loadCheck} = true`,
runAt: 'document_start',
allFrames
});
};
chrome.tabs.onUpdated.addListener(listener);
const registeredContentScript = {
async unregister() {
return p_(chrome.tabs.onUpdated.removeListener.bind(chrome.tabs.onUpdated), listener);
}
};
if (typeof callback === 'function') {
callback(registeredContentScript);
}
return Promise.resolve(registeredContentScript);
} | async register(contentScriptOptions, callback) {
const {
js = [],
css = [],
allFrames,
matchAboutBlank,
matches,
runAt
} = contentScriptOptions;
// Injectable code; it sets a `true` property on `document` with the hash of the files as key.
const loadCheck = `document[${JSON.stringify(JSON.stringify({ js, css }))}]`;
const matchesRegex = patternToRegex(...matches);
const listener = async (tabId, { status }) => {
if (status !== 'loading') {
return;
}
const { url } = await p_(chrome.tabs.get, tabId);
if (
!url || // No URL = no permission;
!matchesRegex.test(url) || // Manual `matches` glob matching
!await isOriginPermitted(url) || // Permissions check
await wasPreviouslyLoaded(tabId, loadCheck) // Double-injection avoidance
) {
return;
}
for (const file of css) {
chrome.tabs.insertCSS(tabId, {
...file,
matchAboutBlank,
allFrames,
runAt: runAt ?? 'document_start' // CSS should prefer `document_start` when unspecified
});
}
for (const file of js) {
chrome.tabs.executeScript(tabId, {
...file,
matchAboutBlank,
allFrames,
runAt
});
}
// Mark as loaded
chrome.tabs.executeScript(tabId, {
code: `${loadCheck} = true`,
runAt: 'document_start',
allFrames
});
};
chrome.tabs.onUpdated.addListener(listener);
const registeredContentScript = {
async unregister() {
return p_(chrome.tabs.onUpdated.removeListener.bind(chrome.tabs.onUpdated), listener);
}
};
if (typeof callback === 'function') {
callback(registeredContentScript);
}
return Promise.resolve(registeredContentScript);
} |
JavaScript | async function registerOnOrigins({ origins: newOrigins }) {
const manifest = chrome.runtime.getManifest().content_scripts;
// Register one at a time to allow removing one at a time as well
for (const origin of newOrigins || []) {
for (const config of manifest) {
regFunc = typeof(browser) !== "undefined" && browser.contentScripts ? browser.contentScripts.register : chrome.contentScripts.register;
const registeredScript = regFunc({
js: (config.js || []).map(convertPath),
css: (config.css || []).map(convertPath),
allFrames: config.all_frames,
matches: config.matches.map(m => origin.slice(0, -2) + new URL(m.replace("*.", "wildcard.")).pathname),
runAt: config.run_at
});
Logger.debug("registered", registeredScript);
registeredScripts.set(origin, [...(registeredScripts.get(origin) || []), registeredScript]);
}
}
} | async function registerOnOrigins({ origins: newOrigins }) {
const manifest = chrome.runtime.getManifest().content_scripts;
// Register one at a time to allow removing one at a time as well
for (const origin of newOrigins || []) {
for (const config of manifest) {
regFunc = typeof(browser) !== "undefined" && browser.contentScripts ? browser.contentScripts.register : chrome.contentScripts.register;
const registeredScript = regFunc({
js: (config.js || []).map(convertPath),
css: (config.css || []).map(convertPath),
allFrames: config.all_frames,
matches: config.matches.map(m => origin.slice(0, -2) + new URL(m.replace("*.", "wildcard.")).pathname),
runAt: config.run_at
});
Logger.debug("registered", registeredScript);
registeredScripts.set(origin, [...(registeredScripts.get(origin) || []), registeredScript]);
}
}
} |
JavaScript | function beforeThisSemester(oldDate) {
let curr = getSemester(new Date());
let prev = getSemester(new Date(oldDate));
if (prev.year < curr.year || prev.year === curr.year && prev.semester !== curr.semester && prev.semester === "Spring") {
return true;
}
return false;
function getSemester(date) {
let m = date.getMonth();
let y = date.getFullYear();
return { semester: m > 0 && m < 8 ? "Spring" : "Fall", year: m == 0 ? y - 1 : y };
}
} | function beforeThisSemester(oldDate) {
let curr = getSemester(new Date());
let prev = getSemester(new Date(oldDate));
if (prev.year < curr.year || prev.year === curr.year && prev.semester !== curr.semester && prev.semester === "Spring") {
return true;
}
return false;
function getSemester(date) {
let m = date.getMonth();
let y = date.getFullYear();
return { semester: m > 0 && m < 8 ? "Spring" : "Fall", year: m == 0 ? y - 1 : y };
}
} |
JavaScript | static open(content, buttons = ["OK"], callback) {
Modal.CONTENT_CONTAINER.innerHTML = "";
Modal.BUTTONS_CONTAINER.innerHTML = "";
var selected = null;
Modal.CONTENT_CONTAINER.appendChild(content);
for (let b of buttons) {
Modal.BUTTONS_CONTAINER.appendChild(createElement("a", ["modal-close", "waves-effect", "waves-dark", "btn-flat"], {
textContent: b,
onclick: e => {
trackEvent("Modal Button", b, "Theme Editor");
selected = b;
}
}));
}
let controller = M.Modal.init(Modal.ELEMENT, { onCloseEnd: () => callback && callback(selected) });
controller.open();
} | static open(content, buttons = ["OK"], callback) {
Modal.CONTENT_CONTAINER.innerHTML = "";
Modal.BUTTONS_CONTAINER.innerHTML = "";
var selected = null;
Modal.CONTENT_CONTAINER.appendChild(content);
for (let b of buttons) {
Modal.BUTTONS_CONTAINER.appendChild(createElement("a", ["modal-close", "waves-effect", "waves-dark", "btn-flat"], {
textContent: b,
onclick: e => {
trackEvent("Modal Button", b, "Theme Editor");
selected = b;
}
}));
}
let controller = M.Modal.init(Modal.ELEMENT, { onCloseEnd: () => callback && callback(selected) });
controller.open();
} |
JavaScript | static open(title, placeholder, buttons, callback) {
let content = htmlToElement(`
<div>
<h4>${title}</h4>
<div class="input-field">
<textarea id="prompt-modal-textarea" class="materialize-textarea"></textarea>
<label for="prompt-modal-textarea">${placeholder}</label>
</div>
</div>
`);
Modal.open(content, buttons, (button) => callback(button, document.getElementById("prompt-modal-textarea").value));
} | static open(title, placeholder, buttons, callback) {
let content = htmlToElement(`
<div>
<h4>${title}</h4>
<div class="input-field">
<textarea id="prompt-modal-textarea" class="materialize-textarea"></textarea>
<label for="prompt-modal-textarea">${placeholder}</label>
</div>
</div>
`);
Modal.open(content, buttons, (button) => callback(button, document.getElementById("prompt-modal-textarea").value));
} |
JavaScript | static open(title, text, buttons, callback) {
let content = htmlToElement(`
<div>
<h4>${title}</h4>
<p>${text}</p>
</div>
`);
Modal.open(content, buttons, callback);
} | static open(title, text, buttons, callback) {
let content = htmlToElement(`
<div>
<h4>${title}</h4>
<p>${text}</p>
</div>
`);
Modal.open(content, buttons, callback);
} |
JavaScript | function generateErrors(j) {
let w = [];
switch (j.version) {
case 2:
if (!j.name) w.push("Theme must have a name");
break;
default:
if (!j.name) w.push("Theme must have a name")
if (j.hue && Number.isNaN(Number.parseFloat(j.hue))) w.push("Value of 'hue' must be a number");
if (j.colors && j.colors.length != 4) w.push("There must be four colors in 'colors'");
if (j.colors && j.colors.map(x => !!validateColor(x)).includes(false)) w.push("One or more values of 'colors' is not a valid color");
break;
}
return w;
} | function generateErrors(j) {
let w = [];
switch (j.version) {
case 2:
if (!j.name) w.push("Theme must have a name");
break;
default:
if (!j.name) w.push("Theme must have a name")
if (j.hue && Number.isNaN(Number.parseFloat(j.hue))) w.push("Value of 'hue' must be a number");
if (j.colors && j.colors.length != 4) w.push("There must be four colors in 'colors'");
if (j.colors && j.colors.map(x => !!validateColor(x)).includes(false)) w.push("One or more values of 'colors' is not a valid color");
break;
}
return w;
} |
JavaScript | function importAndRender(object) {
errors = [];
warnings = [];
renderTheme(importThemeFromObject(object));
} | function importAndRender(object) {
errors = [];
warnings = [];
renderTheme(importThemeFromObject(object));
} |
JavaScript | function migrateTheme(t) {
switch (t.version) {
case 2:
break;
default:
t.version = 2;
if (t.colors) {
t.color = {
custom: {
primary: t.colors[0],
background: t.colors[1],
hover: t.colors[2],
border: t.colors[3]
}
};
delete t.colors;
delete t.hue;
} else if (t.hue) {
t.color = {
hue: t.hue
};
delete t.hue;
}
if (t.logo) {
switch (t.logo) {
case "schoology":
t.logo = { preset: "schoology_logo" };
break;
case "lausd":
t.logo = { preset: "lausd_legacy" };
break;
case "lausd_new":
t.logo = { preset: "lausd_2019" };
break;
default:
t.logo = { url: t.logo };
break;
}
}
if (t.cursor) {
t.cursor = { primary: t.cursor };
}
if (t.icons) {
let newIconsArray = [];
for (let icon of t.icons) {
newIconsArray.push({
regex: icon[0],
url: icon[1]
});
}
t.icons = newIconsArray;
}
break;
}
return t.version == CURRENT_VERSION ? t : migrateTheme(t);
} | function migrateTheme(t) {
switch (t.version) {
case 2:
break;
default:
t.version = 2;
if (t.colors) {
t.color = {
custom: {
primary: t.colors[0],
background: t.colors[1],
hover: t.colors[2],
border: t.colors[3]
}
};
delete t.colors;
delete t.hue;
} else if (t.hue) {
t.color = {
hue: t.hue
};
delete t.hue;
}
if (t.logo) {
switch (t.logo) {
case "schoology":
t.logo = { preset: "schoology_logo" };
break;
case "lausd":
t.logo = { preset: "lausd_legacy" };
break;
case "lausd_new":
t.logo = { preset: "lausd_2019" };
break;
default:
t.logo = { url: t.logo };
break;
}
}
if (t.cursor) {
t.cursor = { primary: t.cursor };
}
if (t.icons) {
let newIconsArray = [];
for (let icon of t.icons) {
newIconsArray.push({
regex: icon[0],
url: icon[1]
});
}
t.icons = newIconsArray;
}
break;
}
return t.version == CURRENT_VERSION ? t : migrateTheme(t);
} |
JavaScript | function importThemeFromObject(j) {
if (!j) {
errors.push("The JSON you have entered is not valid");
updatePreview(false);
return;
}
errors = generateErrors(j);
if (errors.length > 0) {
updatePreview(false);
return;
}
j = migrateTheme(j);
return SchoologyTheme.loadFromObject(j);
} | function importThemeFromObject(j) {
if (!j) {
errors.push("The JSON you have entered is not valid");
updatePreview(false);
return;
}
errors = generateErrors(j);
if (errors.length > 0) {
updatePreview(false);
return;
}
j = migrateTheme(j);
return SchoologyTheme.loadFromObject(j);
} |
JavaScript | function initPicker(id, color = undefined, onupdate = updateOutput, showAlpha = false) {
$(`#${id}`).spectrum({
showInput: true,
containerClassName: "full-spectrum",
showInitial: true,
showPalette: true,
showSelectionPalette: true,
maxPaletteSize: 10,
preferredFormat: "hex",
showAlpha: showAlpha,
color: color || ["red", "blue", "yellow", "green", "magenta"][init++ % 5],
move: function (color) {
onupdate(color);
},
hide: function (color) {
onupdate(color);
},
palette: [
["rgb(0, 0, 0)", "rgb(67, 67, 67)", "rgb(102, 102, 102)", /*"rgb(153, 153, 153)","rgb(183, 183, 183)",*/
"rgb(204, 204, 204)", "rgb(217, 217, 217)", /*"rgb(239, 239, 239)", "rgb(243, 243, 243)",*/ "rgb(255, 255, 255)"],
["rgb(152, 0, 0)", "rgb(255, 0, 0)", "rgb(255, 153, 0)", "rgb(255, 255, 0)", "rgb(0, 255, 0)",
"rgb(0, 255, 255)", "rgb(74, 134, 232)", "rgb(0, 0, 255)", "rgb(153, 0, 255)", "rgb(255, 0, 255)"],
["rgb(230, 184, 175)", "rgb(244, 204, 204)", "rgb(252, 229, 205)", "rgb(255, 242, 204)", "rgb(217, 234, 211)",
"rgb(208, 224, 227)", "rgb(201, 218, 248)", "rgb(207, 226, 243)", "rgb(217, 210, 233)", "rgb(234, 209, 220)"],
["rgb(221, 126, 107)", "rgb(234, 153, 153)", "rgb(249, 203, 156)", "rgb(255, 229, 153)", "rgb(182, 215, 168)",
"rgb(162, 196, 201)", "rgb(164, 194, 244)", "rgb(159, 197, 232)", "rgb(180, 167, 214)", "rgb(213, 166, 189)"],
["rgb(204, 65, 37)", "rgb(224, 102, 102)", "rgb(246, 178, 107)", "rgb(255, 217, 102)", "rgb(147, 196, 125)",
"rgb(118, 165, 175)", "rgb(109, 158, 235)", "rgb(111, 168, 220)", "rgb(142, 124, 195)", "rgb(194, 123, 160)"],
["rgb(166, 28, 0)", "rgb(204, 0, 0)", "rgb(230, 145, 56)", "rgb(241, 194, 50)", "rgb(106, 168, 79)",
"rgb(69, 129, 142)", "rgb(60, 120, 216)", "rgb(61, 133, 198)", "rgb(103, 78, 167)", "rgb(166, 77, 121)"],
["rgb(133, 32, 12)", "rgb(153, 0, 0)", "rgb(180, 95, 6)", "rgb(191, 144, 0)", "rgb(56, 118, 29)",
"rgb(19, 79, 92)", "rgb(17, 85, 204)", "rgb(11, 83, 148)", "rgb(53, 28, 117)", "rgb(116, 27, 71)"],
["rgb(91, 15, 0)", "rgb(102, 0, 0)", "rgb(120, 63, 4)", "rgb(127, 96, 0)", "rgb(39, 78, 19)",
"rgb(12, 52, 61)", "rgb(28, 69, 135)", "rgb(7, 55, 99)", "rgb(32, 18, 77)", "rgb(76, 17, 48)"]
]
});
} | function initPicker(id, color = undefined, onupdate = updateOutput, showAlpha = false) {
$(`#${id}`).spectrum({
showInput: true,
containerClassName: "full-spectrum",
showInitial: true,
showPalette: true,
showSelectionPalette: true,
maxPaletteSize: 10,
preferredFormat: "hex",
showAlpha: showAlpha,
color: color || ["red", "blue", "yellow", "green", "magenta"][init++ % 5],
move: function (color) {
onupdate(color);
},
hide: function (color) {
onupdate(color);
},
palette: [
["rgb(0, 0, 0)", "rgb(67, 67, 67)", "rgb(102, 102, 102)", /*"rgb(153, 153, 153)","rgb(183, 183, 183)",*/
"rgb(204, 204, 204)", "rgb(217, 217, 217)", /*"rgb(239, 239, 239)", "rgb(243, 243, 243)",*/ "rgb(255, 255, 255)"],
["rgb(152, 0, 0)", "rgb(255, 0, 0)", "rgb(255, 153, 0)", "rgb(255, 255, 0)", "rgb(0, 255, 0)",
"rgb(0, 255, 255)", "rgb(74, 134, 232)", "rgb(0, 0, 255)", "rgb(153, 0, 255)", "rgb(255, 0, 255)"],
["rgb(230, 184, 175)", "rgb(244, 204, 204)", "rgb(252, 229, 205)", "rgb(255, 242, 204)", "rgb(217, 234, 211)",
"rgb(208, 224, 227)", "rgb(201, 218, 248)", "rgb(207, 226, 243)", "rgb(217, 210, 233)", "rgb(234, 209, 220)"],
["rgb(221, 126, 107)", "rgb(234, 153, 153)", "rgb(249, 203, 156)", "rgb(255, 229, 153)", "rgb(182, 215, 168)",
"rgb(162, 196, 201)", "rgb(164, 194, 244)", "rgb(159, 197, 232)", "rgb(180, 167, 214)", "rgb(213, 166, 189)"],
["rgb(204, 65, 37)", "rgb(224, 102, 102)", "rgb(246, 178, 107)", "rgb(255, 217, 102)", "rgb(147, 196, 125)",
"rgb(118, 165, 175)", "rgb(109, 158, 235)", "rgb(111, 168, 220)", "rgb(142, 124, 195)", "rgb(194, 123, 160)"],
["rgb(166, 28, 0)", "rgb(204, 0, 0)", "rgb(230, 145, 56)", "rgb(241, 194, 50)", "rgb(106, 168, 79)",
"rgb(69, 129, 142)", "rgb(60, 120, 216)", "rgb(61, 133, 198)", "rgb(103, 78, 167)", "rgb(166, 77, 121)"],
["rgb(133, 32, 12)", "rgb(153, 0, 0)", "rgb(180, 95, 6)", "rgb(191, 144, 0)", "rgb(56, 118, 29)",
"rgb(19, 79, 92)", "rgb(17, 85, 204)", "rgb(11, 83, 148)", "rgb(53, 28, 117)", "rgb(116, 27, 71)"],
["rgb(91, 15, 0)", "rgb(102, 0, 0)", "rgb(120, 63, 4)", "rgb(127, 96, 0)", "rgb(39, 78, 19)",
"rgb(12, 52, 61)", "rgb(28, 69, 135)", "rgb(7, 55, 99)", "rgb(32, 18, 77)", "rgb(76, 17, 48)"]
]
});
} |
JavaScript | function updatePreview(updateJSON = true) {
if (updateJSON) output.value = JSON.stringify(theme, null, 4);
let warningCard = document.getElementById("warning-card");
if (warnings.length > 0) {
warningCard.style.display = "block";
document.getElementById("warning-content").innerHTML = warnings.join("<br/>");
}
else {
warningCard.style.display = "none";
}
let errorCard = document.getElementById("error-card");
if (errors.length > 0 && inEditMode()) {
errorCard.style.display = "block";
document.getElementById("error-content").innerHTML = errors.join("<br/>");
}
else {
errorCard.style.display = "none";
}
M.updateTextFields();
M.textareaAutoResize(output);
iconPreview();
} | function updatePreview(updateJSON = true) {
if (updateJSON) output.value = JSON.stringify(theme, null, 4);
let warningCard = document.getElementById("warning-card");
if (warnings.length > 0) {
warningCard.style.display = "block";
document.getElementById("warning-content").innerHTML = warnings.join("<br/>");
}
else {
warningCard.style.display = "none";
}
let errorCard = document.getElementById("error-card");
if (errors.length > 0 && inEditMode()) {
errorCard.style.display = "block";
document.getElementById("error-content").innerHTML = errors.join("<br/>");
}
else {
errorCard.style.display = "none";
}
M.updateTextFields();
M.textareaAutoResize(output);
iconPreview();
} |
JavaScript | function saveTheme(apply = false) {
if (errors.length > 0) throw new Error("Please fix all errors before saving the theme:\n" + errors.join("\n"));
let t = JSON.parse(output.value);
if (origThemeName && t.name != origThemeName) {
ConfirmModal.open("Rename Theme?", `Are you sure you want to rename "${origThemeName}" to "${t.name}"?`, ["Rename", "Cancel"], b => b === "Rename" && doSave(t));
} else {
doSave(t);
}
function doSave(t) {
chrome.storage.sync.get({ themes: [] }, s => {
let themes = s.themes.filter(x => x.name != (origThemeName || t.name));
themes.push(t);
chrome.storage.sync.set({ themes: themes }, () => {
if (chrome.runtime.lastError) {
if (chrome.runtime.lastError.message.includes("QUOTA_BYTES_PER_ITEM")) {
alert("No space remaining to save theme. Please delete another theme or make this theme smaller in order to save.");
throw new Error("No space remaining to save theme. Please delete another theme or make this theme smaller in order to save.");
}
}
ConfirmModal.open("Theme saved successfully", "", ["OK"], () => {
origThemeName = t.name;
if (apply) chrome.storage.sync.set({ theme: t.name }, () => location.href = `https://${defaultDomain}`);
else location.reload();
});
});
});
}
} | function saveTheme(apply = false) {
if (errors.length > 0) throw new Error("Please fix all errors before saving the theme:\n" + errors.join("\n"));
let t = JSON.parse(output.value);
if (origThemeName && t.name != origThemeName) {
ConfirmModal.open("Rename Theme?", `Are you sure you want to rename "${origThemeName}" to "${t.name}"?`, ["Rename", "Cancel"], b => b === "Rename" && doSave(t));
} else {
doSave(t);
}
function doSave(t) {
chrome.storage.sync.get({ themes: [] }, s => {
let themes = s.themes.filter(x => x.name != (origThemeName || t.name));
themes.push(t);
chrome.storage.sync.set({ themes: themes }, () => {
if (chrome.runtime.lastError) {
if (chrome.runtime.lastError.message.includes("QUOTA_BYTES_PER_ITEM")) {
alert("No space remaining to save theme. Please delete another theme or make this theme smaller in order to save.");
throw new Error("No space remaining to save theme. Please delete another theme or make this theme smaller in order to save.");
}
}
ConfirmModal.open("Theme saved successfully", "", ["OK"], () => {
origThemeName = t.name;
if (apply) chrome.storage.sync.set({ theme: t.name }, () => location.href = `https://${defaultDomain}`);
else location.reload();
});
});
});
}
} |
JavaScript | function validateColor(c) {
var ele = document.createElement("div");
ele.style.color = c;
return ele.style.color.split(/\s+/).join('').toLowerCase();
} | function validateColor(c) {
var ele = document.createElement("div");
ele.style.color = c;
return ele.style.color.split(/\s+/).join('').toLowerCase();
} |
JavaScript | function checkImage(imageSrc, validCallback, invalidCallback) {
try {
var img = new Image();
img.onload = validCallback;
img.onerror = invalidCallback;
img.src = imageSrc;
} catch {
invalidCallback();
}
} | function checkImage(imageSrc, validCallback, invalidCallback) {
try {
var img = new Image();
img.onload = validCallback;
img.onerror = invalidCallback;
img.src = imageSrc;
} catch {
invalidCallback();
}
} |
JavaScript | function deleteTheme(name) {
ConfirmModal.open("Delete Theme?", `Are you sure you want to delete the theme "${name}"?\nThe page will reload when the theme is deleted.`, ["Delete", "Cancel"], b => {
if (b === "Delete") {
trackEvent(`Theme: ${name}`, "delete", "Theme List");
chrome.storage.sync.get(["theme", "themes"], s => {
chrome.storage.sync.set({ theme: s.theme == name ? null : s.theme, themes: s.themes.filter(x => x.name != name) }, () => window.location.reload());
});
}
});
} | function deleteTheme(name) {
ConfirmModal.open("Delete Theme?", `Are you sure you want to delete the theme "${name}"?\nThe page will reload when the theme is deleted.`, ["Delete", "Cancel"], b => {
if (b === "Delete") {
trackEvent(`Theme: ${name}`, "delete", "Theme List");
chrome.storage.sync.get(["theme", "themes"], s => {
chrome.storage.sync.set({ theme: s.theme == name ? null : s.theme, themes: s.themes.filter(x => x.name != name) }, () => window.location.reload());
});
}
});
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.