commit
stringlengths 40
40
| subject
stringlengths 1
3.25k
| old_file
stringlengths 4
311
| new_file
stringlengths 4
311
| old_contents
stringlengths 0
26.3k
| lang
stringclasses 3
values | proba
float64 0
1
| diff
stringlengths 0
7.82k
|
---|---|---|---|---|---|---|---|
aa3bddfe77d9d73831f48b440a4d3bca41fa2c0c
|
Check there is a content-type header and catch other 200 responses
|
src/app/utilities/http-methods/request.js
|
src/app/utilities/http-methods/request.js
|
import { HttpError } from './error';
import log, { eventTypes } from '../log';
import uuid from 'uuid/v4';
import user from '../api-clients/user';
import notifications from '../notifications';
/**
*
* @param {string} method - must match an HTTP method (eg "GET")
* @param {string} URI - URI to make a request to
* @param {boolean} willRetry - (default = true) if true then this function will retry the connection on failure
* @param {object} body - JSON of the request body (if it's an applicable HTTP method)
* @param {function} onRetry - Runs whenever the request is going to be retried. Added for use in unit tests, so that we can run our mocked timeOuts (or else the async test breaks)
* @param {boolean} callerHandles401 - Flag to decide whether caller or global handler is to handle 401 responses
*
* @returns {Promise} which returns the response body in JSON format
*/
export default function request(method, URI, willRetry = true, onRetry = () => {}, body, callerHandles401) {
const baseInterval = 50;
let interval = baseInterval;
const maxRetries = 5;
let retryCount = 0;
return new Promise(function(resolve, reject) {
tryFetch(resolve, reject, URI, willRetry, body);
});
function tryFetch(resolve, reject, URI, willRetry, body) {
const UID = uuid();
const logEventPayload = {
method: method,
requestID: UID,
willRetry,
retryCount,
URI
};
const fetchConfig = {
method,
credentials: "include",
headers: {
'Content-Type': 'application/json',
'Request-ID': UID,
'internal-token': "FD0108EA-825D-411C-9B1D-41EF7727F465"
}
}
if (method === "POST" || method === "PUT") {
fetchConfig.body = JSON.stringify(body || {});
}
log.add(eventTypes.requestSent, {...logEventPayload});
fetch(URI, fetchConfig).then(response => {
logEventPayload.status = response.status;
logEventPayload.message = response.message;
log.add(eventTypes.requestReceived, logEventPayload);
const responseIsJSON = response.headers.get('content-type').match(/application\/json/);
const responseIsText = response.headers.get('content-type').match(/text\/plain/);
if (response.status >= 500) {
throw new HttpError(response);
}
if (response.status === 401) {
if (callerHandles401) {
reject({status: response.status, message: response.statusText});
return;
}
// To save doing this exact same function throughout the app we handle a 401
// here (ie at the lowest level possible)
const notification = {
type: "neutral",
message: "Your session has expired so you've been redirected to the login screen",
isDismissable: true,
autoDismiss: 20000
}
user.logOut();
notifications.add(notification);
reject({status: response.status, message: response.statusText});
return;
}
if (!response.ok) {
reject({status: response.status, message: response.statusText});
return;
}
logEventPayload.status = 200;
if (!responseIsJSON && method !== "POST" && method !== "PUT") {
log.add(eventTypes.runtimeWarning, `Received request response for method '${method}' that didn't have the 'application/json' header`)
}
// We've detected a text response so we should try to parse as text, not JSON
if (responseIsText) {
(async () => {
try {
const text = await response.text();
resolve(text);
} catch (error) {
console.error("Error trying to parse request body as text: ", error);
log.add(eventTypes.unexpectedRuntimeError, 'Attempt to parse text response from request but unable to. Error message: ' + error);
if (method === "POST" || method === "PUT") {
resolve();
return;
}
reject({status: response.status, message: "Text response body couldn't be parsed"});
}
})()
return
}
// We're wrapping this try/catch in an async function because we're using 'await'
// which requires being executed inside an async function (which the 'fetch' can't be set as)
(async () => {
try {
const json = await response.json();
resolve(json);
} catch (error) {
// We're not necessarily relying on a response with these methods
// so we should still resolve the promise, just with no response body
if (method === "POST" || method === "PUT") {
resolve();
return;
}
console.error("Error trying to parse request body as JSON: ", error);
log.add(eventTypes.unexpectedRuntimeError, 'Attempt to parse JSON response from request but unable to. Error message: ' + error);
// We're trying to get data at this point and the body can't be parsed
// which means this request is a failure and the promise should be rejected
reject({status: response.status, message: "JSON response body couldn't be parsed"});
}
})()
}).catch((fetchError = {message: "No error message given"}) => {
logEventPayload.message = fetchError.message;
log.add(eventTypes.requestFailed, logEventPayload);
if (willRetry) {
// retry post
if (retryCount < maxRetries) {
setTimeout(function() { tryFetch(resolve, reject, URI, willRetry, body) }, interval);
retryCount++;
interval = interval * 2;
onRetry(retryCount);
} else {
// pass error back to caller when max number of retries is met
if (fetchError instanceof TypeError) {
// connection failed
reject({status: 'FETCH_ERR', error: fetchError});
} else if (fetchError instanceof HttpError) {
// unexpected response
reject({status: 'RESPONSE_ERR', error: fetchError})
} else {
// unexpected error
reject({status: 'UNEXPECTED_ERR', error: fetchError})
}
retryCount = 0;
interval = baseInterval;
}
return;
}
// pass error back to caller when max number of retries is met
if (fetchError instanceof TypeError) {
// connection failed
reject({status: 'FETCH_ERR', error: fetchError});
} else if (fetchError instanceof HttpError) {
// unexpected response
reject({status: 'RESPONSE_ERR', error: fetchError})
} else {
// unexpected error
reject({status: 'UNEXPECTED_ERR', error: fetchError})
}
});
}
}
|
JavaScript
| 0 |
@@ -2214,22 +2214,20 @@
response
-IsJSON
+Type
= respo
@@ -2249,32 +2249,96 @@
('content-type')
+;%0A const responseIsJSON = responseType ? responseType
.match(/applicat
@@ -2348,16 +2348,24 @@
%5C/json/)
+ : false
;%0A
@@ -2405,36 +2405,27 @@
onse
-.headers.get('content-t
+Type ? responseT
ype
-')
.mat
@@ -2441,16 +2441,24 @@
/plain/)
+ : false
;%0A%0A
@@ -3594,16 +3594,177 @@
s = 200;
+%0A%0A if (!responseType && response.ok) %7B%0A console.log(%22IN THIS THING!%22);%0A resolve();%0A return;%0A %7D
%0A
@@ -6223,32 +6223,33 @@
%7D)()
+;
%0A %7D).catc
@@ -6302,24 +6302,61 @@
ven%22%7D) =%3E %7B%0A
+ console.log(fetchError);%0A
|
703e243609aa5ac39a94fbfe9991133721ad9690
|
add cookie path.
|
app/assets/javascripts/application/articles/edit.js
|
app/assets/javascripts/application/articles/edit.js
|
//= require editor
var ArticleEdit = function() {
this.editor = new Editor({
toolbar: '#toolbar',
editable: '#editarea article'
});
this.article = $('#editarea article');
this.connect('#urlname-form', 'submit', this.saveUrlname);
this.connect('#save-button', 'click', this.saveArticle);
this.connect('#publish-button', 'click', this.publishArticle);
this.connect('#draft-button', 'click', this.draftArticle);
this.connect('#book-form', 'submit', this.saveBook);
this.connect('#new-book-form', 'submit', this.createBook);
this.connect('#pick-up-button', 'click', this.pickUpTopbar);
$('#book-form .dropdown').on('click', '.dropdown-menu li a', this.selectBook);
var _this = this;
Mousetrap.bind('ctrl+s', function(event) {
_this.saveArticle(event);
});
};
ArticleEdit.prototype = {
connect: function(element, event, fn) {
var _this = this;
$(element).on(event, function(event) {
fn.call(_this, event, this);
});
},
isPersisted: function() {
return !!this.article.data('id');
},
updateArticle: function(data, success_callback, error_callback) {
$.ajax({
url: '/articles/' + this.article.data('id'),
data: data,
type: 'put',
dataType: 'json'
}).success(success_callback).error(error_callback);
},
saveUrlname: function(event) {
event.preventDefault();
var urlname = $('#article-urlname').val();
if (this.isPersisted()) {
this.updateArticle($('#urlname-form').serializeArray(), function(data) {
$('#topbar .urlname').text(data.urlname);
Dialog.hide('#urlname-modal');
});
} else {
this.article.data('urlname', urlname);
$('#topbar .urlname').text(urlname);
Dialog.hide('#urlname-modal');
}
},
saveBook: function(event) {
event.preventDefault();
var bookId = $('#article-book-id').val();
var bookName = $('#book-form .dropdown-toggle').text();
var _this = this;
if (this.isPersisted()) {
this.updateArticle($('#book-form').serializeArray(), function(data) {
_this.article.data('book-id', bookId);
$('#topbar .book-name').text(bookId ? bookName : '');
Dialog.hide('#select-book-modal');
});
} else {
this.article.data('book-id', bookId);
$('#topbar .book-name').text(bookId ? bookName : '');
Dialog.hide('#select-book-modal');
}
},
createBook: function(event) {
event.preventDefault();
$.ajax({
url: '/books/',
data: $('#new-book-form').serializeArray(),
type: 'post',
dataType: 'json'
}).success(function(data) {
var $li = $('<li><a href="#">');
$li.find('a').text(data.name).data('book-id', data.urlname);
$('#book-form .dropdown-menu').prepend($li);
$('#book-form .dropdown-toggle').text(data.name);
$('#article-book-id').val(data.urlname);
Dialog.hide('#new-book-modal');
});
},
selectBook: function(event) {
event.preventDefault();
var $item = $(this);
$item.closest('.dropdown').find('.dropdown-toggle').text($item.text());
$('#article-book-id').val($item.data('book-id'));
},
saveArticle: function(event) {
event.preventDefault();
if (this.isPersisted()) {
this.updateArticle({
article: {
title: this.editor.editable.find('h1').text(),
body: this.editor.editable.html()
}
});
} else {
this.createArticle();
}
},
createArticle: function() {
var _this = this;
$.ajax({
url: '/articles',
data: {
article: {
title: this.editor.editable.find('h1').text(),
body: this.editor.editable.html(),
urlname: this.article.data('urlname'),
book_id : this.article.data('book-id'),
status: this.article.data('status')
}
},
type: 'post',
dataType: 'json'
}).success(function(data) {
_this.article.data('id', data.id);
history.replaceState(null, null, '/articles/' + data.id + '/edit');
});
},
setPbulishClass: function(isPublish) {
if (isPublish) {
$('#draft-button').removeClass('button-actived');
$('#publish-button').addClass('button-actived');
} else {
$('#publish-button').removeClass('button-actived');
$('#draft-button').addClass('button-actived');
}
},
publishArticle: function(event) {
var _this = this;
this.setPbulishClass(true);
event.preventDefault();
if (this.isPersisted()) {
this.updateArticle({
article: {
status: 'publish'
}
}, null, function(data) {
this.setPbulishClass(false);
_this.article.data('status', 'draft');
});
} else {
this.article.data('status', 'publish');
}
},
draftArticle: function(event) {
var _this = this;
event.preventDefault();
this.setPbulishClass(false);
if (this.isPersisted()) {
this.updateArticle({
article: {
status: 'draft'
}
}, null, function(data) {
_this.setPbulishClass(true);
this.article.data('status', 'publish');
});
} else {
this.article.data('status', 'draft');
}
},
pickUpTopbar: function() {
$('body').toggleClass('pick-up-topbar');
if ($('body').hasClass('pick-up-topbar')) {
$.cookie('pick_up_topbar', true);
} else {
$.removeCookie('pick_up_topbar');
}
}
};
page_ready(function() {
if ($('body#articles-edit').length) {
window.articleEdit = new ArticleEdit();
}
});
|
JavaScript
| 0 |
@@ -5368,24 +5368,47 @@
opbar', true
+, %7B path: '/articles' %7D
);%0A %7D els
@@ -5444,24 +5444,48 @@
k_up_topbar'
+, %7B path: '/articles' %7D
);%0A %7D%0A %7D
|
44230efdbea44ccbdd1449c4aa87d7cd77e316ec
|
Move count assert to end for debugging
|
test/watcher.js
|
test/watcher.js
|
var assert = require('assert'),
fs = require('fs'),
lib = require('./lib'),
watcher = require('../lib/watcher'),
wrench = require('wrench');
if (!fs.watch) {
// Watch is unsupported on 0.4 and earlier, no tests for this case
return;
}
describe('watcher', function() {
var outdir;
before(function() {
outdir = lib.testDir('watcher', 'touch');
wrench.copyDirSyncRecursive('test/artifacts', outdir);
});
afterEach(function() {
watcher.unwatchAll();
});
it('should not notify on file read', function(done) {
this.timeout(1000);
watcher.watchFile(outdir + '/index.html', [], function(type, fileName, sourceChange) {
assert.fail('Watch event occurred.');
});
fs.open(outdir + '/index.html', 'r+', function(err, fd) {
var buffer = new Buffer(4);
fs.read(fd, buffer, 0, buffer.length, 0, function(err, bytesRead, buffer) {
fs.close(fd, function() {
setTimeout(done, 500);
});
});
});
});
it ('should notify on write', function(done) {
var count = 0;
var testFile = outdir + '/file-modules.json';
watcher.watchFile(testFile, [], function(type, fileName, sourceChange) {
assert.equal(1, ++count);
assert.equal('change', type);
assert.equal(testFile, fileName);
assert.equal(testFile, sourceChange);
done();
});
fs.open(testFile, 'w', function(err, fd) {
var buffer = new Buffer([1, 2, 3, 4]);
fs.write(fd, buffer, 0, buffer.length, 0, function(err, written, buffer) {
fs.close(fd);
});
});
});
it('should notify on unlink', function(done) {
var count = 0;
var testFile = outdir + '/application-namespace.json';
watcher.watchFile(testFile, [], function(type, fileName, sourceChange) {
assert.equal(1, ++count);
assert.equal('remove', type);
assert.equal(testFile, fileName);
assert.equal(testFile, sourceChange);
done();
});
setTimeout(function() {
fs.unlink(testFile);
}, 100);
});
it('should notify on rename', function(done) {
if (require('os').platform() !== 'darwin') {
// This does not appear to work on linux and has not been tested on windows.
// Unclear at this time if the error is do to the events not being sent
// or if the fs.rename API doesn't generate the proper events
return done();
}
var count = 0;
var testFile = outdir + '/generated-load-prefix.json';
watcher.watchFile(testFile, [], function(type, fileName, sourceChange) {
assert.equal(1, ++count);
assert.equal('remove', type);
assert.equal(testFile, fileName);
assert.equal(testFile, sourceChange);
done();
});
setTimeout(function() {
fs.rename(testFile, outdir + '/foo');
}, 100);
});
it('should notify on overwrite', function(done) {
var count = require('os').platform() === 'darwin' ? 0 : 1;
var testFile = outdir + '/index-update.json';
watcher.watchFile(testFile, [], function(type, fileName, sourceChange) {
assert.ok(2 >= ++count, 'Unexpected count:' + count);
assert.equal(count === 1 ? 'rename' : 'change', type);
assert.equal(testFile, fileName);
assert.equal(testFile, sourceChange);
if (count >= 2) {
done();
}
});
setTimeout(function() {
fs.rename(outdir + '/static.json', testFile, function() {
setTimeout(function() {
fs.open(testFile, 'w', function(err, fd) {
var buffer = new Buffer([1, 2, 3, 4]);
fs.write(fd, buffer, 0, buffer.length, 0, function(err, written, buffer) {
fs.close(fd);
});
});
}, 100);
});
}, 100);
});
it('should notify on child creation', function(done) {
var count = 0;
var testFile = outdir + '/bar';
watcher.watchFile(outdir, [], function(type, fileName, sourceChange) {
assert.equal(1, ++count);
assert.equal('create', type);
assert.equal(outdir, fileName);
assert.equal(outdir, sourceChange);
done();
});
setTimeout(function() {
fs.writeFile(testFile, 'bar');
}, 100);
});
});
|
JavaScript
| 0 |
@@ -1197,40 +1197,8 @@
) %7B%0A
- assert.equal(1, ++count);%0A
@@ -1305,32 +1305,64 @@
sourceChange);%0A
+ assert.equal(1, ++count);%0A
done();%0A
@@ -3938,40 +3938,8 @@
) %7B%0A
- assert.equal(1, ++count);%0A
@@ -4042,32 +4042,64 @@
sourceChange);%0A
+ assert.equal(1, ++count);%0A
done();%0A
|
342f743035bc40dbe395b1eaf5c7a2898644d1d7
|
Write moveLeft function
|
js/application.js
|
js/application.js
|
$(document).ready(function() {
var Game = function(givenBoard) {
function getRandomIndex(maxExclusive) {
return Math.floor(Math.random() * maxExclusive)
}
function randomBoard() {
var board = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
var index1 = getRandomIndex(16)
var index2 = index1
do {
index2 = getRandomIndex(16)
} while (index2 === index1)
var startingNumbers = [2, 4]
var startingNum1 = startingNumbers[getRandomIndex(2)]
var startingNum2 = startingNumbers[getRandomIndex(2)]
board[index1] = startingNum1
board[index2] = startingNum2
return board
}
function presetBoard(board) {
var boardArray = board.split("")
for (i = 0; i < boardArray.length; i++) {
boardArray[i] = parseInt(boardArray[i])
}
return boardArray
}
if (givenBoard === undefined) {
this.board = randomBoard()
} else {
this.board = presetBoard(givenBoard)
}
}
function createWorkingBoard(board) {
return [
board.slice(0,4),
board.slice(4,8),
board.slice(8,12),
board.slice(12,16)
]
}
function removeZeros(board) {
var workingBoard = createWorkingBoard(board)
for (i = 0; i < workingBoard.length; i++) {
for (j = 0; j < workingBoard[i].length; j++) {
if (workingBoard[i][j] === 0) {
workingBoard[i].splice(j, 1)
j = j-1
}
}
}
return workingBoard
}
// move: right
function combineTilesRight(board) {
for (i = 0; i < board.length; i++) {
for (j = board[i].length-1; j > 0; j--) {
if (board[i][j] === board[i][j-1]) {
board[i][j] *=2
board[i].splice(j-1, 1)
}
}
}
return board
}
// move: right (therefore padding zeros from the left)
function padZeros(board) {
for (i = 0; i < board.length; i++) {
if (board[i].length !== 4) {
do {
board[i].unshift(0)
} while (board[i].length < 4)
}
}
return board
}
Game.prototype.saveBoard = function(board) {
this.board = [].concat.apply([], board)
}
Game.prototype.moveRight = function() {
var noZeros = removeZeros(this.board)
var tilesCombined = combineTilesRight(noZeros)
var updatedBoard = padZeros(tilesCombined)
this.saveBoard(updatedBoard)
return this.board
}
game = new Game("2222242402002204")
console.log(game.moveRight())
})
|
JavaScript
| 0.004426 |
@@ -1194,58 +1194,8 @@
) %7B%0A
- var workingBoard = createWorkingBoard(board)%0A%0A
@@ -1210,24 +1210,17 @@
0; i %3C
-workingB
+b
oard.len
@@ -1253,24 +1253,17 @@
0; j %3C
-workingB
+b
oard%5Bi%5D.
@@ -1289,24 +1289,17 @@
if (
-workingB
+b
oard%5Bi%5D%5B
@@ -1320,24 +1320,17 @@
-workingB
+b
oard%5Bi%5D.
@@ -1399,16 +1399,9 @@
urn
-workingB
+b
oard
@@ -2113,24 +2113,78 @@
unction() %7B%0A
+ var workingBoard = createWorkingBoard(this.board)%0A
var noZe
@@ -2201,22 +2201,24 @@
veZeros(
-this.b
+workingB
oard)%0A
@@ -2373,16 +2373,610 @@
rd%0A %7D%0A%0A
+ function reverseBoard(board) %7B%0A var reverseBoard = %5B%5D%0A for (i = 0; i %3C board.length; i++) %7B%0A reverseBoard.push(board%5Bi%5D.reverse())%0A %7D%0A return reverseBoard%0A %7D%0A%0A Game.prototype.moveLeft = function() %7B%0A var workingBoard = createWorkingBoard(this.board)%0A var reversedBoard = reverseBoard(workingBoard)%0A var noZeros = removeZeros(reversedBoard)%0A var tilesCombined = combineTilesRight(noZeros)%0A var updatedReversedBoard = padZeros(tilesCombined)%0A var updatedBoard = reverseBoard(updatedReversedBoard)%0A this.saveBoard(updatedBoard)%0A return this.board%0A %7D%0A%0A
game =
@@ -2990,27 +2990,58 @@
me(%22
-22222424020022
+02024402222240
04%22)%0A
+ console.log(game.moveLeft())%0A
co
@@ -3068,13 +3068,12 @@
ight())%0A
-%0A
%7D)%0A%0A
|
f59a27cfa37667aa69287890a88c28f966b51148
|
use Id for keeping track of last seen in scrape.js; tweak code
|
scrape.js
|
scrape.js
|
#!/usr/bin/env node
const fs = require('fs');
const cacheFile = 'cache/last-seen-committees.json';
const Browser = require('zombie');
const browser = new Browser({waitDuration: '30s'});
browser.visit('https://efiling.ocf.dc.gov/Disclosure')
.then(getTypes)
.then(getLastSeen)
.then(findNewRecords);
function getTypes() {
const types = [];
const options = browser.field('#FilerTypeId').options;
for (const option of options) {
if (option.value) {
types.push(option.text);
}
}
return types;
}
function getLastSeen(types) {
return new Promise(function (resolve, reject) {
fs.readFile(cacheFile, function (err, json) {
const lastSeen = err ? {} : JSON.parse(json);
for (const type of types) {
if (!lastSeen[type]) {
lastSeen[type] = null;
}
}
resolve(lastSeen);
});
});
}
async function findNewRecords(lastSeen) {
const types = Object.keys(lastSeen);
for (const type of types) {
const newRecords = await findNewRecordsForType(type, lastSeen[type]);
console.log(type, newRecords);
if (newRecords[0]) {
lastSeen[type] = getRecordKey(newRecords[0]);
}
}
fs.writeFileSync(cacheFile, JSON.stringify(lastSeen, null, 2));
return lastSeen;
}
function getRecordKey(record) {
return record.CommitteeKey || record.CandidateKey;
}
function findNewRecordsForType(type, lastSeenKey) {
return browser.select('#FilerTypeId', type)
.then(pause)
.then(() => browser.click('#btnSubmitSearch'))
.then(getSearchData)
.then(function (records) {
const newRecords = [];
for (const record of records) {
const key = getRecordKey(record);
if (lastSeenKey && key === lastSeenKey) {
break;
}
newRecords.push(record);
}
return newRecords;
});
}
function pause() {
return new Promise(resolve => setTimeout(resolve, 5000));
}
function getSearchData() {
let i = browser.resources.length;
while (i > 0) {
i--;
const resource = browser.resources[i];
if (resource.request.url.match(/\/Search$/)) {
return JSON.parse(resource.response.body).data;
}
}
}
|
JavaScript
| 0 |
@@ -1000,43 +1000,27 @@
-const types = Object.keys(lastSeen)
+let changed = false
;%0A
@@ -1028,37 +1028,70 @@
for (const
+%5B
type
- of types
+, lastSeenId%5D of Object.entries(lastSeen)
) %7B%0A
@@ -1151,22 +1151,18 @@
lastSeen
-%5Btype%5D
+Id
);%0A
@@ -1257,230 +1257,186 @@
%5D =
-getRecordKey(newRecords%5B0%5D);%0A %7D%0A %7D%0A fs.writeFileSync(cacheFile, JSON.stringify(lastSeen, null, 2));%0A return lastSeen;%0A%7D%0A%0Afunction getRecordKey(record) %7B%0A return record.CommitteeKey %7C%7C record.CandidateKey
+newRecords%5B0%5D.Id;%0A changed = true;%0A %7D%0A %7D%0A if (changed) %7B%0A fs.writeFileSync(cacheFile, JSON.stringify(lastSeen, null, 2));%0A %7D%0A return lastSeen
;%0A%7D%0A
@@ -1473,35 +1473,34 @@
e(type, lastSeen
-Key
+Id
) %7B%0A return b
@@ -1758,58 +1758,8 @@
) %7B%0A
- const key = getRecordKey(record);%0A
@@ -1786,18 +1786,23 @@
Seen
-Key
+Id
&&
-key
+record.Id
===
@@ -1814,11 +1814,10 @@
Seen
-Key
+Id
) %7B%0A
|
10e56fbae14f6d060a2dfa01576c001247a8593c
|
fix openInStyleboard href in embed mode
|
scripts/styleboard.js
|
scripts/styleboard.js
|
require(['Parser', 'Context', 'Example',
'TabbedFrameView', 'DictionaryView', 'RenderedView', 'MarkupView', 'RulesView',
'FooterView', 'SettingsView', 'appState'],
function( Parser, Context, Example,
TabbedFrameView, DictionaryView, RenderedView, MarkupView, RulesView,
FooterView, SettingsView, appState) {
// copy this JSON into ../styleboard.config to configure styleboard.
var configs = {
'default': 'styleboard',
'styleboard': {
'cssUrl': 'styles/styleboard.css',
'options': {}
}
};
$.ajax({
dataType: 'json',
cache: false,
url: '../styleboard.config',
success: function ( jsonObject ) {
configs = jsonObject;
},
error: function ( jqxhr, status, error ) {
console.warn( "No configuration: " + status + "(" + error + ")" );
},
complete: function () {
var config = configs['default'];
if ( !_.isObject(config) ) {
// then it's the name of the default config
config = configs[config];
}
new StyleBoard( config, window.location.hash );
}
});
function StyleBoard( config, hash ) {
var sb = this,
cssUrl = config.cssUrl || 'samples/home.css',
parser = new Parser();
parser.load( cssUrl, function (doc) {
sb.doc = doc;
var patterns = doc.getAllOfType('pattern').map( function (node) {
return new Context({ doc: doc, node: node });
});
var dictionary = new Backbone.Collection( patterns );
// initialize each view, if it exists in the markup
$('#dictionaryView').each( function () {
(new DictionaryView({ el: $(this), model: dictionary })).render();
});
$('#tabbedView').each( function () {
(new TabbedFrameView({ el: $(this) })).render();
});
$('#sandbox').each( function () {
(new RenderedView({ el: $(this), cssUrl: cssUrl })).render();
});
$('#example').each( function () {
(new MarkupView({ el: $(this), doc: doc })).render();
});
$('#sources').each( function () {
(new RulesView({ el: $('#sources'), doc: doc })).render();
});
$('#settings').each( function () {
(new SettingsView({ el: $('#settings') })).render();
});
$('#embedFooter').each( function () {
(new FooterView({ el: $(this) })).render();
});
$('#openInStyleboard').each( function () {
var $a = $(this);
appState.on('change', function () {
var pattern = appState.get('pattern'),
example = appState.get('example'),
href = './#' + pattern.get('name');
if ( example ) {
href = href + '/' + (example.get('slug') || example.get('index') || '');
}
$a.attr('href', href);
});
});
if ( hash ) {
route( hash.slice(1) );
}
$(window).on('hashchange', function() {
var hash = window.location.hash;
route( hash.slice(1) );
});
});
return sb;
// Load the state of the app from a string (usually the URL hash)
// Possible routes:
// <pattern> go to pattern, show first example
// <pattern>/<N> go to example N of pattern
// <pattern>/<slug> find example by slug for the pattern
function route( string ) {
var path = string.split('/'),
pattern,
examples,
index,
example;
if ( path.length ) {
pattern = new Context({ doc: sb.doc, node: sb.doc.findByName( path[0] ) });
examples = pattern.getNodesOfType('example', Example);
if ( path.length > 1 ) {
if ( path[1].match( /^\d+$/ ) ) {
// example number
index = parseInt( path[1] );
if ( index < examples.length ) {
example = examples[index];
}
} else {
// example slug
example = _(examples).find( function (xmp) {
return xmp.getName() === path[1];
});
}
} else if ( examples.length ) {
// first example
example = examples[0];
}
}
appState.set('pattern', pattern || new Context({doc: sb.doc}) );
appState.set('example', example || new Example({doc: sb.doc}) );
}
}
});
|
JavaScript
| 0 |
@@ -3014,15 +3014,13 @@
.get
-('name'
+Name(
);%0A
@@ -3099,17 +3099,16 @@
+ '/' +
-(
example.
@@ -3114,46 +3114,13 @@
.get
-('slug') %7C%7C example.get('index') %7C%7C ''
+Name(
);%0A
|
41e0329a9ed87371c96dba105cb61206f9198192
|
Check for updates to episode on item save.
|
opal/static/js/opal/controllers/edit_item.js
|
opal/static/js/opal/controllers/edit_item.js
|
angular.module('opal.controllers').controller(
'EditItemCtrl', function($scope, $cookieStore, $timeout,
$modalInstance, $modal,
ngProgressLite,
profile, item, options, episode) {
$scope.profile = profile;
$scope.episode = episode.makeCopy();
// Some fields should only be shown for certain categories.
// Make that category available to the template.
$scope.episode_category = episode.location[0].category
$scope.editing = item.makeCopy();
// This is the patientname displayed in the modal header
$scope.editingName = item.episode.demographics[0].name;
$scope.columnName = item.columnName;
// initially display episodes of interest to current user
$scope.currentTag = $cookieStore.get('opal.currentTag') || 'mine';
// initially display episodes of interest to current user
$scope.currentSubTag = 'all';
$scope.showSubtags = function(withsubtags){
return _.some(withsubtags, function(tag){ return item[tag] });
};
for (var name in options) {
if (name.indexOf('micro_test') != 0) {
$scope[name + '_list'] = options[name];
};
};
// TODO - don't hardcode this
if (item.columnName == 'microbiology_test' || item.columnName == 'lab_test' || item.columnName == 'investigation') {
$scope.microbiology_test_list = [];
$scope.microbiology_test_lookup = {};
$scope.micro_test_defaults = options.micro_test_defaults;
for (var name in options) {
if (name.indexOf('micro_test') == 0) {
for (var ix = 0; ix < options[name].length; ix++) {
$scope.microbiology_test_list.push(options[name][ix]);
$scope.microbiology_test_lookup[options[name][ix]] = name;
};
};
};
$scope.$watch('editing.test', function(testName) {
$scope.testType = $scope.microbiology_test_lookup[testName];
if( _.isUndefined(testName) || _.isUndefined($scope.testType) ){
return;
}
if($scope.testType in $scope.micro_test_defaults){
_.each(
_.pairs($scope.micro_test_defaults[$scope.testType]),
function(values){
var field = values[0];
var _default = values[1];
var val = _default
if($scope.editing[field]){
val = $scope.editing[field]
}
$scope.editing[field] = val;
});
}
});
};
$scope.episode_category_list = ['Inpatient', 'Outpatient', 'Review'];
//
// Save the item that we're editing.
//
$scope.save = function(result) {
ngProgressLite.set(0);
ngProgressLite.start();
item.save($scope.editing).then(function() {
ngProgressLite.done();
$modalInstance.close(result);
});
};
// Let's have a nice way to kill the modal.
$scope.cancel = function() {
$modalInstance.close('cancel');
};
$scope.undischarge = function() {
undischargeMoadal = $modal.open({
templateUrl: '/templates/modals/undischarge.html/',
controller: 'UndischargeCtrl',
resolve: {episode: function(){ return episode } }
}
).result.then(function(result){
$modalInstance.close(episode.location[0])
});
};
$scope.prepopulate = function($event) {
$event.preventDefault();
var data = $($event.target).data()
_.each(_.keys(data), function(key){
if(data[key] == 'true'){
data[key] = true;
return
}
if(data[key] == 'false'){
data[key] = false;
return
}
});
angular.extend($scope.editing, data);
};
});
|
JavaScript
| 0 |
@@ -153,16 +153,20 @@
$modal,
+ $q,
%0A
@@ -302,16 +302,51 @@
rofile;%0A
+ $scope._episode = episode;%0A
@@ -3062,22 +3062,39 @@
tart();%0A
-%09%09
+ to_save = %5B
item.sav
@@ -3110,16 +3110,205 @@
editing)
+%5D;%0A if(!angular.equals($scope._episode.makeCopy(), $scope.episode))%7B%0A to_save.push($scope._episode.save($scope.episode));%0A %7D%0A $q.all(to_save)
.then(fu
|
a90052b0d20903928ba0e4bec9efaed6c922ee71
|
Revert "指摘修正"
|
lib/runtime/components/questions/MultiNumberQuestion.js
|
lib/runtime/components/questions/MultiNumberQuestion.js
|
/* eslint-env browser */
import React from 'react';
import { connect } from 'react-redux';
import S from 'string';
import classNames from 'classnames';
import { parseInteger } from '../../../utils';
import TransformQuestion from './TransformQuestion';
import MultiNumberQuestionState from '../../states/MultiNumberQuestionState';
import ItemDefinition from '../../models/survey/questions/internal/ItemDefinition';
import QuestionDetail from '../parts/QuestionDetail';
import * as Actions from '../../actions';
/** 設問:数値記入 */
class MultiNumberQuestion extends TransformQuestion {
constructor(props) {
super(props, MultiNumberQuestionState);
}
/** Reactのライフサイクルメソッド */
componentDidMount() {
this.rootEl.addEventListener('change', () => this.setTotalValue(), false);
this.rootEl.addEventListener('keyup', () => this.setTotalValue(), false);
}
/** 入力値をもとに合計値を設定する */
setTotalValue() {
const { question, executeNextTick } = this.props;
const idList = this.state.model.getTransformedItems().map(item => question.getOutputName(false, item.getIndex())).toList();
const doc = this.rootEl.ownerDocument;
// totalElを更新する前に次のページに遷移してしまう可能性があるため、executingフラグをtrueにすることで「進む」ボタンを押せないようにする
executeNextTick(() => {
// sdj-numericが全角を半角にした後に計算する必要があるため、nextTickで処理を行う
const total = idList.reduce((reduction, id) => reduction + parseInteger(doc.getElementById(id).value, 0), 0);
const totalId = question.getOutputName(true);
const totalEl = doc.getElementById(totalId);
if (totalEl) {
totalEl.value = total;
}
});
}
/** 制御情報を作成する */
createItemDetail(item) {
const { options, question } = this.props;
if (!options.isShowDetail()) return null;
if (!question.isRandom() || !item.isRandomFixed()) return null;
return (
<span className="detail-function" style={{ verticalAlign: 'top' }}>ランダム固定</span>
);
}
/** itemに対応するelementを作成する */
createItem(item, isTotal = false) {
const { survey, runtime, options, replacer, question } = this.props;
const name = question.getOutputName(isTotal, item.getIndex());
const totalEqualTo = question.getTotalEqualTo();
const errorContainerId = `${name}_error_container`;
const className = classNames('multiNumberLine', {
multiNumberTotal: isTotal,
[item.calcVisibilityClassName(survey, runtime.getAnswers(true))]: !options.isVisibilityConditionDisabled(),
});
return (
<div key={`${question.getId()}_${item.getIndex()}`} className={className}>
<div className="multiNumberLabel">
<label dangerouslySetInnerHTML={{ __html: replacer.id2Value(item.getLabel()) }} />
</div>
<div className="multiNumberAssociated mini">
<div className="multiNumberInput">
<input
type="text"
pattern="\d*"
maxLength="16"
id={name}
name={name}
className={classNames('sdj-numeric', { disabled: isTotal })}
readOnly={isTotal}
data-output-no={survey.findOutputNoFromName(name)}
data-response-multiple
data-response-item-index={isTotal ? null : item.getIndex()}
data-parsley-required={!isTotal}
data-parsley-type="digits"
data-parsley-min={isTotal || S(question.getMin()).isEmpty() ? null : replacer.id2Value(question.getMin())}
data-parsley-max={isTotal || S(question.getMax()).isEmpty() ? null : replacer.id2Value(question.getMax())}
data-parsley-equal={isTotal && !S(totalEqualTo).isEmpty() ? replacer.id2Value(totalEqualTo) : null}
data-parsley-errors-container={`#${errorContainerId}`}
/>
<span className="multiNumberUnit"> {question.getUnit()}</span>
<span id={errorContainerId} />
</div>
</div>
{this.createItemDetail(item)}
</div>
);
}
/** itemsに対応するelementを作成する */
createItems() {
const { model } = this.state;
const items = model.getTransformedItems();
if (items.size === 0) {
throw new Error('items attribute is not defined');
}
return items.map(item => this.createItem(item));
}
/** 合計のelementを作成する */
createTotalItem() {
const { question } = this.props;
if (!question.isShowTotal()) {
return null;
}
return this.createItem(new ItemDefinition({ label: '合計' }), true);
}
render() {
const { replacer, question, options } = this.props;
const title = question.getTitle();
const description = question.getDescription();
const answers = {};
return (
<div ref={(el) => { this.rootEl = el || this.rootEl; }} className={this.constructor.name}>
<h2 className="question-title" dangerouslySetInnerHTML={{ __html: replacer.id2Value(title, answers) }} />
<h3 className="question-description" dangerouslySetInnerHTML={{ __html: replacer.id2Value(description, answers) }} />
<div className="question validation-hover-target">
{this.createItems()}
{this.createTotalItem()}
</div>
{ options.isShowDetail() ? <QuestionDetail question={question} random min max totalEqualTo={question.isShowTotal()} /> : null }
</div>
);
}
}
const stateToProps = state => ({
survey: state.getSurvey(),
runtime: state.getRuntime(),
view: state.getViewSetting(),
options: state.getOptions(),
});
const actionsToProps = dispatch => ({
executeNextTick: func => Actions.executeNextTick(dispatch, func),
});
export default connect(
stateToProps,
actionsToProps,
)(MultiNumberQuestion);
|
JavaScript
| 0 |
@@ -1283,16 +1283,28 @@
%E5%BF%85%E8%A6%81%E3%81%8C%E3%81%82%E3%82%8B%E3%81%9F%E3%82%81%E3%80%81
+setTimeout%E3%81%97%E3%81%A6
nextTick
@@ -1595,16 +1595,22 @@
%7D%0A %7D
+, true
);%0A %7D%0A%0A
|
6a120500b964567a9efdb55f9cdb58042e5b5d6d
|
Fix flot y-axis format
|
js/charts/flot.js
|
js/charts/flot.js
|
ds.charts = ds.charts || {}
/**
* Chart provider for rendering dashboard chart with flot, which
* provides Canvas-based interactivity.
*/
ds.charts.flot =
(function() {
var self = {}
self.CHART_IMPL_TYPE = 'flot'
function get_default_options() {
var theme_colors = ds.charts.util.get_colors()
var default_options = {
colors: ds.charts.util.get_palette(),
series: {
lines: { show: true, lineWidth: 1, fill: false},
stack: null,
points: { show: false },
bars: { show: false }
},
xaxis: {
mode: "time",
twelveHourClock: true,
timezone: ds.config.DISPLAY_TIMEZONE,
// timeformat: '',
tickColor: theme_colors.minorGridLineColor
// axisLabel: 'Time'
},
yaxes: [
{
tickFormatter: d3.format(',3s'), /* TODO: get from item options */
reserveSpace: 30,
labelWidth: 30,
tickColor: theme_colors.minorGridLineColor
// axisLabel: 'Things'
},
{
// tickFormatter: opendash.format_kmbt,
color: '#ccc'
}
],
points: {
show: false,
radius: 2,
symbol: "circle"
},
shadowSize: 0,
legend: {
container: null,
noColumns: 2,
position: 'sw',
backgroundColor: 'transparent',
labelBoxBorderColor: 'transparent'
},
grid: {
borderWidth: 0,
hoverable: true,
clickable: true,
autoHighlight: false,
/* grid.color actually sets the color of the legend
* text. WTH? */
color: theme_colors.fgcolor
},
selection: {
mode: "x",
color: "red"
},
multihighlight: {
mode: "x"
},
crosshair: {
mode: "x",
color: "#BBB",
lineWidth: 1
}
}
return default_options
}
function show_tooltip(x, y, contents) {
$('<div id="ds-tooltip">' + contents + '</div>').css( {
position: 'absolute',
display: 'none',
top: y + 5,
left: x + 5
}).appendTo("body").show()
}
function setup_plugins(container, context) {
$(container).bind("multihighlighted", function(event, pos, items) {
if ( !items )
return
var series = context.plot.getData()
var item = items[0]
var point = series[item.serieIndex].data[item.dataIndex]
var contents = ds.templates.flot.tooltip({
time: point[0],
items: items.map(function(item) {
return {
series: series[item.serieIndex],
value: series[item.serieIndex].data[item.dataIndex][1]
}
})
})
$("#ds-tooltip").remove()
show_tooltip(pos.pageX, pos.pageY, contents)
})
$(container).bind("unmultihighlighted", function(event) {
$("#ds-tooltip").remove()
})
}
self.simple_line_chart = function(e, item, query) {
var options = item.options || {}
var context = {
plot: null
}
setup_plugins(e, context)
context.plot = $.plot($(e), [query.chart_data('flot')[0]],
ds.extend(get_default_options(), {
colors: ds.charts.util.get_palette(options.palette),
grid: {
show: false
},
legend: {
show: false
}
}))
return self
}
self.standard_line_chart = function(e, item, query) {
var options = item.options || {}
var context = {
plot: null
}
setup_plugins(e, context)
var defaults = get_default_options()
context.plot = $.plot($(e), query.chart_data('flot'),
ds.extend(get_default_options(), {
colors: ds.charts.util.get_palette(options.palette),
grid: ds.extend(defaults.grid, {
borderWidth: 0,
hoverable: true,
clickable: true,
autoHighlight: false
}),
legend: {
container: '#ds-legend-' + item.item_id,
labelBoxBorderColor: 'transparent',
show: true,
noColumns: 4
}
}))
return self
}
self.simple_area_chart = function(e, item, query) {
var options = item.options || {}
var context = {
plot: null
}
setup_plugins(e, context)
context.plot = $.plot($(e), [query.chart_data('flot')[0]],
ds.extend(get_default_options(), {
colors: ds.charts.util.get_palette(options.palette),
grid: {
show: false
},
legend: {
show: false
},
series: {
lines: {
show: true,
fill: 1
}
}
}))
return self
}
self.stacked_area_chart = function(e, item, query) {
var options = item.options || {}
var context = {
plot: null
}
setup_plugins(e, context)
context.plot = $.plot($(e), query.chart_data('flot'),
ds.extend(get_default_options(), {
colors: ds.charts.util.get_palette(options.palette),
legend: {
container: '#ds-legend-' + item.item_id,
labelBoxBorderColor: 'transparent',
show: true,
noColumns: 4
},
series: {
lines: { show: true, lineWidth: 1, fill: 1},
stack: true,
points: { show: false },
bars: { show: false }
}
}))
return self
}
self.donut_chart = function(e, item, query) {
ds.charts.nvd3.donut_chart(e, item, query)
return self
}
self.process_series = function(series) {
var result = {}
if (series.summation) {
result.summation = series.summation
}
result.label = series.target
result.data = series.datapoints.map(function(point) {
return [point[1] * 1000, point[0]]
})
return result
}
return self
})()
|
JavaScript
| 0.999878 |
@@ -885,47 +885,14 @@
t(',
+.
3s'),
- /* TODO: get from item options */
%0A
@@ -1005,43 +1005,8 @@
lor%0A
- // axisLabel: 'Things'%0A
@@ -1037,19 +1037,16 @@
- //
tickFor
@@ -1057,28 +1057,25 @@
er:
-opendash.format_kmbt
+d3.format(',.3s')
,%0A
|
2c40cbe92c48c17376ffc553d7b0919eab94a328
|
Update namespace
|
lib/node_modules/@stdlib/math/iter/special/lib/index.js
|
lib/node_modules/@stdlib/math/iter/special/lib/index.js
|
/**
* @license Apache-2.0
*
* Copyright (c) 2019 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
/*
* When adding modules to the namespace, ensure that they are added in alphabetical order according to module name.
*/
// MODULES //
var setReadOnly = require( '@stdlib/utils/define-read-only-property' );
// MAIN //
/**
* Top-level namespace.
*
* @namespace ns
*/
var ns = {};
/**
* @name iterAbs
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/iter/special/abs}
*/
setReadOnly( ns, 'iterAbs', require( '@stdlib/math/iter/special/abs' ) );
/**
* @name iterAbs2
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/iter/special/abs2}
*/
setReadOnly( ns, 'iterAbs2', require( '@stdlib/math/iter/special/abs2' ) );
/**
* @name iterAcos
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/iter/special/acos}
*/
setReadOnly( ns, 'iterAcos', require( '@stdlib/math/iter/special/acos' ) );
/**
* @name iterAcosh
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/iter/special/acosh}
*/
setReadOnly( ns, 'iterAcosh', require( '@stdlib/math/iter/special/acosh' ) );
/**
* @name iterAdd
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/iter/special/add}
*/
setReadOnly( ns, 'iterAdd', require( '@stdlib/math/iter/special/add' ) );
/**
* @name iterAsin
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/iter/special/asin}
*/
setReadOnly( ns, 'iterAsin', require( '@stdlib/math/iter/special/asin' ) );
/**
* @name iterAsinh
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/iter/special/asinh}
*/
setReadOnly( ns, 'iterAsinh', require( '@stdlib/math/iter/special/asinh' ) );
/**
* @name iterAtan
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/iter/special/atan}
*/
setReadOnly( ns, 'iterAtan', require( '@stdlib/math/iter/special/atan' ) );
/**
* @name iterCos
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/iter/special/cos}
*/
setReadOnly( ns, 'iterCos', require( '@stdlib/math/iter/special/cos' ) );
/**
* @name iterDivide
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/iter/special/divide}
*/
setReadOnly( ns, 'iterDivide', require( '@stdlib/math/iter/special/divide' ) );
/**
* @name iterMod
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/iter/special/mod}
*/
setReadOnly( ns, 'iterMod', require( '@stdlib/math/iter/special/mod' ) );
/**
* @name iterMultiply
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/iter/special/multiply}
*/
setReadOnly( ns, 'iterMultiply', require( '@stdlib/math/iter/special/multiply' ) );
/**
* @name iterSin
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/iter/special/sin}
*/
setReadOnly( ns, 'iterSin', require( '@stdlib/math/iter/special/sin' ) );
/**
* @name iterSubtract
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/iter/special/subtract}
*/
setReadOnly( ns, 'iterSubtract', require( '@stdlib/math/iter/special/subtract' ) );
// EXPORTS //
module.exports = ns;
|
JavaScript
| 0.000001 |
@@ -2503,32 +2503,236 @@
ial/atan' ) );%0A%0A
+/**%0A* @name iterAtanh%0A* @memberof ns%0A* @readonly%0A* @type %7BFunction%7D%0A* @see %7B@link module:@stdlib/math/iter/special/atanh%7D%0A*/%0AsetReadOnly( ns, 'iterAtanh', require( '@stdlib/math/iter/special/atanh' ) );%0A%0A
/**%0A* @name iter
|
d1d7e49caf894708d52a5e5c5de7637006236bb3
|
reduce maxResult for yutup query
|
js/controllers.js
|
js/controllers.js
|
angular.module('myApp')
// Controller
.controller('VideosController', function ($scope, $http, $log, VideosService) {
init();
function init() {
$scope.youtube = VideosService.getYoutube();
$scope.results = VideosService.getResults();
$scope.history = VideosService.getHistory();
}
$scope.loadd = function () {
var xmlhttp = new XMLHttpRequest();
var url = "js/members.json";
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 ) {
$scope.myArr = JSON.parse(this.responseText);
$scope.getAvatars();
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
};
$scope.getAvatars = function () {
var i = 0;
while($scope.myArr.length > i) {
if($scope.myArr[i].type == 'user')
{
$http.get('https://www.googleapis.com/youtube/v3/channels', {
params: {
key: 'AIzaSyDDheDyEodFf3EPUqMw876deYCoqBIFeoU',
type: 'channel',
maxResults: '50',
part: 'id, snippet, contentDetails',
forUsername: $scope.myArr[i].id
}
})
.success( function (data) {
if (data.items.length === 0) {
$scope.label = 'No results were found!';
}
else {
for (var i = $scope.myArr.length - 1; i >= 0; i--) {
if($scope.myArr[i].name == data.items[0].snippet.title)
$scope.myArr[i].avatar = data.items[0].snippet.thumbnails.medium.url;
}
}
})
.error( function () {
$log.info('Search error');
})
.finally( function () {
$scope.loadMoreButton.stopSpin();
$scope.loadMoreButton.setDisabled(false);
$scope.loading = false;
});
} else {
$http.get('https://www.googleapis.com/youtube/v3/channels', {
params: {
key: 'AIzaSyDDheDyEodFf3EPUqMw876deYCoqBIFeoU',
part: 'id,snippet,contentDetails',
id: $scope.myArr[i].id
}
})
.success( function (data) {
if (data.items.length === 0) {
$scope.label = 'No results were found!';
}
else {
for (var k = $scope.myArr.length - 1; k >= 0; k--) {
if($scope.myArr[k].name == data.items[0].snippet.title)
$scope.myArr[k].avatar = data.items[0].snippet.thumbnails.medium.url;
}
}
})
.error( function () {
$log.info('Search error');
})
.finally( function () {
$scope.loadMoreButton.stopSpin();
$scope.loadMoreButton.setDisabled(false);
$scope.loading = false;
});
}
i++;
}
};
$scope.reload =function() {
if($scope.lastChannelType == "channel")
$scope.searchByChannel($scope.lastChannel,false);
else
$scope.search($scope.lastChannel,false);
}
$scope.launch = function (video, archive) {
VideosService.launchPlayer(video.id, video.title);
if (archive) {
VideosService.archiveVideo(video);
}
$log.info('Launched id:' + video.id + ' and title:' + video.title);
};
$scope.nextPageToken = '';
$scope.label = 'You haven\'t searched for any video yet!';
$scope.loading = false;
$scope.lastChannel = "";
$scope.lastChannelType = "";
$scope.search = function (channelName,isNewQuery) {
$scope.loading = true;
if(isNewQuery) {
$scope.lastChannel = channelName;
$scope.lastChannelType = "user";
}
$http.get('https://www.googleapis.com/youtube/v3/channels', {
params: {
key: 'AIzaSyDDheDyEodFf3EPUqMw876deYCoqBIFeoU',
type: 'channel',
maxResults: '50',
pageToken: isNewQuery ? '' : $scope.nextPageToken,
part: 'id, snippet, contentDetails',
forUsername: $scope.lastChannel
}
})
.success( function (data) {
if (data.items.length === 0) {
$scope.label = 'No results were found!';
}
else {
var item = data.items[0];
var _playListId = item.contentDetails.relatedPlaylists.uploads;
$http.get('https://www.googleapis.com/youtube/v3/playlistItems', {
params: {
key: 'AIzaSyDDheDyEodFf3EPUqMw876deYCoqBIFeoU',
maxResults: '50',
pageToken: isNewQuery ? '' : $scope.nextPageToken,
part: 'id,snippet,contentDetails',
order: 'date',
playlistId: _playListId
}
})
.success( function (data) {
if (data.items.length === 0) {
$scope.label = 'No results were found!';
}
VideosService.listResults(data, $scope.nextPageToken && !isNewQuery);
$scope.nextPageToken = data.nextPageToken;
$log.info(data);
})
.error( function () {
$log.info('Search error');
})
.finally( function () {
$scope.loadMoreButton.stopSpin();
$scope.loadMoreButton.setDisabled(false);
$scope.loading = false;
});
}
})
.error( function () {
$log.info('Search error');
})
.finally( function () {
$scope.loadMoreButton.stopSpin();
$scope.loadMoreButton.setDisabled(false);
$scope.loading = false;
});
};
$scope.searchByChannel = function (channelName,isNewQuery) {
$scope.loading = true;
if(isNewQuery) {
$scope.lastChannel = channelName;
$scope.lastChannelType = "channel";
}
$http.get('https://www.googleapis.com/youtube/v3/search', {
params: {
key: 'AIzaSyDDheDyEodFf3EPUqMw876deYCoqBIFeoU',
maxResults: '50',
pageToken: isNewQuery ? '' : $scope.nextPageToken,
part: 'id,snippet',
order: 'date',
channelId: $scope.lastChannel
}
})
.success( function (data) {
if (data.items.length === 0) {
$scope.label = 'No results were found!';
}
else {
VideosService.listResults(data, $scope.nextPageToken && !isNewQuery);
$scope.nextPageToken = data.nextPageToken;
$log.info(data);
}
})
.error( function () {
$log.info('Search error');
})
.finally( function () {
$scope.loadMoreButton.stopSpin();
$scope.loadMoreButton.setDisabled(false);
$scope.loading = false;
});
};
});
|
JavaScript
| 0.998291 |
@@ -809,26 +809,16 @@
%3E i) %7B%0A
-
%0A
@@ -1075,33 +1075,33 @@
maxResults: '
-5
+3
0',%0A
@@ -3964,33 +3964,33 @@
maxResults: '
-5
+1
0',%0A pa
@@ -4607,33 +4607,33 @@
maxResults: '
-5
+1
0',%0A
@@ -6157,9 +6157,9 @@
s: '
-5
+1
0',%0A
|
c5e4274e3f8b8d09dcf6ea10da0d72eae83ad233
|
fix backend
|
backend/server.js
|
backend/server.js
|
if(!process.argv[2]) {
console.error('usage: node ' + process.argv[1] + ' <port>');
process.exit(1);
}
var express = require('express'),
bodyParser = require('body-parser'),
app = express(),
actions = [],
tasks = [],
port = parseInt(process.argv[2]);
function pushAction(id, action) {
if(!actions[id]) actions[id] = [];
if(actions[id].length <= 20) actions[id].push(action);
}
function getAction(id) {
if(!actions[id] || actions[id].length <= 0) return {action: "none"};
else return actions[id].pop();
}
function getClientTasks(id) {
if(!actions[id]) return [];
else return actions[id];
}
app.use(bodyParser.json());
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
app.get('/get', function (req, res) {
var id = req.query.id;
if (typeof id !== 'undefined' && id) {
res.type('application/json');
var tsk = JSON.stringify(getAction(id));
console.log("send " + id + " task: " + tsk);
res.send(tsk);
} else res.status(500).end();
});
app.get('/get_report', function (req, res) {
var id = req.query.id;
if (typeof id !== 'undefined' && id) {
res.type('application/json');
var rpt = JSON.stringify(getClientTasks(id));
console.log("send " + id + " report: " + rpt);
res.send(rpt);
} else res.status(500).end();
});
app.post('/control', function (req, res) {
var id = req.query.id;
if (typeof id !== 'undefined' && id) {
try {
console.log(id + " added task: " + JSON.stringify(req.body));
pushAction(id, req.body);
res.status(200).end();
} catch(e) {
console.log(e);
res.status(500).end();
}
} else res.status(500).end();
});
app.post('/report', function (req, res) {
var id = req.query.id;
if (typeof id !== 'undefined' && id) {
try {
console.log(id + " reported: " + JSON.stringify(req.body));
tasks[id] = req.body;
res.status(200).end();
} catch(e) {
console.log(e);
res.status(500).end();
}
} else res.status(500).end();
});
app.listen(port, function () {
console.log("nato_play server running on port " + port + ".");
});
|
JavaScript
| 0.000001 |
@@ -563,30 +563,28 @@
id) %7B%0A if(!
-action
+task
s%5Bid%5D) retur
@@ -599,30 +599,28 @@
else return
-action
+task
s%5Bid%5D;%0A%7D%0A%0Aap
|
9256b816c23d7700ea81190933959d356ce5842d
|
FIX storybook config
|
.storybook/webpack.config.js
|
.storybook/webpack.config.js
|
var path = require('path');
module.exports = {
module: {
rules: [
{
test: /\.(js|jsx)$/,
loaders: ['react-hot-loader', 'babel-loader'],
include: [path.join(__dirname, 'src')],
// include: [path.join(__dirname, 'src'), path.join(__dirname, 'example')]
},
],
},
};
|
JavaScript
| 0.000001 |
@@ -43,47 +43,84 @@
s =
-%7B%0A module: %7B%0A rules: %5B%0A
+async (%7B config %7D) =%3E %7B%0A console.log(config);%0A config.module.rules.push(
%7B%0A
-
@@ -140,20 +140,16 @@
jsx)$/,%0A
-
load
@@ -191,20 +191,16 @@
ader'%5D,%0A
-
incl
@@ -239,20 +239,16 @@
)%5D,%0A
-
-
// inclu
@@ -320,26 +320,29 @@
%5D%0A
- %7D,%0A %5D,%0A %7D,
+%7D);%0A%0A return config;
%0A%7D;%0A
|
b56f103a74999701d4aa65b596be8754b908fa1d
|
Enable flow type check
|
template-create-react-app/src/App.js
|
template-create-react-app/src/App.js
|
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
class App extends Component {
render() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h1 className="App-title">Welcome to React</h1>
</header>
<p className="App-intro">
To get started, edit <code>src/App.js</code> and save to reload.
</p>
</div>
);
}
}
export default App;
|
JavaScript
| 0.000001 |
@@ -1,12 +1,22 @@
+// @flow%0A%0A
import React
@@ -97,16 +97,34 @@
.css';%0A%0A
+type Props = %7B%7D;%0A%0A
class Ap
@@ -142,16 +142,23 @@
omponent
+%3CProps%3E
%7B%0A ren
|
656f3bab9d96e1803243e4772846b84b5544dfb4
|
Fix formatting for nightwatch configuration
|
template/test/e2e/nightwatch.conf.js
|
template/test/e2e/nightwatch.conf.js
|
require('babel-register')
var config = require('../../config')
// http://nightwatchjs.org/gettingstarted#settings-file
module.exports = {
src_folders: ['test/e2e/spec'],
output_folder: 'test/e2e/report',
selenium: {
start_process: true,
server_path: require('selenium-server').path,
host: '127.0.0.1',
port: 4444,
cli_args: {
'webdriver.chrome.driver': require('chromedriver').path
}
},
test_settings: {
default: {
selenium_port: 4444,
selenium_host: 'localhost',
silent: true,
globals: {
devServerURL: 'http://localhost:' + (process.env.PORT || config.dev.port)
}
},
chrome: {
desiredCapabilities: {
browserName: 'chrome',
javascriptEnabled: true,
acceptSslCerts: true
}
},
firefox: {
desiredCapabilities: {
browserName: 'firefox',
javascriptEnabled: true,
acceptSslCerts: true
}
}
}
}
|
JavaScript
| 0.000002 |
@@ -132,16 +132,18 @@
rts = %7B%0A
+
src_fo
@@ -170,16 +170,18 @@
ec'%5D,%0A
+
+
output_f
@@ -207,16 +207,18 @@
port',%0A%0A
+
seleni
@@ -219,24 +219,28 @@
selenium: %7B%0A
+
start_pr
@@ -256,16 +256,20 @@
ue,%0A
+
+
server_p
@@ -306,16 +306,20 @@
).path,%0A
+
host
@@ -333,16 +333,20 @@
0.0.1',%0A
+
port
@@ -349,24 +349,28 @@
port: 4444,%0A
+
cli_args
@@ -369,24 +369,30 @@
cli_args: %7B%0A
+
'webdr
@@ -449,16 +449,24 @@
-%7D%0A
+ %7D%0A
%7D,%0A%0A
+
te
@@ -476,24 +476,28 @@
settings: %7B%0A
+
default:
@@ -495,24 +495,30 @@
default: %7B%0A
+
seleni
@@ -534,24 +534,30 @@
4444,%0A
+
+
selenium_hos
@@ -572,16 +572,22 @@
lhost',%0A
+
si
@@ -604,16 +604,22 @@
,%0A
+
+
globals:
@@ -617,24 +617,32 @@
globals: %7B%0A
+
devS
@@ -711,24 +711,30 @@
v.port)%0A
+
%7D%0A
%7D,%0A%0A
@@ -717,32 +717,36 @@
)%0A %7D%0A
+
%7D,%0A%0A chro
@@ -741,16 +741,20 @@
%7D,%0A%0A
+
+
chrome:
@@ -751,24 +751,30 @@
chrome: %7B%0A
+
desire
@@ -790,32 +790,40 @@
ties: %7B%0A
+
+
browserName: 'ch
@@ -829,32 +829,40 @@
hrome',%0A
+
+
javascriptEnable
@@ -862,32 +862,40 @@
tEnabled: true,%0A
+
acceptSs
@@ -913,30 +913,40 @@
e%0A
+
+
%7D%0A
+
+
%7D,%0A%0A
firefox:
@@ -937,16 +937,20 @@
%7D,%0A%0A
+
+
firefox:
@@ -948,24 +948,30 @@
firefox: %7B%0A
+
desire
@@ -987,32 +987,40 @@
ties: %7B%0A
+
+
browserName: 'fi
@@ -1027,32 +1027,40 @@
refox',%0A
+
+
javascriptEnable
@@ -1060,32 +1060,40 @@
tEnabled: true,%0A
+
acceptSs
@@ -1115,16 +1115,28 @@
+
+
%7D%0A
+
-%7D%0A
+ %7D%0A
%7D%0A
|
34d8e20727528031c51f36d093f27fe51d763b71
|
Update navigation bar docs
|
packages/bpk-docs/src/pages/NavigationBarPage/NavigationBarPage.js
|
packages/bpk-docs/src/pages/NavigationBarPage/NavigationBarPage.js
|
/*
* Backpack - Skyscanner's Design System
*
* Copyright 2018 Skyscanner Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* @flow */
import React from 'react';
import ArrowIcon from 'bpk-component-icon/sm/long-arrow-left';
import CloseIcon from 'bpk-component-icon/sm/close';
import { withRtlSupport } from 'bpk-component-icon';
import BpkNavigationBar, {
BpkNavigationBarIconButton,
BpkNavigationBarButtonLink,
} from 'bpk-component-navigation-bar';
import navigationBarReadme from 'bpk-component-navigation-bar/readme.md';
import { cssModules } from 'bpk-react-utils';
import DocsPageBuilder from './../../components/DocsPageBuilder';
import Paragraph from './../../components/Paragraph';
import IntroBlurb from './../../components/neo/IntroBlurb';
import AirlineIcon from './page-components';
import STYLES from './NavigationBarPage.scss';
const getClassNames = cssModules(STYLES);
const ArrowIconWithRtl = withRtlSupport(ArrowIcon);
const components = [
{
id: 'default',
title: 'Default',
blurb: [],
examples: [
<div className={getClassNames('bpk-navigation-bar-example')}>
<BpkNavigationBar
id="default-bpk-nav"
title="Backpack"
leadingButton={
<BpkNavigationBarIconButton
onClick={() => {}}
icon={ArrowIconWithRtl}
label="back"
/>
}
/>
</div>,
],
},
{
id: 'with-text-button',
title: 'With text button',
blurb: [
<Paragraph>
The navigation bar can be composed with text buttons.
</Paragraph>,
],
examples: [
<div className={getClassNames('bpk-navigation-bar-example')}>
<BpkNavigationBar
id="default-bpk-nav"
title="Backpack"
leadingButton={
<BpkNavigationBarIconButton
onClick={() => {}}
icon={ArrowIconWithRtl}
label="back"
/>
}
trailingButton={
<BpkNavigationBarButtonLink onClick={() => {}}>
Done
</BpkNavigationBarButtonLink>
}
/>
</div>,
],
},
{
id: 'with-icon-button',
title: 'With icon button',
blurb: [
<Paragraph>
The navigation bar can be composed with different icon buttons.
</Paragraph>,
],
examples: [
<div className={getClassNames('bpk-navigation-bar-example')}>
<BpkNavigationBar
id="default-bpk-nav"
title="Backpack"
leadingButton={
<BpkNavigationBarIconButton
onClick={() => {}}
icon={ArrowIconWithRtl}
label="back"
/>
}
trailingButton={
<BpkNavigationBarIconButton
onClick={() => {}}
icon={CloseIcon}
label="close"
/>
}
/>
</div>,
],
},
{
id: 'with-icon-title',
title: 'With icon in title',
blurb: [
<Paragraph>The title can include elements other than text.</Paragraph>,
],
examples: [
<div className={getClassNames('bpk-navigation-bar-example')}>
<BpkNavigationBar
id="default-bpk-nav"
title={
<span
className={getClassNames(
'bpk-navigation-bar-example__title-content-wrapper',
)}
>
<AirlineIcon />
</span>
}
leadingButton={
<BpkNavigationBarIconButton
onClick={() => {}}
icon={ArrowIconWithRtl}
label="back"
/>
}
trailingButton={
<BpkNavigationBarButtonLink onClick={() => {}}>
Done
</BpkNavigationBarButtonLink>
}
/>
</div>,
],
},
];
const isNeo = process.env.BPK_NEO;
const blurb = [
<IntroBlurb>
The navigation bar component encapsulates a title and icon/text actions for
controlling views.
</IntroBlurb>,
];
const NavigationBarPage = ({ ...rest }: { [string]: any }) => (
<DocsPageBuilder
title="Navigation bar"
blurb={isNeo ? null : blurb}
components={components}
readme={navigationBarReadme}
{...rest}
/>
);
export default NavigationBarPage;
|
JavaScript
| 0 |
@@ -3502,21 +3502,30 @@
ith
-icon in title
+a custom title element
',%0A
|
47b2a110029f22fbd2e3d6c46fb3b44ffdda53c4
|
Update field 'fullName' when user updates its profile
|
public/app/services/user.service.js
|
public/app/services/user.service.js
|
(function () {
'use strict';
angular
.module('PLMApp')
.factory('userService', userService)
.run(function (userService) {}); // To instanciate the service at startup
userService.$inject = ['$timeout', '$cookies', 'connection', 'listenersHandler', '$auth', 'toasterUtils', 'gettextCatalog'];
function userService($timeout, $cookies, connection, listenersHandler, $auth, toasterUtils, gettextCatalog) {
listenersHandler.register('onmessage', handleMessage);
var user = {};
var actorUUID;
var timeoutProfileUpdate;
var service = {
isAuthenticated: isAuthenticated,
signUp: signUp,
signInWithCredentials: signInWithCredentials,
signInWithProvider: signInWithProvider,
signOut: signOut,
getUser: getUser,
setTrackUser: setTrackUser,
askTrackUser: askTrackUser,
setNextAskTrackUser: setNextAskTrackUser,
updateUser: updateUser,
cloneUser: cloneUser
};
return service;
function isAuthenticated() {
return $auth.isAuthenticated()
}
function signUp(email, password, firstName, lastName) {
return $auth.signup({
email: email,
password: password,
firstName: firstName,
lastName: lastName
});
}
function signInWithCredentials(email, password) {
return $auth.login({
email: email,
password: password
});
}
function signInWithProvider(provider) {
return $auth.authenticate(provider);
}
function signOut() {
$auth.logout()
.then(function () {
var msg = gettextCatalog.getString('You have been logged out');
toasterUtils.info(msg);
});
connection.sendMessage('signOut', {});
}
function getUser() {
return user;
}
function setUser(data) {
delete $cookies.gitID;
user = data;
}
function cloneUser() {
return {
firstName: user.firstName,
lastName: user.lastName,
trackUser: user.trackUser
};
}
function updateUser(newUser) {
user.firstName = newUser.firstName;
user.lastName = newUser.lastName;
user.trackUser = newUser.trackUser;
connection.sendMessage('updateUser', {
firstName: user.firstName,
lastName: user.lastName,
trackUser: user.trackUser
});
timeoutProfileUpdate = $timeout(function () {
var title = gettextCatalog.getString('Error during update');
var msg = gettextCatalog.getString('An error occurred while updating your profile. Please excuse us for the inconvenience and retry to submit your changes later.');
toasterUtils.error(title, msg);
}, 10000);
}
function setGitID(gitID) {
$cookies.gitID = gitID;
if ($auth.isAuthenticated()) {
$auth.logout();
}
}
function setTrackUser(trackUser) {
user.trackUser = trackUser;
delete localStorage.nextAskTrackUser;
connection.sendMessage('setTrackUser', {
trackUser: trackUser
});
}
function askTrackUser() {
var now;
var nextAskTrackUser;
if (localStorage.nextAskTrackUser === undefined) {
return true;
}
now = new Date();
nextAskTrackUser = new Date(localStorage.nextAskTrackUser);
return nextAskTrackUser < now;
}
function setNextAskTrackUser() {
var nextAskTrackUser = new Date();
nextAskTrackUser.setDate(nextAskTrackUser.getDate() + 3); // Ask again in 3 days
localStorage.nextAskTrackUser = nextAskTrackUser;
}
function handleMessage(data) {
var cmd = data.cmd;
var args = data.args;
switch (cmd) {
case 'actorUUID':
actorUUID = args.actorUUID;
$cookies.actorUUID = actorUUID;
break;
case 'gitID':
setGitID(args.gitID);
break;
case 'user':
setUser(args.user);
break;
case 'userUpdated':
$timeout.cancel(timeoutProfileUpdate);
toasterUtils.info(gettextCatalog.getString('Your profile has been successfully updated'));
break;
}
}
}
})();
|
JavaScript
| 0.000001 |
@@ -2159,32 +2159,95 @@
wUser.lastName;%0A
+ user.fullName = user.firstName + ' ' + newUser.lastName;%0A
user.track
|
39c5a39bff9a8feca89663195c4d7d2f02b7e30a
|
Improve infoContent.js
|
js/infoContent.js
|
js/infoContent.js
|
define(['text!../views/infoContent.html', 'utils', 'jquery'], function(html, utils, $) {
'use strict';
var _infoContent = function(posts) {
var container = document.getElementById('container');
if (!utils._isUnd(posts) && !utils._isUnd(html)) {
container.innerHTML = html;
var miniPanel = document.getElementById('infoMiniPanel');
if (!utils._isUnd(miniPanel)) {
var title = document.createElement('h5'),
link = document.createElement('a'),
postsContainer = document.createElement('div'),
pContainer = document.getElementById('infoContentPanel');
title.innerHTML = posts.title;
utils._setAttr(link, 'href', posts.link + '.html');
link.innerHTML = posts.link;
postsContainer.className = 'postMenu';
if (!utils._isUnd(posts.entries) && posts.entries.length > 0) {
var i = 0,
entries = posts.entries.length;
for (i; i < entries; i++) {
var subDiv = document.createElement('div'),
subLink = document.createElement('a'),
subText = document.createElement('p'),
author = document.createElement('p');
utils._setAttr(subLink, 'href', '#');
utils._setAttr(subLink, 'data', posts.entries[i].link);
subLink.className = 'infoSubMenuLink';
subLink.innerHTML = posts.entries[i].title;
subText.innerHTML = posts.entries[i].publishedDate;
author.innerHTML = posts.entries[i].author;
utils._appendArr(subDiv, [subLink, subText, author]);
postsContainer.appendChild(subDiv);
if (miniPanel.childNodes.length > 0) {
var j = 0,
minLength = miniPanel.childNodes.length,
firstNode = null;
for (j; j < minLength; j++) {
if (typeof miniPanel.childNodes[j] === 'object' && miniPanel.childNodes[j].tagName === 'DIV') {
firstNode = miniPanel.childNodes[j].childNodes[0].childNodes[0].getAttribute('data');
}
}
utils._appendContent(pContainer, firstNode);
}
}
if (!utils._isUnd(document.getElementsByClassName('infoSubMenuLink'))) {
$('.infoSubMenuLink').click(function(ev) {
$('#infoContentPanel').empty();
var panel = miniPanel.childNodes[3].childNodes,
link = ev.currentTarget.attributes.data.value,
i = 0,
panelLength = panel.length;
for (i; i < panelLength; i++) {
var links = panel[i].childNodes[0];
if ($(links).hasClass('now')) {
$(links).removeClass('now');
}
}
$(this).addClass('selected');
$(this).addClass('now');
utils._appendContent(pContainer, link);
});
}
}
utils._appendArr(miniPanel, [title, link, postsContainer]);
}
}
};
return {
infoContent: _infoContent
};
});
|
JavaScript
| 0 |
@@ -1906,44 +1906,201 @@
-postsContainer.appendChild(subDiv);%0A
+utils._appendArr(miniPanel, %5Btitle, link, postsContainer%5D);%0A postsContainer.appendChild(subDiv);%0A %7D%0A%0A window.setTimeout(function() %7B
%0A
@@ -2625,24 +2625,67 @@
te('data');%0A
+ break;%0A
@@ -2848,38 +2848,59 @@
%7D
-%0A%0A
+, 500);%0A
+%7D%0A%0A
@@ -2992,20 +2992,16 @@
-
-
$('.info
@@ -3059,20 +3059,16 @@
-
-
$('#info
@@ -3088,28 +3088,24 @@
).empty();%0A%0A
-
@@ -3188,28 +3188,24 @@
-
-
link = ev.cu
@@ -3271,23 +3271,15 @@
-
i = 0,%0A
-
@@ -3347,36 +3347,32 @@
-
for (i; i %3C pane
@@ -3379,36 +3379,32 @@
lLength; i++) %7B%0A
-
@@ -3451,20 +3451,16 @@
des%5B0%5D;%0A
-
@@ -3543,20 +3543,16 @@
-
$(links)
@@ -3596,33 +3596,26 @@
- %7D%0A
+%7D%0A
@@ -3622,32 +3622,27 @@
-
%7D%0A%0A
-
@@ -3699,36 +3699,32 @@
-
$(this).addClass
@@ -3748,36 +3748,32 @@
-
-
utils._appendCon
@@ -3816,20 +3816,16 @@
-
%7D);%0A
@@ -3840,108 +3840,9 @@
- %7D%0A %7D%0A%0A utils._appendArr(miniPanel, %5Btitle, link, postsContainer%5D);
+%7D
%0A
|
e161e4763e39a5f306dfed015c7f488ae9be0d29
|
Fix child process termination in Electron app
|
KenticoInspector.DesktopApplication/main.js
|
KenticoInspector.DesktopApplication/main.js
|
// Modules to control application life and create native browser window
const {app, BrowserWindow} = require('electron')
const path = require('path')
const { spawn } = require('child_process');
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow
function createWindow () {
// Create the browser window.
mainWindow = new BrowserWindow({width: 800, height: 600})
// and load the index.html of the app.
mainWindow.loadURL('https://localhost:5001/')
//mainWindow.loadFile('index.html')
// Open the DevTools.
// mainWindow.webContents.openDevTools()
// Emitted when the window is closed.
mainWindow.on('closed', function () {
// Dereference the window object, usually you would store windows
// in an array if your app supports multi windows, this is the time
// when you should delete the corresponding element.
mainWindow = null
})
}
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', startApi)
// Quit when all windows are closed.
// app.on('window-all-closed', function () {
// // On macOS it is common for applications and their menu bar
// // to stay active until the user quits explicitly with Cmd + Q
// if (process.platform !== 'darwin') {
// app.quit()
// }
// })
// app.on('activate', function () {
// // On macOS it's common to re-create a window in the app when the
// // dock icon is clicked and there are no other windows open.
// if (mainWindow === null) {
// createWindow()
// }
// })
// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.
var apiProcess = null;
function startApi() {
// run server
const apipath = path.join(__dirname, '..\\publish\\console\\KenticoInspector.WebApplication.exe')
apiProcess = spawn(apipath, [], { shell: true });
//apiProcess = child_process.exec(apipath,)
apiProcess.stdout.on('data', (data) => {
writeLog(`stdout: ${data}`);
if (mainWindow == null) {
createWindow();
}
});
}
//Kill process when electron exits
process.on('exit', function () {
writeLog('exit');
spawn("taskkill", ["/pid", apiProcess.pid, '/f', '/t']);
});
function writeLog(msg){
console.log(msg);
}
|
JavaScript
| 0.000004 |
@@ -2056,77 +2056,10 @@
path
-, %5B%5D, %7B shell: true %7D);%0A //apiProcess = child_process.exec(apipath,
)
+;
%0A%0A
@@ -2113,22 +2113,22 @@
iteLog(%60
-stdout
+Server
: $%7Bdata
@@ -2238,22 +2238,18 @@
its%0A
-process
+app
.on('
-ex
+qu
it',
@@ -2289,62 +2289,24 @@
;%0A
-spawn(%22taskkill%22, %5B%22/pid%22, apiProcess.pid, '/f', '/t'%5D
+apiProcess.kill(
);%0A%7D
|
ebd2eeebbb1a3854dcd9a5fa14cdbee386e0ce63
|
add possibility to stub intl messages
|
packages/core/tocco-test-util/src/testingLibrary/testingLibrary.js
|
packages/core/tocco-test-util/src/testingLibrary/testingLibrary.js
|
import {render} from '@testing-library/react'
import PropTypes from 'prop-types'
import {IntlProvider} from 'react-intl'
import {Provider} from 'react-redux'
import TestThemeProvider from '../TestThemeProvider'
const defaultLocale = 'en'
const locale = defaultLocale
const IntlProviderWrapper = ({children}) => {
const ignoreError = () => {}
return (
<IntlProvider onError={ignoreError} locale={locale} defaultLocale={defaultLocale}>
<TestThemeProvider>{children}</TestThemeProvider>
</IntlProvider>
)
}
IntlProviderWrapper.propTypes = {
children: PropTypes.any
}
const renderWithIntl = (ui, options) => render(ui, {wrapper: IntlProviderWrapper, ...options})
const ReduxProviderWrapper = ({store, children}) => (
<Provider store={store}>
<IntlProviderWrapper>{children}</IntlProviderWrapper>
</Provider>
)
ReduxProviderWrapper.propTypes = {
store: PropTypes.any,
children: PropTypes.any
}
const renderWithStore = (ui, {store, ...renderOptions} = {}) => {
const Wrapper = ({children}) => {
return <ReduxProviderWrapper store={store}>{children}</ReduxProviderWrapper>
}
Wrapper.propTypes = {
children: PropTypes.any
}
// Return an object with the store and all of RTL's query functions
return {store, ...render(ui, {wrapper: Wrapper, ...renderOptions})}
}
export {renderWithIntl, renderWithStore}
|
JavaScript
| 0 |
@@ -285,32 +285,51 @@
iderWrapper = (%7B
+intlMessages = %7B%7D,
children%7D) =%3E %7B%0A
@@ -387,16 +387,40 @@
Provider
+ messages=%7BintlMessages%7D
onError
@@ -622,16 +622,50 @@
ypes.any
+,%0A intlMessages: PropTypes.object
%0A%7D%0Aconst
@@ -698,16 +698,18 @@
ions) =%3E
+%0A
render(
@@ -705,32 +705,37 @@
%3E%0A render(ui, %7B
+%0A
wrapper: IntlPro
@@ -727,16 +727,26 @@
rapper:
+props =%3E %3C
IntlProv
@@ -752,25 +752,80 @@
viderWrapper
-,
+ %7B...props%7D intlMessages=%7Boptions?.intlMessages%7D /%3E,%0A
...options%7D
@@ -823,16 +823,19 @@
.options
+%0A
%7D)%0A%0Acons
|
39afac0e3358b20106a32b41e9d663742c0f89f8
|
Update flushReadings.js
|
mainRPi/sockets/serverSocket/functions/flushReadings.js
|
mainRPi/sockets/serverSocket/functions/flushReadings.js
|
var fs=require('fs');
var async=require('../../../async');
var constants= require('../../../constants.js');
var envVariables=require('../../../envVariables.js');
var Reading=require('../../../server/models/reading.js');
module.exports=function(socket){
var i=0;
var j=0;
async.whilst(function(){i<docs.length},function(){
async.whilst(function(){i==j},function(){
socket.emit('rReading',docs[i],function(err,res){
if(err){
throw err;
}
if(res.status){
Reading.findById(docs[i]._id,function(err,doc){
if(err){
throw err;
}
doc.remove(function(err,res){
if(err){
throw err;
}
});
});
i++;
}
});
j++;
},function(){});
},function(){});
}
|
JavaScript
| 0 |
@@ -43,16 +43,19 @@
./../../
+../
async');
@@ -88,16 +88,19 @@
./../../
+../
constant
@@ -142,16 +142,19 @@
./../../
+../
envVaria
@@ -194,16 +194,19 @@
./../../
+../
server/m
|
6147d24ea622f261d3c29c250ddf2a662b1140dc
|
update the program of problem 661
|
problems/661_image-smoother/index.js
|
problems/661_image-smoother/index.js
|
/**
* Problem: https://leetcode.com/problems/image-smoother/description/
*/
/**
* @param {number[][]} M
* @return {number[][]}
*/
var imageSmoother = function(M) {
const result = [];
for (let i = 0; i < M.length; i++) result.push([]);
const { floor } = Math;
const calc = (i, j) => {
let count = 1;
let sum = M[i][j];
if (M[i - 1] && M[i - 1][j - 1] !== undefined) {
count++;
sum += M[i - 1][j - 1];
}
if (M[i - 1] && M[i - 1][j] !== undefined) {
count++;
sum += M[i - 1][j];
}
if (M[i - 1] && M[i - 1][j + 1] !== undefined) {
count++;
sum += M[i - 1][j + 1];
}
if (M[i][j - 1] !== undefined) {
count++;
sum += M[i][j - 1];
}
if (M[i][j + 1] !== undefined) {
count++;
sum += M[i][j + 1];
}
if (M[i + 1] && M[i + 1][j - 1] !== undefined) {
count++;
sum += M[i + 1][j - 1];
}
if (M[i + 1] && M[i + 1][j] !== undefined) {
count++;
sum += M[i + 1][j];
}
if (M[i + 1] && M[i + 1][j + 1] !== undefined) {
count++;
sum += M[i + 1][j + 1];
}
return floor(sum / count);
};
for (let i = 0; i < M.length; i++) {
for (let j = 0; j < (M[0] && M[0].length); j++) {
result[i][j] = calc(i, j);
}
}
return result;
};
module.exports = imageSmoother;
|
JavaScript
| 0.000001 |
@@ -346,36 +346,46 @@
if (M%5Bi - 1%5D
- &&
+) %7B%0A if (
M%5Bi - 1%5D%5Bj - 1%5D
@@ -399,32 +399,34 @@
efined) %7B%0A
+
count++;%0A s
@@ -416,32 +416,34 @@
count++;%0A
+
+
sum += M%5Bi - 1%5D%5B
@@ -446,34 +446,38 @@
1%5D%5Bj - 1%5D;%0A
-%7D%0A
+ %7D%0A
if (M%5Bi - 1%5D
@@ -469,36 +469,24 @@
if (M%5Bi -
- 1%5D && M%5Bi -
1%5D%5Bj%5D !== u
@@ -495,32 +495,34 @@
efined) %7B%0A
+
count++;%0A s
@@ -506,32 +506,34 @@
count++;%0A
+
sum += M%5Bi
@@ -538,34 +538,38 @@
%5Bi - 1%5D%5Bj%5D;%0A
-%7D%0A
+ %7D%0A
if (M%5Bi - 1%5D
@@ -569,20 +569,8 @@
%5Bi -
- 1%5D && M%5Bi -
1%5D%5B
@@ -591,32 +591,34 @@
efined) %7B%0A
+
count++;%0A s
@@ -602,32 +602,34 @@
count++;%0A
+
sum += M%5Bi
@@ -634,32 +634,40 @@
%5Bi - 1%5D%5Bj + 1%5D;%0A
+ %7D%0A
%7D%0A if (M%5B
@@ -832,36 +832,46 @@
if (M%5Bi + 1%5D
- &&
+) %7B%0A if (
M%5Bi + 1%5D%5Bj - 1%5D
@@ -885,32 +885,34 @@
efined) %7B%0A
+
count++;%0A s
@@ -902,32 +902,34 @@
count++;%0A
+
+
sum += M%5Bi + 1%5D%5B
@@ -932,34 +932,38 @@
1%5D%5Bj - 1%5D;%0A
-%7D%0A
+ %7D%0A
if (M%5Bi + 1%5D
@@ -955,36 +955,24 @@
if (M%5Bi +
- 1%5D && M%5Bi +
1%5D%5Bj%5D !== u
@@ -981,32 +981,34 @@
efined) %7B%0A
+
count++;%0A s
@@ -992,32 +992,34 @@
count++;%0A
+
sum += M%5Bi
@@ -1028,26 +1028,30 @@
1%5D%5Bj%5D;%0A
-%7D%0A
+ %7D%0A
if (M%5Bi
@@ -1055,20 +1055,8 @@
%5Bi +
- 1%5D && M%5Bi +
1%5D%5B
@@ -1077,32 +1077,34 @@
efined) %7B%0A
+
count++;%0A s
@@ -1088,32 +1088,34 @@
count++;%0A
+
sum += M%5Bi
@@ -1120,32 +1120,40 @@
%5Bi + 1%5D%5Bj + 1%5D;%0A
+ %7D%0A
%7D%0A return
|
d8ea804ef70a95a70883c3ca75fa790b4645ce9c
|
add menu option for dependency output
|
legaleseMain.js
|
legaleseMain.js
|
/* legaleseMain MANIFEST
*
* inside a legaleseMain project file you will find multiple scripts:
* legaleseMain
* controller
* svg
* owl
* esop
* captable
* form
* format
* lingua
* unused
* templates
* readrows
*
* these subsidiary modules represent chunks of functionality that reside in separate files both in the source repo and in the production google app.
* why? because that's better than having everything in one file, that's why.
*
*/
// ---------------------------------------------------------------------------------------------------- state
//
// a brief discussion regarding state.
//
// A spreadsheet may contain one or more sheets with deal-terms and entity particulars.
//
// When the user launches a routine from the Legalese menu, the routine usually takes its configuration from the ActiveSheet.
//
// But some routines are not launched from the Legalese menu. The form's submission callback writes to a sheet. How will it know which sheet to write to?
//
// Whenever we create a form, we shall record the ID of the then activeSheet into a UserProperty, "formActiveSheetId".
// Until the form is re-created, all submissions will feed that sheet.
//
// What happens if the user starts working on a different sheet? The user may expect that form submissions will magically follow their activity.
//
// To correct this impression, we give the user some feedback whenever the activeSheet is not the formActiveSheet.
//
// The showSidebar shall check and complain.
//
// That same test is also triggered when a function is called: if the activesheet is different to the form submission sheet, we alert() a warning.
//
//
var DEFAULT_AVAILABLE_TEMPLATES = "https://docs.google.com/spreadsheets/d/1rBuKOWSqRE7QgKgF6uVWR9www4LoLho4UjOCHPQplhw/edit#gid=981127052";
var DEFAULT_CAPTABLE_TEMPLATE = "https://docs.google.com/spreadsheets/d/1rBuKOWSqRE7QgKgF6uVWR9www4LoLho4UjOCHPQplhw/edit#gid=827871932";
// ---------------------------------------------------------------------------------------------------------------- onOpen
/**
* Adds a custom menu to the active spreadsheet.
* The onOpen() function, when defined, is automatically invoked whenever the
* spreadsheet is opened.
* For more information on using the Spreadsheet API, see
* https://developers.google.com/apps-script/service_spreadsheet
*/
function onOpen(addOnMenu, legaleseSignature) {
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var sheet = spreadsheet.getActiveSheet();
addOnMenu = addOnMenu || SpreadsheetApp.getUi().createAddonMenu();
addOnMenu
.addItem("Create Form", "legaleseMain.setupForm")
.addItem("Generate PDFs", "legaleseMain.fillTemplates")
.addItem("Compute Dependencies", "legaleseMain.computeDependencies")
// .addItem("Do Nothing", "legaleseMain.DoNothing")
// .addItem("Update TOTAL Column", "legaleseMain.updateTotal")
// .addItem("Add a new Investor or other Party", "legaleseMain.addEntity")
// .addItem("Add a Round to the Cap Table", "legaleseMain.addRound")
;
if (legaleseSignature && legaleseSignature._loaded) {
var echosignService = legaleseSignature.getEchoSignService();
if (echosignService != null) {
addOnMenu.addItem("Send to EchoSign", "legaleseSignature.uploadAgreement");
}
}
addOnMenu.addItem("Clone Spreadsheet", "legaleseMain.cloneSpreadsheet");
addOnMenu.addToUi();
// when we release this as an add-on the menu-adding will change.
// resetDocumentProperties_("oauth2.echosign");
// next time we uncomment this we need to take legalese.uniq.x into account
// resetDocumentProperties_("legalese.folder.id");
// resetDocumentProperties_("legalese.rootfolder");
PropertiesService.getDocumentProperties().deleteProperty("legalese.muteFormActiveSheetWarnings");
// if we're on the Natural Language UI, reset C2's data validation to the appropriate range.
if (sheet.getName() == "UI") {
var sectionRange = sectionRangeNamed(sheet,"Entity Groups");
var myRange = sheet.getRange(sectionRange[0], 2, sectionRange[1]-sectionRange[0]+1, 1);
Logger.log("resetting C2 datavalidation range to " + myRange.getA1Notation());
setDataValidation(sheet, "C2", myRange.getA1Notation());
}
if (legaleseSignature && legaleseSignature._loaded) {
legaleseSignature.showSidebar(sheet);
}
};
// ---------------------------------------------------------------------------------------------------------------- quicktest
function quicktest() {
Logger.log("i will run new capTable_()");
var capTable = new capTable_();
// Logger.log("i haz run new capTable_() and got back %s", capTable);
capTable.columnNames();
}
// spreadsheet functions.
// code.js needs to pass these through
function LOOKUP2D(wanted, range, left_right_top_bottom) {
// LOOKUP2D will search for the wanted element in the range %s and return the top/bottom/left/right element corresponding from the range"
for (var i in range) {
for (var j in range[i]) {
if (range[i][j] == wanted) {
// "found it at "+i+","+j+"; returning "
switch (left_right_top_bottom) {
case "top": return range[0][j];
case "right": return range[i][range[i].length-1];
case "bottom": return range[range.length-1][j];
default: return range[i][0];
}
}
}
}
return null;
}
function DoNothing() {
SpreadsheetApp.getUi().alert("noop succeeded!");
}
// -----------------------
var _loaded = true;
|
JavaScript
| 0.000001 |
@@ -2751,16 +2751,87 @@
ncies%22)%0A
+ %09.addItem(%22Do Dependency Thing%22, %22legaleseMain.depWriteForceLayout%22)%0A
//
|
29a8de6383b2f4b606d6edfe9c2c06e1be229145
|
Switch os
|
Nightwatchfile.js
|
Nightwatchfile.js
|
module.exports = {
src_folders: ['./tests/spec'],
output_folder: './results',
custom_assertions_path: '',
globals_path: './globals.json',
live_output: true,
selenium: {
start_process: true,
server_path: './node_modules/selenium-server/lib/runner/selenium-server-standalone-2.44.0.jar',
log_path: './results',
host: '127.0.0.1',
port: 4444,
cli_args: {
'webdriver.chrome.driver': './node_modules/chromedriver/lib/chromedriver/chromedriver.exe',
'webdriver.ie.driver': './node_modules/dalek-browser-ie/lib/bin/IEDriverServer.exe'
}
},
test_settings: {
default: {
launch_url: 'http://localhost',
selenium_host: '127.0.0.1',
selenium_port: 4444,
silent: true,
disable_colors: false,
screenshots: {
enabled: true,
path: './results/screenshots'
},
desiredCapabilities: {
browserName: 'chrome',
// browserName: 'firefox',
javascriptEnabled: true,
acceptSslCerts: true
}
},
chrome: {
desiredCapabilities: {
browserName: 'chrome',
javascriptEnabled: true
}
},
ie: {
desiredCapabilities: {
browserName: 'internet explorer',
javascriptEnabled: true
}
},
phantom: {
desiredCapabilities: {
browserName: 'phantomjs',
'phantomjs.binary.path': require('phantomjs').path,
javascriptEnabled: true
}
}
}
};
|
JavaScript
| 0.000001 |
@@ -431,16 +431,21 @@
modules/
+.bin/
chromedr
@@ -452,44 +452,116 @@
iver
-/lib/
+.cmd', // in windows%0A // 'webdriver.
chrome
+.
driver
-/chromedriver.exe',
+': './node_modules/.bin/chromedriver', // in mac
%0A
@@ -1027,16 +1027,96 @@
refox',%0A
+ // browserName: 'internet explorer',%0A browserName: 'phantomjs',%0A
|
b82d6ab0b1c499841ccc463c99ef7f50be39681a
|
call onClick, onChange after setState (#362)
|
src/components/NumberInput/NumberInput.js
|
src/components/NumberInput/NumberInput.js
|
import PropTypes from 'prop-types';
import React, { Component } from 'react';
import Icon from '../Icon';
import classNames from 'classnames';
export default class NumberInput extends Component {
static propTypes = {
className: PropTypes.string,
disabled: PropTypes.bool,
iconDescription: PropTypes.string.isRequired,
id: PropTypes.string.isRequired,
label: PropTypes.string,
max: PropTypes.number,
min: PropTypes.number,
onChange: PropTypes.func,
onClick: PropTypes.func,
step: PropTypes.number,
value: PropTypes.number,
};
static defaultProps = {
disabled: false,
iconDescription: 'choose a number',
label: ' ',
onChange: () => {},
onClick: () => {},
step: 1,
value: 0,
};
constructor(props) {
super(props);
let value = props.value;
if (props.min || props.min === 0) {
value = Math.max(props.min, value);
}
this.state = {
value,
};
}
componentWillReceiveProps(nextProps) {
if (nextProps.value !== this.props.value) {
this.setState({ value: nextProps.value });
}
}
handleChange = evt => {
if (!this.props.disabled) {
this.setState({
value: evt.target.value,
});
this.props.onChange(evt);
}
};
handleArrowClick = (evt, direction) => {
let value =
typeof this.state.value === 'string'
? Number(this.state.value)
: this.state.value;
const { disabled, min, max, step } = this.props;
const conditional =
direction === 'down'
? (min !== undefined && value > min) || min === undefined
: (max !== undefined && value < max) || max === undefined;
if (!disabled && conditional) {
value = direction === 'down' ? value - step : value + step;
this.setState({
value,
});
this.props.onClick(evt);
this.props.onChange(evt);
}
};
render() {
const {
className,
disabled,
iconDescription, // eslint-disable-line
id,
label,
max,
min,
step,
...other
} = this.props;
const numberInputClasses = classNames('bx--number', className);
const props = {
disabled,
id,
max,
min,
step,
onChange: this.handleChange,
value: this.state.value,
};
return (
<div className="bx--form-item">
<label htmlFor={id} className="bx--label">
{label}
</label>
<div className={numberInputClasses}>
<input type="number" pattern="[0-9]*" {...other} {...props} />
<div className="bx--number__controls">
<button
className="bx--number__control-btn"
onClick={evt => this.handleArrowClick(evt, 'up')}>
<Icon
className="up-icon"
name="caret--up"
description={this.props.iconDescription}
viewBox="0 2 10 5"
/>
</button>
<button
className="bx--number__control-btn"
onClick={evt => this.handleArrowClick(evt, 'down')}>
<Icon
className="down-icon"
name="caret--down"
viewBox="0 2 10 5"
description={this.props.iconDescription}
/>
</button>
</div>
</div>
</div>
);
}
}
|
JavaScript
| 0 |
@@ -1216,36 +1216,47 @@
t.value,%0A %7D
-);%0A%0A
+, (evt) =%3E %7B%0A
this.props
@@ -1263,32 +1263,43 @@
.onChange(evt);%0A
+ %7D);%0A%0A
%7D%0A %7D;%0A%0A ha
@@ -1840,28 +1840,39 @@
lue,%0A %7D
-);%0A%0A
+, (evt) =%3E %7B%0A
this.p
@@ -1892,24 +1892,26 @@
evt);%0A
+
this.props.o
@@ -1920,24 +1920,34 @@
hange(evt);%0A
+ %7D);%0A
%7D%0A %7D;%0A%0A
|
4c8db689134f35e4f2f7623ed042912b953d533e
|
remove test output
|
packages/login/src/components/TwoStepLoginForm/TwoStepLoginForm.js
|
packages/login/src/components/TwoStepLoginForm/TwoStepLoginForm.js
|
import React, {Component} from 'react'
import {FormattedMessage, intlShape} from 'react-intl'
import * as Tocco from 'tocco-ui'
import '../Login/styles.scss'
export class TwoStepLoginForm extends Component {
constructor(props) {
super(props)
this.state = {
userCode: ''
}
}
handleSubmit(e) {
e.preventDefault()
this.props.twoStepLogin(this.props.username, this.props.password, this.props.requestedCode, this.state.userCode)
}
handleUserCodeChange(e) {
this.setState({
userCode: e.target.value
})
}
render() {
return (
<div className="login-form">
{this.props.showTitle && <h1><FormattedMessage id="client.login.form.title"/></h1>}
<form>
<p><FormattedMessage id="client.login.twoStepLogin.introduction"/></p>
<p><FormattedMessage id="client.login.twoStepLogin.requestedCode"/>{this.props.requestedCode}</p>
<div className="input-group">
<span className="input-group-addon"><i className="glyphicon glyphicon-lock"/></span>
<input
type="text"
className="form-control"
name="code"
autoComplete="off"
onChange={this.handleUserCodeChange.bind(this)}
placeholder={this.msg('client.login.twoStepLogin.codePlaceholder')}
/>
</div>
<div>
<span>TEST: {this.props.loginPending}</span>
<Tocco.Button
label={this.msg('client.login.form.button')}
name="submit"
onClick={this.handleSubmit.bind(this)}
disabled={!this.state.userCode || this.props.loginPending}
pending={this.props.loginPending}
icon="glyphicon-log-in"
className="m-t-5"
/>
</div>
</form>
</div>
)
}
msg(id) {
return this.props.intl.formatMessage({
id
})
}
}
TwoStepLoginForm.propTypes = {
intl: intlShape.isRequired,
twoStepLogin: React.PropTypes.func.isRequired,
username: React.PropTypes.string,
password: React.PropTypes.string,
requestedCode: React.PropTypes.string,
showTitle: React.PropTypes.bool,
loginPending: React.PropTypes.bool
}
|
JavaScript
| 0.000009 |
@@ -1382,65 +1382,8 @@
iv%3E%0A
- %3Cspan%3ETEST: %7Bthis.props.loginPending%7D%3C/span%3E%0A
|
1410a6781d119ac65b74e4d2f1ab285ce5d444e6
|
Allow xr-spatial-tracking for websurfaces
|
scripts/websurface.js
|
scripts/websurface.js
|
elation.require(['engine.things.generic'], function() {
elation.component.add('engine.things.januswebsurface', function() {
this.postinit = function() {
elation.engine.things.januswebsurface.extendclass.postinit.call(this);
this.defineProperties({
websurface_id: { type: 'string' },
image_id: { type: 'string' },
color: { type: 'color', default: 0xffffff },
hovercolor: { type: 'color', default: 0x009900 },
activecolor: { type: 'color', default: 0x00ff00 }
});
var websurface = this.room.websurfaces[this.properties.websurface_id];
if (websurface) {
var url = websurface.src;
if (url && !url.match(/^(https?:)?\/\//)) {
url = this.room.baseurl + url;
}
// So...it turns out this is a bad time to be doing this sort of 3d iframe hackery in the browser.
// The internet is slowly transitioning from HTTP to HTTPS, but we're currently only at about 50%
// encrypted. Within the Janus community this is even lower, around 10%. Due to browser security
// concerns, WebVR content must be run on HTTPS since it's considered a "powerful new feature" and
// browser developers are using this as a wedge to drive the internet towards greater adoption of
// HTTPS. This requirement combines with the "HTTPS sites must not load any unencrypted resources"
// restriction to mean that we can only show WebSurfaces of HTTPS websites.
// As a last-ditch effort, we'll try loading the page as HTTPS even if the user specified HTTP,
// and hope that most sites are running both.
this.url = url.replace(/^http:/, 'https:');
}
// FIXME - binding of member functions should happen at object creation
this.deactivate = elation.bind(this, this.deactivate);
this.activate = elation.bind(this, this.activate);
// Used for debouncing clicks
this.lastinteraction = performance.now();
this.cooldown = 200;
elation.events.add(this, 'mouseover', elation.bind(this, this.hover));
elation.events.add(this, 'mouseout', elation.bind(this, this.unhover));
elation.events.add(this, 'click', elation.bind(this, this.click));
}
this.createObject3D = function() {
var plane = new THREE.PlaneBufferGeometry(1,1);
var mat = new THREE.MeshBasicMaterial({
color: 0x000000,
opacity: 0,
transparent: true,
blending: THREE.NoBlending,
side: THREE.DoubleSide
});
var selectionmat = new THREE.MeshBasicMaterial({
color: this.hovercolor,
blending: THREE.NormalBlending,
opacity: 1,
polygonOffset: true,
polygonOffsetFactor: 1,
polygonOffsetUnit: 10
});
this.material = mat;
//plane.applyMatrix(new THREE.Matrix4().makeTranslation(.5,-.5,0));
var obj = new THREE.Mesh(plane, mat);
var selection = new THREE.Mesh(plane, selectionmat);
var ratio = this.scale.x / this.scale.y;
selection.scale.set(1 + this.scale.x / 100,1 + this.scale.y / 100, 1);
selection.position.z = -.01;
obj.add(selection);
selection.visible = false;
this.selection = selection;
this.selectionmaterial = selectionmat;
return obj;
}
this.createObjectDOM = function() {
var websurface = this.room.websurfaces[this.properties.websurface_id];
if (websurface) {
var width = websurface.width || 1024,
height = websurface.height || 768;
var iframe = elation.html.create('iframe');
iframe.src = this.url;
iframe.allow = 'vr';
var div = elation.html.create('div');
div.className = 'janusweb_websurface ';
div.appendChild(iframe);
div.style.width = width + 'px';
div.style.height = height + 'px';
iframe.style.width = width + 'px';
iframe.style.height = height + 'px';
var obj = new THREE.CSS3DObject(div);
obj.scale.set(1/width, 1/height, 1);
this.iframe = iframe;
this.domobj = obj;
}
}
this.activate = function() {
if (!this.active) {
var canvas = this.engine.client.view.rendersystem.renderer.domElement;
canvas.style.pointerEvents = 'none';
canvas.style.position = 'absolute';
this.engine.systems.controls.releasePointerLock();
this.active = true;
this.selectionmaterial.color.copy(this.activecolor);
setTimeout(elation.bind(this, function() {
elation.events.add(window, 'click,dragover,focus', this.deactivate);
}), 10);
this.lastinteraction = performance.now();
}
}
this.deactivate = function(ev) {
if (this.active) {
var canvas = this.engine.client.view.rendersystem.renderer.domElement;
canvas.style.pointerEvents = 'all';
canvas.style.position = 'static';
this.engine.systems.controls.requestPointerLock();
ev.stopPropagation();
ev.preventDefault();
this.selection.visible = false;
this.active = false;
elation.events.remove(window, 'click,dragover,focus', this.deactivate);
this.lastinteraction = performance.now();
}
}
this.click = function(ev) {
var now = performance.now();
if (!this.active && ev.button == 0 && now - this.lastinteraction > this.cooldown) {
this.activate();
ev.stopPropagation();
ev.preventDefault();
}
}
this.hover = function() {
this.selection.visible = true;
this.selectionmaterial.color.copy(this.active ? this.activecolor : this.hovercolor);
if (this.selection.material !== this.selectionmaterial) this.selection.material = this.selectionmaterial;
//this.material.color.setHex(0xff0000);
}
this.unhover = function() {
if (!this.active) {
this.selection.visible = false;
}
this.selectionmaterial.color.copy(this.active ? this.activecolor : this.hovercolor);
//this.material.color.setHex(0x000000);
}
this.start = function() {
if (!this.started) {
this.objects['3d'].add(this.domobj);
this.started = true;
}
}
this.stop = function() {
if (this.started) {
this.started = false;
this.objects['3d'].remove(this.domobj);
}
}
}, elation.engine.things.janusbase);
});
|
JavaScript
| 0.000001 |
@@ -3672,10 +3672,27 @@
= '
-vr
+xr-spatial-tracking
';%0A
|
91aff21681fb8ab808baacefa3fc57c4b967a18e
|
Stop enforcing defaultValue to be defined in SearchInput
|
src/components/SearchInput/SearchInput.js
|
src/components/SearchInput/SearchInput.js
|
import React from 'react'
import PropTypes from 'prop-types'
import styles from './SearchInput.scss'
class SearchInput extends React.PureComponent {
static propTypes = {
placeholder: PropTypes.string,
defaultValue: PropTypes.string.isRequired,
hasButton: PropTypes.bool,
buttonLabel: PropTypes.string,
onSearch: PropTypes.func.isRequired
}
static defaultProps = {
placeholder: 'Rechercher…',
hasButton: false,
buttonLabel: 'Rechercher'
}
onSubmit = event => {
const { onSearch } = this.props
event.preventDefault();
onSearch(event.target.query.value);
}
render() {
const { placeholder, defaultValue, hasButton, buttonLabel } = this.props
return (
<form onSubmit={this.onSubmit} className={styles.container}>
<input
type='text'
name='query'
defaultValue={defaultValue}
className={styles.input}
placeholder={placeholder}
/>
{hasButton && (
<button type='submit' className={styles.button}>
{buttonLabel}
</button>
)}
</form>
)
}
}
export default SearchInput
|
JavaScript
| 0 |
@@ -236,27 +236,16 @@
s.string
-.isRequired
,%0A%0A h
@@ -408,16 +408,38 @@
rcher%E2%80%A6',
+%0A defaultValue: '',
%0A%0A ha
|
f24fe75b9929e581efd4ed266fa564f5f3ed4115
|
Add await arround callback in api gateway proxy
|
lib/middleware/apiGatewayProxy/apiGatewayProxy.js
|
lib/middleware/apiGatewayProxy/apiGatewayProxy.js
|
const smash = require("../../../smash.js");
const logger = smash.logger("ApiGatewayProxy");
const errorUtil = new smash.SmashError(logger);
const Next = require("./lib/next.js");
const Request = require("./lib/request.js");
const Response = require("./lib/response.js");
const Router = require("./lib/router.js");
const Route = require("./lib/route.js");
const RESPONSE_HEADERS_DEFAULT = "apiGatewayProxy.response.headers.default";
class ApiGatewayProxy extends Next {
constructor() {
super();
this._router = new Router();
this._link();
}
get smash() {
return smash;
}
get router() {
return this._router;
}
_link() {
this.setNext(this.router);
this.router.setNext(this);
return this;
}
_buildRequest(event, context) {
const request = new Request(event, context);
return request;
}
_buildResponse(request) {
const response = new Response(this, request);
const headers = smash.config.get(RESPONSE_HEADERS_DEFAULT);
response.addHeaders(headers);
return response;
}
handleEvent(event, context, callback) {
if (typeof callback !== 'function') {
throw new Error("Third parameter of handleEvent() must be a function, " + errorUtil.typeOf(callback));
}
this._callback = callback;
const request = this._buildRequest(event, context);
const response = this._buildResponse(request);
if (typeof event !== "object" || this.isEvent(event) === false) {
response.handleError(errorUtil.internalServerError("Wrong type of event as argument to ApiGatewayProxy.handleEvent()"));
} else {
this.next(request, response);
}
}
handleRequest(request, response) {
if (request === undefined || request === null || request.constructor !== Request) {
response.handleError(errorUtil.internalServerError("First parameter of handleRequest() must be Request object type, " + errorUtil.typeOf(request)));
return this;
}
if (response === undefined || response === null || response.constructor !== Response) {
response.handleError(errorUtil.internalServerError("Second parameter of handleRequest() must be Response object type, " + errorUtil.typeOf(response)));
return this;
}
if (request.constructor !== Request || request.route.constructor !== Route) {
response.handleError(errorUtil.internalServerError("Missing matched route in request"));
return this;
}
logger.info("RequestId: " + request.requestId);
logger.info("Matched route: " + request.route.method + " " + request.route.path + "; version: " + request.route.version + "; request: " + request.route.method + " " + request.path + " in env: " + smash.getEnv("ENV") + " with user: " + (request.user ? request.user.username : "Anonymous"));
smash.setCurrentEvent(request);
if (smash.binder.requiredRuleExist(request.route.action) === true) {
const bodyIsValid = smash.binder.hasRequired(request.route.action, request.body);
if (bodyIsValid !== true) {
response.handleError(errorUtil.badRequestError("Invalid body", bodyIsValid));
return this;
}
}
try {
request.route.callback.call(smash, request, response);
} catch (error) {
response.handleError(error);
}
return this;
}
handleResponse(response) {
logger.info("Response code: " + response.code);
this._callback(null, {
statusCode: response.code,
headers: response.headers,
body: response.stringifiedBody,
});
return this;
}
isEvent(event) {
if (event.httpMethod && event.path && !event.type) {
return true;
}
return false;
}
get(route, callback) {
try {
this.router.get(route, callback);
} catch (error) {
logger.error("Failed to register GET route", route, error);
response.handleError(errorUtil.internalServerError());
}
return this;
}
post(route, callback) {
try {
this.router.post(route, callback);
} catch (error) {
logger.error("Failed to register POST route", route, error);
response.handleError(errorUtil.internalServerError());
}
return this;
}
put(route, callback) {
try {
this.router.put(route, callback);
} catch (error) {
logger.error("Failed to register PUT route", route, error);
response.handleError(errorUtil.internalServerError());
}
return this;
}
delete(route, callback) {
try {
this.router.delete(route, callback);
} catch (error) {
logger.error("Failed to register DELETE route", route, error);
response.handleError(errorUtil.internalServerError());
}
return this;
}
patch(route, callback) {
try {
this.router.patch(route, callback);
} catch (error) {
logger.error("Failed to register PATCH route", route, error);
response.handleError(errorUtil.internalServerError());
}
return this;
}
options(route, callback) {
try {
this.router.options(route, callback);
} catch (error) {
logger.error("Failed to register OPTIONS route", route, error);
response.handleError(errorUtil.internalServerError());
}
return this;
}
head(route, callback) {
try {
this.router.head(route, callback);
} catch (error) {
logger.error("Failed to register HEAD route", route, error);
response.handleError(errorUtil.internalServerError());
}
return this;
}
getHandlers() {
return this.router.getRoutes();
}
expose() {
return [
{
"functionName": "get",
"function": "get"
},
{
"functionName": "post",
"function": "post"
},
{
"functionName": "put",
"function": "put"
},
{
"functionName": "delete",
"function": "delete"
},
{
"functionName": "patch",
"function": "patch"
},
{
"functionName": "options",
"function": "options"
},
{
"functionName": "head",
"function": "head"
}
];
}
}
module.exports = ApiGatewayProxy;
|
JavaScript
| 0 |
@@ -1766,32 +1766,38 @@
%7D%0A %7D%0A%0A
+async
handleRequest(re
@@ -3398,16 +3398,22 @@
+await
request.
|
1e766b221a7d6bce51652109491b3767aa5ca368
|
increase slideshow speed
|
script.js
|
script.js
|
$(document).ready(function () {
$(this).scrollTop(0);
$(".modal").modal();
if (location.hash.length > 0) {
if ("#imprint" === location.hash) {
M.Modal.getInstance($("#imprint-modal")).open();
}
}
$(".language").click(function () {
window.open("https://google.com/search?q=" + $(this).text().trim(), "_blank");
});
let dragging = false;
$.ajax("./slideshow.json").done(function (slideData) {
$.each(slideData, function (i, slide) {
let el = $('' +
'<div class="slideshow-item" data-href="' + slide.href + '">' +
' <div class="slideshow-item-background"></div>' +
' <div class="slideshow-item-content flow-text">' +
' <h2>' + slide.title + '</h2>' +
' <div class="slideshow-item-left">' +
(slide.icon ? ' <div class="slideshow-item-icon"></div>' : '') +
' </div>' +
' <div class="slideshow-item-right">' +
' <div class="slideshow-item-text flow-text">' +
' <p>' + (slide.description || "") + '</p>' +
' </div>' +
' </div>' +
' </div>' +
'</div>' +
'');
el.appendTo($(".slideshow"));
setTimeout(function () {
el.find(".slideshow-item-background").css("background-image", "url('" + slide.bg + "')");
}, i * 500);
if (slide.icon) {
setTimeout(function () {
el.find(".slideshow-item-icon").css("background-image", "url('" + slide.icon + "')");
}, i * 1000);
}
el.on('mousedown', (e) => {
dragging = false;
});
el.on('mousemove', (e) => {
dragging = true;
});
el.on('mouseup', (e) => {
if (!dragging) {
window.open(slide.href + "?utm_source=inventivetalent.org&utm_medium=slideshow", "_blank")
}
});
})
$(".slideshow").slick({
arrows: false,
autoplay: true,
autoplaySpeed: 5000,
slidesToShow: 1,
zIndex: 2
})
});
let avatar = $("#mercy");
avatar.attr("src", avatar.data("src"));
let voicelines = [];
$.ajax("https://api.github.com/repos/Js41637/Overwatch-Item-Tracker/contents/resources/heroes/mercy/voicelines").done(function (vs) {
for (let i = 0; i < vs.length; i++) {
voicelines.push(vs[i].path)
}
})
avatar.click(function () {
new Audio("https://cdn.rawgit.com/Js41637/Overwatch-Item-Tracker/development/" + voicelines[Math.floor(Math.random() * voicelines.length)]).play();
})
})
|
JavaScript
| 0 |
@@ -2271,18 +2271,18 @@
ySpeed:
+3
5
-0
00,%0A
|
49f615523f7d4b666e6d321f682af3fbe7f63114
|
remove space modernizrTest.js line 11
|
troposphere/static/js/components/modals/unsupported/modernizrTest.js
|
troposphere/static/js/components/modals/unsupported/modernizrTest.js
|
var modernizr = require('lib/modernizr-latest.js'),
_ = require('underscore');
var features = modernizr;
var requiredFeatures = [
//this we know we don't have support
//'regions',
//'microdata',
//'proximity',
//'display-runin',
// 'mathml',
//'dart',
//the actual tests so far we are concerned about
'cssanimations',
'es5',
'es5array',
'es5date',
'es5function',
'es5object',
'strictmode',
'es5string',
'json',
'es5syntax',
'es5undefined',
'ruby',
'svg',
'flexbox',
'inlinesvg',
'cssgradients',
'rgba',
'eventlistener',
'ellipsis'
];
var unsupportedFeatures = _.map(_.filter(_.pairs(features), _.negate(_.last)), _.first);
var breakingFeatures = _.intersection(requiredFeatures, unsupportedFeatures);
//console.log("Unsupported = " + unsupportedFeatures);
//console.log("Breaking Bad = " + breakingFeatures);
var unsupported = function(){
return breakingFeatures.length <= 0;
};
module.exports = {
unsupportedFeatures: unsupportedFeatures,
breakingFeatures: breakingFeatures,
unsupported: unsupported,
}
|
JavaScript
| 0.000157 |
@@ -289,17 +289,16 @@
//
-
'mathml'
|
4849e040f8b63b7d2ef6564f7d89d3af37108382
|
make suggested changes
|
filesdk/index.js
|
filesdk/index.js
|
"use strict";
const fs = require('fs');
const q = require('q');
const rimraf = require('rimraf');
const extract = require('extract-zip')
const targz = require('targz');
const ncp = require('ncp').ncp;
ncp.limit = 16;
/* working */
let readFile = (path) => {
let defer = q.defer();
fs.readFile(path, 'utf8', function (err, contents) {
if (err) return defer.reject(err);
return defer.resolve(contents);
});
return defer.promise;
}
/* working, overwrites or creates new file */
let writeFile = (path, contents) => {
let defer = q.defer();
fs.writeFile(path, contents, (err) => {
if (err) return defer.reject(err);
return defer.resolve("File has been written");
});
return defer.promise;
}
/* working */
let deleteFile = (path) => {
let defer = q.defer();
fs.unlink(path, function (err) {
if (err) return defer.reject(err);
return defer.resolve("File has been deleted");
});
return defer.promise;
}
/* working */
let deleteDir = (path) => {
let defer = q.defer();
rimraf(path, function (err) {
if (err) return defer.reject(err);
return defer.resolve("Directory has been deleted");
});
return defer.promise;
}
/* works for every use case */
let copy = (source, destination) => {
let defer = q.defer();
ncp(source, destination, function (err) {
if (err) return defer.reject(err);
return defer.resolve("Copied!!!");
});
return defer.promise;
}
/* works for every use case */
let move = (source, destination) => {
let defer = q.defer();
fs.rename(source, destination, function (err) {
if (err) return defer.reject(err);
return defer.resolve("Moved!!!");
});
return defer.promise;
}
/* works for every use case */
let rename = (source, destination) => {
let defer = q.defer();
fs.rename(source, destination, function (err) {
if (err) return defer.reject(err);
return defer.resolve("Renamed!!!");
});
return defer.promise;
}
/*
works for directory
*/
let readdir = (path) => {
let defer = q.defer();
fs.readdir(path, function (err, items) {
if (err) return defer.reject(err);
return defer.resolve(items);
});
return defer.promise;
}
/*
works for dir and file
*/
let getInfo = (path) => {
let defer = q.defer();
fs.stat(path, function (err, stats) {
if (err) return defer.reject(err);
return defer.resolve(stats);
});
return defer.promise;
}
/* works */
let extractZip = (source, destination) => {
let defer = q.defer();
extract(source, { dir: destination }, function (err) {
if (err) return defer.reject(err);
return defer.resolve("Done!!!");
})
return defer.promise;
}
/* works */
let extractTar = (source, destination) => {
let defer = q.defer();
targz.decompress({
src: source,
dest: destination
}, function (err) {
if (err) return defer.reject(err);
return defer.resolve("Done!!!");
});
return defer.promise;
}
/* works */
let createTar = (source, destination) => {
let defer = q.defer();
targz.compress({
src: source,
dest: destination
}, function (err) {
if (err) return defer.reject(err);
return defer.resolve("Done!!!");
});
return defer.promise;
}
module.exports = {
readFile,
writeFile,
deleteFile,
deleteDir,
copy,
move,
rename,
readdir,
getInfo,
extractZip,
extractTar,
createTar
}
/* tests */
// let playground = '/home/stuart/Documents/work/pinut/OpenRAP/filesdk/playground/';
// extractTar(playground + 'test.tar.gz', playground).then(data => {
// console.log(data);
// }, err => {
// console.log(err);
// })
|
JavaScript
| 0.000016 |
@@ -212,30 +212,16 @@
= 16;%0A%0A
-/* working */%0A
let read
@@ -446,54 +446,8 @@
;%0A%7D%0A
-/* working, overwrites or creates new file */%0A
let
@@ -681,38 +681,24 @@
.promise;%0A%7D%0A
-/* working */%0A
let deleteFi
@@ -916,22 +916,8 @@
;%0A%7D%0A
-/* working */%0A
let
@@ -1144,39 +1144,8 @@
;%0A%7D%0A
-/* works for every use case */%0A
let
@@ -1377,39 +1377,8 @@
;%0A%7D%0A
-/* works for every use case */%0A
let
@@ -1615,307 +1615,9 @@
;%0A%7D%0A
-/* works for every use case */%0Alet rename = (source, destination) =%3E %7B%0A let defer = q.defer();%0A fs.rename(source, destination, function (err) %7B%0A if (err) return defer.reject(err);%0A return defer.resolve(%22Renamed!!!%22);%0A %7D);%0A return defer.promise;%0A%7D%0A/*%0Aworks for directory%0A*/
%0A
+
let
@@ -1831,38 +1831,8 @@
%0A%7D%0A%0A
-/*%0Aworks for dir and file %0A*/%0A
let
@@ -2034,36 +2034,24 @@
.promise;%0A%7D%0A
-/* works */%0A
let extractZ
@@ -2283,36 +2283,24 @@
.promise;%0A%7D%0A
-/* works */%0A
let extractT
@@ -2576,20 +2576,8 @@
;%0A%7D%0A
-/* works */%0A
let
@@ -3043,242 +3043,4 @@
r%0A%7D%0A
-%0A/* tests */%0A// let playground = '/home/stuart/Documents/work/pinut/OpenRAP/filesdk/playground/';%0A// extractTar(playground + 'test.tar.gz', playground).then(data =%3E %7B%0A// console.log(data);%0A// %7D, err =%3E %7B%0A// console.log(err);%0A// %7D)
|
9686b793acf767ea9169ef1ba3a049cde18215e0
|
Update HorizontalScroll.min.js
|
js/HorizontalScroll.min.js
|
js/HorizontalScroll.min.js
|
(function ($) {$.fn.createHorizontalOverflow = function () {var width = 0;this.find('.containers').children('div').each(function () {width += $(this).outerWidth(true);});this.find('.containers').css('width', width + "px");};}(jQuery));
|
JavaScript
| 0 |
@@ -8,16 +8,19 @@
on ($) %7B
+%0A
$.fn.cre
@@ -56,16 +56,21 @@
ion () %7B
+%0A
var widt
@@ -75,16 +75,21 @@
dth = 0;
+%0A
this.fin
@@ -109,21 +109,77 @@
s').
-children('div
+each(function ()%0A %7B%0A var width = 0;%0A $(this).find('.each
').e
@@ -195,16 +195,25 @@
ion () %7B
+%0A
width +=
@@ -242,35 +242,119 @@
ue);
-%7D);this.find('.containers')
+%0A %7D).promise().done(function () %7B%0A var container = $(this).parent('.containers');%0A container
.css
@@ -381,10 +381,32 @@
x%22);
+%0A %7D);%0A %7D);%0A
%7D;
+%0A
%7D(jQ
|
c73e4010d22e5ab22cdea3125903dad0a8b65abc
|
add tooltip to breakpoint snippet
|
public/js/components/Breakpoints.js
|
public/js/components/Breakpoints.js
|
"use strict";
const React = require("react");
const { connect } = require("react-redux");
const { bindActionCreators } = require("redux");
const ImPropTypes = require("react-immutable-proptypes");
const Isvg = React.createFactory(require("react-inlinesvg"));
const actions = require("../actions");
const { getSource, getPause, getBreakpoints, makeLocationId } = require("../selectors");
const { truncateStr } = require("../util/utils");
const { DOM: dom, PropTypes } = React;
require("./Breakpoints.css");
function isCurrentlyPausedAtBreakpoint(state, breakpoint) {
const pause = getPause(state);
if (!pause || pause.get("isInterrupted")) {
return false;
}
const breakpointLocation = makeLocationId(breakpoint.get("location").toJS());
const pauseLocation = makeLocationId(
pause.getIn(["frame", "location"]).toJS()
);
return breakpointLocation == pauseLocation;
}
const Breakpoints = React.createClass({
propTypes: {
breakpoints: ImPropTypes.map.isRequired,
enableBreakpoint: PropTypes.func.isRequired,
disableBreakpoint: PropTypes.func.isRequired,
selectSource: PropTypes.func.isRequired
},
displayName: "Breakpoints",
handleCheckbox(breakpoint) {
const loc = breakpoint.get("location").toJS();
if (breakpoint.get("disabled")) {
this.props.enableBreakpoint(loc);
} else {
this.props.disableBreakpoint(loc);
}
},
selectBreakpoint(breakpoint) {
const sourceId = breakpoint.getIn(["location", "sourceId"]);
const line = breakpoint.getIn(["location", "line"]);
this.props.selectSource(sourceId, { line });
},
renderBreakpoint(breakpoint) {
const snippet = truncateStr(breakpoint.get("text") || "", 30);
const locationId = breakpoint.get("locationId");
const line = breakpoint.getIn(["location", "line"]);
const isCurrentlyPaused = breakpoint.get("isCurrentlyPaused");
const isPausedIcon = isCurrentlyPaused && Isvg({
className: "pause-indicator",
src: "images/pause-circle.svg"
});
return dom.div(
{
className: "breakpoint",
key: locationId,
onClick: () => this.selectBreakpoint(breakpoint)
},
dom.input(
{
type: "checkbox",
checked: !breakpoint.get("disabled"),
onChange: () => this.handleCheckbox(breakpoint)
}),
dom.div(
{ className: "breakpoint-label" },
`${line} ${snippet}`
),
isPausedIcon
);
},
render() {
const { breakpoints } = this.props;
return dom.div(
{ className: "breakpoints-list" },
(breakpoints.size === 0 ?
dom.div({ className: "pane-info" }, "No Breakpoints") :
breakpoints.valueSeq().map(bp => {
return this.renderBreakpoint(bp);
}))
);
}
});
function _getBreakpoints(state) {
return getBreakpoints(state).map(breakpoint => {
const source = getSource(state, breakpoint.getIn(["location", "actor"]));
const isCurrentlyPaused = isCurrentlyPausedAtBreakpoint(state, breakpoint);
const locationId = makeLocationId(breakpoint.get("location").toJS());
return breakpoint.setIn(["location", "source"], source)
.set("locationId", locationId)
.set("isCurrentlyPaused", isCurrentlyPaused);
});
}
module.exports = connect(
(state, props) => ({
breakpoints: _getBreakpoints(state)
}),
dispatch => bindActionCreators(actions, dispatch)
)(Breakpoints);
|
JavaScript
| 0.000001 |
@@ -2395,16 +2395,47 @@
t-label%22
+, title: breakpoint.get(%22text%22)
%7D,%0A
|
d8a312185800fd7ee32f7a1bbe590cca63beb32e
|
Fix typo on a keyup handler that was causing chrome to throw errors on every key press
|
lib/modules/apostrophe-search/public/js/always.js
|
lib/modules/apostrophe-search/public/js/always.js
|
$(function() {
$('body').on('click', '[data-apos-search-filter]', function() {
$(this).closest('form').submit();
});
$('body').on('keyup', '[data-apos-search-field]').keyup(function (e) {
if (e.keyCode == 13) {
$(this).closest('form').submit();
return false;
}
});
});
|
JavaScript
| 0.000002 |
@@ -172,16 +172,10 @@
ld%5D'
-).keyup(
+,
func
|
daeb1ebbe4b9e783ecd4d36eb0f716b6bd2672ea
|
correct fixtures, use new changed keys
|
test/fixtures/web_configs.fixture.js
|
test/fixtures/web_configs.fixture.js
|
var fix = fix || {};
fix.conf = {};
fix.conf.plain = {
libs: {
jquery: '../assets/jquery.min',
handlebars: '../assets/handlebars.min',
ember: 'lib/ember-latest.min',
jasmine: '../assets/jasmine/jasmine'
}
};
fix.conf.baseUrl = {
baseUrl: 'js/',
libs: {
jquery: '../assets/jquery.min',
handlebars: '../assets/handlebars.min',
ember: 'lib/ember-latest.min',
jasmine: '../assets/jasmine/jasmine'
}
};
fix.conf.baseUrlAbsolute = {
baseUrl: '/js/',
libs: {
jquery: '../assets/jquery.min',
handlebars: '../assets/handlebars.min',
ember: 'lib/ember-latest.min',
jasmine: '../assets/jasmine/jasmine'
}
};
fix.conf.baseUrlDotSlash = {
baseUrl: './',
libs: {
jquery: '../assets/jquery.min',
handlebars: '../assets/handlebars.min',
ember: 'lib/ember-latest.min',
jasmine: '../assets/jasmine/jasmine'
}
};
|
JavaScript
| 0 |
@@ -52,17 +52,23 @@
n = %7B%0A
-l
+vendorL
ibs: %7B%0A
@@ -263,33 +263,39 @@
seUrl: 'js/',%0A
-l
+vendorL
ibs: %7B%0A jquer
@@ -495,25 +495,31 @@
: '/js/',%0A
-l
+vendorL
ibs: %7B%0A j
@@ -725,17 +725,23 @@
'./',%0A
-l
+vendorL
ibs: %7B%0A
|
6a5717b4487a81381f904e84f966dafdc536cff4
|
reset startX on mouse move
|
src/components/containers/zoom-helpers.js
|
src/components/containers/zoom-helpers.js
|
import { Selection, Collection } from "victory-core";
import { throttle, isFunction } from "lodash";
const Helpers = {
/**
* Generates a new domain scaled by factor and constrained by the original domain.
* @param {[Number, Number]} currentDomain The domain to be scaled.
* @param {[Number, Number]} originalDomain The original domain for the data set.
* @param {Number} factor The delta to translate by
* @return {[Number, Number]} The scale domain
*/
scale(currentDomain, originalDomain, factor) {
const [fromBound, toBound] = originalDomain;
const [from, to] = currentDomain;
const range = Math.abs(from - to);
const midpoint = +from + (range / 2);
const newRange = (range * Math.abs(factor)) / 2;
const minDomain = Collection.containsDates(originalDomain) ?
[ new Date(midpoint - 4), new Date(midpoint) ] : // 4ms is standard browser date precision
[ midpoint - 1 / Number.MAX_SAFE_INTEGER, midpoint ];
const newDomain = [
Collection.getMaxValue([midpoint - newRange, fromBound]),
Collection.getMinValue([midpoint + newRange, toBound])
];
return Math.abs(minDomain[1] - minDomain[0]) > Math.abs(newDomain[1] - newDomain[0]) ?
minDomain : newDomain;
},
/**
* Generate a new domain translated by the delta and constrained by the original domain.
* @param {[Number, Number]} currentDomain The domain to be translated.
* @param {[Number, Number]} originalDomain The original domain for the data set.
* @param {Number} delta The delta to translate by
* @return {[Number, Number]} The translated domain
*/
pan(currentDomain, originalDomain, delta) {
const [fromCurrent, toCurrent] = currentDomain.map((val) => +val);
const [fromOriginal, toOriginal] = originalDomain.map((val) => +val);
const lowerBound = fromCurrent + delta;
const upperBound = toCurrent + delta;
let newDomain;
if (lowerBound > fromOriginal && upperBound < toOriginal) {
newDomain = [lowerBound, upperBound];
} else if (lowerBound < fromOriginal) { // Clamp to lower limit
const dx = toCurrent - fromCurrent;
newDomain = [fromOriginal, fromOriginal + dx];
} else if (upperBound > toOriginal) { // Clamp to upper limit
const dx = toCurrent - fromCurrent;
newDomain = [toOriginal - dx, toOriginal];
} else {
newDomain = currentDomain;
}
return Collection.containsDates(currentDomain) || Collection.containsDates(originalDomain) ?
newDomain.map((val) => new Date(val)) : newDomain;
},
getDomainScale(domain, scale) {
const {x: [from, to]} = domain;
const rangeX = scale.x.range();
const plottableWidth = Math.abs(rangeX[0] - rangeX[1]);
return plottableWidth / (to - from);
},
handleAnimation(ctx) {
const getTimer = isFunction(ctx.getTimer) && ctx.getTimer.bind(ctx);
if (getTimer && isFunction(getTimer().bypassAnimation)) {
getTimer().bypassAnimation();
return isFunction(getTimer().resumeAnimation) ?
() => getTimer().resumeAnimation() : undefined;
}
},
onMouseDown(evt, targetProps) {
evt.preventDefault();
const originalDomain = targetProps.originalDomain || targetProps.domain;
const currentDomain = targetProps.currentDomain || targetProps.zoomDomain || originalDomain;
const {x} = Selection.getSVGEventCoordinates(evt);
return [{
target: "parent",
mutation: () => {
return {
startX: x, domain: currentDomain, cachedZoomDomain: targetProps.zoomDomain,
originalDomain, currentDomain, panning: true,
parentControlledProps: ["domain"]
};
}
}];
},
onMouseUp() {
return [{
target: "parent",
mutation: () => {
return {panning: false};
}
}];
},
onMouseLeave() {
return [{
target: "parent",
mutation: () => {
return {panning: false};
}
}];
},
onMouseMove(evt, targetProps, eventKey, ctx) { // eslint-disable-line max-params
if (targetProps.panning) {
const { scale, startX, onDomainChange, domain, zoomDomain } = targetProps;
const {x} = Selection.getSVGEventCoordinates(evt);
const originalDomain = targetProps.originalDomain || domain;
const lastDomain = targetProps.currentDomain || targetProps.zoomDomain || originalDomain;
const calculatedDx = (startX - x) / this.getDomainScale(lastDomain, scale);
const nextXDomain = this.pan(lastDomain.x, originalDomain.x, calculatedDx);
const currentDomain = { x: nextXDomain, y: originalDomain.y };
const resumeAnimation = this.handleAnimation(ctx);
if (isFunction(onDomainChange)) {
onDomainChange(currentDomain);
}
return [{
target: "parent",
callback: resumeAnimation,
mutation: () => {
return {
parentControlledProps: ["domain"],
domain: currentDomain, currentDomain, originalDomain, cachedZoomDomain: zoomDomain
};
}
}];
}
},
onWheel(evt, targetProps, eventKey, ctx) { // eslint-disable-line max-params
if (!targetProps.allowZoom) {
return {};
}
const { onDomainChange, domain, zoomDomain } = targetProps;
const originalDomain = targetProps.originalDomain || domain;
const lastDomain = targetProps.currentDomain || zoomDomain || originalDomain;
const {x} = lastDomain;
const xBounds = originalDomain.x;
const sign = evt.deltaY > 0 ? 1 : -1;
const delta = Math.min(Math.abs(evt.deltaY / 300), 0.75); // TODO: Check scale factor
const nextXDomain = this.scale(x, xBounds, 1 + sign * delta);
const currentDomain = { x: nextXDomain, y: originalDomain.y };
const resumeAnimation = this.handleAnimation(ctx);
if (isFunction(onDomainChange)) {
onDomainChange(currentDomain);
}
return [{
target: "parent",
callback: resumeAnimation,
mutation: () => {
return {
domain: currentDomain, currentDomain, originalDomain, cachedZoomDomain: zoomDomain,
parentControlledProps: ["domain"], panning: false
};
}
}];
}
};
export default {
onMouseDown: Helpers.onMouseDown.bind(Helpers),
onMouseUp: Helpers.onMouseUp.bind(Helpers),
onMouseLeave: Helpers.onMouseLeave.bind(Helpers),
onMouseMove: throttle(Helpers.onMouseMove.bind(Helpers), 16, {leading: true}),
onWheel: throttle(Helpers.onWheel.bind(Helpers), 16, {leading: true})
};
|
JavaScript
| 0.000001 |
@@ -4968,16 +4968,27 @@
omain%22%5D,
+ startX: x,
%0A
|
e0a3de8dae7ed9f830c42c61f102bf487c5a0e53
|
Fix socket close handler
|
projects/elm-irc/wsproxy/index.js
|
projects/elm-irc/wsproxy/index.js
|
/*jshint esversion: 6 */
const tls = require('tls');
const url = require('url');
const WebSocket = require('ws');
const SUPPORTED_CAPS = [
'znc.in/server-time-iso',
'server-time'
];
const wss = new WebSocket.Server({ port: 6676 });
wss.on('connection', function connection(ws) {
console.log('connection', ws);
let query = url.parse(ws.upgradeReq.url, true).query;
const required = ['host', 'port', 'nick'];
for (let i in required) {
if (!query[required[i]])
return ws.send(`missing required param ${required[i]}`);
}
const socket = tls.connect({
host: query.host,
port: +query.port,
rejectUnauthorized: false
}, function () {
console.log('connected');
SUPPORTED_CAPS.forEach(c => {
this.write(`CAP REQ ${c}\n`);
});
this.write('CAP END\n');
if (query.pass)
this.write(`PASS ${query.pass}\n`);
this.write(`NICK ${query.nick}\n`);
this.write(`USER ${query.nick} * * :${query.nick}\n`);
})
.setEncoding('utf8')
.on('data', (data) => {
console.log(data.replace(/[\r\n]+/, ''));
ws.send(data);
})
.on('end', () => { ws.close(); });
ws.on('message', function incoming(message) {
console.log('received: >%s<', message);
socket.write(message + '\n');
}).on('end', () => socket.close());
});
|
JavaScript
| 0.000001 |
@@ -1434,27 +1434,29 @@
%0A %7D).on('
-end
+close
', () =%3E soc
@@ -1459,21 +1459,23 @@
socket.
-close
+destroy
());%0A%7D);
|
cdbde9f5f352dac077fe15d1c9082b49e36c3dbf
|
Allow object and array field descriptions in unpackItem
|
src/services/spListProvider.js
|
src/services/spListProvider.js
|
angular
.module('ngSharepoint')
.provider('$spList', function () {
var siteUrl = "";
var default_limit = 500;
var Query = function() {};
Query.prototype.unpackItem = function(item) {
var obj = {};
this.__values.forEach(function(field) {
var value = item.get_item(field);
obj[field] = value;
});
return obj;
};
Query.prototype.packItem = function(item) {
var query = this;
Object.getOwnPropertyNames(query.__values).forEach(function(key) {
item.set_item(key, query.__values[key]);
});
};
var Select_Query = function(list, fields) {
this.__list = list;
this.__values = fields;
this.__where = null;
this.__limit = null;
return this;
};
Select_Query.prototype = new Query();
Select_Query.prototype.where = function(field) {
this.__where = new Where_Query(this, field);
return this.__where;
};
Select_Query.prototype.limit = function(amount) {
this.__limit = amount;
};
Select_Query.prototype.execute = function() {
var query = this;
return new Promise(function(resolve, reject) {
var clientContext = new SP.ClientContext(siteUrl);
var list = clientContext.get_web().get_lists().getByTitle(query.__list);
var camlQuery = new SP.CamlQuery();
var caml = ['<View>'];
if (query.__where !== null) {
query.__where.push(caml);
}
caml.push('<ViewFields>');
query.__values.forEach(function(field) {
caml.push('<FieldRef Name="' + field + '"/>');
});
caml.push('</ViewFields>');
if (query.__limit !== null) {
caml.push('<RowLimit>' + query.__limit + '</RowLimit>');
}
caml.push('</View>');
camlQuery.set_viewXml(caml.join(''));
var items = list.getItems(camlQuery);
clientContext.load(items);
clientContext.executeQueryAsync(
function(sender, args) {
var result = [];
var itemIterator = items.getEnumerator();
while (itemIterator.moveNext()) {
var item = itemIterator.get_current();
result.push(query.unpackItem(item));
}
resolve(result);
},
function(sender, args) {
reject(args);
}
);
});
};
var Update_Query = function(list) {
this.__list = list;
this.__values = {};
this.__where = null;
};
Update_Query.prototype = new Query();
Update_Query.prototype.where = function(field) {
this.__where = new Where_Query(this, field);
return this.__where;
};
Update_Query.prototype.execute = function() {
var query = this;
return new Promise(function(resolve, reject) {
var clientContext = new SP.ClientContext(siteUrl);
var list = clientContext.get_web().get_lists().getByTitle(query.__list);
var camlQuery = new SP.CamlQuery();
var caml = ['<View>'];
if (query.__where !== null) {
query.__where.push(caml);
}
caml.push('</View>');
camlQuery.set_viewXml(caml.join(''));
var items = list.getItems(camlQuery);
clientContext.load(items);
clientContext.executeQueryAsync(function(sender, args) {
var itemIterator = items.getEnumerator();
while (itemIterator.moveNext()) {
var item = itemIterator.get_current();
query.packItem(item);
item.update();
}
clientContext.executeQueryAsync(function(sender, args) {
resolve(args);
}, function(sender, args) {
reject(args);
});
}, function(sender, args) {
reject(args);
});
});
};
Update_Query.prototype.set = function(key, value) {
this.__values[key] = value;
return this;
};
var Insert_Into_Query = function(list) {
this.__list = list;
this.__values = {};
return this;
};
Insert_Into_Query.prototype = new Query();
Insert_Into_Query.prototype.value = function(key, field) {
this.__values[key] = field;
};
Insert_Into_Query.prototype.execute = function() {
var query = this;
return new Promise(function(resolve, reject) {
var clientContext = new SP.ClientContext(siteUrl);
var list = clientContext.get_web().get_lists().getByTitle(query.__list);
var itemInfo = new SP.ListItemCreationInformation();
var item = list.addItem(itemInfo);
query.packItem(item);
item.update();
clientContext.load(item);
clientContext.executeQueryAsync(function(sender, args) {
resolve(unpackItem(item));
}, function(sender, args) {
reject(args);
});
});
};
var Where_Query = function(query, field) {
this.__query = query;
this.__field = field;
this.__value = "";
this.__operator = "";
};
Where_Query.prototype.equals = function(value) {
this.__operator = "equals";
this.__value = value;
return this.__query;
};
Where_Query.prototype.push = function(caml) {
caml.push('<Query>');
caml.push('<Where>');
switch (this.__operator) {
case "equals":
caml.push('<Eq>');
break;
}
caml.push('<FieldRef Name="' + this.__field + '"/>');
caml.push('<Value Type="Number">' + this.__value + '</Value>');
switch (this.__operator) {
case "equals":
caml.push('</Eq>');
break;
}
caml.push('</Where>');
caml.push('</Query>');
};
//select("test").and().where("test").equals("dis").and("ID").greater(4).end_and().execute();
return {
setSiteUrl: function(url) {
siteUrl = url;
},
$get: function() {
return ({
select: function(from, fields) {
return new Select_Query(from, fields);
},
update: function(list) {
return new Update_Query(list);
},
insertInto: function(list) {
return new Insert_Into_Query(list);
}
});
}
};
});
|
JavaScript
| 0.000001 |
@@ -236,34 +236,118 @@
var
-obj = %7B%7D;%0A this
+query = this;%0A var obj = %7B%7D;%0A if (Array.isArray(query.__values)) %7B%0A query
.__v
@@ -365,33 +365,35 @@
ch(function(
-field) %7B%0A
+key) %7B%0A
@@ -422,24 +422,255 @@
et_item(
-field);%0A
+key);%0A obj%5Bkey%5D = value;%0A %7D); %0A %7Delse %7B%0A Object.getOwnPropertyNames(query.__values).forEach(function(key) %7B%0A var value = item.get_item(key);%0A
@@ -681,21 +681,19 @@
obj%5B
-field
+key
%5D = valu
@@ -699,35 +699,53 @@
ue;%0A
-%7D);
+ %7D);%0A %7D
%0A ret
|
edb46c73f1cba71277c315a7a165013df8cd7f53
|
fix deleting orders
|
food-ordering.js
|
food-ordering.js
|
Orders = new Mongo.Collection("orders");
Groups = new Mongo.Collection("groups");
// ROUTES
Router.configure({
layoutTemplate: 'main'
});
Router.route('/', {
template: 'Groups'
});
Router.route('/groups/:group', function () {
var group = this.params.group;
console.log("group: " + group);
this.render('todayOrder', {data: {group: group}});
});
// HELPER FUNCTIONS GLOBALS
currentDate = function() {
var date = new Date();
return date.getDate() + ":" + date.getMonth();
};
isOrderCompleted = function(group) {
var order = findTodayOrderForGroup(group);
console.log("is order completed? " + order);
return (order && order.orders_size == Object.keys(order.orders).length);
};
findTodayOrderForGroup = function(group) {
return Orders.findOne({data: currentDate(), group: group});
}
// CLIENT SIDE
if (Meteor.isClient) {
var today = currentDate();
Template.listGroups.helpers({
groups: function() {
return Groups.find({});
}
});
Template.addGroup.events({
'submit .add-group ': function (event) {
event.preventDefault();
console.log("Adding group " + event.target.name.value);
Groups.insert({name: event.target.name.value});
}
});
Template.orders_size.helpers({
selectors: function(group) {
var orders = findTodayOrderForGroup(group);
var selected = '-';
if (orders) {
selected = orders.orders_size;
}
return [
{value: '-', isSelected: (selected == 2 ? 'selected' : '')},
{value: '1', isSelected: (selected == 1 ? 'selected' : '')},
{value: '2', isSelected: (selected == 2 ? 'selected' : '')},
{value: '3', isSelected: (selected == 3 ? 'selected' : '')},
{value: '4', isSelected: (selected == 4 ? 'selected' : '')},
{value: '5', isSelected: (selected == 5 ? 'selected' : '')},
{value: '6', isSelected: (selected == 6 ? 'selected' : '')},
{value: '7', isSelected: (selected == 7 ? 'selected' : '')},
{value: '8', isSelected: (selected == 8 ? 'selected' : '')}
];
},
ordersSizeDisabled: function() {
var orders = findTodayOrderForGroup(this.group);
if (orders && isOrderCompleted(this.group)) {
return "disabled";
} else {
return "";
}
}
});
Template.orders_size.events({
'change .orderssize': function(event) {
event.preventDefault();
var selectedValue = event.target.value;
console.log("change orders size: " + selectedValue);
Meteor.call("setOrdersSize", this.group, selectedValue);
Meteor.call("tryComplete", this.group);
}
});
Template.order_food.events({
'submit .submit-order': function (event) {
event.preventDefault();
var name = event.target.name.value;
var meal = event.target.meal.value;
var order = findTodayOrderForGroup(this.group);
if (order) {
order.orders[name] = meal;
Orders.update(order._id, {$set: {'orders': order.orders}});
} else {
var o = {};
o[name] = meal;
Orders.insert({data: today, group: this.group, orders_size: "-", orders: o});
}
Meteor.call("tryComplete", this.group);
}
});
Template.order_food.helpers({
orderDisabled: function() {
return isOrderCompleted(this.group) ? "disabled" : "";
}
});
Template.orders_list.helpers({
orders: function() {
var orders = findTodayOrderForGroup(this.group)
if (orders) {
var result = [];
Object.keys(orders.orders).forEach(function (k) {
result.push({'name': k, 'meal': orders.orders[k]});
});
return result;
} else {
return [];
}
}
});
Template.orders_list.events({
'submit .order-removed': function (event) {
event.preventDefault();
console.log(event.target.id);
var orders = Orders.findOne({data: today});
delete orders.orders[event.target.id];
Orders.update({_id: orders._id}, {$set: {orders: orders.orders}});
}
});
Template.order_guy.helpers({
order_completed: function() {
return isOrderCompleted(this.group);
},
order_caller: function() {
var completed = Orders.findOne({data: today, group: this.group});
return completed.caller;
}
});
};
Meteor.methods({
setOrdersSize: function(group, newValue) {
var today = currentDate();
var orders = findTodayOrderForGroup(group);
if (!orders) {
Orders.insert({data: today, group: group, orders_size: newValue, orders: {}})
} else {
Orders.update({data: today, group: group}, {$set: {orders_size: newValue}});
}
},
tryComplete: function(group) {
var today = currentDate();
var orders = findTodayOrderForGroup(group);
if (isOrderCompleted(group)) {
var people = Object.keys(orders.orders);
var random = Math.floor((Math.random() * people.length));
console.log("Randomly chosen " + random + " from " + people);
var caller = people[random];
Orders.update({data: today, group: group}, {$set: {caller: caller}});
console.log("Randomized caller to be " + caller);
}
}
});
|
JavaScript
| 0.000004 |
@@ -235,20 +235,16 @@
) %7B%0A
-var
group =
@@ -3876,16 +3876,17 @@
s.group)
+;
%0A
@@ -4354,16 +4354,28 @@
ole.log(
+%22DELETE %22 +
event.ta
@@ -4381,16 +4381,33 @@
arget.id
+ + %22 GG %22 + group
);%0A
@@ -4430,36 +4430,71 @@
s =
-Orders.findOne(%7Bdata: today%7D
+findTodayOrderForGroup(group);%0A console.debug(orders
);%0A
@@ -5209,16 +5209,17 @@
rs: %7B%7D%7D)
+;
%0A
|
444f66a62c38eddc9324cc4ebea51631d3927a9b
|
Fix bug with color picking due to left jQuery syntax
|
js/link_editor.js
|
js/link_editor.js
|
this.LinkEditor = (function() {
function LinkEditor() {}
LinkEditor.editing = false;
var _actionFor = {};
_actionFor['category-remove-btn'] = function() {
return LinkEditor.removeCategory(LinkEditor.getCategoryID(this));
};
_actionFor['category-edit-btn'] = function() {
return LinkEditor.toggleEditingCategory(LinkEditor.getContainingCategory(this));
};
_actionFor['category-add-item-btn'] = function() {
var catID;
catID = LinkEditor.getCategoryID(this);
return LinkEditor.addEntry(catID);
};
_actionFor['entry-edit-btn'] = function() {
return LinkEditor.editEntry(this);
};
_actionFor['entry-remove-btn'] = function() {
return LinkEditor.removeEntry(this);
};
_actionFor['colorpicker-color'] = function() {
return LinkEditor.updateCategoryColor(this);
};
function executeAction(event, element, className) {
if(_actionFor.hasOwnProperty(className)){
event.stopPropagation();
return _actionFor[className].call(element);
}
};
LinkEditor.registerEvents = function() {
//event delegation mechanism
document.querySelector(".links-wrapper").addEventListener('click', function(ev) {
ev.target.classList.forEach( function(name){
executeAction(ev, ev.target, name);
});
});
document.querySelector('#edit-editmode').addEventListener('click', function(){
return LinkEditor.toggleEditMode();
}, true);
document.querySelector('#edit-add').addEventListener('click', function(){
return LinkEditor.addEmptyCategory();
}, true);
document.querySelector('#edit-raw-data').addEventListener('click', function(){
return LinkEditor.openRawEditor();
}, true);
document.querySelector('.remodal[data-remodal-id="edit-entry"] .remodal-confirm').addEventListener('click',
function() {
var categoryID, entryID;
var modalForm = document.querySelector("#entry-edit-form");
entryID = parseInt(modalForm["entry_id"].value);
categoryID = parseInt(modalForm["category_id"].value);
Links.contents[categoryID].entries[entryID] = {
title: modalForm["entry_title"].value,
href: modalForm["entry_href"].value
};
Links.saveToLocalStorage();
return Links.render();
}
);
document.querySelector('#raw-data-cancel').addEventListener('click', function(){
return LinkEditor.closeRawEditor();
}, true);
document.querySelector('#raw-data-save').addEventListener('click', function(){
return LinkEditor.saveRawEditor();
}, true);
};
LinkEditor.addEmptyCategory = function() {
LinkEditor.saveCurrentlyEditing();
Links.contents.push({
name: "New Category",
color: "#2c3e50",
entries: []
});
return LinkEditor.updateLinks();
};
LinkEditor.toggleEditingCategory = function(category) {
if (!category.classList.contains('editing')) {
category.classList.add('editing');
return LinkEditor.editCategory(category);
} else {
category.classList.remove('editing');
return LinkEditor.stopEditCategory(category);
}
};
LinkEditor.editCategory = function(category) {
var title, titleElement;
titleElement = category.querySelector('.title');
titleElement.contentEditable = "true";
};
LinkEditor.stopEditCategory = function(category) {
category.querySelector(".title").contentEditable = "false";
return LinkEditor.updateSavedCategory(category);
};
LinkEditor.updateSavedCategory = function(category) {
var saved = Links.contents[LinkEditor.getCategoryID(category)];
saved.name = category.querySelector('.title').innerText;
Links.saveToLocalStorage();
return saved.name;
};
LinkEditor.removeCategory = function(id) {
LinkEditor.saveCurrentlyEditing();
if(!confirm("Supprimer la catégorie "+Links.contents[id].name+" ?"))
return;
Links.contents.splice(id, 1);
return LinkEditor.updateLinks();
};
LinkEditor.updateCategoryColor = function(clickedColorPickerColor) {
var catID;
catID = LinkEditor.getCategoryID(clickedColorPickerColor);
Links.contents[catID].color = clickedColorPickerColor.attr('data-color');
LinkEditor.saveCurrentlyEditing();
return Links.render();
};
LinkEditor.editEntry = function(entry) {
var entryID, modelEntry;
entryID = LinkEditor.getEntryID(entry);
var modalForm = document.querySelector("#entry-edit-form");
modalForm["entry_id"].value = entryID;
modalForm["category_id"].value = LinkEditor.getCategoryID(entry);
modelEntry = Links.contents[LinkEditor.getCategoryID(entry)].entries[entryID];
modalForm["entry_title"].value = modelEntry.title;
modalForm["entry_href"].value = modelEntry.href;
return location.hash = "edit-entry";
};
LinkEditor.addEntry = function(categoryID) {
var entry;
Links.contents[categoryID].entries.push({
title: '',
href: 'http://'
});
Links.render();
entry = $('.category[data-category-index="' + categoryID + '"] > .entries > .entry:last-of-type');
return LinkEditor.editEntry(entry);
};
LinkEditor.removeEntry = function(entry) {
var title = Links.contents[LinkEditor.getCategoryID(entry)].entries[LinkEditor.getEntryID(entry)]["title"]
if(!confirm("Supprimer le lien "+title+" ?"))
return;
Links.contents[LinkEditor.getCategoryID(entry)].entries.splice(LinkEditor.getEntryID(entry), 1);
Links.saveToLocalStorage();
return Links.render();
};
LinkEditor.updateLinks = function() {
return Links.render();
};
LinkEditor.getCategoryID = function(element) {
return parseInt(LinkEditor.getContainingCategory(element).dataset.categoryIndex);
};
LinkEditor.getContainingCategory = function(element) {
return element.closest('.category');
};
LinkEditor.getEntryID = function(element) {
return parseInt(LinkEditor.getContainingEntry(element).dataset.entryIndex);
};
LinkEditor.getContainingEntry = function(element) {
return element.closest('.entry');
};
LinkEditor.saveCurrentlyEditing = function() {
document.querySelectorAll('.category.editing').forEach(function(cat) {
return LinkEditor.stopEditCategory(cat);
});
};
LinkEditor.openRawEditor = function() {
LinkEditor.saveCurrentlyEditing();
var editor = document.querySelector('#raw-data-editor');
var editorBox = document.querySelector('#raw-data-box');
editorBox.value = JSON.stringify(Links.contents, null, " ");
return editor.classList.add('editing');
};
LinkEditor.closeRawEditor = function() {
return editor.classList.remove('editing');
};
LinkEditor.saveRawEditor = function() {
var code, data, e;
try {
code = editorBox.value;
if (!code || /^\s*$/.test(code)) {
Links.contents = [];
} else {
data = JSON.parse(code);
if (data instanceof Array) {
Links.contents = data;
} else {
throw "No array given";
}
}
Links.render();
return LinkEditor.closeRawEditor();
} catch (_error) {
e = _error;
return alert('Please check the format of the data you entered.');
}
};
LinkEditor.toggleEditMode = function() {
LinkEditor.editing = !LinkEditor.editing;
if (LinkEditor.editing) {
document.querySelector('#editbar').classList.add('editing');
return document.querySelector('#link-view').classList.add('editing');
} else {
LinkEditor.saveCurrentlyEditing();
document.querySelectorAll('.editing').forEach( function(el) {
el.classList.remove('editing');
});
return Links.saveToLocalStorage();
}
};
return LinkEditor;
})();
document.addEventListener('DOMContentLoaded', function() {
return LinkEditor.registerEvents();
}, false);
|
JavaScript
| 0 |
@@ -4189,26 +4189,21 @@
lor.
+d
at
-tr('data-
+aset.
color
-')
;%0A
|
fb9ce4fe6f55c83c96fa311a0973dfa77e5740af
|
correct validateAlignedFunctionParameters values
|
lib/rules/validate-aligned-function-parameters.js
|
lib/rules/validate-aligned-function-parameters.js
|
/**
* Validates proper alignment of function parameters.
*
* Type: `Object` or `Boolean`
*
* Values: `"lineBreakAfterOpeningBraces"`, `"lineBreakBeforeClosingBraces"` as child properties or `true`.
*
* #### Example
*
* ```js
* "validateAlignedFunctionParameters": {
* "lineBreakAfterOpeningBraces": true,
* "lineBreakBeforeClosingBraces": true
* }
* ```
*
* ##### Valid
* ```js
* function (
* thisIs,
* theLongestList,
* ofParametersEverWritten
* ) {}
* ```
* ##### Invalid
* ```js
* function (thisIs,
* theLongestList,
* ofParametersEverWritten) {}
* ```
*/
var assert = require('assert');
module.exports = function() {};
module.exports.prototype = {
configure: function(options) {
var validProperties = [
'lineBreakAfterOpeningBrace',
'lineBreakBeforeClosingBrace'
];
var optionName = this.getOptionName();
assert(
typeof options === 'object' || options === true,
optionName + ' option must be an object or boolean true'
);
if (typeof options === 'object') {
validProperties.forEach(function(key) {
var isPresent = key in options;
if (isPresent) {
assert(
options[key] === true,
optionName + '.' + key + ' property requires true value or should be removed'
);
}
});
validProperties.forEach(function(property) {
this['_' + property] = Boolean(options[property]);
}.bind(this));
}
},
getOptionName: function() {
return 'validateAlignedFunctionParameters';
},
check: function(file, errors) {
var lineBreakAfterOpeningBrace = this._lineBreakAfterOpeningBrace;
var lineBreakBeforeClosingBrace = this._lineBreakBeforeClosingBrace;
file.iterateNodesByType(['FunctionDeclaration', 'FunctionExpression'], function(node) {
// ignore this rule if there are no parameters
if (!(node.params && node.params.length > 0)) {
return;
}
// ignore this rule if the parameters are not multi-line
var firstParameter = file.getFirstNodeToken(node.params[0]);
var lastParameter = node.params[node.params.length - 1];
if (firstParameter.loc.start.line === lastParameter.loc.end.line) {
return;
}
// look for the furthest parameter start position
var maxParamStartPos = 0;
node.params.forEach(function(parameter) {
maxParamStartPos = Math.max(maxParamStartPos, parameter.loc.start.column);
});
// make sure all parameters are lined up
node.params.forEach(function(parameter) {
if (parameter.loc.start.column !== maxParamStartPos) {
errors.add('Multi-line parameters are not aligned.', parameter.loc.start);
}
});
// make sure the first parameter is on a new line
if (lineBreakAfterOpeningBrace) {
var openingBrace = file.getPrevToken(firstParameter);
errors.assert.differentLine({
token: openingBrace,
nextToken: firstParameter,
message: 'There is no line break after the opening brace'
});
}
// make sure the closing brace is on a new line
if (lineBreakBeforeClosingBrace) {
var bodyToken = file.getFirstNodeToken(node.body);
var closingBrace = file.getPrevToken(bodyToken);
errors.assert.differentLine({
token: lastParameter,
nextToken: closingBrace,
message: 'There is no line break before the closing brace'
});
}
});
}
};
|
JavaScript
| 0 |
@@ -127,17 +127,16 @@
ingBrace
-s
%22%60, %60%22li
@@ -160,17 +160,16 @@
ingBrace
-s
%22%60 as ch
@@ -295,25 +295,24 @@
OpeningBrace
-s
%22: true,%0A *
@@ -341,17 +341,16 @@
ingBrace
-s
%22: true%0A
|
24c921cd4bb89061023eb94bf6829510411b418c
|
Make it clear the messages appear for every open result
|
test/integration/bankHolidayAlert.js
|
test/integration/bankHolidayAlert.js
|
const chai = require('chai');
const chaiHttp = require('chai-http');
const cheerio = require('cheerio');
const nock = require('nock');
const constants = require('../../app/lib/constants');
const getSampleResponse = require('../resources/getSampleResponse');
const iExpect = require('../lib/expectations');
const server = require('../../server');
const expect = chai.expect;
chai.use(chaiHttp);
const resultsRoute = `${constants.SITE_ROOT}/results`;
const numberOfOpenResults = constants.numberOfOpenResults;
const numberOfNearbyResults = constants.numberOfNearbyResultsToRequest;
const yourLocation = constants.yourLocation;
describe('The bank holiday alert messaging', () => {
after('clean nock', () => {
nock.cleanAll();
});
afterEach('reset DATE', () => {
process.env.DATE = '2017-12-12';
});
describe('on the day of the bank holiday', () => {
before('set DATE', () => {
process.env.DATE = '2017-12-25';
});
it('should show a message about the bank holiday for each open result', (done) => {
const reverseGeocodeResponse = getSampleResponse('postcodesio-responses/reverseGeocodeEngland.json');
const serviceApiResponse = getSampleResponse('service-api-responses/-1,54.json');
const latitude = 52.75;
const longitude = -1.55;
nock('https://api.postcodes.io')
.get('/postcodes')
.query({
limit: 1, radius: 20000, wideSearch: true, lon: longitude, lat: latitude
})
.times(1)
.reply(200, reverseGeocodeResponse);
nock(process.env.API_BASE_URL)
.get(`/nearby?latitude=${latitude}&longitude=${longitude}&limits:results:open=${numberOfOpenResults}&limits:results:nearby=${numberOfNearbyResults}`)
.times(1)
.reply(200, serviceApiResponse);
chai.request(server)
.get(resultsRoute)
.query({ location: yourLocation, latitude, longitude })
.end((err, res) => {
iExpect.htmlWith200Status(err, res);
const $ = cheerio.load(res.text);
expect($('.callout--warning').first().text()).to.equal('Today is a bank holiday. Please call to check opening times.');
expect($('.callout--warning').length).to.equal(4);
done();
});
});
});
});
|
JavaScript
| 0 |
@@ -1010,19 +1010,27 @@
ach
-open
result
+ that is open
', (
@@ -2077,15 +2077,114 @@
g').
-first()
+length).to.equal(4);%0A $('callout--warning').toArray().forEach((item) =%3E %7B%0A expect(item
.tex
@@ -2276,56 +2276,9 @@
-expect($('.callout--warning').length).to.equal(4
+%7D
);%0A%0A
|
eef654e0e3189a8fcba03c8463d62ecbe2a3e745
|
fix indentation and remove console.log
|
src/components/views/elements/Confetti.js
|
src/components/views/elements/Confetti.js
|
const confetti = {
//set max confetti count
maxCount: 150,
//syarn addet the particle animation speed
speed: 3,
//the confetti animation frame interval in milliseconds
frameInterval: 15,
//the alpha opacity of the confetti (between 0 and 1, where 1 is opaque and 0 is invisible)
alpha: 1.0,
//call to start confetti animation (with optional timeout in milliseconds)
start: null,
//call to stop adding confetti
stop: null,
//call to stop the confetti animation and remove all confetti immediately
remove: null,
isRunning: null,
//call and returns true or false depending on whether the animation is running
animate: null,
};
(function() {
confetti.start = startConfetti;
confetti.stop = stopConfetti;
confetti.remove = removeConfetti;
confetti.isRunning = isConfettiRunning;
confetti.animate = animateConfetti;
const supportsAnimationFrame = window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame;
const colors = ["rgba(30,144,255,", "rgba(107,142,35,", "rgba(255,215,0,",
"rgba(255,192,203,", "rgba(106,90,205,", "rgba(173,216,230,",
"rgba(238,130,238,", "rgba(152,251,152,", "rgba(70,130,180,",
"rgba(244,164,96,", "rgba(210,105,30,", "rgba(220,20,60,"];
let streamingConfetti = false;
// let animationTimer = null;
let lastFrameTime = Date.now();
let particles = [];
let waveAngle = 0;
let context = null;
function resetParticle(particle, width, height) {
particle.color = colors[(Math.random() * colors.length) | 0] + (confetti.alpha + ")");
particle.color2 = colors[(Math.random() * colors.length) | 0] + (confetti.alpha + ")");
particle.x = Math.random() * width;
particle.y = Math.random() * height - height;
particle.diameter = Math.random() * 10 + 5;
particle.tilt = Math.random() * 10 - 10;
particle.tiltAngleIncrement = Math.random() * 0.07 + 0.05;
particle.tiltAngle = Math.random() * Math.PI;
return particle;
}
function runAnimation() {
if (particles.length === 0) {
context.clearRect(0, 0, window.innerWidth, window.innerHeight);
//animationTimer = null;
} else {
const now = Date.now();
const delta = now - lastFrameTime;
if (!supportsAnimationFrame || delta > confetti.frameInterval) {
context.clearRect(0, 0, window.innerWidth, window.innerHeight);
updateParticles();
drawParticles(context);
lastFrameTime = now - (delta % confetti.frameInterval);
}
requestAnimationFrame(runAnimation);
}
}
function startConfetti(roomWidth, timeout) {
const width = roomWidth;
const height = window.innerHeight;
window.requestAnimationFrame = (function() {
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(callback) {
return window.setTimeout(callback, confetti.frameInterval);
};
})();
let canvas = document.getElementById("confetti-canvas");
if (canvas === null) {
canvas = document.createElement("canvas");
canvas.setAttribute("id", "confetti-canvas");
canvas.setAttribute("style",
"display:block;z-index:999999;pointer-events:none;position:fixed;top:0; right:0");
document.body.prepend(canvas);
canvas.width = width;
canvas.height = height;
window.addEventListener("resize", function() {
canvas.width = roomWidth;
canvas.height = window.innerHeight;
}, true);
context = canvas.getContext("2d");
} else if (context === null) {
context = canvas.getContext("2d");
}
const count = confetti.maxCount;
while (particles.length < count) {
particles.push(resetParticle({}, width, height));
}
streamingConfetti = true;
runAnimation();
if (timeout) {
window.setTimeout(stopConfetti, timeout);
}
}
function stopConfetti() {
streamingConfetti = false;
}
function removeConfetti() {
stop();
particles = [];
}
function isConfettiRunning() {
return streamingConfetti;
}
function drawParticles(context) {
let particle;
let x; let x2; let y2;
for (let i = 0; i < particles.length; i++) {
particle = particles[i];
context.beginPath();
context.lineWidth = particle.diameter;
x2 = particle.x + particle.tilt;
x = x2 + particle.diameter / 2;
y2 = particle.y + particle.tilt + particle.diameter / 2;
if (confetti.gradient) {
const gradient = context.createLinearGradient(x, particle.y, x2, y2);
gradient.addColorStop("0", particle.color);
gradient.addColorStop("1.0", particle.color2);
context.strokeStyle = gradient;
} else {
context.strokeStyle = particle.color;
}
context.moveTo(x, particle.y);
context.lineTo(x2, y2);
context.stroke();
}
}
function updateParticles() {
const width = window.innerWidth;
const height = window.innerHeight;
let particle;
waveAngle += 0.01;
for (let i = 0; i < particles.length; i++) {
particle = particles[i];
if (!streamingConfetti && particle.y < -15) {
particle.y = height + 100;
} else {
particle.tiltAngle += particle.tiltAngleIncrement;
particle.x += Math.sin(waveAngle) - 0.5;
particle.y += (Math.cos(waveAngle) + particle.diameter + confetti.speed) * 0.5;
particle.tilt = Math.sin(particle.tiltAngle) * 15;
}
if (particle.x > width + 20 || particle.x < -20 || particle.y > height) {
if (streamingConfetti && particles.length <= confetti.maxCount) {
resetParticle(particle, width, height);
} else {
particles.splice(i, 1);
i--;
}
}
}
}
})();
export function convertToHex(content) {
const contentBodyToHexArray = [];
let hex;
if (content.body) {
for (let i = 0; i < content.body.length; i++) {
hex = content.body.codePointAt(i).toString(16);
contentBodyToHexArray.push(hex);
}
}
return contentBodyToHexArray;
}
export function isConfettiEmoji(content) {
const hexArray = convertToHex(content);
return !!(hexArray.includes('1f389') || hexArray.includes('1f38a'));
}
export function animateConfetti(roomWidth) {
confetti.start(roomWidth, 3000);
}
export function forceStopConfetti() {
console.log('confetti should stop');
confetti.remove();
}
|
JavaScript
| 0.000003 |
@@ -7272,28 +7272,24 @@
oomWidth) %7B%0A
-
confetti
@@ -7357,49 +7357,8 @@
) %7B%0A
- console.log('confetti should stop');%0A
|
04578f9976ac9559d0b073b2a8238b6b1cfe73e7
|
Update init.js
|
draw/init.js
|
draw/init.js
|
if(!Draw || KAPhy.version !== KAPhy.current) {
var CENTER = "CENTER";
var CORNER = "CORNER";
var RADIUS = "RADIUS";
var CORNERS = "CORNERS";
var MITER = "miter";
var ROUND = "round";
var BEVEL = "bevel";
var BUTT = "butt";
var SQUARE = "square";
var Draw = {
currentRectMode: "CORNER",
currentImageMode: "CORNER",
currentEllipseMode: "CENTER",
shapeOpen: false,
};
}
|
JavaScript
| 0.000001 |
@@ -224,12 +224,14 @@
var
-BUTT
+SQUARE
= %22
@@ -239,30 +239,31 @@
utt%22;%0A var
-SQUARE
+PROJECT
= %22square%22;
|
293bf05782e8453edabdb5181d811d5ebc8c4f39
|
fix remembering where you were last
|
script.js
|
script.js
|
var displayTime = function(seconds) {
var s = parseFloat(seconds);
if (s > 0) {
return (Math.floor(s / 60).toString() + 'm ' +
(s % 60).toString() + 's');
} else {
return '...';
}
};
var formatPredictionRow = function(prediction) {
return '<li class="list-group-item"> ' +
'<span class="label label-primary pull-left route">' +
prediction.route + '</span>' +
'<span class="label label-info pull-left direction">' +
prediction.direction + '</span> ' +
'<span class="badge pull-right time">' +
displayTime(prediction.seconds) + '</span></li>';
};
var tickDown = function(time) {
var match = /^(\d+)m\s+(\d+)s$/.exec(time);
if (match) {
var min = parseInt(match[1]);
var sec = parseInt(match[2]);
return displayTime((60 * min) + sec - 1);
} else {
return time;
}
};
var parsePredictions = function(xhrResult) {
var ret = [];
$(xhrResult).find('predictions').each(function() {
var route = $(this).attr('routeTitle');
$(this).find('direction').each(function() {
var direction = $(this).attr('title');
$(this).find('prediction').each(function() {
ret.push({
route: route,
direction: direction,
seconds: $(this).attr('seconds')
});
});
});
});
return _.sortBy(ret, function(p) {
return parseFloat(p.seconds);
});
};
var openStop = function(stop, xhrResult) {
var $box = $('#predictions');
var $head = $box.find('.panel-heading');
var predictions = parsePredictions(xhrResult);
var p;
$head.find('.title').html(stop.title);
$box.find('.list-group').html('');
for (var i = 0; i < predictions.length; i++) {
$box.find('.list-group').append(formatPredictionRow(predictions[i]));
}
$('#map').css('width', '70%');
$box.show();
};
var loadStop = function(stop) {
$('#predictions').find('.loading').css({ display: 'block' });
$('#predictions').find('.refresh').hide();
$.ajax({
type: 'GET',
url: 'http://webservices.nextbus.com/service/publicXMLFeed' +
'?command=predictions&a=mbta&stopId=' + stop.id,
dataType: 'xml',
success: function(data) {
$('#predictions').find('.loading').css({ display: 'none' });
$('#predictions').find('.refresh').show();
openStop(stop, data);
},
error: function() {
$('#predictions').find('.loading').css({ display: 'none' });
$('#predictions').find('.refresh').show();
console.log('An Error occurred');
}
});
};
var autoReload = function() {
if (currentStop) {
loadStop(currentStop);
}
setTimeout(autoReload, 60 * 1000);
};
var currentStop;
var initialLocation;
var boston = new google.maps.LatLng(42.38, -71.1);
var browserSupportFlag;
function initialize() {
var myOptions = {
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map"), myOptions);
// Try W3C Geolocation (Preferred)
if(navigator.geolocation) {
browserSupportFlag = true;
navigator.geolocation.getCurrentPosition(function(position) {
initialLocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
map.setCenter(initialLocation);
map.setZoom(17);
}, function() {
handleNoGeolocation(browserSupportFlag);
});
}
// Browser doesn't support Geolocation
else {
browserSupportFlag = false;
handleNoGeolocation(browserSupportFlag);
}
google.maps.event.addListener(map, 'bounds_changed', function() {
window.localStorage.setItem('zoom', map.getZoom());
window.localStorage.setItem('lat', map.getCenter().lat());
window.localStorage.setItem('lng', map.getCenter().lng());
});
function handleNoGeolocation(errorFlag) {
if (window.localStorage.getItem('zoom') &&
window.localStorage.getItem('lat') &&
window.localStorage.getItem('lng')) {
map.setCenter(new google.maps.LatLng(window.localStorage.getItem('lat'),
window.localStorage.getItem('lng')));
map.setZoom(window.localStorage.getItem('zoom'));
} else {
//alert("Geolocation service failed.");
initialLocation = boston;
map.setCenter(initialLocation);
}
}
for (var i = 0; i < stops.length; i++) {
(function(stop) {
var pos = new google.maps.LatLng(stop.lat, stop.lon);
var marker = new google.maps.Marker({
position: pos,
map: map,
title: stop.title
});
google.maps.event.addListener(marker, 'click', function() {
currentStop = stop;
loadStop(stop);
});
}).call(this, stops[i]);
}
$('#predictions').find('.close').click(function() {
$('#map').css('width', '100%');
$('#predictions').hide();
});
$('#predictions').find('.refresh').click(function() {
if (currentStop) {
loadStop(currentStop);
}
});
autoReload();
}
google.maps.event.addDomListener(window, 'load', initialize);
var countDownTimer;
var countDown = function() {
$('.time').each(function() {
var time = $(this).text();
$(this).text(tickDown(time));
});
countDownTimer = setTimeout(countDown, 1000);
};
countDown();
|
JavaScript
| 0.000001 |
@@ -3946,16 +3946,17 @@
.LatLng(
++
window.l
@@ -4018,32 +4018,33 @@
++
window.localStor
@@ -4083,16 +4083,17 @@
setZoom(
++
window.l
|
d2c7385245193a5f280760461c85a37192ef25a1
|
Reset map position before loading new session, fix #23
|
src/containers/SessionsHandler/actions.js
|
src/containers/SessionsHandler/actions.js
|
import makeActionCreator from 'utils/makeActionCreator';
import { MESSAGE_STATUS, URLS } from 'constants';
import { loadJSON, postJSON } from 'utils/requests';
import { getDataToSave } from './utils';
import { displaySystemMessage } from '../MessagesBox/actions';
import { setSessionID, updateSessionName } from '../Session/actions';
import { addPathEventListener, removePathEventListener } from '../Paths/actions';
import { stopMetronome } from '../Metronome/actions';
export const NEW_SESSION = 'NEW_SESSION';
export const SAVE_SESSION = 'SAVE_SESSION';
export const LOAD_SESSION = 'LOAD_SESSION';
export const BACKEND_SAVE_REQUEST = 'BACKEND_SAVE_REQUEST';
export const BACKEND_SAVE_SUCCESS = 'BACKEND_SAVE_SUCCESS';
export const BACKEND_SAVE_FAILURE = 'BACKEND_SAVE_FAILURE';
export const BACKEND_LOAD_REQUEST = 'BACKEND_LOAD_REQUEST';
export const BACKEND_LOAD_SUCCESS = 'BACKEND_LOAD_SUCCESS';
export const BACKEND_LOAD_FAILURE = 'BACKEND_LOAD_FAILURE';
export const BACKEND_DELETE_SUCCESS = 'BACKEND_DELETE_SUCCESS';
// no need to exports all these actions as they will be used internally in saveSession
const backendSaveRequest = makeActionCreator(BACKEND_SAVE_REQUEST, 'sessionID', 'dataToSave');
const backendSaveSuccess = makeActionCreator(BACKEND_SAVE_SUCCESS, 'sessionID');
const backendSaveFailure = makeActionCreator(BACKEND_SAVE_FAILURE, 'msg');
const backendLoadRequest = makeActionCreator(BACKEND_LOAD_REQUEST);
const backendLoadSuccess = makeActionCreator(BACKEND_LOAD_SUCCESS);
const backendLoadFailure = makeActionCreator(BACKEND_LOAD_FAILURE, 'msg');
const backendDeleteSuccess = makeActionCreator(BACKEND_DELETE_SUCCESS);
export const newSession = makeActionCreator(NEW_SESSION);
const saveToBackend = (sessionID, dataToSave) => (dispatch) => {
let url = URLS.SAVE_SESSION;
if (sessionID) {
url = `${url}?sid=${sessionID}`;
}
dispatch(backendSaveRequest(sessionID, dataToSave));
dispatch(displaySystemMessage('Saving session...'));
postJSON(url, dataToSave).then(
(data) => {
dispatch(backendSaveSuccess(data.sessionID));
dispatch(setSessionID(data.sessionID));
dispatch(updateSessionName(data.sessionName));
dispatch(displaySystemMessage(
`Session successfully saved '${data.sessionName}'!`, MESSAGE_STATUS.SUCCESS));
},
(data) => {
const message = (data && data.msg) || 'Unknown error';
dispatch(backendSaveFailure(message));
dispatch(displaySystemMessage(
`Could not save the session: ${message}`, MESSAGE_STATUS.ERROR));
}
);
};
export const saveSession = () => (dispatch, getStore) => {
const currentState = getStore();
const dataToSave = getDataToSave(currentState);
if (currentState.login.isEndUserAuthSupported) {
dispatch(saveToBackend(currentState.session.id, dataToSave));
} else {
// TODO: save to local storage
dispatch(displaySystemMessage('Cant\'t save because no backend has been detected...',
MESSAGE_STATUS.ERROR));
}
};
export const saveSessionAs = sessionName => (dispatch, getStore) => {
dispatch(updateSessionName(sessionName));
const currentState = getStore();
const dataToSave = getDataToSave(currentState);
if (currentState.login.isEndUserAuthSupported) {
dispatch(saveToBackend(undefined, dataToSave)); // Always create a new session id
} else {
// TODO: save to local storage
dispatch(displaySystemMessage('Cant\'t save as because no backend has been detected...',
MESSAGE_STATUS.ERROR));
}
};
const preRestoreSession = () => (dispatch, getStore) => {
dispatch(stopMetronome());
const state = getStore();
state.paths.paths.forEach(path => dispatch(removePathEventListener(path.id)));
};
const postRestoreSession = () => (dispatch, getStore) => {
// Use this function to do all the stuff that is needed to
// make a loaded session ready for playing/continue editing (e.g. setting listeners on paths)
const state = getStore();
state.paths.paths.forEach(path => dispatch(addPathEventListener(path.id)));
};
const loadFromBackend = sessionID => (dispatch) => {
const url = `${URLS.LOAD_SESSION}?sid=${sessionID}`;
dispatch(backendLoadRequest());
dispatch(displaySystemMessage('Loading session...'));
loadJSON(url).then(
(data) => {
dispatch(preRestoreSession());
dispatch(Object.assign({}, data.data, { type: LOAD_SESSION }));
dispatch(postRestoreSession());
dispatch(backendLoadSuccess());
dispatch(displaySystemMessage(
'Session loaded!', MESSAGE_STATUS.SUCCESS));
},
(data) => {
const message = (data && data.msg) || 'Unknown error';
dispatch(backendLoadFailure());
dispatch(displaySystemMessage(
`Error loading session: ${message}`, MESSAGE_STATUS.ERROR));
}
);
};
export const loadSession = sessionID => (dispatch, getStore) => {
const currentState = getStore();
if (currentState.login.isEndUserAuthSupported) {
dispatch(loadFromBackend(sessionID));
} else {
// TODO: load from local storage
dispatch(displaySystemMessage('Cant\'t load because no backend has been detected...',
MESSAGE_STATUS.ERROR));
}
};
const removeFromBackend = sessionID => (dispatch) => {
const url = `${URLS.REMOVE_SESSION}?sid=${sessionID}`;
loadJSON(url).then(
(data) => {
dispatch(backendDeleteSuccess());
dispatch(displaySystemMessage(`Deleted session ${data.name}!`, MESSAGE_STATUS.SUCCESS));
},
(data) => {
const message = (data && data.msg) || 'Unknown error';
dispatch(displaySystemMessage(
`Error loading session: ${message}`, MESSAGE_STATUS.ERROR));
}
);
};
export const removeSession = sessionID => (dispatch, getStore) => {
const currentState = getStore();
if (currentState.login.isEndUserAuthSupported) {
dispatch(removeFromBackend(sessionID));
} else {
// TODO: remove from local storage
dispatch(displaySystemMessage('Cant\'t delete because no backend has been detected...',
MESSAGE_STATUS.ERROR));
}
};
|
JavaScript
| 0 |
@@ -249,32 +249,89 @@
esBox/actions';%0A
+import %7B forceMapPositionUpdate %7D from '../Map/actions';%0A
import %7B setSess
@@ -3635,24 +3635,104 @@
tronome());%0A
+ dispatch(forceMapPositionUpdate(%7B translateX: 0, translateY: 0, scale: 1 %7D));%0A
const stat
|
62c6b7c58effdda18a9d1352f335a6ce65a70425
|
add auto slide up when mouse not hover
|
js/menu_on_top.js
|
js/menu_on_top.js
|
/**
* @package menu_on_top
* @category base
* @author Awikatchikaen
* @copyright 2012-2013 Awikatchikaen <[email protected]>
* @license GNU Affero General Public license (AGPL)
* @link information http://apps.owncloud.com/content/show.php?content=157091
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
* License as published by the Free Software Foundation; either
* version 3 of the license, or any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU AFFERO GENERAL PUBLIC LICENSE for more details.
*
* You should have received a copy of the GNU Affero General Public
* License along with this library.
* If not, see <http://www.gnu.org/licenses/>.
*
*/
/**
* @file js/menu_on_top.JS
* @author Awikatchikaen
*/
$(document).ready(function () {
$("#navigation").hide();
$("#navigation").css("visibility", "visible");
$("#owncloud").click(function(e){
e.preventDefault();
$("#navigation").slideToggle();
});
$("#navigation li a").click(function(e){
$("#navigation").slideUp();
});
/*$("#navigation, #owncloud").mouseleave(function(){
$("#navigation").slideUp();
});*/
});
/*
$(function () {
//$(".campaign-box span:last").hide();
$("#owncloud").hover(function () {
//$("#navigation").css("opacity", 0.5);
$("#navigation").fadeIn("fast");
}, function () {
//$("#navigation").css("opacity", 1);
$("#navigation").hide("slow");
});
});
*/
|
JavaScript
| 0.000001 |
@@ -1008,16 +1008,18 @@
on () %7B%0A
+
$(%22#na
@@ -1037,16 +1037,18 @@
hide();%0A
+
$(%22#na
@@ -1088,16 +1088,18 @@
ible%22);%0A
+
$(%22#ow
@@ -1130,16 +1130,20 @@
e)%7B%0A
+
+
e.preven
@@ -1150,24 +1150,28 @@
tDefault();%0A
+
$(%22#navi
@@ -1199,16 +1199,18 @@
); %0A
+
%7D);%0A
%0A %0A
@@ -1205,20 +1205,30 @@
%7D);%0A
-%0A
+ %0A
%0A
+
$(%22#na
@@ -1258,24 +1258,28 @@
unction(e)%7B%0A
+
$(%22#navi
@@ -1305,17 +1305,23 @@
%0A
+
+
%7D);%0A
+
%0A
-/*
+
$(%22#
@@ -1334,19 +1334,8 @@
tion
-, #owncloud
%22).m
@@ -1356,16 +1356,20 @@
tion()%7B%0A
+
$(%22#
@@ -1395,24 +1395,23 @@
p();
-
%0A
+
%7D);
-*/
+%0A
%0A%7D);%0A%0A
-%0A
/*%0A$
|
b8a424a62bb63658b246846342ceca1dbc5b39ba
|
Update TweetBeacon.js
|
public/javascripts/TweetBeacon.js
|
public/javascripts/TweetBeacon.js
|
/**
* TweetBeacon extends THREE.Object3D
* A Three.js object that constructs and animates itself
*/
TweetBeacon = function(tweet) {
this.tweet = tweet;
// Call the constructor
THREE.Object3D.call(this);
// An empty container oriented to make it easier to work with child objects
this.container = new THREE.Object3D();
this.container.rotation.y = THREE.Math.degToRad(180);
this.add(this.container);
// Set base color depending on sentiment score
this.color = 0xFFFFFF;
//if (tweet.sentiment.score < 0) {
//this.color = 0xFF0000;
//}
if (tweet.sentiment.score > 1) {
this.color = 0x0066FF;}
else if (tweet.sentiment.score > 0) {
this.color = 0xDDDD00;
}
this.addBeam();
this.addShockwave();
};
TweetBeacon.prototype = new THREE.Object3D();
TweetBeacon.prototype.constructor = TweetBeacon;
TweetBeacon.prototype.supr = THREE.Object3D.prototype;
/**
* The line that shoots out from the surface of the Earth
*/
TweetBeacon.prototype.addBeam = function () {
var lineGeo = new THREE.Geometry();
lineGeo.vertices.push(new THREE.Vector3(0, 0, 0));
lineGeo.vertices.push(new THREE.Vector3(0, 0, 1));
var lineMat = new THREE.LineBasicMaterial({
color: this.color,
linewidth: 2,
opacity: 0.0,
transparent: true
});
this.lineMesh = new THREE.Line(lineGeo, lineMat);
this.container.add(this.lineMesh);
this.show();
}
/**
* The shockwave at the base of the beacon line
*/
TweetBeacon.prototype.addShockwave = function () {
var self = this;
var material = new THREE.MeshBasicMaterial({
color: this.color,
transparent: true,
opacity: 1.0
});
var radius = 20;
var segments = 16 ;
var circleGeometry = new THREE.CircleGeometry(radius, segments);
var circle = new THREE.Mesh(circleGeometry, material);
circle.position.z = 5;
circle.scale.x = circle.scale.y = circle.scale.x = 0.1;
this.container.add(circle);
var time = 2;
// Animates opacity of shockwave
TweenLite.to(circle.material, time, {
opacity: 0,
ease: Quad.easeOut
});
// Animates scale/size of shockwave
TweenLite.to(circle.scale, time, {
x: 1.0, y: 1.0, z: 1.0,
ease: Quart.easeOut,
onComplete: function () {
// remove when animation completes to keep number of object in scene to a minimum
self.container.remove(circle);
}
});
}
/**
* Animation of line emerging from beacon base
*/
TweetBeacon.prototype.show = function () {
var self = this;
var time = 4;
// Define the line height based on the sentiment score
this.beamHeight = 400 + Math.abs(this.tweet.sentiment.score) * 100
// Animate opacity
TweenLite.to(this.lineMesh.material, time, {
opacity: 0.75,
ease: Quart.easeOut
});
// Animate line length
TweenLite.to(this.lineMesh.geometry.vertices[1], time, {
z: this.beamHeight,
ease: Quart.easeOut,
onUpdate: function () {
// this is required for Three.js to re-render the line
self.lineMesh.geometry.verticesNeedUpdate = true;
}
});
// Set the life span of the beacon before it shoots into space
setTimeout(function () {
self.hide()
}, time * 1000);
};
/**
* Animation of beacon shooting into space
*/
TweetBeacon.prototype.hide = function () {
var self = this;
var time = 10;
// Animate opacity
TweenLite.to(this.lineMesh.material, time, {
opacity: 0.0,
ease: Quart.easeOut,
onComplete: function () {
// when animation completes callback to notify
if (self.onHideCallback) {
self.onHideCallback();
}
}
});
// Animate length of line
TweenLite.to(this.lineMesh.geometry.vertices[0], time / 2, {
z: this.beamHeight,
ease: Quart.easeOut,
onUpdate: function () {
// this is required for Three.js to re-render the line
self.lineMesh.geometry.verticesNeedUpdate = true;
}
});
// Animate distance of line from beacon base / surface of earth
TweenLite.to(this.lineMesh.position, time, {
z: this.beamHeight + 300,
ease: Quart.easeOut
});
}
/**
* Sets a callback for aniamtion complete and beacon has expired
*/
TweetBeacon.prototype.onHide = function (callback) {
this.onHideCallback = callback;
}
|
JavaScript
| 0.000001 |
@@ -491,18 +491,16 @@
FFF;%0A%0A
-//
if (twee
@@ -526,20 +526,16 @@
0) %7B%0A
- //
this.col
@@ -555,11 +555,21 @@
;%0A
-//%7D
+%7D //-%3E DELETE
%0A i
@@ -627,16 +627,28 @@
0066FF;%7D
+ //%3C- DELETE
%0A else
|
77ebb1292198a37081289f3b05e2dd2a57e21de3
|
Move JSON en/decoding out of collab module
|
src/collab/index.js
|
src/collab/index.js
|
import {defineOption, eventMixin} from "../edit"
import {applyStep, Step} from "../transform"
import {rebaseSteps} from "./rebase"
export {rebaseSteps}
defineOption("collab", false, (pm, value) => {
if (pm.mod.collab) {
pm.mod.collab.detach()
pm.mod.collab = null
}
if (value) {
pm.mod.collab = new Collab(pm, value)
}
})
class Collab {
constructor(pm, options) {
this.pm = pm
this.options = options
this.version = options.version || 0
this.versionDoc = pm.doc
this.unconfirmedSteps = []
this.unconfirmedMaps = []
pm.on("transform", this.onTransform = transform => {
for (let i = 0; i < transform.steps.length; i++) {
this.unconfirmedSteps.push(transform.steps[i])
this.unconfirmedMaps.push(transform.maps[i])
}
this.signal("mustSend")
})
pm.on("beforeSetDoc", this.onSetDoc = () => {
throw new Error("setDoc is not supported on a collaborative editor")
})
pm.history.allowCollapsing = false
}
detach() {
this.pm.off("transform", this.onTransform)
this.pm.off("beforeSetDoc", this.onSetDoc)
this.pm.history.allowCollapsing = true
}
hasSendableSteps() {
return this.unconfirmedSteps.length > 0
}
sendableSteps() {
return {
version: this.version,
doc: this.pm.doc,
steps: this.unconfirmedSteps.map(s => s.toJSON())
}
}
confirmSteps(sendable) {
this.unconfirmedSteps.splice(0, sendable.steps.length)
this.unconfirmedMaps.splice(0, sendable.steps.length)
this.version += sendable.steps.length
this.versionDoc = sendable.doc
}
receive(steps) {
let doc = this.versionDoc
let maps = steps.map(json => {
let step = Step.fromJSON(json)
let result = applyStep(doc, step)
doc = result.doc
return result.map
})
this.version += steps.length
this.versionDoc = doc
let rebased = rebaseSteps(doc, maps, this.unconfirmedSteps, this.unconfirmedMaps)
this.unconfirmedSteps = rebased.transform.steps.slice()
this.unconfirmedMaps = rebased.transform.maps.slice()
this.pm.updateDoc(rebased.doc, rebased.mapping)
this.pm.history.rebased(maps, rebased.transform, rebased.positions)
}
}
eventMixin(Collab)
|
JavaScript
| 0.000001 |
@@ -1355,27 +1355,14 @@
eps.
-map(s =%3E s.toJSON()
+slice(
)%0A
@@ -1674,54 +1674,17 @@
map(
-json =%3E %7B%0A let step = Step.fromJSON(json)
+step =%3E %7B
%0A
@@ -2163,16 +2163,32 @@
itions)%0A
+ return maps%0A
%7D%0A%7D%0A%0Ae
|
051bdb993d38a175d7f3bd65ef5bc89d550ff43b
|
clean the test with the edbug cacth and the console.log %j
|
test/lib/model-validation-promise.js
|
test/lib/model-validation-promise.js
|
/*global describe, it*/
require('../initialize-globals').load();
var Md = require('../../app/models/model');
var ModelValidator = require('../../app/lib/model-validation-promise');
describe('#model-validation-promise', function() {
describe('##validation on metadatas', function() {
var Model = Md.extend({
metadatas: {
firstName: {
domain: "DO_TEXTE_30",
required: false
},
lastName: {
domain: "DO_TEXTE_30",
required: true
},
email: {
domain: "DO_EMAIL"
}
}
});
it('should validate the metadatas', function(done) {
var model = new Model({
firstName: "Pierre",
lastName: "Besson",
email: "[email protected]"
});
ModelValidator.validate(model).then(function(modelSuccess) {
console.log("modelSuccess %j", modelSuccess);
done();
}).catch(function(errors) {
console.log("errors %j", errors);
//done();
});
});
if ('shoud be invalidated with the metadatas', function(done) {
ModelValidator.validate(new Model()).catch(done());
});
});
describe('##validation on model', function() {
var Model = Md.extend({
metadatas:{},//Turning off the metadatas in order to be focus on the validation attribute.
validation: {
firstName: {
required: true
}
}
});
var model = new Model({
firstName: "Pierre",
lastName: "Besson"
});
it('The validation shoul be ok', function(done) {
ModelValidator.validate(model).then(function(modelSuccess) {
modelSuccess.toJSON().should.have.property('firstName', 'Pierre');
done();
});
});
it('The validation shoul be ko', function(done) {
model.unset('firstName', {
silent: true
});
ModelValidator.validate(model).
catch (function(error) {
error.should.have.property('firstName').with.length.above(2);
done();
});
});
});
});
|
JavaScript
| 0.000001 |
@@ -826,180 +826,20 @@
ion(
-modelSuccess) %7B%0A console.log(%22modelSuccess %25j%22, modelSuccess);%0A done();%0A %7D).catch(function(errors) %7B%0A console.log(%22errors %25j%22, errors);%0A //
+) %7B%0A
done
|
5cfff4ab752af11f2d0c133c2b75e03e3ba28130
|
Implement auth methods
|
src/dashboard/components/ajax-provider.js
|
src/dashboard/components/ajax-provider.js
|
'use strict';
|
JavaScript
| 0.000001 |
@@ -7,8 +7,2927 @@
trict';%0A
+%0A/**%0A * Stores system-wide HTTP configuration.%0A */%0Aconst HTTP_CONFIG = %7B%7D;%0A%0Afunction _configure(options) %7B%0A const request = %7B%0A method: options.method,%0A url: options.url %7C%7C HTTP_CONFIG.host + options.resource,%0A headers: %7B%7D,%0A withCredentials: false%0A %7D;%0A%0A if (typeof options.data === 'object') request.data = options.data;%0A%0A if (typeof HTTP_CONFIG.authorization === 'string') %7B%0A request.withCredentials = true;%0A request.headers%5B'Authorization'%5D = HTTP_CONFIG.authorization;%0A %7D%0A%0A if (typeof HTTP_CONFIG.accept === 'string') request.headers%5B'Accept'%5D = HTTP_CONFIG.accept;%0A%0A if (typeof HTTP_CONFIG.contentType === 'string') request.headers%5B'Content-Type'%5D = HTTP_CONFIG.contentType;%0A%0A if (typeof options.headers === 'object') %7B%0A Object.keys(options.headers).forEach(function (item) %7B%0A request.headers%5Bitem%5D = options.headers%5Bitem%5D;%0A %7D);%0A %7D%0A%0A if (typeof options.query === 'object') %7B%0A const query = new URLSearchParams();%0A%0A for (let param in options.query) %7B%0A if (options.query%5Bparam%5D !== null) %7B%0A query.append(param, options.query%5Bparam%5D);%0A %7D%0A %7D%0A%0A request.url = %60$%7Brequest.url%7D?%60 + query.toString();%0A %7D%0A%0A if (Object.keys(request.headers).length %3C= 0) delete request.headers;%0A%0A return request;%0A%7D%0A%0Afunction _request(http) %7B%0A return %7B%0A request: function (options) %7B%0A return http(_configure(options));%0A %7D,%0A get: function (options) %7B%0A options.method = 'GET';%0A return http(_configure(options));%0A %7D,%0A post: function (options) %7B%0A options.method = 'POST';%0A return http(_configure(options));%0A %7D,%0A put: function (options) %7B%0A options.method = 'PUT';%0A return http(_configure(options));%0A %7D,%0A patch: function (options) %7B%0A options.method = 'PATCH';%0A return http(_configure(options));%0A %7D,%0A delete: function (options) %7B%0A options.method = 'DELETE';%0A return http(_configure(options));%0A %7D,%0A setHost: function (host) %7B%0A HTTP_CONFIG.host = host;%0A %7D /*,%0A basicAuth: function (username, password) %7B%0A if (!username) return;%0A httpConfig.authorization = 'Basic ' + $base64.encode(username + ':' + (password %7C%7C ''));%0A %7D*/%0A %7D;%0A%7D%0A%0Afunction AJAXProvider(base64) %7B%0A this.setHost = (host) =%3E %7B%0A HTTP_CONFIG.host = host;%0A %7D;%0A%0A this.basicAuth = (username, password) =%3E %7B%0A HTTP_CONFIG.authorization = 'Basic ' + base64.encode(username + ':' + (password %7C%7C ''));%0A %7D;%0A%0A this.accept = (type) =%3E %7B%0A HTTP_CONFIG.accept = type;%0A %7D;%0A%0A this.contentType = (type) =%3E %7B%0A HTTP_CONFIG.contentType = type;%0A %7D;%0A%0A this.$get = %5B'$http', _request%5D;%0A%7D%0A%0Aexport default AJAXProvider;%0A
|
02cace1341e69b99d96bdab6463034605c760798
|
revert earlier javascript change
|
public/javascripts/application.js
|
public/javascripts/application.js
|
// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults
$(document).ready(function() {
if ($('#login') && $('#username')) {
$('#username').focus();
}
$('.link_select').change(function(e) {
window.location = this.value;
});
$('form#ajax_form').submit(function(e){
e.preventDefault(); //Prevent the normal submission action
var form = $(this);
var submit = $("input[type='submit']",form);
var submit_val = submit.val();
submit.val("Please Wait...");
submit.attr("disabled", true);
jQuery.ajax({
type: "post",
data: form.serialize(),
url: form.attr('action'),
timeout: 25000,
success: function(r) {
$('#result').html(r);
submit.val(submit_val);
submit.attr("disabled", false);
},
error: function() {
$('#result').html('<p>There was an error retrieving results. Please try again.</p>');
submit.val(submit_val);
submit.attr("disabled", false);
}
});
});
$('#content').click(function(e){
var element = $(e.target);
if (element.is('a') && element.parents('div.ajax_links').length == 1) {
e.preventDefault(); //Prevent the normal action
jQuery.ajax({
url: element.attr('href'),
timeout: 25000,
success: function(r) {
$('#result').html(r);
},
error: function() {
$('#result').html('<p>There was an error retrieving results. Please try again.</p>');
}
});
} else {
return;
}
});
$('.sync_select').change(function(e) {
var selected_value = this.value;
$('.sync_select[name='+this.name+']').each(function(e) {
this.value = selected_value;
});
});
$('.select_all').click(function(e) {
var check = this.innerHTML == 'Select All' ? true : false;
$('.select_all').each(function() {
this.innerHTML = check ? 'Select None' : 'Select All';
});
$('.toggle:checkbox').each(function() {
this.checked = check;
});
return false;
});
$('.menu_accordion li.sub_menu').click(function() {
if ($(this).find('ul').is(":hidden")) {
$(this).find('ul').toggle();
$(this).siblings("li").find("ul").hide();
}
});
$('.menu_accordion li.sub_menu').has("ul li a.active").each(function() {
$(this).find('ul').show();
});
$('#filter_toggle').click(function(){
$('#filter_container').toggle('fast');
});
function loadTabCounts() {
var tabs = [];
$('.tab_counts a:not(.active)').each(function() {
if (this.id) {
tabs.push(this.id);
// Add a spinner
$(this).append('<span class="updating"></span>');
}
});
if (tabs.length > 0) {
var base = FACILITY_PATH;
var active_tab = $('#main_navigation .active').attr('id')
if (active_tab.indexOf('reservations') > -1) {
base += '/reservations/';
} else if (active_tab.indexOf('orders') > -1) {
base += '/orders/';
}
$.ajax({
url: base + 'tab_counts',
dataType: 'json',
data: { tabs: tabs },
success: function(data, textStatus, xhr) {
for (i in tabs) {
$('.tab_counts').find('a#' + tabs[i] + ' .updating').text("(" + data[tabs[i]] + ")").removeClass('updating').addClass('updated');
}
}
});
}
};
//loadTabCounts();
$("fieldset.collapsable").each(function() {
$this = $(this);
$this.find("> :not(legend)").toggle(!$this.hasClass("collapsed"));
$this.enableDisableFields = function() {
this.find("input, select").prop('disabled', $this.hasClass('collapsed'));
}
$this.enableDisableFields();
$this.find("legend").click(function() {
// $this is still the fieldset, but 'this' is legend
$this.toggleClass("collapsed").find("> :not(legend)").slideToggle();
$this.enableDisableFields();
});
});
});
String.prototype.endsWith = function(suffix) {
return this.indexOf(suffix, this.length - suffix.length) !== -1;
};
|
JavaScript
| 0 |
@@ -3426,18 +3426,16 @@
%0A %7D;%0A
-//
loadTabC
|
9410b498a23052f68a5cee2b7a2599ecba12c421
|
use environment variables as base URLs
|
react-components/oodt_opsui_sample_app/src/constants/connection.js
|
react-components/oodt_opsui_sample_app/src/constants/connection.js
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import axios from "axios";
export const fmconnection = axios.create({
baseURL: "http://localhost:8080/cas_product_war/jaxrs/v2"
});
export const wmconnection = axios.create({
baseURL: "http://localhost:8080/workflow_services_war/wmservice/v2"
});
|
JavaScript
| 0.000003 |
@@ -881,56 +881,45 @@
RL:
-%22http://localhost:8080/cas_product_war/jaxrs/v2%22
+process.env.REACT_APP_FM_REST_API_URL
%0A%7D);
@@ -980,66 +980,46 @@
RL:
-%22http://localhost:8080/workflow_services_war/wmservice/v2%22
+process.env.REACT_APP_WM_REST_API_URL
%0A%7D);
+%0A
|
b65a63eb436b1a09b5e586b46dbcc9110e874d50
|
rename serializable tests
|
test/models/concerns/serializable.js
|
test/models/concerns/serializable.js
|
'use strict';
let _ = require('lodash');
module.exports = function(factoryName) {
return function(opts={}) {
describe('#serialize', () => {
context(`with ${factoryName} factory`, () => {
let params, model, serialized;
beforeEach(() => {
model = factory.buildSync(factoryName);
return model.save().then(() => {
params = { baseUrl: random.string() };
serialized = model.serialize(params);
});
});
it(`removes ${opts.omit || 'nothing'} and
add ${opts.merge || 'nothing'}`, () => {
let expected = _(model.toJSON())
.omit(opts.omit || {})
.merge(opts.merge || {})
.value();
expect(_.omit(serialized, 'links')).to.deep.equal(expected);
});
if (!!opts.links) {
opts.links.forEach(link => {
it(`add link to ${link}`, () => {
let expected = {};
expected[link] = `${params.baseUrl}/${model.id}/${link}`;
expect(serialized.links[link]).to.deep.equal(expected[link]);
});
});
}
});
});
};
};
|
JavaScript
| 0.000006 |
@@ -175,24 +175,16 @@
oryName%7D
- factory
%60, () =%3E
@@ -892,16 +892,18 @@
it(%60add
+a
link to
|
fbf1c83e2fce602a7c7d19ac78372309b6b86be7
|
Fix exception for 'load' on jQuery 1.8 and above
|
script.js
|
script.js
|
/**
* Script for AutoTabber
* Handles Tab Keypress
* @author MarcosBL <[email protected]>
*/
/* DOKUWIKI:include taboverride.js */
/* DOKUWIKI:include taboverride.escape.js */
jQuery(window).load(function(){
var textareas = document.getElementsByTagName('textarea');
tabOverride.set(textareas).tabSize(0).autoIndent(true).escape(true);
});
|
JavaScript
| 0 |
@@ -192,13 +192,19 @@
ow).
+on('
load
-(
+',
func
|
b82d0e6d5399049f517e68e8fe9790148c69139e
|
Add working directory is not clean test
|
__tests__/lib/index-test.js
|
__tests__/lib/index-test.js
|
const gitPick = require('../../lib/');
const git = require('../../lib/git');
const shell = require('../../lib/shell');
describe('index.js', () => {
describe('function exec()', () => {
beforeEach(() => {
git.isAvailable = jest.fn(() => true);
git.isCommitAvailable = jest.fn(() => true);
git.isWorkingDirectoryClean = jest.fn(() => true);
git.getRootDirectoryPath = jest.fn(() => '/Users/Daniel/Projects/git-pick');
git.getCurrentBranch = jest.fn(() => 'master');
git.checkout = jest.fn();
git.isCommitMergeable = jest.fn(() => true);
git.cherryPick = jest.fn();
git.push = jest.fn();
shell.cd = jest.fn();
shell.succeed = jest.fn();
gitPick('1234abc', ['branch1', 'branch2', 'branch3']);
});
it('to be called git.isAvailable', () => {
expect(git.isAvailable).toHaveBeenCalledTimes(1);
});
it('to be called git.isCommitAvailable', () => {
expect(git.isCommitAvailable).toHaveBeenCalledTimes(1);
});
it('to be called git.isCommitAvailable with "1234abc"', () => {
expect(git.isCommitAvailable).toBeCalledWith('1234abc');
});
it('to be called git.isWorkingDirectoryClean', () => {
expect(git.isWorkingDirectoryClean).toHaveBeenCalledTimes(1);
});
it('to be called git.getRootDirectoryPath', () => {
expect(git.getRootDirectoryPath).toHaveBeenCalledTimes(1);
});
it('to be called git.getCurrentBranch', () => {
expect(git.getCurrentBranch).toHaveBeenCalledTimes(1);
});
it('to be called git.checkout', () => {
expect(git.checkout).toHaveBeenCalledTimes(4);
});
it('to be called git.isCommitMergeable', () => {
expect(git.isCommitMergeable).toHaveBeenCalledTimes(3);
});
it('to be called git.isCommitMergeable with "1234abc"', () => {
expect(git.isCommitMergeable).toBeCalledWith('1234abc');
});
it('to be called git.cherryPick', () => {
expect(git.cherryPick).toHaveBeenCalledTimes(3);
});
it('to be called git.cherryPick with "1234abc"', () => {
expect(git.cherryPick).toBeCalledWith('1234abc');
});
it('to be called git.push', () => {
expect(git.push).toHaveBeenCalledTimes(3);
});
it('to be called shell', () => {
expect(shell.succeed).toHaveBeenCalledTimes(3);
});
});
describe('git not available', () => {
beforeEach(() => {
git.isAvailable = jest.fn(() => false);
shell.stop = jest.fn();
gitPick('1234abc', ['branch1']);
});
it('to be called git.isAvailable', () => {
expect(git.isAvailable).toHaveBeenCalledTimes(1);
});
it('to be called shell.stop', () => {
expect(shell.stop).toHaveBeenCalledTimes(1);
});
it('to be called shell.stop with "git-pick requires git"', () => {
expect(shell.stop).toBeCalledWith('git-pick requires git');
});
});
describe('Commit does not exist', () => {
beforeEach(() => {
git.isAvailable = jest.fn(() => true);
git.isCommitAvailable = jest.fn(() => false);
shell.stop = jest.fn();
gitPick('1234abc', ['branch1']);
});
it('to be called git.isCommitAvailable', () => {
expect(git.isCommitAvailable).toHaveBeenCalledTimes(1);
});
it('to be called shell.stop', () => {
expect(shell.stop).toHaveBeenCalledTimes(1);
});
it('to be called shell.stop with "Commit does not exist"', () => {
expect(shell.stop).toBeCalledWith('Commit does not exist');
});
});
});
|
JavaScript
| 0.000618 |
@@ -3518,13 +3518,730 @@
);%0A %7D);
+%0A%0A describe('Working directory is not clean', () =%3E %7B%0A beforeEach(() =%3E %7B%0A git.isAvailable = jest.fn(() =%3E true);%0A git.isCommitAvailable = jest.fn(() =%3E true);%0A git.isWorkingDirectoryClean = jest.fn(() =%3E false);%0A shell.stop = jest.fn();%0A%0A gitPick('1234abc', %5B'branch1'%5D);%0A %7D);%0A%0A it('to be called git.isWorkingDirectoryClean', () =%3E %7B%0A expect(git.isWorkingDirectoryClean).toHaveBeenCalledTimes(1);%0A %7D);%0A%0A it('to be called shell.stop', () =%3E %7B%0A expect(shell.stop).toHaveBeenCalledTimes(1);%0A %7D);%0A%0A it('to be called shell.stop with %22Working directory is not clean%22', () =%3E %7B%0A expect(shell.stop).toBeCalledWith('Working directory is not clean');%0A %7D);%0A %7D);
%0A%7D);%0A
|
86e06634bcdfd8d5dc99817fe77783d7bfd4e224
|
update front: to work /top
|
frontend/main.js
|
frontend/main.js
|
(function() {
'use strict';
var source_data = [
{'id': 'some',
'value': 'some-some-some'},
{'id': 'any',
'value': 'any-any-any'},
{'id': 'alt',
'value': 'alt-alt-alt'},
];
var config = angular.module('front', ['ngRoute', 'ctls', 'servs', 'filters']),
ctls = angular.module('ctls', []),
servs = angular.module('servs', ['ngResource']),
filters = angular.module('filters', []);
config.config([
'$routeProvider',
function($routeProvider) {
$routeProvider
.when('/top', {
controller: 'TopController',
templateUrl: '/partial/top.html'
})
.when('/top/some/:someId', {
controller: 'DetailController',
templateUrl: '/partial/detail.html'
})
.otherwise({
redirectTo: '/top'
});
}]);
ctls.controller('TopController', [
'$scope', 'Products',
function($scope, Products) {
Products
.query_all()
.$promise
.then(function(data) {
var keys = Object.keys(data).sort();
$scope.items = [];
for(var i = 0; i < keys.length; i++) {
$scope.items.push({
'name': data[keys[i]]['name'],
'price': data[keys[i]]['price']});
}
});
$scope.addItem = function(itemKey, itemValue) {
$scope.items.push({'name': itemKey, 'price': itemValue});
};
}]);
ctls.controller('DetailController', [
'$scope', '$routeParams',
function($scope, $routeParams) {
$scope.someId = $routeParams.someId;
$scope.someValue = '';
for (var i = 0; i < source_data.length; i++) {
if (source_data[i].id === $scope.someId) {
$scope.someValue = source_data[i].value;
break;
}
}
$scope.someClick = function(msg) {
alert(msg);
};
}]);
servs.factory('Products', [
'$resource',
function($resource) {
return $resource('http://localhost:8080/products', {}, {
query_all: {
method: 'GET',
isArray: true,
transformResponse: function(data, headersGetter) {
var json_data = angular.fromJson(data),
keys = Object.keys(json_data).sort(),
lst = [];
for (var i = 0; i < keys.length; i++) {
lst.push(json_data[keys[i]]);
}
return lst;
}}
});
}]);
filters.filter(
'tohage',
function() {
return function(input) {
return input === 'some-some-some' ? 'hage-hage-hage' : input;
};
});
})();
|
JavaScript
| 0 |
@@ -1002,54 +1002,8 @@
) %7B%0A
- var keys = Object.keys(data).sort();%0A
@@ -1038,16 +1038,17 @@
for
+
(var i =
@@ -1047,36 +1047,36 @@
(var i = 0; i %3C
-keys
+data
.length; i++) %7B%0A
@@ -1132,23 +1132,17 @@
': data%5B
-keys%5Bi%5D
+i
%5D%5B'name'
@@ -1171,23 +1171,17 @@
': data%5B
-keys%5Bi%5D
+i
%5D%5B'price
|
9c720435df559d1e09c14ea96daa7a04918cf06b
|
Refactor code to use ES6 syntax.
|
src/simple-segment-aggregation.js
|
src/simple-segment-aggregation.js
|
import _ from 'underscore';
var SimpleSegmentAggregation = {
// Segment an array of events by scale
aggregate: function(group, scale, options) {
scale = scale || 'weeks';
options = options || {};
_.defaults(options, {
idAttribute: 'id'
});
var aggregates = [];
if (!group || !group.length) {
return aggregates;
}
var prevIds,
currentIds,
i = 0,
intersect,
sameLength,
allEvents,
continuesBackward;
_.each(group, function(g, index) {
currentIds = _.pluck(g.events, options.idAttribute);
continuesBackward = false;
if (index) {
// Whether the contents have the same length
sameLength = currentIds.length === prevIds.length;
intersect = _.intersection(currentIds, prevIds);
// Whether the events in the current list are all contained within the last
allEvents = intersect.length === currentIds.length;
// This means that they occupy the same aggregate
if (sameLength && allEvents) {
aggregates[i].duration++;
}
// Otherwise, we need to make a new aggregate
else {
i++;
if (intersect.length) {
aggregates[i - 1].continuesForward = true;
continuesBackward = true;
}
}
}
// The algorithm is pessimistic. Assume that the
// block does not extend forward. Subsequent
// iterations disprove, and modify, the assumption
if (!aggregates[i]) {
aggregates[i] = {
events: _.clone(g.events),
start: +g.timestamp,
duration: 1,
continuesForward: false,
continuesBackward: continuesBackward
};
}
prevIds = currentIds;
});
return aggregates;
}
};
export default SimpleSegmentAggregation;
|
JavaScript
| 0 |
@@ -112,18 +112,8 @@
gate
-: function
(gro
@@ -493,16 +493,8 @@
up,
-function
(g,
@@ -495,24 +495,27 @@
, (g, index)
+ =%3E
%7B%0A cur
|
64f62ceb5496317aa5246b9c67e3667a31ac2d3e
|
isMulti可以不传,默认为false
|
bpmcenter/WebContent/js/select.js
|
bpmcenter/WebContent/js/select.js
|
/**
* 所有HTML选人界面的控制层
* @param type 选择界面类型
* @param isMulti 是否多选
* @returns 选择的List<Map>
*/
function FixSelect(obj){
//var that = arguments[arguments.length-1];
var rv = null;
var w = obj.width||"800px";
var h = obj.height||"600px";
switch(obj.type){
case "user":
rv = window.showModalDialog("FlowCenter?action=selectUserList&isMulti="+obj.isMulti,null,"dialogWidth="+w+";dialogHeight="+h);
break;
case "node":
rv = window.showModalDialog("FlowCenter?action=selectNodeList&taskId="+obj.taskId,null,"dialogWidth="+w+";dialogHeight="+h);
break;
case "step":
rv = window.showModalDialog("FlowCenter?action=selectStepList&taskId="+obj.taskId,null,"dialogWidth="+w+";dialogHeight="+h);
break;
default:
break;
}
return rv;
};
|
JavaScript
| 0.999846 |
@@ -245,16 +245,54 @@
00px%22;%0D%0A
+%09var isMulti = obj.isMulti%7C%7C%22false%22;%0D%0A
%09switch(
@@ -394,20 +394,16 @@
Multi=%22+
-obj.
isMulti,
|
3225fa2c3b67edb6955f74e01272b62751733790
|
bump phase change hps up by 1%
|
ui/raidboss/data/triggers/unending_coil_ultimate.js
|
ui/raidboss/data/triggers/unending_coil_ultimate.js
|
// UCU - The Unending Coil Of Bahamut (Ultimate)
[{
// TODO: Zone name is empty string for now lol?
zoneRegex: /(The Unending Coil Of Bahamut \(Ultimate\)|^$)/,
triggers: [
// --- State ---
{
regex: /:(y{Name}) gains the effect of Firescorched/,
condition: function(data, matches) { return data.me == matches[1]; },
run: function(data) { data.fireDebuff = true; },
},
{
regex: /:(y{Name}) loses the effect of Firescorched/,
condition: function(data, matches) { return data.me == matches[1]; },
run: function(data) { data.fireDebuff = false; },
},
{
regex: /:(y{Name}) gains the effect of Icebitten/,
condition: function(data, matches) { return data.me == matches[1]; },
run: function(data) { data.iceDebuff = true; },
},
{
regex: /:(y{Name}) loses the effect of Icebitten/,
condition: function(data, matches) { return data.me == matches[1]; },
run: function(data) { data.iceDebuff = false; },
},
// --- Twintania ---
{ id: 'UCU Twisters',
regex: /:26AA:Twintania starts using/,
alertText: function(data) {
return 'Twisters';
},
},
{ id: 'UCU Death Sentence',
regex: /:Twintania readies Death Sentence/,
alertText: function(data, matches) {
if (data.role == 'tank' || data.role == 'healer')
return 'Death Sentence';
},
},
{ id: 'UCU Fireball Marker',
regex: /1B:........:(\y{Name}):....:....:0075:0000:0000:0000:/,
infoText: function(data, matches) {
if (data.me != matches[1])
return 'fireball on ' + matches[1];
},
alertText: function(data, matches) {
if (data.me == matches[1])
return 'fireball on YOU';
},
},
{ id: 'UCU Hatch Marker',
regex: /1B:........:(\y{Name}):....:....:0076:0000:0000:0000:/,
infoText: function(data, matches) {
if (data.me != matches[1])
return 'hatch on ' + matches[1];
},
alarmText: function(data, matches) {
if (data.me == matches[1])
return 'hatch on YOU';
},
},
{ id: 'UCU Twintania P2',
regex: /:Twintania HP at 74%/,
sound: 'Long',
infoText: function(data, matches) {
return "Phase 2 Push";
},
},
{ id: 'UCU Twintania P3',
regex: /:Twintania HP at 44%/,
sound: 'Long',
infoText: function(data, matches) {
return "Phase 3 Push";
},
},
// --- Nael ---
{ id: 'UCU Nael Quote 1',
regex: /From on high I descend, in blessed light to bask/,
alertText: function(data) { return "spread => in"; },
},
{ id: 'UCU Nael Quote 2',
regex: /From on high I descend, mine enemies to smite/,
alertText: function(data) { return "spread => out"; },
},
{ id: 'UCU Nael Quote 3',
regex: /refulgent moon, shine down your light/,
alertText: function(data) { return "stack => in"; },
},
{ id: 'UCU Nael Quote 4',
regex: /Blazing path, lead me to conquest/,
alertText: function(data) { return "stack => out"; },
},
{ id: 'UCU Nael Quote 5',
regex: /red moon, scorch mine enemies/,
alertText: function(data) { return "in => stack"; },
},
{ id: 'UCU Nael Quote 6',
regex: /red moon, shine the path to conquest/,
alertText: function(data) { return "in => out"; },
},
{ id: 'UCU Nael Quote 7',
regex: /Fleeting light, score the earth with a fiery kiss/,
alertText: function(data) { return "away from MT => stack"; },
},
{ id: 'UCU Nael Quote 8',
regex: /Fleeting light, outshine the starts for the moon/,
alertText: function(data) { return "spread => away from MT"; },
},
{ id: 'UCU Nael Thunderstruck',
// Note: The 0A event happens before "gains the effect" and "starts
// casting on" only includes one person.
regex: /:Thunderwing:26C7:.*?:........:(\y{Name}):/,
condition: function(data, matches) { return data.me == matches[1]; },
alarmText: function(data) { return "Thunder on YOU"; },
},
{ id: 'UCU Nael Doom',
regex: /:(\y{Name}) gains the effect of Doom from .*? for ([0-9.]+) Seconds/,
condition: function(data, matches) { return data.me == matches[1]; },
alarmText: function(data) {
if (parseFloat(matches[2]) == 6)
return "Doom #1 on YOU";
if (parseFloat(matches[2]) == 11)
return "Doom #2 on YOU";
if (parseFloat(matches[2]) == 16)
return "Doom #3 on YOU";
// TODO: remove this catchall once times are better known.
return "Doom: " + parseFloat(matches[2]) + " seconds on you";
// TODO: call out all doom people
// TODO: reminder to clear at the right time
},
},
// TODO: fire callouts
// (1) if you have tether (is there a 1B mark??)< whether in or out
// (2) if you have fire (to stay out), if you have ice (to get in)
// TODO: cauterize markers
// TODO: cauterize placement from dragons
]
}]
|
JavaScript
| 0 |
@@ -2194,17 +2194,17 @@
HP at 7
-4
+5
%25/,%0A
@@ -2371,17 +2371,17 @@
HP at 4
-4
+5
%25/,%0A
|
5658492475eb633bd69a6afdccb1b52c5d28e259
|
fix bug
|
javascripts/admin.js
|
javascripts/admin.js
|
$(function() {
Parse.$ = jQuery;
// Replace this line with the one on your Quickstart Guide Page
Parse.initialize("G8cXsz7Z2PCMYbyKMRubHvk6BAgEYci2oYNMSUmm", "ovq6mqOtamFGGldOIKJXQLHLisXb3Z1sm1QpHObU");
var LoginView = Parse.View.extend({
template: Handlebars.compile($('#login-tpl').html()),
events: {
'submit .form-signin': 'login'
},
login: function(e) {
// Prevent Default Submit Event
e.preventDefault();
// Get data from the form and put them into variables
var data = $(e.target).serializeArray(),
username = data[0].value,
password = data[1].value;
// Call Parse Login function with those variables
Parse.User.logIn(username, password, {
// If the username and password matches
success: function(user) {
var welcomeView = new WelcomeView({ model: user });
welcomeView.render();
$('.main-container').html(welcomeView.el);
},
// If there is an error
error: function(user, error) {
console.log(error);
}
});
},
render: function(){
this.$el.html(this.template());
}
});
var loginView = new LoginView();
loginView.render();
$('.main-container').html(loginView.el);
});
|
JavaScript
| 0.000001 |
@@ -709,24 +709,96 @@
value;%0A
+ console.log(username);%0A console.log(password);
%0A
@@ -993,24 +993,74 @@
ion(user) %7B%0A
+ console.log(%22success login%22);%0A
|
453e27bcee01584daac3747a60ec6b54ee18a568
|
Update url
|
tests/util/shared.js
|
tests/util/shared.js
|
var restify = require('restify');
var knex = require('knex')({
client: 'mysql',
connection: {
host : '127.0.0.1',
user : 'root',
password : 'root',
database : 'brestful_test',
charset : 'utf8'
}
});
var bookshelf = require('bookshelf')(knex);
var server = restify.createServer({
name: 'TestApp'
});
exports.server = server;
exports.bookshelf = bookshelf;
exports.knex = knex;
exports.createServer = function() {
return restify.createServer({
name: 'TestApp'
});
};
exports.client = restify.createJSONClient({
url: 'http://localhost:5000'
});
|
JavaScript
| 0.000001 |
@@ -577,11 +577,11 @@
ost:
-500
+808
0'%0A%7D
|
45d069be9a62bb61d68d855e5f8930eafbe033f8
|
Fix notificatin of connections
|
lib/abstract.js
|
lib/abstract.js
|
'use strict';
const EventHandler = require('@scola/events');
class AbstractModel extends EventHandler {
constructor() {
super();
this.messenger = null;
this.validator = null;
this.meta = {};
this.values = {};
this.connections = new Map();
}
getName() {
throw new Error('not_implemented');
}
getQualifiedName(postfix) {
return this.getName() + (postfix ? '.' + postfix : '');
}
getMessenger() {
return this.messenger;
}
setMessenger(messenger) {
this.messenger = messenger;
this.addHandlers();
return this;
}
getValidator() {
return this.validator;
}
setValidator(validator) {
this.validator = validator;
return this;
}
getMeta() {
return this.meta;
}
setMeta(meta) {
this.meta = meta;
return this;
}
destroy() {
this.removeHandlers();
this.messenger.deleteModel(this);
return this;
}
addHandlers() {
this.bindListener(
this.getQualifiedName('change'),
this.messenger,
this.change
);
return this;
}
removeHandlers() {
this.unbindListener(
this.getQualifiedName('change'),
this.messenger,
this.change
);
return this;
}
bind(event) {
this.connections.set(
event.connection.getId(),
event.message.getHead()
);
return this;
}
unbind(event) {
this.connections.delete(event.connection.getId());
if (this.connections.size === 0) {
this.destroy();
}
return this;
}
authorize() {}
validate() {}
select() {
throw new Error('not_implemented');
}
insert() {
throw new Error('not_implemented');
}
update() {
throw new Error('not_implemented');
}
delete() {
throw new Error('not_implemented');
}
change() {}
get(name) {
return this.values[name];
}
set(name, value) {
this.values[name] = value;
return this;
}
getAll() {
return this.values;
}
setAll(values) {
Object.assign(this.values, values);
return this;
}
isSet() {
return Object.keys(this.values).length > 0;
}
notifySender(method, data, event) {
const message = event.message.clone().setMasked(false).setBody({
data,
method
});
this.messenger.send(message);
return this;
}
notifyModels(method, data) {
this.messenger.emit(this.getQualifiedName('change'), {
data,
method,
model: this
});
return this;
}
notifyConnections(data) {
if (this.connections.size === 0) {
return this;
}
const message = this.messenger
.createMessage()
.setBody({
data,
method: 'change'
})
.encode()
.then((message) => {
this.connections.forEach((head) => {
this.messenger.send(message.clone().setHead(head));
});
});
return this;
}
getIdentifier() {
let identifier = {};
if (this.meta.id) {
identifier = {
id: this.meta.id
};
} else if (this.meta.filter) {
identifier = {
filter: this.meta.filter || {},
order: this.meta.order || {}
};
}
return this.getQualifiedName(JSON.stringify(identifier));
}
}
module.exports = AbstractModel;
|
JavaScript
| 0.000036 |
@@ -2572,32 +2572,16 @@
%7D%0A%0A
- const message =
this.me
@@ -2838,16 +2838,118 @@
%7D);%0A
+ %7D)%0A .catch((error) =%3E %7B%0A this.messenger.emit('error', %7B%0A error%0A %7D);%0A
%7D)
|
396a996b4c49e3230fea28590bcebeeb461b4622
|
Use console.warn instead of console.error
|
backend/app/assets/javascripts/spree/backend/translation.js
|
backend/app/assets/javascripts/spree/backend/translation.js
|
(function() {
// Resolves string keys with dots in a deeply nested object
// http://stackoverflow.com/a/22129960/4405214
var resolveObject = function(path, obj) {
return path
.split('.')
.reduce(function(prev, curr) {
return prev && prev[curr];
}, obj || self);
}
Spree.t = function(key, options) {
options = (options || {});
if(options.scope) {
key = options.scope + "." + key;
}
var translation = resolveObject(key, Spree.translations);
if (translation) {
return translation;
} else {
console.error("No translation found for " + key + ".");
return key;
}
}
Spree.human_attribute_name = function(model, attr) {
return Spree.t("activerecord.attributes." + model + '.' + attr);
}
})();
|
JavaScript
| 0.000151 |
@@ -575,13 +575,12 @@
ole.
-error
+warn
(%22No
|
551a1514dc415aa127a95267c3a3e583586331ee
|
fix bad test
|
frameworks/foundation/tests/debug/control_test_pane/ui.js
|
frameworks/foundation/tests/debug/control_test_pane/ui.js
|
// ==========================================================================
// Project: SproutCore - JavaScript Application Framework
// Copyright: ©2006-2009 Sprout Systems, Inc. and contributors.
// portions copyright @2009 Apple, Inc.
// License: Licened under MIT license (see license.js)
// ==========================================================================
/*global module test htmlbody ok equals same stop start */
(function() {
// var content = []
// for (var idx=0, len=20; idx<len; ++idx) {
// content.push(SC.Record.create({
// id: 'item_'+idx,
// title: 'Item ' + idx
// }))
// }
//
// var singleSelection = [content[0]];
// var multiSelectionContiguous = [content[0], content[1], content[2]];
// var multiSelectionDiscontiguous = [content[0], content[2], content[4]];
//
// var pane = SC.ControlTestPane.design({ height: 100 })
// .add("basic", SC.ListView, {
// content: content,
// contentValueKey: 'title'
// })
//
// .add("disabled", SC.ListView, {
// isEnabled: NO,
// content: content,
// contentValueKey: 'title'
// })
//
// .add("disabled - single selection", SC.ListView, {
// isEnabled: NO,
// content: content,
// contentValueKey: 'title',
// selection: singleSelection
// })
//
// .add("single selection", SC.ListView, {
// content: content,
// contentValueKey: 'title',
// selection: singleSelection
// })
//
// .add("multiple selection, contiguous", SC.ListView, {
// content: content,
// contentValueKey: 'title',
// selection: multiSelectionContiguous
// })
//
// .add("multiple selection, discontiguous", SC.ListView, {
// content: content,
// contentValueKey: 'title',
// selection: multiSelectionDiscontiguous
// })
//
// pane.show(); // add a test to show the test pane
// ..........................................................
// TEST PANE
//
module('SC.ControlTestPane UI');
test("showing/removing a pane", function() {
var pane = SC.ControlTestPane.design() ;
pane = pane.create() ;
ok(pane.$().hasClass('sc-control-test-pane'), 'should have class sc-control-test-pane');
ok(pane.get('isVisible'), 'control test pane should be visible after we create it');
ok(pane.get('isVisibleInWindow'), 'control tast pane should be visible in the window after we create it');
pane.remove() ;
ok(!pane.get('isVisible'), 'control test pane should NOT be visible after we remove it');
ok(!pane.get('isVisibleInWindow'), 'control tast pane should NOT be visible in the window after we remove it');
});
test("adding named children to the pane", function() {
var pane = SC.ControlTestPane.design() ;
pane.add('first', SC.View) ;
pane.add('second', SC.View) ;
pane.add('third', SC.View) ;
equals(pane.prototype.childViews.length, 6, 'control test pane has correct number of children before create') ;
pane = pane.create() ;
equals(pane.getPath('childViews.length'), 6, 'control test pane has correct number of children after create') ;
var childViews = pane.get('childViews') ;
var firstLabel = childViews[0] ;
equals(firstLabel.$().text(), 'first:', 'first label should be correct') ;
var secondLabel = childViews[2] ;
equals(secondLabel.$().text(), 'second:', 'second label should be correct') ;
var thirdLabel = childViews[4] ;
equals(thirdLabel.$().text(), 'third:', 'third label should be correct') ;
var paneLayer = pane.get('layer') ;
for (var idx=0, len=6; idx<len; ++idx) {
var view = childViews[idx] ;
var layer = view.get('layer') ;
equals(layer.parentNode.parentNode, paneLayer, 'control test pane childView has layer with correct parentNode');
}
// pane.remove() ;
});
})();
|
JavaScript
| 0.003293 |
@@ -2531,33 +2531,32 @@
) ;%0A %0A ok(
-!
pane.get('isVisi
@@ -2577,35 +2577,37 @@
l test pane
+still
should
-NOT
be visible a
|
f35cf8185b542d39293dbb35aa6e07dd18fcd668
|
Change usage of flag that was renamed.
|
packages/babel-runtime/scripts/build-dist.js
|
packages/babel-runtime/scripts/build-dist.js
|
"use strict";
const outputFile = require("output-file-sync");
const coreDefinitions = require("babel-plugin-transform-runtime").definitions;
const helpers = require("babel-helpers");
const babel = require("../../babel-core");
const t = require("../../babel-types");
const paths = ["is-iterable", "get-iterator"];
Object.keys(coreDefinitions.builtins).forEach((key) => {
const path = coreDefinitions.builtins[key];
paths.push(path);
});
Object.keys(coreDefinitions.methods).forEach((key) => {
const props = coreDefinitions.methods[key];
Object.keys(props).forEach((key2) => {
const path = props[key2];
paths.push(path);
});
});
paths.forEach(function(path) {
writeFile(
"core-js/" + path + ".js",
defaultify(`require("core-js/library/fn/${path}")`)
);
});
function relative(filename) {
return `${__dirname}/../${filename}`;
}
function defaultify(name) {
return `module.exports = { "default": ${name}, __esModule: true };`;
}
function writeRootFile(filename, content) {
filename = relative(filename);
//console.log(filename);
outputFile(filename, content);
}
function writeFile(filename, content) {
return writeRootFile(filename, content);
}
function makeTransformOpts(modules, useBuiltIns) {
const opts = {
presets: [[require("../../babel-preset-es2015"), { modules: false }]],
plugins: [
[
require("../../babel-plugin-transform-runtime"),
{ useBuiltIns, useESModules: modules === false },
],
],
};
if (modules === "commonjs") {
opts.plugins.push([
require("../../babel-plugin-transform-es2015-modules-commonjs"),
{ loose: true, strict: false },
]);
} else if (modules !== false) {
throw new Error("Unsupported module type");
}
return opts;
}
function buildRuntimeRewritePlugin(relativePath, helperName) {
return {
pre(file) {
const original = file.get("helperGenerator");
file.set("helperGenerator", (name) => {
// make sure that helpers won't insert circular references to themselves
if (name === helperName) return false;
return original(name);
});
},
visitor: {
ImportDeclaration(path) {
path.get("source").node.value = path
.get("source")
.node.value.replace(/^babel-runtime/, relativePath);
},
CallExpression(path) {
if (
!path.get("callee").isIdentifier({ name: "require" }) ||
path.get("arguments").length !== 1 ||
!path.get("arguments")[0].isStringLiteral()
) {
return;
}
// replace any reference to babel-runtime with a relative path
path.get("arguments")[0].node.value = path
.get("arguments")[0]
.node.value.replace(/^babel-runtime/, relativePath);
},
},
};
}
function buildHelper(helperName, modules, useBuiltIns) {
const tree = t.program(helpers.get(helperName).nodes);
const transformOpts = makeTransformOpts(modules, useBuiltIns);
const relative = useBuiltIns ? "../.." : "..";
return babel.transformFromAst(tree, null, {
presets: transformOpts.presets,
plugins: transformOpts.plugins.concat([
buildRuntimeRewritePlugin(
modules === false ? `../${relative}` : relative,
helperName
),
]),
}).code;
}
for (const modules of ["commonjs", false]) {
for (const builtin of [false, true]) {
const dirname = `helpers/${builtin ? "builtin/" : ""}${!modules ? "es6/" : ""}`;
for (const helperName of helpers.list) {
writeFile(
`${dirname}${helperName}.js`,
buildHelper(helperName, modules, builtin)
);
}
}
}
|
JavaScript
| 0 |
@@ -1642,16 +1642,20 @@
, strict
+Mode
: false
|
131aafe66d52064d8f76f5a1900be53a604fc5dd
|
Remove autoselect dropdown
|
assets/javascripts/modules/conditional-subfields.js
|
assets/javascripts/modules/conditional-subfields.js
|
/**
* Conditional sub fields
*
* Supports the ability to conditionally show and hide content based on the
* value of a field.
*
* The element to be shown requires 2 attributes:
* [data-controlled-by] - this is the name of the field which controls it
* [data-control-value] - the value by which this element should be displayed
* Can include multiple control values using `||` to
* separate each value
*
* It also requires a basic bit of style to work:
*
* [data-controlled-by] {
* display: none;
* }
* [data-controlled-by].is-active {
* display: block;
* }
*
* Note: it is recommend to only apply this if javascript is enabled
*
* @example
*
* <label>
* <input name="control-field" value="yes" type="radio">Yes
* </label>
* <label>
* <input name="control-field" value="no" type="radio">No
* </label>
*
* <div class="js-ConditionalSubfield" data-controlled-by="control-field" data-control-value="yes">
* Visible when `control-field` equals `yes`
* </div>
*
*/
const uniq = require('lodash/uniq')
const includes = require('lodash/includes')
const { addClass, removeClass } = require('../lib/helpers')
const ConditionalSubfields = {
selector: 'js-ConditionalSubfield',
activeClass: 'is-active',
onChangeHandler: null,
controllers: [],
wrapper: null,
init (wrapper = document) {
this.wrapper = wrapper
this.cacheEls()
if (this.controllers.length) {
this.bindEvents()
this.render()
}
},
cacheEls () {
const conditionalSubFields = this.wrapper.getElementsByClassName(this.selector)
this.onChangeHandler = this.onChange.bind(this)
this.controllers = uniq([...conditionalSubFields].map((controller, i) => {
return controller.getAttribute('data-controlled-by')
}))
},
bindEvents () {
this.wrapper.addEventListener('change', this.onChangeHandler)
},
render () {
this.controllers.forEach((controller) => {
const field = this.wrapper.querySelector(`[name="${controller}"]`)
this._handleField(field)
})
},
destroy () {
this.wrapper.removeEventListener('change', this.onChangeHandler)
},
onChange (evt) {
const field = evt.target
if (includes(this.controllers, field.name)) {
this._handleField(field)
}
},
_handleField (controlInput) {
if (!controlInput) {
return
}
const subFields = this.wrapper.querySelectorAll(`[data-controlled-by="${controlInput.name}"]`)
const tagName = controlInput.tagName
let controlInputValue
if (tagName === 'SELECT') {
controlInputValue = controlInput.value
} else if (tagName === 'INPUT') {
const type = controlInput.type
if (type === 'radio' || type === 'checkbox') {
const checked = this.wrapper.querySelector(`[name="${controlInput.name}"]:checked`)
controlInputValue = checked ? checked.value : null
} else {
controlInputValue = controlInput.value
}
}
Array.from(subFields).forEach((subField) => {
const values = (subField.getAttribute('data-control-value') + '').split('||')
let isVisible
isVisible = includes(values, controlInputValue)
this._toggleSubField(subField, isVisible)
})
},
_toggleSubField (subField, isVisible) {
if (isVisible) {
addClass(subField, this.activeClass)
} else {
removeClass(subField, this.activeClass)
}
subField.setAttribute('aria-expanded', isVisible)
subField.setAttribute('aria-hidden', !isVisible)
if (!isVisible && !subField.getAttribute('data-persist-values')) {
const children = subField.querySelectorAll('input, select, checkbox, textarea')
Array.from(children).forEach((field) => {
if (!field.getAttribute('data-persist-values')) {
if (['select', 'radio', 'checkbox'].indexOf(field.type) > -1) {
field.checked = false
} else {
// Auto selects first available option on dropdown if only 1 option with a non empty value is available
const isSingleOptionSelect = field.type === 'select-one' && field.options.length === 2 && field.options[0].value === ''
field.value = isSingleOptionSelect ? field.options[1].value : ''
}
}
const event = this.wrapper.createEvent('HTMLEvents')
event.initEvent('change', true, false)
field.dispatchEvent(event)
})
}
},
}
module.exports = ConditionalSubfields
|
JavaScript
| 0.000002 |
@@ -3958,317 +3958,21 @@
-// Auto selects first available option on dropdown if only 1 option with a non empty value is available%0A const isSingleOptionSelect = field.type === 'select-one' && field.options.length === 2 && field.options%5B0%5D.value === ''%0A field.value = isSingleOptionSelect ? field.options%5B1%5D.value :
+field.value =
''%0A
|
09c622e1baec419c16d36139f4e8abf916c68d1c
|
Refactor animate() context options
|
animation.js
|
animation.js
|
/* eslint-disable no-underscore-dangle */
/**
* @typedef {{
* ?easing: string|function(number):number,
* ?stopPrevious: boolean,
* ?duration: number,
* }} mojave.AnimationOptions
*
* @typedef {{
* currentFrame: ?number,
* easing: function(number):number,
* duration: number,
* ?stopPrevious: boolean,
* onAnimationFinished: function(),
* }} mojave.AnimationContext
*
* @typedef {{
* stop: function(),
* }|Promise} mojave.AnimationDirector
*/
import "./polyfill/promise";
import {getStyle, setStyles} from "./dom/css";
import {merge} from "./extend";
// taken from https://gist.github.com/gre/1650294
export const EASE_LINEAR = (t) => t;
export const EASE_IN_QUAD = (t) => t*t;
export const EASE_OUT_QUAD = (t) => t*(2-t);
export const EASE_IN_OUT_QUAD = (t) => t<.5 ? 2*t*t : -1+(4-2*t)*t;
export const EASE_IN_CUBIC = (t) => t*t*t;
export const EASE_OUT_CUBIC = (t) => (--t)*t*t+1;
export const EASE_IN_OUT_CUBIC = (t) => t<.5 ? 4*t*t*t : (t-1)*(2*t-2)*(2*t-2)+1;
export const EASE_IN_QUART = (t) => t*t*t*t;
export const EASE_OUT_QUART = (t) => 1-(--t)*t*t*t;
export const EASE_IN_OUT_QUART = (t) => t<.5 ? 8*t*t*t*t : 1-8*(--t)*t*t*t;
export const EASE_IN_QUINT = (t) => t*t*t*t*t;
export const EASE_OUT_QUINT = (t) => 1+(--t)*t*t*t*t;
export const EASE_IN_OUT_QUINT = (t) => t<.5 ? 16*t*t*t*t*t : 1+16*(--t)*t*t*t*t;
/**
* Animates to the given properties for the given element.
*
* @param {HTMLElement} element
* @param {Object.<string, *>} properties
* @param {mojave.AnimationOptions} options
* @return {mojave.AnimationDirector}
*/
export function animate (element, properties, options = {})
{
let values = null;
// stop previous animation by default
if (typeof options.stopPrevious === "undefined" || true === options.stopPrevious)
{
stopAnimation(element);
}
const director = animateCallback(
(progress) =>
{
if (null === values)
{
// if first run:
// - parse current properties
// - no update needed, as the progress is 0 in the first run
values = fetchPropertyValues(element, properties);
}
else
{
// consecutive runs
// - update values
applyAllInterpolatedValues(element, values, progress);
}
},
options
);
// store the director in the element that is currently animated
element._currentAnimation = director;
// register the done callback to remove the director from the element
const onDone = () => {
element._currentAnimation = null;
};
director.then(onDone, onDone);
// return the director
return director;
}
/**
* Runs an animation with a custom callback.
*
*
* @param {function(number)} callback
* @param {mojave.AnimationOptions} options
* @return {mojave.AnimationDirector}
*/
export function animateCallback (callback, options = {})
{
// Build animation director + promise
let onAnimationFinished, onAnimationAborted;
const animationDirector = new Promise((resolve, reject) => {
onAnimationFinished = resolve;
onAnimationAborted = reject;
});
// first set default options,
// then merge with given options,
// then merge with context-specific parameters
/** @type {mojave.AnimationContext} context */
const context = merge({
duration: 400,
easing: EASE_IN_OUT_CUBIC,
}, options, {
currentFrame: null,
onAnimationFinished: onAnimationFinished,
});
// register first animation frame
context.currentFrame = window.requestAnimationFrame(
(time) => runAnimationStep(time, time, callback, context)
);
// add stop() method to animation director (the context needs to be initialized)
animationDirector.stop = () =>
{
onAnimationAborted();
window.cancelAnimationFrame(context.currentFrame);
};
return animationDirector;
}
/**
* Runs a single animation step
*
* @param {number} time
* @param {number} start
* @param {function(number)} callback
* @param {mojave.AnimationContext} context
*/
function runAnimationStep (time, start, callback, context)
{
const linearProgress = Math.min(1, (time - start) / context.duration);
const easedProgress = context.easing(linearProgress);
callback(easedProgress);
if (linearProgress < 1)
{
context.currentFrame = window.requestAnimationFrame(
(time) => runAnimationStep(time, start, callback, context)
);
}
else
{
context.onAnimationFinished();
}
}
export function stopAnimation (element)
{
if (typeof element._currentAnimation !== "undefined" && element._currentAnimation !== null)
{
element._currentAnimation.stop();
element._currentAnimation = null;
}
}
/**
* Fetches the current values of all the given properties.
*
* @param {HTMLElement|Window} element
* @param {Object.<string, *>} properties
* @return {Object.<string, {start: number, delta: number}>}
*/
function fetchPropertyValues (element, properties)
{
const values = {};
for (const property in properties)
{
if (!properties.hasOwnProperty(property))
{
continue;
}
const start = getStyle(element, property);
values[property] = {
start: start,
delta: properties[property] - start,
};
}
return values;
}
/**
* First this function calculates the new interpolated value according to the current progress.
* Then all values are applied to the given element.
*
* @param {HTMLElement|Window} element
* @param {Object.<string, {start: number, delta: number}>} initialValues
* @param {number} progress
*/
function applyAllInterpolatedValues (element, initialValues, progress)
{
const updates = {};
for (const property in initialValues)
{
if (!initialValues.hasOwnProperty(property))
{
continue;
}
updates[property] = initialValues[property].start + (initialValues[property].delta * progress);
}
setStyles(element, updates);
}
|
JavaScript
| 0.000001 |
@@ -3036,249 +3036,8 @@
)%0A%7B%0A
- // Build animation director + promise%0A let onAnimationFinished, onAnimationAborted;%0A const animationDirector = new Promise((resolve, reject) =%3E %7B%0A onAnimationFinished = resolve;%0A onAnimationAborted = reject;%0A %7D);%0A%0A
@@ -3310,20 +3310,55 @@
ions
-, %7B
+);%0A
%0A
-
+// set internal parameters%0A context.
curr
@@ -3369,65 +3369,236 @@
rame
-:
+ =
null
-,
+;%0A
%0A
- onAnimationFinished: onAnimationFinished,
+// Build animation director + promise%0A let onAnimationAborted;%0A const animationDirector = new Promise((resolve, reject) =%3E %7B%0A context.onAnimationFinished = resolve;%0A onAnimationAborted = reject;
%0A
|
6272a1fa17ce31cb1a27ae1c7e76c63af7d1bc96
|
remove deprecated / unused JS function from lit-HTML
|
packages/core/renderers/renderer-lit-html.js
|
packages/core/renderers/renderer-lit-html.js
|
import { html, render } from 'lit-html';
import {
withComponent,
shadow,
props,
hasNativeShadowDomSupport,
findParentTag,
} from '../utils';
import { BoltBase } from './bolt-base';
export { html, render } from 'lit-html';
export { unsafeHTML } from 'lit-html/lib/unsafe-html';
export function withLitHtml(Base = HTMLElement) {
return class extends withComponent(BoltBase(Base)) {
static props = {
onClick: props.string,
onClickTarget: props.string,
};
constructor(...args) {
super(...args);
}
renderStyles(styles) {
if (styles) {
return html`<style>${styles}</style>`;
}
}
slot(name) {
if (typeof this.slots[name] === 'undefined') {
this.slots[name] = [];
}
if (this.useShadow && hasNativeShadowDomSupport) {
if (name === 'default') {
return html`<slot />`;
} else {
return html`<slot name="${name}" />`;
}
} else {
if (name === 'default') {
return html`${this.slots.default}`;
} else if (this.slots[name] && this.slots[name] !== []) {
return html`${this.slots[name]}`;
} else {
return ''; // No slots assigned so don't return any markup.
console.log(`The ${name} slot doesn't appear to exist...`);
}
}
}
renderer(root, call) {
render(call(), root);
}
};
}
|
JavaScript
| 0.000003 |
@@ -230,63 +230,8 @@
ml';
-%0Aexport %7B unsafeHTML %7D from 'lit-html/lib/unsafe-html';
%0A%0Aex
|
08c8e048ac49794a035da07a0f87c094747cb02e
|
Set JsTestCase.state to TEARDOWN before calling afterEachTests() method.
|
Implementation/WebTier/WebContent/JavaScript/JsUnit/app/JsTestCase.js
|
Implementation/WebTier/WebContent/JavaScript/JsUnit/app/JsTestCase.js
|
/*
* JsTestCase
*/
var JsTestCase = new Class({
Implements : [Events, Options],
Binds : ['afterEachTestWrapper', 'beforeEachTestWrapper', 'callAfterEachTest', 'callBeforeEachTest', 'checkTimeOut', 'notifyOnTestCaseReady', 'notifyOnTestCaseStart', 'onRunTestFinished', 'run', 'testRunWrapper'],
options : {
delayAfterTest : 10,
eventFireDelay : 10,
isAfterEachTestAsynchron : false,
isBeforeEachTestAsynchron : false,
maxTries: 20,
url: null,
waitDelay: 200
},
//Constructor
initialize : function( name, options ){
this.setOptions( options );
this.asynchron = false;
this.name = name;
this.numberOfTries;
this.state = JsTestCase.States.INITIALIZED;
this.testCaseActionChain = new Chain();
this.testResult;
this.timer;
},
//Public accessors and mutators
checkTimeOut: function(){
this.numberOfTries++;
if( this.numberOfTries >= this.options.maxTries ){
clearInterval( this.timer );
this.testResult.testFailed( new JsTestCaseTimeOutException( this.name, this.options.waitDelay * this.options.maxTries ));
this.testCaseActionChain.callChain();
}
},
onAfterEachTestFinished : function(){
this.testCaseActionChain.callChain();
},
onBeforeEachTestFinished : function(){
this.testCaseActionChain.callChain();
},
onRunTestFinished : function( error ){
clearInterval( this.timer );
if( error ) this.testResult.testFailed( error );
else this.testResult.testFinished();
this.testCaseActionChain.callChain();
},
run : function(){
this.testResult = new JsTestCaseResult( this );
this.compileTestCaseChain();
try{
this.testCaseActionChain.callChain();
}catch( exception ){
this.testResult.testFailed( exception );
this.testCaseActionChain.callChain();
}
},
//Properties
getName : function() { return this.name; },
getFullName : function() { return this.options.url ? this.options.url.toLowerCase() + ":" + this.name : this.name; },
getState : function() { return this.state; },
isAsynchron : function() { return this.asynchron; },
//Protected, private helper methods
afterEachTestWrapper: function(){
this.callAfterEachTest();
if( this.options.isAfterEachTestAsynchron )
this.waitForTestMethod();
else{
this.testCaseActionChain.callChain();
}
},
beforeEachTestWrapper: function(){
this.callBeforeEachTest();
this.testResult.testStarted();
if( this.options.isBeforeEachTestAsynchron )
this.waitForTestMethod();
else{
this.testCaseActionChain.callChain();
}
},
compileTestCaseChain : function(){
this.testCaseActionChain.chain(
function(){ this.notifyOnTestCaseStart(); }.bind( this ),
function(){ this.beforeEachTestWrapper(); }.bind( this ),
function(){ this.testRunWrapper(); }.bind( this ),
function(){ this.afterEachTestWrapper(); }.bind( this ),
function(){ this.notifyOnTestCaseReady(); }.bind( this )
);
}.protect(),
notifyOnTestCaseReady : function(){
this.state = JsTestCase.States.INITIALIZED;
this.fireEvent( 'testCaseReady', this.testResult, this.options.eventFireDelay );
this.testCaseActionChain.clearChain();
}.protect(),
notifyOnTestCaseStart : function(){
this.fireEvent( 'testCaseStart', this.testResult );
this.testCaseActionChain.callChain();
}.protect(),
testRunWrapper : function(){
try{
this.runTest();
if( this.asynchron ) {
this.waitForTestMethod();
} else {
this.testResult.testFinished();
this.testCaseActionChain.callChain();
}
}catch( e ){
this.testResult.testFailed( e );
this.testCaseActionChain.callChain();
}
},
waitForTestMethod: function(){
this.numberOfTries = 0;
this.timer = this.checkTimeOut.periodical( this.options.waitDelay, this );
}.protect()
});
JsTestCase.States = { INITIALIZED : "initialized", SETUP : "setUp", VERIFY : "verify", TEARDOWN : "tearDown" };
|
JavaScript
| 0 |
@@ -2385,32 +2385,80 @@
r: function()%7B%0D%0A
+ this.state = JsTestCase.States.TEARDOWN;%0D%0A
this.callA
@@ -2674,32 +2674,77 @@
r: function()%7B%0D%0A
+ this.state = JsTestCase.States.SETUP;%0D%0A
this.callB
@@ -3861,32 +3861,81 @@
)%7B%0D%0A try%7B%0D%0A
+ this.state = JsTestCase.States.VERIFY;%0D%0A
this.ru
|
cc6db46660805944641bfe2eea5cb34e7bcf3939
|
make AWS host permission optional
|
build-config.js
|
build-config.js
|
'use strict'
const config = {
'manifest': {
'common': {
'name': 'RunMyCode Online',
'short_name': 'RunMyCode',
'description': 'Run code online from sites like Github, Gitlab and more',
'author': 'Shatrughn Gupta',
'homepage_url': 'https://runmycode.online',
'version': '1.2.0',
'icons': { '128': 'icon128.png' },
'manifest_version': 2,
'content_scripts': [
{
'matches': [
'https://github.com/*',
'https://gist.github.com/*',
'https://gitlab.com/*',
'https://bitbucket.org/*',
'https://gobyexample.com/*'
],
'js': ['browser-polyfill.min.js', 'content-script.js'],
'css': ['runmycode-panel.css'],
'run-at': 'document_idle'
},
{
'matches': ['https://runmycode.online/dashboard.html*'],
'js': ['browser-polyfill.min.js', 'auto-configure.js'],
'run-at': 'document_idle'
}
],
'background': {
'scripts': ['browser-polyfill.min.js', 'background.js'],
'persistent': false
},
'options_ui': {
'page': 'options.html'
},
'permissions': [
'tabs', // for detecting url change and page loading complete for SPA like Github
'storage', // for storing API URL and key
'https://api.runmycode.online/', // for making CORS calls
'https://*.amazonaws.com/' // to allow for custom RunMyCode APIG deployment
]
}
},
'include_files': {
'common': [
'browser-polyfill.min.js',
'background.js',
'content-script.js',
'options.html',
'options.js',
'runmycode-panel.css',
'icon128.png',
'auto-configure.js'
]
}
}
// const manifests = config['manifest']
// manifests['chrome'] = {
// 'options_ui': Object.assign({}, manifests['common']['options_ui'], {
// 'chrome_style': true
// })
// }
// manifests['opera'] = manifests['chrome']
module.exports = config
|
JavaScript
| 0.000018 |
@@ -308,17 +308,17 @@
on': '1.
-2
+3
.0',%0A
@@ -1392,17 +1392,16 @@
online/'
-,
// for
@@ -1417,16 +1417,88 @@
RS calls
+ for code run and key gen/usage%0A %5D,%0A 'optional_permissions': %5B
%0A
@@ -1562,17 +1562,16 @@
Code API
-G
deploym
@@ -1573,16 +1573,35 @@
ployment
+ on AWS API Gateway
%0A %5D
|
0949cf5963f240a3751c3cce09f8ce4f8598fb8d
|
update script
|
script.js
|
script.js
|
'use strict';
const _ = require('lodash');
const Script = require('smooch-bot').Script;
const scriptRules = require('./script.json');
function wait(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
module.exports = new Script({
processing: {
//prompt: (bot) => bot.say('Beep boop...'),
receive: () => 'processing'
},
start: {
receive: (bot) => {
return bot.say('Get started by saying BOT.')
.then(() => 'speak');
}
},
speak: {
receive: (bot, message) => {
let upperText = message.text.trim().toUpperCase();
function updateSilent() {
switch (upperText) {
case "CONNECT ME":
return bot.setProp("silent", true);
case "DISCONNECT":
return bot.setProp("silent", false);
default:
return Promise.resolve();
}
}
function getSilent() {
return bot.getProp("silent");
}
function processMessage(isSilent) {
if (isSilent) {
return Promise.resolve("speak");
}
if (!_.has(scriptRules, upperText)) {
return bot.say(`So, I'm good at structured conversations but stickers, emoji and sentences still confuse me. Say 'more' to chat about something else.`).then(() => 'speak');
}
var response = scriptRules[upperText];
var lines = response.split('\n');
var p = Promise.resolve();
_.each(lines, function(line) {
line = line.trim();
p = p.then(function() {
console.log(line);
return wait(50).then(function() {
return bot.say(line);
});
});
});
return p.then(() => 'speak');
}
return updateSilent()
.then(getSilent)
.then(processMessage);
}
}
});
|
JavaScript
| 0.000001 |
@@ -390,32 +390,36 @@
tart: %7B%0A
+
receive: (bot) =
@@ -426,32 +426,36 @@
%3E %7B%0A
+
return bot.say('
@@ -458,71 +458,528 @@
ay('
-Get started by saying BOT.')%0A .then(() =%3E 'speak
+Hoi.')%0A .then(() =%3E 'askName');%0A %7D%0A %7D,%0A%0A askName: %7B%0A prompt: (bot) =%3E bot.say('Hoe heet je - want maakt praten een stuk eenvoudiger'),%0A receive: (bot, message) =%3E %7B%0A const name = message.text;%0A return bot.setProp('name', name)%0A .then(() =%3E bot.say(%60Great! I'll call you $%7Bname%7D%0A Is that OK? %25%5BYes%5D(postback:yes) %25%5BNo%5D(postback:no)%60))%0A .then(() =%3E 'finish
');%0A
@@ -982,26 +982,42 @@
');%0A
+
-%7D%0A
+ %7D%0A
%7D,%0A%0A
|
52214f1ad7cad7c956066cfa1a5ea84270417848
|
update appId in URL if not defined
|
corehq/apps/cloudcare/static/cloudcare/js/formplayer/menus/collections.js
|
corehq/apps/cloudcare/static/cloudcare/js/formplayer/menus/collections.js
|
/*global Backbone */
hqDefine("cloudcare/js/formplayer/menus/collections", function () {
var FormplayerFrontend = hqImport("cloudcare/js/formplayer/app"),
Util = hqImport("cloudcare/js/formplayer/utils/util");
var MenuSelect = Backbone.Collection.extend({
commonProperties: [
'appId',
'appVersion',
'breadcrumbs',
'clearSession',
'notification',
'persistentCaseTile',
'queryKey',
'selections',
'tiles',
'title',
'type',
],
entityProperties: [
'actions',
'currentPage',
'hasInlineTile',
'headers',
'maxHeight',
'maxWidth',
'numEntitiesPerRow',
'pageCount',
'redoLast',
'shouldRequestLocation',
'shouldWatchLocation',
'sortIndices',
'styles',
'titles',
'useUniformUnits',
'widthHints',
'multiSelect',
],
commandProperties: [
'layoutStyle',
],
detailProperties: [
'isPersistentDetail',
],
formProperties: [
'langs',
],
parse: function (response) {
_.extend(this, _.pick(response, this.commonProperties));
if (response.selections) {
var urlObject = Util.currentUrlToObject();
urlObject.setSelections(response.selections);
Util.setUrlToObject(urlObject, true);
sessionStorage.removeItem('selectedValues');
}
if (response.commands) {
_.extend(this, _.pick(response, this.commandProperties));
return response.commands;
} else if (response.entities) {
_.extend(this, _.pick(response, this.entityProperties));
return response.entities;
} else if (response.type === "query") {
return response.displays;
} else if (response.details) {
_.extend(this, _.pick(response, this.detailProperties));
return response.details;
} else if (response.tree) {
// form entry time, doggy
_.extend(this, _.pick(response, this.formProperties));
FormplayerFrontend.trigger('startForm', response, this.app_id);
}
},
sync: function (method, model, options) {
Util.setCrossDomainAjaxOptions(options);
return Backbone.Collection.prototype.sync.call(this, 'create', model, options);
},
});
return function (response, options) {
return new MenuSelect(response, options);
};
});
|
JavaScript
| 0 |
@@ -1407,133 +1407,385 @@
-if (response.selections) %7B%0A var urlObject = Util.currentUrlToObject();%0A urlObject.setSelections
+var urlObject = Util.currentUrlToObject(),%0A updateUrl = false;%0A if (!urlObject.appId && response.appId) %7B%0A // will be undefined on urlObject when coming from an incomplete form%0A urlObject.appId = response.appId;%0A this.appId = urlObject.appId;%0A updateUrl = true;%0A %7D%0A if
(res
@@ -1797,25 +1797,26 @@
.selections)
-;
+ %7B
%0A
@@ -1824,43 +1824,51 @@
-Util.setUrlToObject(urlObject, true
+urlObject.setSelections(response.selections
);%0A
@@ -1927,16 +1927,147 @@
lues');%0A
+ updateUrl = true;%0A %7D%0A if (updateUrl) %7B%0A Util.setUrlToObject(urlObject, true);%0A
|
bbefc366bb9a2da59ccab5a22cfd2750020d10ae
|
optimize ListItem
|
src/_ListItem/ListItem.js
|
src/_ListItem/ListItem.js
|
/**
* @file ListItem component
* @author liangxiaojun([email protected])
*/
import React, {Component} from 'react';
import PropTypes from 'prop-types';
import Checkbox from '../Checkbox';
import Radio from '../Radio';
import CircularLoading from '../CircularLoading';
import TipProvider from '../TipProvider';
import TouchRipple from '../TouchRipple';
import Theme from '../Theme';
import Util from '../_vendors/Util';
import Position from '../_statics/Position';
import SelectMode from '../_statics/SelectMode';
export default class ListItem extends Component {
constructor(props, ...restArgs) {
super(props, ...restArgs);
this.state = {
checked: props.checked
};
this.checkboxChangeHandler = ::this.checkboxChangeHandler;
this.radioChangeHandler = ::this.radioChangeHandler;
this.touchTapHandler = ::this.touchTapHandler;
}
checkboxChangeHandler(checked) {
this.setState({
checked
}, () => {
const {onSelect, onDeselect} = this.props;
if (checked) {
onSelect && onSelect();
} else {
onDeselect && onDeselect();
}
});
}
radioChangeHandler() {
const {checked} = this.state;
if (!checked) {
this.setState({
checked: true
}, () => {
const {onSelect} = this.props;
onSelect && onSelect();
});
}
}
touchTapHandler(e) {
e.preventDefault();
const {disabled, isLoading, readOnly} = this.props;
if (disabled || isLoading || readOnly) {
return;
}
const {onTouchTap} = this.props;
onTouchTap && onTouchTap(e);
const {selectMode} = this.props;
switch (selectMode) {
case SelectMode.MULTI_SELECT:
this.checkboxChangeHandler(!this.state.checked);
return;
case SelectMode.SINGLE_SELECT:
this.radioChangeHandler();
return;
}
}
componentWillReceiveProps(nextProps) {
if (nextProps.checked !== this.state.checked) {
this.setState({
checked: nextProps.checked
});
}
}
render() {
const {
index, className, style, theme, data, text, desc, iconCls, rightIconCls, tip, tipPosition,
disabled, isLoading, disableTouchRipple, rippleDisplayCenter, renderer, itemRenderer, readOnly,
selectTheme, selectMode, radioUncheckedIconCls, radioCheckedIconCls,
checkboxUncheckedIconCls, checkboxCheckedIconCls, checkboxIndeterminateIconCls,
onMouseEnter, onMouseLeave
} = this.props,
{checked} = this.state,
listItemClassName = (theme ? ` theme-${theme}` : '') + (checked ? ' activated' : '')
+ (className ? ' ' + className : ''),
loadingIconPosition = (rightIconCls && !iconCls) ? 'right' : 'left';
return (
<TipProvider className='block'
text={tip}
tipPosition={tipPosition}>
<div className={'list-item' + listItemClassName}
style={style}
disabled={disabled || isLoading}
readOnly={readOnly}
onTouchTap={this.touchTapHandler}
onMouseEnter={onMouseEnter}
onMouseLeave={onMouseLeave}>
{
selectMode === SelectMode.SINGLE_SELECT ?
<Radio className="list-item-checked"
theme={selectTheme}
checked={checked}
disabled={disabled || isLoading}
uncheckedIconCls={radioUncheckedIconCls}
checkedIconCls={radioCheckedIconCls}/>
:
null
}
{
selectMode === SelectMode.MULTI_SELECT ?
<Checkbox className="list-item-checkbox"
theme={selectTheme}
checked={checked}
disabled={disabled || isLoading}
uncheckedIconCls={checkboxUncheckedIconCls}
checkedIconCls={checkboxCheckedIconCls}
indeterminateIconCls={checkboxIndeterminateIconCls}/>
:
null
}
{
isLoading && loadingIconPosition === 'left' ?
<div className="button-icon button-icon-left">
<CircularLoading className="button-loading-icon"
size="small"/>
</div>
:
(
iconCls ?
<i className={`button-icon button-icon-left ${iconCls}`}
aria-hidden="true"></i>
:
null
)
}
{
itemRenderer && typeof itemRenderer === 'function' ?
itemRenderer(data, index)
:
(
renderer && typeof renderer === 'function' ?
renderer(data, index)
:
(
desc ?
<div className="list-item-content">
<div className="list-item-content-value">
{text}
</div>
<div className="list-item-content-desc">
{desc}
</div>
</div>
:
text
)
)
}
{
isLoading && loadingIconPosition === 'right' ?
<CircularLoading className="button-icon button-icon-right button-loading-icon"
size="small"/>
:
(
rightIconCls ?
<i className={`button-icon button-icon-right ${rightIconCls}`}
aria-hidden="true"></i>
:
null
)
}
{
disableTouchRipple || readOnly ?
null
:
<TouchRipple ref="touchRipple"
className={disabled || isLoading ? 'hidden' : ''}
displayCenter={rippleDisplayCenter}/>
}
</div>
</TipProvider>
);
}
};
ListItem.propTypes = {
index: PropTypes.number,
className: PropTypes.string,
style: PropTypes.object,
theme: PropTypes.oneOf(Util.enumerateValue(Theme)),
selectTheme: PropTypes.oneOf(Util.enumerateValue(Theme)),
selectMode: PropTypes.oneOf(Util.enumerateValue(SelectMode)),
data: PropTypes.oneOfType([PropTypes.string, PropTypes.number, PropTypes.object]),
value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
text: PropTypes.any,
desc: PropTypes.string,
disabled: PropTypes.bool,
isLoading: PropTypes.bool,
disableTouchRipple: PropTypes.bool,
rippleDisplayCenter: PropTypes.bool,
checked: PropTypes.bool,
readOnly: PropTypes.bool,
iconCls: PropTypes.string,
rightIconCls: PropTypes.string,
tip: PropTypes.string,
tipPosition: PropTypes.oneOf(Util.enumerateValue(Position)),
itemRenderer: PropTypes.func,
renderer: PropTypes.func,
radioUncheckedIconCls: PropTypes.string,
radioCheckedIconCls: PropTypes.string,
checkboxUncheckedIconCls: PropTypes.string,
checkboxCheckedIconCls: PropTypes.string,
checkboxIndeterminateIconCls: PropTypes.string,
onTouchTap: PropTypes.func,
onSelect: PropTypes.func,
onDeselect: PropTypes.func,
onMouseEnter: PropTypes.func,
onMouseLeave: PropTypes.func
};
ListItem.defaultProps = {
index: 0,
className: null,
style: null,
theme: null,
selectTheme: null,
selectMode: SelectMode.NORMAL,
data: null,
value: null,
text: null,
desc: null,
disabled: false,
isLoading: false,
disableTouchRipple: false,
rippleDisplayCenter: false,
checked: false,
readOnly: false,
iconCls: null,
rightIconCls: null,
tip: null,
tipPosition: Position.BOTTOM,
radioUncheckedIconCls: 'fa fa-check',
radioCheckedIconCls: 'fa fa-check',
checkboxUncheckedIconCls: 'fa fa-square-o',
checkboxCheckedIconCls: 'fa fa-check-square',
checkboxIndeterminateIconCls: 'fa fa-minus-square'
};
|
JavaScript
| 0.000088 |
@@ -4078,32 +4078,93 @@
oCheckedIconCls%7D
+%0A disableTouchRipple=%7Btrue%7D
/%3E%0A
@@ -4826,16 +4826,80 @@
IconCls%7D
+%0A disableTouchRipple=%7Btrue%7D
/%3E%0A
|
5ef28b7e1196f1202e1c071ea3333bb2a17f48c7
|
fix #1888 csslint worker gives error for empty file
|
lib/ace/mode/css_worker.js
|
lib/ace/mode/css_worker.js
|
/* ***** BEGIN LICENSE BLOCK *****
* Distributed under the BSD license:
*
* Copyright (c) 2010, Ajax.org B.V.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Ajax.org B.V. nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* ***** END LICENSE BLOCK ***** */
define(function(require, exports, module) {
"use strict";
var oop = require("../lib/oop");
var lang = require("../lib/lang");
var Mirror = require("../worker/mirror").Mirror;
var CSSLint = require("./css/csslint").CSSLint;
var Worker = exports.Worker = function(sender) {
Mirror.call(this, sender);
this.setTimeout(400);
this.ruleset = null;
this.setDisabledRules("ids");
this.setInfoRules("adjoining-classes|qualified-headings|zero-units|gradients|import|outline-none");
};
oop.inherits(Worker, Mirror);
(function() {
this.setInfoRules = function(ruleNames) {
if (typeof ruleNames == "string")
ruleNames = ruleNames.split("|");
this.infoRules = lang.arrayToMap(ruleNames);
this.doc.getValue() && this.deferredUpdate.schedule(100);
};
this.setDisabledRules = function(ruleNames) {
if (!ruleNames) {
this.ruleset = null;
} else {
if (typeof ruleNames == "string")
ruleNames = ruleNames.split("|");
var all = {};
CSSLint.getRules().forEach(function(x){
all[x.id] = true;
});
ruleNames.forEach(function(x) {
delete all[x];
});
this.ruleset = all;
}
this.doc.getValue() && this.deferredUpdate.schedule(100);
};
this.onUpdate = function() {
var value = this.doc.getValue();
var infoRules = this.infoRules;
var result = CSSLint.verify(value, this.ruleset);
this.sender.emit("csslint", result.messages.map(function(msg) {
return {
row: msg.line - 1,
column: msg.col - 1,
text: msg.message,
type: infoRules[msg.rule.id] ? "info" : msg.type,
rule: msg.rule.name
}
}));
};
}).call(Worker.prototype);
});
|
JavaScript
| 0 |
@@ -3120,16 +3120,88 @@
alue();%0A
+ if (!value)%0A return this.sender.emit(%22csslint%22, %5B%5D);%0A
|
bc0766dc7e1adc0715296eb823f4c133005cb1ee
|
Remove console.log
|
server/api/issue/issue.controller.js
|
server/api/issue/issue.controller.js
|
import Issue from './issue.model';
export function show(req, res) {
return Issue
.find({section: req.params.section})
.populate('user')
.exec()
.then(list => res.json(list))
.catch(err => res.status(500).send(err.toString()));
}
export function create(req, res) {
return Issue
.create(req.body)
.then(created => res.json(created))
.catch(err => res.status(500).send(err.toString()));
}
export function toggle(req, res) {
return Issue
.findById(req.params.id)
.then(found => {
if (!found) {
return res.status(404).send();
}
found.closed = !found.closed;
return found.save().then(saved => {
console.log(saved.closed);
return res.json(saved);
});
})
.catch(err => res.status(500).send(err.toString()));
}
|
JavaScript
| 0.000004 |
@@ -668,43 +668,8 @@
%3E %7B%0A
- console.log(saved.closed);%0A
|
30c7618eff5a5afcb0dab2a64fc2c78f91191615
|
stop and click play
|
augmented-paintings/fire/learn-video_edgeActions.js
|
augmented-paintings/fire/learn-video_edgeActions.js
|
(function($,Edge,compId){var Composition=Edge.Composition,Symbol=Edge.Symbol;
//Edge symbol: 'stage'
(function(symbolName){Symbol.bindTriggerAction(compId,symbolName,"Default Timeline",4750,function(sym,e){sym.play(0);});
//Edge binding end
})("stage");
//Edge symbol end:'stage'
})(jQuery,AdobeEdge,"learn-video");
|
JavaScript
| 0.000001 |
@@ -204,18 +204,236 @@
,e)%7B
-sym.play(0
+%7D);%0A//Edge binding end%0ASymbol.bindElementAction(compId,symbolName,%22$%7B_Comp_12%7D%22,%22click%22,function(sym,e)%7Bsym.play(0);%7D);%0A//Edge binding end%0ASymbol.bindTriggerAction(compId,symbolName,%22Default Timeline%22,0,function(sym,e)%7Bsym.stop(
);%7D)
|
6034574f1299343c7df07cfbb65b889fd8b526fd
|
Add hide alert action creator
|
src/actions/appActions.js
|
src/actions/appActions.js
|
export function changeLocation(location) {
return {
type: 'CHANGE_LOCATION',
location
};
}
export function changeUnitType(unitType) {
return {
type: 'CHANGE_UNIT_TYPE',
unitType
};
}
export function setAlert({type, message}) {
return {
type: 'SET_ALERT',
alert: {
type,
message
}
};
}
export function setTooltip({x, y, contentElement, originTarget, title}) {
return {
type: 'SET_TOOLTIP',
tooltip: {
x,
y,
contentElement,
originTarget,
title
}
};
}
export function hideTooltip() {
return {
type: 'SET_TOOLTIP',
tooltip: {}
};
}
|
JavaScript
| 0 |
@@ -325,32 +325,118 @@
e%0A %7D%0A %7D;%0A%7D%0A%0A
+export function hideAlert() %7B%0A return %7B%0A type: 'SET_ALERT',%0A alert: %7B%7D%0A %7D;%0A%7D%0A%0A
export function
|
92ad4980bce635a6b237852ada57274170fd426b
|
Fix for part of issue #907 Network and network_weights had been improperly renamed in #897. It was fixed in the imports but not the exports
|
server/controllers/exporters/xlsx.js
|
server/controllers/exporters/xlsx.js
|
const xlsx = require("node-xlsx");
const buildGeneNameArray = function (genes) {
const geneNameArray = genes.map(gene => gene["name"]);
return geneNameArray;
};
const createArrayWithZeroes = function (length) {
return Array.apply(null, Array(length)).map(() => 0);
};
const buildWorkbookSheet = function (genes, links) {
const geneNameArray = buildGeneNameArray(genes);
// The +1 to length is because we ALSO add the gene name to each of the network sheet arrays.
const workbookSheet = genes.map(() => createArrayWithZeroes(genes.length + 1));
// Place the gene name in the beginning of the network sheet array.
// EX: ["CIN5", 0, 0, 1]
Object.keys(geneNameArray).forEach(index => workbookSheet[index][0] = geneNameArray[index]);
geneNameArray.unshift("cols regulators/rows targets");
links.forEach((link) => {
workbookSheet[link.source][link.target + 1] = link.value;
});
workbookSheet.unshift(geneNameArray);
return workbookSheet;
};
const convertToSheet = function (name, testSheet) {
const singularName = name.toLowerCase().endsWith("s") ? name.substring(0, name.length - 1) : name;
return {
name: name,
data: [["id", singularName], ...Object.keys(testSheet).map(key => [key, testSheet[key]])]
};
};
const buildTestSheets = testSheet => ["production_rates", "degradation_rates", "threshold_b"]
.filter(name => testSheet[name])
.map(name => convertToSheet(name, testSheet[name]));
const buildMetaSheet = function (metaDataContainer) {
const metaSheet = { name: "optimization_parameters", data: [] };
metaSheet["data"].push(["optimization_parameter", "value"]);
Object.keys(metaDataContainer).forEach((parameter) => {
const metaData = metaDataContainer[parameter];
const cleanedUpData = Array.isArray(metaData)
? [parameter, ...metaData]
: [parameter, metaData];
metaSheet["data"].push(cleanedUpData);
});
return metaSheet;
};
const buildExpressionSheets = function (expressions) {
const builtExpressionSheets = [];
Object.keys(expressions).forEach((expression) => {
const builtSheet = { name: expression, data: []};
Object.keys(expressions[expression]["data"]).forEach((key) => {
const expressionData = expressions[expression]["data"][key];
builtSheet["data"].push([key, ...expressionData]);
});
builtExpressionSheets.push(builtSheet);
});
return builtExpressionSheets;
};
const buildXlsxSheet = function (workbook) {
const resultSheet = [];
resultSheet.push(
{
"name": "workbook",
"data": buildWorkbookSheet(workbook.genes, workbook.links)
},
{
"name": "workbook_weights",
"data": buildWorkbookSheet(workbook.genes, workbook.links)
}
);
Object.keys(workbook).forEach((key) => {
switch (key) {
case "meta":
resultSheet.push(buildMetaSheet(workbook[key]));
break;
case "test":
resultSheet.push(...buildTestSheets(workbook[key]));
break;
case "expression":
resultSheet.push(...buildExpressionSheets(workbook[key]));
break;
default:
break;
}
});
return resultSheet;
};
module.exports = function (workbook) {
return xlsx.build(buildXlsxSheet(workbook));
};
|
JavaScript
| 0 |
@@ -2651,23 +2651,22 @@
name%22: %22
+net
wor
-kboo
k%22,%0A
@@ -2775,23 +2775,22 @@
name%22: %22
+net
wor
-kboo
k_weight
|
031b829b12036ec26b7dc0bf877240e00345691b
|
fix error handling problem when closing the server to early
|
tests/test-event-forwarding.js
|
tests/test-event-forwarding.js
|
var server = require('./server')
, assert = require('assert')
, request = require('../index')
;
var s = server.createServer();
var expectedBody = "waited";
var remainingTests = 1;
s.listen(s.port, function () {
s.on('/', function (req, resp) {
resp.writeHead(200, {'content-type':'text/plain'})
resp.write(expectedBody)
resp.end()
});
})
var shouldEmitSocketEvent = {
url: s.url + '/',
}
var req = request(shouldEmitSocketEvent)
req.on('socket', function(socket) {
var requestSocket = req.req.socket
assert.equal(requestSocket, socket)
checkDone()
})
req.on('error', function(err) {
// I get an ECONNREFUSED error
})
function checkDone() {
if(--remainingTests == 0) {
console.log("All tests passed.");
s.close();
}
}
|
JavaScript
| 0 |
@@ -181,9 +181,9 @@
s =
-1
+2
;%0A%0As
@@ -448,16 +448,45 @@
ketEvent
+, function() %7B%0A s.close();%0A%7D
)%0A%0Areq.o
@@ -613,77 +613,8 @@
%7D)%0A%0A
-req.on('error', function(err) %7B%0A // I get an ECONNREFUSED error%0A%7D)%0A%0A
func
@@ -658,24 +658,24 @@
sts == 0) %7B%0A
+
console.
@@ -704,23 +704,8 @@
%22);%0A
- s.close();%0A
%7D%0A
|
82d3d7b16bdaac08f34facc4822986b1b648ecc2
|
Add context to deduction result
|
addon/ad/language_deducer.js
|
addon/ad/language_deducer.js
|
// Using Chain of responsability to detect the language.
// Each logic will have its class and the first that succeeds is used.
const Deduction = function(language, method){
this.language = language;
this.method = method;
}
Deduction.METHODS = {
REMEMBER:"remember",
GUESS:"guess"
}
export const LanguageDeducer = function(ad){
this.ad = ad;
this.deducerChain = [
this.rememberByAllRecipients,
this.rememberByTos,
this.rememberByAnyTo,
this.rememberByAnyCC,
this.guessFromTos
]
}
function deductionOrNull(value, method){
if(!value){
return null;
}
return new Deduction(value,method);
}
LanguageDeducer.prototype = {
deduce: async function(){
var context = await this.buildContext();
var deduction = null;
for(const deducer of this.deducerChain) {
deduction = await deducer(context);
if(deduction) break;
}
return deduction;
},
buildContext: async function(){
return {
ad: this.ad,
recipients: {
to: await this.ad.getRecipients(),
cc: await this.ad.getRecipients('cc')
}
}
},
rememberByAllRecipients: async function (context) {
const toandcc_key = context.ad.getKeyForRecipients(context.recipients);
context.ad.logger.debug("Deducing language for: " + toandcc_key);
const lang = await context.ad.getLangFor(toandcc_key);
return deductionOrNull(lang, Deduction.METHODS.REMEMBER);
},
rememberByTos: async function(context){
const alltogether_key = context.ad.stringifyRecipientsGroup( context.recipients.to );
const lang = await context.ad.getLangFor( alltogether_key );
return deductionOrNull(lang, Deduction.METHODS.REMEMBER);
},
rememberByAnyTo: async function(context){
var lang = null;
for( const recipient of context.recipients.to ){
lang = await context.ad.getLangFor( recipient );
if( lang ){
break;
}
}
return deductionOrNull(lang, Deduction.METHODS.REMEMBER);
},
rememberByAnyCC: async function(context){
var lang = null;
for( const recipient of context.recipients.cc ){
lang = await context.ad.getLangFor( recipient );
if( lang ){
break;
}
}
return deductionOrNull(lang, Deduction.METHODS.REMEMBER);
},
guessFromTos: async function(context){
if(await context.ad.allowHeuristic()){
const lang = await context.ad.heuristic_guess(context.recipients.to);
return deductionOrNull(lang, Deduction.METHODS.GUESS);
}
}
}
|
JavaScript
| 0.002121 |
@@ -165,19 +165,31 @@
, method
+, recipients
)%7B%0A
-
this.l
@@ -232,16 +232,48 @@
method;%0A
+ this.recipients = recipients;%0A
%7D%0A%0ADeduc
@@ -565,25 +565,30 @@
unction
-d
+buildD
eduction
OrNull(v
@@ -579,22 +579,16 @@
eduction
-OrNull
(value,
@@ -597,45 +597,19 @@
thod
-)%7B%0A if(!value)%7B%0A return null;%0A %7D
+, context)%7B
%0A r
@@ -640,16 +640,36 @@
e,method
+, context.recipients
);%0A%7D%0A%0ALa
@@ -901,16 +901,25 @@
eduction
+.language
) break;
@@ -1414,33 +1414,38 @@
%0A return
-d
+buildD
eduction
OrNull(lang,
@@ -1424,38 +1424,32 @@
n buildDeduction
-OrNull
(lang, Deduction
@@ -1457,32 +1457,41 @@
METHODS.REMEMBER
+, context
);%0A %7D,%0A rememb
@@ -1686,33 +1686,38 @@
%0A return
-d
+buildD
eduction
OrNull(lang,
@@ -1696,38 +1696,32 @@
n buildDeduction
-OrNull
(lang, Deduction
@@ -1729,32 +1729,41 @@
METHODS.REMEMBER
+, context
);%0A %7D,%0A rememb
@@ -1981,33 +1981,38 @@
%0A return
-d
+buildD
eduction
OrNull(lang,
@@ -1991,38 +1991,32 @@
n buildDeduction
-OrNull
(lang, Deduction
@@ -2024,32 +2024,41 @@
METHODS.REMEMBER
+, context
);%0A %7D,%0A rememb
@@ -2276,33 +2276,38 @@
%0A return
-d
+buildD
eduction
OrNull(lang,
@@ -2286,38 +2286,32 @@
n buildDeduction
-OrNull
(lang, Deduction
@@ -2327,16 +2327,25 @@
REMEMBER
+, context
);%0A %7D,%0A
@@ -2517,25 +2517,30 @@
return
-d
+buildD
eduction
OrNull(l
@@ -2535,14 +2535,8 @@
tion
-OrNull
(lan
@@ -2561,16 +2561,25 @@
DS.GUESS
+, context
);%0A %7D
|
756b42f5a186cac1f20f9fcd1a9c59d3ef92ecff
|
add put route with no id
|
api/index.js
|
api/index.js
|
'use strict';
const router = require('koa-router')();
const db = require('../db/data-service');
const _ = require('lodash');
const body = require('koa-body')();
const secretKey = 'm1chael';
function auth(parent) {
if (!parent.request.query || (parent.request.query.key !== secretKey)) {
parent.body = 'Error: incorrect secret key';
parent.status = 401;
return false;
} else {
return true;
}
}
router.get('/api/list', function*() {
if (!auth(this)) return;
const response = yield db.listDatabases();
this.body = response;
});
router.get('/api/list/:database', function*() {
if (!auth(this)) return;
const response = yield db.listTables(this.params);
this.body = response;
});
router.get('/api/list/:database/:table', function*() {
if (!auth(this)) return;
const response = yield db.scan(this.params);
this.body = response;
});
router.get('/api/get/:database/:table/:id', function*() {
if (!auth(this)) return;
this.params.id = parseInt(this.params.id, 10);
const response = yield db.getItem(this.params);
this.body = response;
});
router.put('/api/put/:database/:table/:id', body, function*() {
if (!auth(this)) return;
this.params.id = parseInt(this.params.id, 10);
const params = _.assign({item: this.request.body}, this.params);
const response = yield db.putItem(params);
this.body = response;
});
module.exports = router;
|
JavaScript
| 0.000001 |
@@ -1074,24 +1074,252 @@
ponse;%0A%7D);%0A%0A
+router.put('/api/put/:database/:table', body, function*() %7B%0A if (!auth(this)) return;%0A const params = _.assign(%7Bitem: this.request.body%7D, this.params);%0A const response = yield db.putItem(params);%0A this.body = response;%0A%7D);%0A%0A
router.put('
|
b0b2053834c763af0bd2a4db7cbfac5ca56d7497
|
add more value constraint tests
|
tests/unit/value-constraint.js
|
tests/unit/value-constraint.js
|
"use strict";
describe("ValueConstraint", function() {
describe("constructor with simple reference and complex type", function() {
var vc;
beforeEach(function() {
vc = new ValueConstraint({
descriptionTemplateRef: "testref",
valueLang: "en",
valueDataType: {
id: "this-test",
valueLabel: "Test",
valueLabelHint: "TEST"
},
editable: "true",
defaultURI: "urn:test",
defaultLiteral: "test"
});
});
it("should have a reference", function() {
expect(vc.hasReference()).toEqual(true);
});
it("should not have multiple references", function() {
expect(vc.hasManyReferences()).toEqual(false);
});
it("should return its reference", function() {
expect(vc.getReference()).toEqual("testref");
});
it("should have a language", function() {
expect(vc.hasLanguage()).toEqual(true);
});
it("should return the language", function() {
expect(vc.getLanguage()).toEqual("en");
});
it("should not have a basic type", function() {
expect(vc.hasBasicType()).toEqual(false);
});
it("should have a complex type", function() {
expect(vc.hasComplexType()).toEqual(true);
});
it("should return the complex type ID", function() {
expect(vc.getComplexTypeID()).toEqual("this-test");
});
it("should return the complex type label", function() {
expect(vc.getComplexTypeLabel()).toEqual("Test");
});
it("should have a type hint", function() {
expect(vc.hasHint()).toEqual(true);
});
it("should return the type hint", function() {
expect(vc.getComplexTypeLabelHint()).toEqual("TEST");
});
it("should be editable", function() {
expect(vc.isEditable()).toEqual(true);
});
it("should have a default URI", function() {
expect(vc.hasDefaultURI()).toEqual(true);
});
it("should return the default URI", function() {
expect(vc.getDefaultURI()).toEqual("urn:test");
});
it("should have a default literal", function() {
expect(vc.hasDefaultLiteral()).toEqual(true);
});
it("should return the default literal", function() {
expect(vc.getDefaultLiteral()).toEqual("test");
});
});
});
|
JavaScript
| 0 |
@@ -2742,13 +2742,1127 @@
%0A %7D);
+%0A%0A describe(%22constructor with complex reference and basic type%22, function() %7B%0A var vc;%0A beforeEach(function() %7B%0A vc = new ValueConstraint(%7B%0A descriptionTemplateRef: %5B%22testref%22, %22testrefAlt%22%5D,%0A valueDataType: %22testType%22%0A %7D);%0A %7D);%0A %0A it(%22should have multiple references%22, function() %7B%0A expect(vc.hasManyReferences()).toEqual(true);%0A %7D);%0A %0A it(%22should return its reference%22, function() %7B%0A expect(vc.getReference()).toEqual(%5B%22testref%22,%22testrefAlt%22%5D);%0A %7D);%0A %0A it(%22should have a basic type%22, function() %7B%0A expect(vc.hasBasicType()).toEqual(true);%0A %7D);%0A %0A it(%22should not have a complex type%22, function() %7B%0A expect(vc.hasComplexType()).toEqual(false);%0A %7D);%0A %0A it(%22should return the type ID%22, function() %7B%0A expect(vc.getBasicType()).toEqual(%22testType%22);%0A %7D);%0A%0A it(%22should be editable by default%22, function() %7B%0A expect(vc.isEditable()).toEqual(true);%0A %7D);%0A %7D);
%0A%7D);%0A
|
7d467a81ca0a1fe525507ea74f435efa95b1acc4
|
fix bug with https redirect
|
backend/server.js
|
backend/server.js
|
import path from 'path';
import express from 'express';
import webpack from 'webpack';
import webpackMiddleware from 'webpack-dev-middleware';
import webpackHotMiddleware from 'webpack-hot-middleware';
import wrap from 'express-async-wrap';
import fs from 'fs-promise';
import search from '../common/search';
import webpackConfig from './webpack.config.babel';
import macros from '../common/macros';
const app = express();
// Http to https redirect.
app.use(function (req, res, next) {
var remoteIp = req.connection.remoteAddress;
if (req.protocol == 'http' && !remoteIp.includes('127.0.0.1') && remoteIp != '::1' && !remoteIp.includes('10.0.0.') && !remoteIp.includes('192.168.1.')) {
// Cache the http to https redirect for 2 months.
res.setHeader('Cache-Control', 'public, max-age=5256000');
res.redirect('https' + req.url.slice('http'.length));
}
else {
next()
}
})
let searchPromise = null;
async function getSearch() {
if (searchPromise) {
return searchPromise;
}
const termDumpPromise = fs.readFile('./public/data/getTermDump/neu.edu/201810.json').then((body) => {
return JSON.parse(body);
});
const searchIndexPromise = fs.readFile('./public/data/getSearchIndex/neu.edu/201810.json').then((body) => {
return JSON.parse(body);
});
const employeeMapPromise = fs.readFile('./public/data/employeeMap.json').then((body) => {
return JSON.parse(body);
});
const employeesSearchIndexPromise = fs.readFile('./public/data/employeesSearchIndex.json').then((body) => {
return JSON.parse(body);
});
try {
searchPromise = Promise.all([termDumpPromise, searchIndexPromise, employeeMapPromise, employeesSearchIndexPromise]).then((...args) => {
return search.create(...args[0]);
});
}
catch (e) {
console.error("Error:", e)
console.error('Not starting search backend.')
return null;
}
return searchPromise;
}
app.get('/search', wrap(async (req, res) => {
if (!req.query.query || typeof req.query.query !== 'string' || req.query.query.length > 100) {
console.error('Need query.');
res.send('Need query param.');
return;
}
let minIndex = 0;
if (req.query.minIndex) {
minIndex = req.query.minIndex;
}
let maxIndex = 10;
if (req.query.maxIndex) {
maxIndex = req.query.maxIndex;
}
const index = await getSearch();
if (!index) {
res.send('Could not start backend. No data found.')
return;
}
const startTime = Date.now();
const results = index.search(req.query.query, minIndex, maxIndex);
const midTime = Date.now();
const string = JSON.stringify(results)
console.log('Search for', req.query.query, 'took ', midTime-startTime, 'ms and stringify took', Date.now()-midTime);
res.send(string);
}));
let middleware;
if (macros.DEV) {
const compiler = webpack(webpackConfig);
middleware = webpackMiddleware(compiler, {
publicPath: webpackConfig.output.publicPath,
stats: {
colors: true,
timings: true,
hash: false,
chunksM: false,
chunkModules: false,
modules: false,
},
});
app.use(middleware);
app.use(webpackHotMiddleware(compiler));
}
app.use(express.static('public'));
app.get('/sw.js', (req, res) => {
res.sendFile(path.join(__dirname, '..', 'frontend', 'sw.js'));
});
app.get('*', (req, res) => {
if (macros.PROD) {
res.sendFile(path.join(__dirname, '..', 'public', 'index.html'));
}
else {
res.write(middleware.fileSystem.readFileSync(path.join(webpackConfig.output.path, 'index.html')));
res.end();
}
});
let port;
if (macros.DEV) {
port = 5000;
}
else {
port = 80;
}
app.listen(port, '0.0.0.0', (err) => {
if (err) console.log(err);
console.info(`Listening on port ${port}.`);
});
|
JavaScript
| 0 |
@@ -837,16 +837,19 @@
ttps
+://
' + req.
url.
@@ -848,32 +848,37 @@
req.
-url.slice('http'.length)
+get('host') + req.originalUrl
);%0A
|
bcd9c86fdd9e26f76bde3b7807401fef723efd5f
|
remove IconPool.insertFontFaceStyle
|
src/sap.ui.mdc/src/sap/ui/mdc/field/FieldBaseRenderer.js
|
src/sap.ui.mdc/src/sap/ui/mdc/field/FieldBaseRenderer.js
|
/*!
* ${copyright}
*/
sap.ui.define([
'sap/ui/core/Renderer',
'sap/ui/core/IconPool',
'sap/ui/mdc/enum/EditMode'
], function(
Renderer,
IconPool,
EditMode
) {
"use strict";
// initialize the Icon Pool
IconPool.insertFontFaceStyle();
/**
* FieldBase renderer.
* @namespace
*/
var FieldBaseRenderer = Renderer.extend("sap.ui.mdc.field.FieldBaseRenderer");
FieldBaseRenderer = Object.assign(FieldBaseRenderer, {
apiVersion: 2
});
FieldBaseRenderer.render = function(oRm, oField) {
var aContent = oField._getContent();
var sWidth = oField.getWidth();
var aConditions = oField.getConditions();
var sEditMode = oField.getEditMode();
var bShowEmptyIndicator = oField.getShowEmptyIndicator() && aConditions.length === 0 && sEditMode === EditMode.Display && !oField.getContent() && !oField.getContentDisplay();
oRm.openStart("div", oField);
oRm.class("sapUiMdcFieldBase");
if (aContent.length > 1) {
oRm.class("sapUiMdcFieldBaseMoreFields");
}
if (bShowEmptyIndicator) {
oRm.class("sapMShowEmpty-CTX"); // to allow the Text control determine if empty indicator is needed or not
}
oRm.style("width", sWidth);
oRm.openEnd();
for (var i = 0; i < aContent.length; i++) {
var oContent = aContent[i];
oRm.renderControl(oContent);
}
oRm.close("div");
};
return FieldBaseRenderer;
});
|
JavaScript
| 0.000001 |
@@ -181,71 +181,8 @@
%22;%0A%0A
-%09// initialize the Icon Pool%0A%09IconPool.insertFontFaceStyle();%0A%0A
%09/**
|
747f2b28472ada854af2faed137225f33ee929b5
|
Move otherwise redundant unsubscription
|
api/mount.js
|
api/mount.js
|
"use strict"
var Vnode = require("../render/vnode")
var autoredraw = require("../api/autoredraw")
module.exports = function(renderer, pubsub) {
return function(root, component) {
pubsub.unsubscribe(root.redraw)
if (component === null) {
renderer.render(root, [])
delete root.redraw
return
}
var run = autoredraw(root, renderer, pubsub, function() {
renderer.render(
root,
Vnode(component, undefined, undefined, undefined, undefined, undefined)
)
})
run()
}
}
|
JavaScript
| 0.000002 |
@@ -179,42 +179,8 @@
) %7B%0A
-%09%09pubsub.unsubscribe(root.redraw)%0A
%09%09if
@@ -232,16 +232,51 @@
ot, %5B%5D)%0A
+%09%09%09pubsub.unsubscribe(root.redraw)%0A
%09%09%09delet
|
77e72fbb29e0d12c8137b9ccb9a80bc6711bab89
|
Make sure to fetch latest update url every time we check for updates
|
packages/client-app/src/browser/auto-update-manager.es6
|
packages/client-app/src/browser/auto-update-manager.es6
|
/* eslint global-require: 0*/
import {dialog} from 'electron';
import {EventEmitter} from 'events';
import path from 'path';
import fs from 'fs';
import qs from 'querystring';
let autoUpdater = null;
const IdleState = 'idle';
const CheckingState = 'checking';
const DownloadingState = 'downloading';
const UpdateAvailableState = 'update-available';
const NoUpdateAvailableState = 'no-update-available';
const UnsupportedState = 'unsupported';
const ErrorState = 'error';
const preferredChannel = 'nylas-mail'
export default class AutoUpdateManager extends EventEmitter {
constructor(version, config, specMode, databaseReader) {
super();
this.state = IdleState;
this.version = version;
this.config = config;
this.databaseReader = databaseReader
this.specMode = specMode;
this.preferredChannel = preferredChannel;
this.updateFeedURL();
this.config.onDidChange(
'nylas.accounts',
this.updateFeedURL
);
setTimeout(() => this.setupAutoUpdater(), 0);
}
parameters = () => {
let updaterId = (this.databaseReader.getJSONBlob("NylasID") || {}).id
if (!updaterId) {
updaterId = "anonymous";
}
const emails = [];
const accounts = this.config.get('nylas.accounts') || [];
for (const account of accounts) {
if (account.email_address) {
emails.push(encodeURIComponent(account.email_address));
}
}
const updaterEmails = emails.join(',');
return {
platform: process.platform,
arch: process.arch,
version: this.version,
id: updaterId,
emails: updaterEmails,
preferredChannel: this.preferredChannel,
};
}
updateFeedURL = () => {
const params = this.parameters();
let host = `edgehill.nylas.com`;
if (this.config.get('env') === 'staging') {
host = `edgehill-staging.nylas.com`;
}
if (process.platform === 'win32') {
// Squirrel for Windows can't handle query params
// https://github.com/Squirrel/Squirrel.Windows/issues/132
this.feedURL = `https://${host}/update-check/win32/${params.arch}/${params.version}/${params.id}/${params.emails}`
} else {
this.feedURL = `https://${host}/update-check?${qs.stringify(params)}`;
}
if (autoUpdater) {
autoUpdater.setFeedURL(this.feedURL)
}
}
setupAutoUpdater() {
if (process.platform === 'win32') {
autoUpdater = require('./windows-updater-squirrel-adapter');
} else if (process.platform === 'linux') {
autoUpdater = require('./linux-updater-adapter').default;
} else {
autoUpdater = require('electron').autoUpdater;
}
autoUpdater.on('error', (event, message) => {
if (this.specMode) return;
console.error(`Error Downloading Update: ${message}`);
this.setState(ErrorState);
});
autoUpdater.setFeedURL(this.feedURL);
autoUpdater.on('checking-for-update', () => {
this.setState(CheckingState)
});
autoUpdater.on('update-not-available', () => {
this.setState(NoUpdateAvailableState)
});
autoUpdater.on('update-available', () => {
this.setState(DownloadingState)
});
autoUpdater.on('update-downloaded', (event, releaseNotes, releaseVersion) => {
this.releaseNotes = releaseNotes;
this.releaseVersion = releaseVersion;
this.setState(UpdateAvailableState);
this.emitUpdateAvailableEvent();
});
this.check({hidePopups: true});
setInterval(() => {
if ([UpdateAvailableState, UnsupportedState].includes(this.state)) {
console.log("Skipping update check... update ready to install, or updater unavailable.");
return;
}
this.check({hidePopups: true});
}, 1000 * 60 * 30);
if (autoUpdater.supportsUpdates && !autoUpdater.supportsUpdates()) {
this.setState(UnsupportedState);
}
}
emitUpdateAvailableEvent() {
if (!this.releaseVersion) {
return;
}
global.application.windowManager.sendToAllWindows("update-available", {}, {
releaseVersion: this.releaseVersion,
releaseNotes: this.releaseNotes,
});
}
setState(state) {
if (this.state === state) {
return;
}
this.state = state;
this.emit('state-changed', this.state);
}
getState() {
return this.state;
}
check({hidePopups} = {}) {
if (!hidePopups) {
autoUpdater.once('update-not-available', this.onUpdateNotAvailable);
autoUpdater.once('error', this.onUpdateError);
}
if (process.platform === "win32") {
// There's no separate "checking" stage on Windows. It also
// "installs" as soon as it downloads. You just need to restart to
// launch the updated app.
autoUpdater.downloadAndInstallUpdate();
} else {
autoUpdater.checkForUpdates();
}
}
install() {
if (process.platform === "win32") {
// On windows the update has already been "installed" and shortcuts
// already updated. You just need to restart the app to load the new
// version.
autoUpdater.restartN1();
} else {
autoUpdater.quitAndInstall();
}
}
iconURL() {
const url = path.join(process.resourcesPath, 'app', 'nylas.png');
if (!fs.existsSync(url)) {
return undefined;
}
return url;
}
onUpdateNotAvailable = () => {
autoUpdater.removeListener('error', this.onUpdateError);
dialog.showMessageBox({
type: 'info',
buttons: ['OK'],
icon: this.iconURL(),
message: 'No update available.',
title: 'No Update Available',
detail: `You're running the latest version of Nylas Mail (${this.version}).`,
});
};
onUpdateError = (event, message) => {
autoUpdater.removeListener('update-not-available', this.onUpdateNotAvailable);
dialog.showMessageBox({
type: 'warning',
buttons: ['OK'],
icon: this.iconURL(),
message: 'There was an error checking for updates.',
title: 'Update Error',
detail: message,
});
}
}
|
JavaScript
| 0 |
@@ -872,94 +872,8 @@
);%0A%0A
- this.config.onDidChange(%0A 'nylas.accounts',%0A this.updateFeedURL%0A );%0A%0A
@@ -4235,24 +4235,50 @@
ps%7D = %7B%7D) %7B%0A
+ this.updateFeedURL();%0A
if (!hid
|
83353949ab5aa6deb7985ce1aa399a310c82e7f9
|
use internal functions to improve readability
|
tests/cases/dom/manipulate/append.js
|
tests/cases/dom/manipulate/append.js
|
import QUnit from "qunitjs";
import {append} from "../../../../dom/manipulate";
QUnit.module("dom/manipulate/append()",
{
beforeEach: () =>
{
document.getElementById("qunit-fixture").innerHTML = `
<div id="test-parent">
<div class="first"></div>
<div class="second"></div>
</div>
`;
},
}
);
QUnit.test(
"with node as parent and child",
(assert) =>
{
const parent = document.getElementById("test-parent");
const appendingChild = document.createElement("div");
appendingChild.classList.add("className");
append(parent, appendingChild);
assert.equal(document.getElementsByClassName("className").length, 1, "has one occurrence");
assert.equal(parent.lastElementChild, appendingChild, "is last element");
}
);
QUnit.test(
"with node as parent and html string as a child",
(assert) =>
{
const parent = document.getElementById("test-parent");
append(parent, `<div class="className"></div>`);
assert.ok(parent.lastElementChild.classList.contains("className"), "is last element");
}
);
QUnit.test(
"with node as parent and an array of nodes as children",
(assert) =>
{
const parent = document.getElementById("test-parent");
const appendingChildren = [document.createElement("div"), document.createElement("div")];
append(parent, appendingChildren);
assert.equal(parent.children[2], appendingChildren[0], "is second to last element");
assert.equal(parent.children[3], appendingChildren[1], "is last element");
}
);
QUnit.test(
"with node as parent and an invalid child",
(assert) =>
{
assert.throws(
() => {
append(document.getElementById("test-parent"), null);
},
"function threw an error"
);
}
);
QUnit.test(
"with invalid parent and a node as a child",
(assert) =>
{
assert.throws(
() => {
append(null, document.createElement("div"));
},
"function threw an error"
);
}
);
|
JavaScript
| 0.000002 |
@@ -4,78 +4,159 @@
ort
-QUnit from %22qunitjs%22;%0Aimport %7Bappend%7D from %22../../../../dom/manipulate
+%7Bappend, createElement%7D from %22../../../../dom/manipulate%22;%0Aimport %7Bchildren, find, findOne%7D from %22../../../../dom/traverse%22;%0Aimport QUnit from %22qunitjs
%22;%0A%0A
@@ -253,33 +253,18 @@
-document.getElementById
+findOne
(%22
+#
quni
@@ -579,33 +579,18 @@
t =
-document.getElementById
+findOne
(%22
+#
test
@@ -631,25 +631,16 @@
Child =
-document.
createEl
@@ -649,53 +649,20 @@
ent(
-%22div%22);%0A appendingChild.classList.add(
+%60%3Cdiv class=
%22cla
@@ -668,16 +668,24 @@
assName%22
+%3E%3C/div%3E%60
);%0A
@@ -745,41 +745,15 @@
ual(
-document.getElementsByClassName
+find
(%22
+.
clas
@@ -1002,33 +1002,18 @@
t =
-document.getElementById
+findOne
(%22
+#
test
@@ -1309,33 +1309,18 @@
t =
-document.getElementById
+findOne
(%22
+#
test
@@ -1365,25 +1365,16 @@
dren = %5B
-document.
createEl
@@ -1387,25 +1387,16 @@
%22div%22),
-document.
createEl
@@ -1466,36 +1466,82 @@
-assert.equal(parent.children
+const childElements = children(parent);%0A assert.equal(childElements
%5B2%5D,
@@ -1618,23 +1618,21 @@
ual(
-parent.children
+childElements
%5B3%5D,
@@ -1837,33 +1837,18 @@
end(
-document.getElementById
+findOne
(%22
+#
test
|
48b55e8ef361ced7372e1d51cd72ff473c22f0f6
|
Fix QueueItem expanded default
|
src/routes/Queue/components/QueueItem/QueueItem.js
|
src/routes/Queue/components/QueueItem/QueueItem.js
|
import PropTypes from 'prop-types'
import React, { useCallback, useState } from 'react'
import { useDispatch } from 'react-redux'
import Buttons from 'components/Buttons'
import Icon from 'components/Icon'
import Swipeable from 'components/Swipeable'
import ToggleAnimation from 'components/ToggleAnimation'
import UserImage from 'components/UserImage'
import styles from './QueueItem.css'
import { requestPlayNext } from 'store/modules/status'
import { showSongInfo } from 'store/modules/songInfo'
import { queueSong, removeItem } from '../../modules/queue'
import { toggleSongStarred } from 'store/modules/userStars'
import { showErrorMessage } from 'store/modules/ui'
const QueueItem = props => {
const [isExpanded, setExpanded] = useState(true)
const handleSwipedLeft = useCallback(() => {
setExpanded(props.isErrored || props.isInfoable || props.isRemovable || props.isSkippable)
}, [props.isErrored, props.isInfoable, props.isRemovable, props.isSkippable])
const handleSwipedRight = useCallback(() => setExpanded(false), [])
const dispatch = useDispatch()
const handleErrorInfoClick = useCallback(() => dispatch(showErrorMessage(props.errorMessage)), [dispatch, props.errorMessage])
const handleSkipClick = useCallback(() => dispatch(requestPlayNext()), [dispatch])
const handleStarClick = useCallback(() => dispatch(toggleSongStarred(props.songId)), [dispatch, props.songId])
const handleInfoClick = useCallback(() => dispatch(showSongInfo(props.songId)), [dispatch, props.songId])
const handleRemoveClick = useCallback(() => dispatch(removeItem(props.queueId)), [dispatch, props.queueId])
return (
<Swipeable
onSwipedLeft={handleSwipedLeft}
onSwipedRight={handleSwipedRight}
preventDefaultTouchmoveEvent
trackMouse
style={{ backgroundSize: (props.isCurrent && props.pctPlayed < 2 ? 2 : props.pctPlayed) + '% 100%' }}
className={styles.container}
>
<div className={styles.content}>
<div className={`${styles.imageContainer} ${props.isPlayed ? styles.greyed : ''}`}>
<UserImage userId={props.userId} dateUpdated={props.dateUpdated} height={72} className={styles.image}/>
<div className={styles.waitContainer}>
{props.isUpcoming &&
<div className={`${styles.wait} ${props.isOwner ? styles.isOwner : ''}`}>
{props.wait}
</div>
}
</div>
</div>
<div className={`${styles.primary} ${props.isPlayed ? styles.greyed : ''}`}>
<div className={styles.innerPrimary}>
<div className={styles.title}>{props.title}</div>
<div className={styles.artist}>{props.artist}</div>
</div>
<div className={`${styles.user} ${props.isOwner ? styles.isOwner : ''}`}>
{props.userDisplayName}
</div>
</div>
<Buttons btnWidth={50} isExpanded={isExpanded}>
{props.isErrored &&
<div onClick={handleErrorInfoClick} className={`${styles.btn} ${styles.danger}`}>
<Icon icon='INFO_OUTLINE' size={44} />
</div>
}
<div onClick={handleStarClick} className={`${styles.btn} ${props.isStarred ? styles.active : ''}`}>
<ToggleAnimation toggle={props.isStarred} className={styles.animateStar}>
<Icon size={44} icon={'STAR_FULL'}/>
</ToggleAnimation>
</div>
{props.isInfoable &&
<div onClick={handleInfoClick} className={`${styles.btn} ${styles.active}`} data-hide>
<Icon icon='INFO_OUTLINE' size={44} />
</div>
}
{props.isRemovable &&
<div onClick={handleRemoveClick} className={`${styles.btn} ${styles.danger}`} data-hide>
<Icon icon='CLEAR' size={44} />
</div>
}
{props.isSkippable &&
<div onClick={handleSkipClick} className={`${styles.btn} ${styles.danger}`} data-hide>
<Icon icon='PLAY_NEXT' size={44} />
</div>
}
</Buttons>
</div>
</Swipeable>
)
}
QueueItem.propTypes = {
artist: PropTypes.string.isRequired,
dateUpdated: PropTypes.number.isRequired,
errorMessage: PropTypes.string.isRequired,
isCurrent: PropTypes.bool.isRequired,
isErrored: PropTypes.bool.isRequired,
isInfoable: PropTypes.bool.isRequired,
isOwner: PropTypes.bool.isRequired,
isPlayed: PropTypes.bool.isRequired,
isRemovable: PropTypes.bool.isRequired,
isSkippable: PropTypes.bool.isRequired,
isStarred: PropTypes.bool.isRequired,
isUpcoming: PropTypes.bool.isRequired,
pctPlayed: PropTypes.number.isRequired,
queueId: PropTypes.number.isRequired,
songId: PropTypes.number.isRequired,
title: PropTypes.string.isRequired,
userId: PropTypes.number.isRequired,
userDisplayName: PropTypes.string.isRequired,
wait: PropTypes.string,
}
export default React.memo(QueueItem)
|
JavaScript
| 0 |
@@ -745,11 +745,12 @@
ate(
-tru
+fals
e)%0A%0A
|
1f6b70abb37279c90c48671aea68d56684237776
|
Implement doesNotThrow() function.
|
lib/assertTheUnexpected.js
|
lib/assertTheUnexpected.js
|
function convertObjectToArray(obj) {
var outputArray = [];
Object.keys(obj).forEach(function (key) {
var keyAsIndex = Number(key);
if (!isNaN(keyAsIndex) && keyAsIndex > -1) {
outputArray[keyAsIndex] = obj[key];
} else {
// attach it as a property
outputArray[key] = obj[key];
}
});
return outputArray;
}
function isComparingObjectAndArray(lhs, rhs) {
var typeLhs = lhs && typeof lhs;
var typeRhs = rhs && typeof rhs;
return ((Array.isArray(lhs) && isObject(rhs)) ||
(Array.isArray(rhs) && isObject(lhs)));
}
function isDate(x) {
if (!x) {
return false;
}
return Object.prototype.toString.call(x) === '[object Date]';
}
function isObject(x) {
return typeof x === 'object';
}
function isRegExp(x) {
return x instanceof RegExp;
}
function isString(x) {
return typeof x === 'string';
}
function assertTheUnexpected(expect) {
function AssertionError(err) {
Error.call(this, '');
err = err || {};
this.name = 'AssertionError';
var assertMessage = this.name + ': ' + (err.message || '');
this.stack = assertMessage + '\n\n' + (err.stack || '');
this.message = assertMessage;
}
AssertionError.prototype = Object.create(Error.prototype);
function createWrappedExpect(localExpect) {
return function wrappedExpect() {
var args = Array.prototype.slice.apply(arguments);
// convert UnexpectedError to AssertionError
try {
localExpect.apply(localExpect, args);
} catch (err) {
throw new AssertionError(err);
}
};
}
var wrappedExpect = createWrappedExpect(expect);
function catchErrorAndThrowOriginal(block) {
try {
block();
} catch (e) {
throw e.originalError;
}
}
function checkThrows(block, errorConstraint) {
function checkError(blockError) {
expect(blockError, 'to be a', errorConstraint).catch(function () {
throw blockError;
});
}
catchErrorAndThrowOriginal(function () {
expect(function () {
block();
}, 'to error', function (blockError) {
if (errorConstraint) {
checkError(blockError);
}
});
});
}
function checkTruthy(value) {
wrappedExpect(value, 'to be truthy');
}
function prepareDeepEqual(actual, expected) {
var a = actual;
var b = expected;
if (Array.isArray(a) && Array.isArray(b)) {
a = a.slice(0);
b = b.slice(0);
for (var i = 0; i < a.length; i += 1) {
var comparisonValues = prepareEqual(a[i], b[i]);
a[i] = comparisonValues.a;
b[i] = comparisonValues.b;
}
return {
a: a,
b: b
};
} else if (
(isObject(a) && isObject(b)) &&
!(isDate(a) && isDate(b)) &&
!(isRegExp(a) && isRegExp(b)) &&
!(a === null || b === null)
) {
return {
a: Object.assign({}, a),
b: Object.assign({}, b)
}
} else if (isComparingObjectAndArray(a, b)) {
if (Array.isArray(a)) {
return {
a: a,
b: convertObjectToArray(b)
};
} else {
return {
a: convertObjectToArray(a),
b: b
};
}
}
return null;
}
function prepareEqual(actual, expected) {
var a = !actual;
var b = !expected;
// undo the null and undefined evaluate equal
if (!(a && b) && !(typeof actual === 'boolean' || typeof expected === 'boolean')) {
a = actual;
b = expected;
}
if ((Number(a) || Number(b)) && (isString(a) || isString(b))) {
a = String(a);
b = String(b);
}
return {
a: a,
b: b
};
}
return Object.assign(function (value) {
checkTruthy(value);
}, {
AssertionError: AssertionError,
deepEqual: function deepEqual(actual, expected) {
var a = actual;
var b = expected;
var comparisonValues;
// first type deep equal preparation
comparisonValues = prepareDeepEqual(a, b);
if (!comparisonValues && !(isObject(a) || isObject(b))) {
comparisonValues = prepareEqual(a, b);
}
if (comparisonValues) {
a = comparisonValues.a;
b = comparisonValues.b;
}
wrappedExpect(a, 'to equal', b);
// handle the lastIndex property
if (actual instanceof RegExp && actual.hasOwnProperty('lastIndex')) {
wrappedExpect(actual.lastIndex, 'to equal', expected.lastIndex);
}
},
deepStrictEqual: function deepStrictEqual(actual, expected) {
wrappedExpect(actual, 'to equal', expected);
if (typeof actual === 'symbol') {
wrappedExpect('symbol', 'to equal', typeof expected);
}
// handle the lastIndex property
if (actual instanceof RegExp && actual.hasOwnProperty('lastIndex')) {
wrappedExpect(actual.lastIndex, 'to equal', expected.lastIndex);
}
},
equal: function equal(actual, expected) {
var comarisonValues = prepareEqual(actual, expected);
var a = comarisonValues.a;
var b = comarisonValues.b;
wrappedExpect(a, 'to be', b);
},
ifError: function ifError(value) {
wrappedExpect(value, 'to be falsy').then(function () {
throw value;
});
},
notEqual: function notEqual(actual, expected) {
wrappedExpect(actual, 'not to be', expected);
},
notDeepEqual: function notDeepEqual(actual, expected) {
wrappedExpect(actual, 'not to equal', expected);
},
notDeepStrictEqual: function notDeepStrictEqual(actual, expected) {
wrappedExpect(actual, 'not to equal', expected);
},
notStrictEqual: function notStrictEqual(actual, expected) {
wrappedExpect(actual, 'not to equal', expected);
},
ok: function (value) {
checkTruthy(value);
},
strictEqual: function strictEqual(actual, expected) {
wrappedExpect(actual, 'to equal', expected);
},
throws: function (block, expected) {
checkThrows(block, expected);
}
});
}
module.exports = assertTheUnexpected(require('unexpected'));
|
JavaScript
| 0.000001 |
@@ -1750,24 +1750,397 @@
%0A %7D%0A %7D%0A%0A
+ function checkNotThrow(block, errorConstraint) %7B%0A try %7B%0A expect(function () %7B%0A block();%0A %7D, 'not to error');%0A %7D catch (e) %7B%0A var blockError = e.originalError;%0A%0A try %7B%0A expect(blockError, 'not to be a', errorConstraint);%0A %7D catch (e2) %7B%0A throw new AssertionError(blockError);%0A %7D%0A%0A throw blockError;%0A %7D%0A %7D%0A%0A
function c
@@ -5280,24 +5280,116 @@
%7D%0A %7D,%0A
+ doesNotThrow: function (block, expected) %7B%0A checkNotThrow(block, expected);%0A %7D,%0A
equal: f
|
d43c3bc9c9e43bb8729a8fa78455d44140df57c6
|
check if we have gluestick in dependencies
|
packages/gluestick/src/cli/execWithConfig.js
|
packages/gluestick/src/cli/execWithConfig.js
|
const path = require('path');
const preparePlugins = require('../config/preparePlugins');
const compileGlueStickConfig = require('../config/compileGlueStickConfig');
const compileWebpackConfig = require('../config/compileWebpackConfig');
const logger = require('./logger');
const execHooks = (context, hooks) => {
if (Array.isArray(hooks)) {
hooks.forEach(fn => fn(context));
} else if (typeof hooks === 'function') {
hooks(context);
}
};
type ExecWithConfig = (
func: Function,
commandArguments: Array<*>,
options: {
useGSConfig: boolean;
useWebpackConfig: boolean;
skipProjectConfig: boolean;
skipClientEntryGeneration: boolean;
skipServerEntryGeneration: boolean;
},
hooks: {
pre: Function;
post: Function;
}
) => void;
module.exports = (
func,
commandArguments,
{
useGSConfig,
useWebpackConfig,
skipProjectConfig,
skipClientEntryGeneration,
skipServerEntryGeneration,
} = {},
{ pre, post } = {},
): ExecWithConfig => {
const projectConfig = skipProjectConfig
? {}
: require(path.join(process.cwd(), 'package.json')).gluestick;
const plugins = preparePlugins(projectConfig);
const GSConfig = useGSConfig ? compileGlueStickConfig(plugins, projectConfig) : null;
const webpackConfig = useWebpackConfig ? compileWebpackConfig(
logger, plugins, projectConfig, GSConfig,
{ skipClientEntryGeneration, skipServerEntryGeneration },
) : null;
const context = {
config: {
projectConfig,
GSConfig,
webpackConfig,
plugins,
},
logger,
};
try {
execHooks(context, pre);
func(context, ...commandArguments);
execHooks(context, post);
} catch (error) {
process.stderr.write(error.message);
process.exit(1);
}
};
|
JavaScript
| 0 |
@@ -1009,62 +1009,57 @@
%7B%0A
-const projectConfig = skipProjectConfig%0A ?
+let packageJson = null;%0A try
%7B
-%7D
%0A
-:
+packageJson =
req
@@ -1104,16 +1104,288 @@
.json'))
+;%0A if (!packageJson.dependencies.gluestick) %7B%0A throw new Error('Command need to be run in gluestick project.');%0A %7D%0A %7D catch (error) %7B%0A logger.error(error.message);%0A process.exit(1);%0A %7D%0A const projectConfig = skipProjectConfig%0A ? %7B%7D%0A : packageJson
.gluesti
|
328f14ad144677420d2268e1cff4bccec92f8e64
|
Add postcss on webpack build config
|
modules/der-reader/config/webpack.config.build.js
|
modules/der-reader/config/webpack.config.build.js
|
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: {
'der-reader': ['./src/der-reader.js'],
'index': './src/index.js'
},
output: {
path: __dirname + '/../dist/',
filename: '[name].js',
library: 'DerReader',
libraryTarget: 'umd'
},
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loaders: [
'babel'
],
},
]
},
externals: {
version: JSON.stringify(require('../package.json').version)
},
plugins: [new HtmlWebpackPlugin({
template: 'src/index.ejs',
filename: 'index.html'
})]
}
|
JavaScript
| 0.000001 |
@@ -82,16 +82,98 @@
lugin');
+%0A/* import postcss config array */%0Avar postCSSConfig = require('./postcss.config')
%0A%0Amodule
@@ -563,16 +563,71 @@
%5D%0A %7D,%0A
+ postcss: function() %7B%0A return postCSSConfig;%0A %7D,%0A
extern
|
6c24d0749f9caf7ab146dca1986f7997b9bc9872
|
use minified version of OpenVeo Player
|
tests/client/frontOfficeKarmaConf.js
|
tests/client/frontOfficeKarmaConf.js
|
'use strict';
// Karma configuration
module.exports = function(config) {
config.set({
// Base path that will be used to resolve all patterns
// (eg. files, exclude)
basePath: '../../',
// Plugins to load
plugins: [
'karma-chai',
'karma-mocha',
'karma-chrome-launcher'
],
// List of files / patterns to load in the browser
files: [
'node_modules/angular/angular.js',
'node_modules/angular-animate/angular-animate.js',
'node_modules/angular-aria/angular-aria.js',
'node_modules/angular-route/angular-route.js',
'node_modules/angular-cookies/angular-cookies.js',
'node_modules/angular-mocks/angular-mocks.js',
'node_modules/angular-sanitize/angular-sanitize.js',
'node_modules/angular-messages/angular-messages.js',
'node_modules/angular-material/angular-material.js',
'node_modules/angulartics/dist/angulartics.min.js',
'node_modules/angulartics-piwik/dist/angulartics-piwik.min.js',
'node_modules/chai-spies/chai-spies.js',
'node_modules/he/he.js',
'node_modules/@openveo/player/dist/openveo-player.js',
'assets/themes/default/i18n/openveo-portal-locale_en.js',
'assets/themes/default/conf.js',
'tests/client/unitTests/init.js',
'app/client/front/js/authentication/AuthenticationApp.js',
'app/client/front/js/i18n/I18nApp.js',
'app/client/front/js/storage/StorageApp.js',
'app/client/front/js/ov/OvApp.js',
'app/client/front/views/*.html',
'app/client/front/js/**/*.js',
'tests/client/unitTests/*.js'
]
});
};
|
JavaScript
| 0 |
@@ -1132,16 +1132,20 @@
-player.
+min.
js',%0A
|
4cc399a05e64e1777e220a18897804e6b06ad2e1
|
Fix bad method name
|
lib/common/manipulation/map.js
|
lib/common/manipulation/map.js
|
'use strict';
/**
* Expose `Map`.
*/
module.exports = Map;
/**
* Initialize a new map.
*/
function Map() {
this._items = {};
this._name = '';
}
Map.defineImplementedInterfaces(['danf:manipulation.map']);
Map.defineDependency('_name', 'string|null');
/**
* @interface {danf:manipulation.map}
*/
Object.defineProperty(Map.prototype, 'name', {
get: function() { return this._name; },
set: function(name) { this._name = name; }
});
/**
* @interface {danf:manipulation.map}
*/
Map.prototype.set = function(name, item) {
this._items[name] = item;
}
/**
* @interface {danf:manipulation.map}
*/
Map.prototype.unset = function(name) {
if (this._items[name]) {
delete this._items[name];
}
}
/**
* @interface {danf:manipulation.map}
*/
Map.prototype.clear = function() {
for (var name in this._items) {
this.deregister(name);
}
}
/**
* @interface {danf:manipulation.map}
*/
Map.prototype.has = function(name) {
return this._items[name] ? true : false;
}
/**
* @interface {danf:manipulation.map}
*/
Map.prototype.get = function(name) {
if (!this.has(name)) {
throw new Error(
'The item "{0}" has not been set {1}.'.format(
name,
this._name ? 'in context "{0}"'.format(this._name) : ''
)
);
}
return this._items[name];
}
/**
* @interface {danf:manipulation.map}
*/
Map.prototype.getAll = function() {
return this._items;
}
|
JavaScript
| 0.999751 |
@@ -862,18 +862,13 @@
his.
-deregister
+unset
(nam
|
afdf09dedbd459bf8ed838270f271c6faa758b2e
|
Fix by code review
|
tests/dummy/app/views/application.js
|
tests/dummy/app/views/application.js
|
import Ember from 'ember';
export default Ember.Component.extend({
tagName: ''
});
|
JavaScript
| 0 |
@@ -21,16 +21,183 @@
mber';%0A%0A
+/**%0A * Overload wrapper tag name for disabling wrapper.%0A *%0A * The sidebar, as per Semantic-UI's documentation,%0A * will need to be directly below the body element.%0A */%0A
export d
|
f6d8a5db21ca0eda93e1156e5146f3790c9f3f15
|
fix THREEShader uniforms
|
three/THREEShader.js
|
three/THREEShader.js
|
import { Vector2 as THREEVector2 } from "three/src/math/Vector2.js";
import { Vector3 as THREEVector3 } from "three/src/math/Vector3.js";
import { Vector4 as THREEVector4 } from "three/src/math/Vector4.js";
import { Matrix3 as THREEMatrix3 } from "three/src/math/Matrix3.js";
import { Matrix4 as THREEMatrix4 } from "three/src/math/Matrix4.js";
import { Texture as THREETexture } from "three/src/textures/Texture.js";
import { CubeTexture as THREECubeTexture } from "three/src/textures/CubeTexture.js";
import Shader from "dlib/webgl/Shader.js";
export default class THREEShader extends Shader {
constructor({vertexShader = `
void main() {
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.);
}
`, fragmentShader = `
void main() {
gl_FragColor = vec4(1.);
}
`, uniforms = {}} = {}) {
super({vertexShader, fragmentShader, uniforms});
}
parseQualifiers() {
super.parseQualifiers({
classes: {
Vector2: THREEVector2,
Vector3: THREEVector3,
Vector4: THREEVector4,
Matrix3: THREEMatrix3,
Matrix4: THREEMatrix4,
TextureCube: THREECubeTexture,
Texture2D: THREETexture
}
});
for (let key in this.uniforms) {
let uniform = this.uniforms[key];
if(typeof uniform !== "object" || !uniform.value) {
this.uniforms[key] = {
value: uniform
}
}
}
}
}
|
JavaScript
| 0.000201 |
@@ -1317,17 +1317,16 @@
ect%22 %7C%7C
-!
uniform.
@@ -1330,16 +1330,30 @@
rm.value
+ === undefined
) %7B%0A
|
663daf22746524aefe57e756f76345d7d9f23a53
|
Update config
|
gatsby-config.js
|
gatsby-config.js
|
module.exports = {
siteMetadata: {
title: `Satyajeet Pal`,
description: `Personal blog.`,
author: `@psatyajeet`,
},
plugins: [
{
resolve: `gatsby-source-filesystem`,
options: {
name: `src`,
path: `${__dirname}/src/`,
},
},
`gatsby-transformer-remark`,
`gatsby-plugin-react-helmet`,
{
resolve: `gatsby-source-filesystem`,
options: {
name: `images`,
path: `${__dirname}/src/images`,
},
},
`gatsby-transformer-sharp`,
`gatsby-plugin-sharp`,
{
resolve: `gatsby-plugin-manifest`,
options: {
name: `personal-site`,
short_name: `starter`,
start_url: `/`,
background_color: `#663399`,
theme_color: `#663399`,
display: `minimal-ui`,
// icon: `src/images/gatsby-icon.png`, // This path is relative to the root of the site.
},
},
'gatsby-plugin-offline',
{
resolve: `gatsby-plugin-typography`,
options: {
pathToConfigModule: `src/utils/typography.js`,
},
},
`gatsby-plugin-styled-components`,
// this (optional) plugin enables Progressive Web App + Offline functionality
// To learn more, visit: https://gatsby.app/offline
// 'gatsby-plugin-offline',
],
}
|
JavaScript
| 0.000001 |
@@ -916,37 +916,8 @@
%7D,%0A
- 'gatsby-plugin-offline',%0A
@@ -1229,19 +1229,16 @@
line%0A
- //
'gatsby
|
d41235c2d9a13d5a8b985e2a143ecb83f547b3ba
|
fix world icon in search example (#1695)
|
docs/app/Examples/modules/Dropdown/Types/DropdownExampleSearchDropdown.js
|
docs/app/Examples/modules/Dropdown/Types/DropdownExampleSearchDropdown.js
|
import React from 'react'
import { Dropdown } from 'semantic-ui-react'
import { languageOptions } from '../common'
// languageOptions = [ { key: 'Arabic', text: 'Arabic', value: 'Arabic' }, ... ]
/**
* NOTE: In this example, the dropdown should contain a label on the
* left of the text:
* <i class="world icon"></i>
*
* @returns {Element}
*/
const DropdownExampleSearchDropdown = () => (
<Dropdown text='Select Language' search floating labeled button className='icon' options={languageOptions} />
)
export default DropdownExampleSearchDropdown
|
JavaScript
| 0.000001 |
@@ -196,161 +196,8 @@
%5D%0A%0A
-/**%0A * NOTE: In this example, the dropdown should contain a label on the%0A * left of the text:%0A * %3Ci class=%22world icon%22%3E%3C/i%3E%0A *%0A * @returns %7BElement%7D%0A */%0A
cons
@@ -276,15 +276,23 @@
age'
+%0A
search
+%0A
flo
@@ -300,16 +300,20 @@
ting
+%0A
labeled
but
@@ -312,15 +312,23 @@
eled
+%0A
button
+%0A
cla
@@ -340,16 +340,37 @@
e='icon'
+%0A icon='world'%0A
options
@@ -387,16 +387,18 @@
Options%7D
+%0A
/%3E%0A)%0A%0Ae
|
0ce6855d84b714943aa59f575e1d07ccd1e1eeec
|
add a new config for gatsby-remark-images
|
gatsby-config.js
|
gatsby-config.js
|
module.exports = {
siteMetadata: {
title: `Eder Christian`,
position: `Partner and Front-end Developer`,
description: `A blog about front-end development and other cool stuff`,
author: `@ederchristian`,
},
plugins: [
`gatsby-plugin-styled-components`,
`gatsby-plugin-react-helmet`,
{
resolve: `gatsby-source-filesystem`,
options: {
name: `images`,
path: `${__dirname}/src/images`,
},
},
{
resolve: `gatsby-source-filesystem`,
options: {
name: `posts`,
path: `${__dirname}/posts`,
},
},
{
resolve: `gatsby-transformer-remark`,
options: {
plugins: [],
},
},
`gatsby-transformer-sharp`,
`gatsby-plugin-sharp`,
{
resolve: `gatsby-plugin-manifest`,
options: {
name: `gatsby-starter-default`,
short_name: `starter`,
start_url: `/`,
background_color: `#663399`,
theme_color: `#663399`,
display: `minimal-ui`,
icon: `src/images/gatsby-icon.png`,
},
},
{
resolve: "gatsby-plugin-react-svg",
options: {
rule: {
include: /assets/
}
}
},
],
}
|
JavaScript
| 0 |
@@ -363,32 +363,187 @@
options: %7B%0A
+ name: %60uploads%60,%0A path: %60$%7B__dirname%7D/static/assets/img%60,%0A %7D,%0A %7D,%0A %7B%0A resolve: %60gatsby-source-filesystem%60,%0A options: %7B%0A
name: %60i
@@ -833,16 +833,386 @@
ugins: %5B
+%0A %7B%0A resolve: %22gatsby-remark-relative-images%22,%0A options: %7B%0A name: %22uploads%22%0A %7D%0A %7D,%0A %7B%0A resolve: %22gatsby-remark-images%22,%0A options: %7B%0A maxWidth: 960,%0A linkImagesToOriginal: false%0A %7D%0A %7D,%0A %60gatsby-remark-lazy-load%60,%0A
%5D,%0A
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.