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
|
---|---|---|---|---|---|---|---|
08fab995cccffd35a7f6618c539394a38c3eb0d8 | Make the issue appear in the tests | test/specs/scenarios.js | test/specs/scenarios.js | const expect = require('expect');
const { run, createProject } = require('../cli');
describe('Child Entries', () => {
beforeEach(createProject);
it('should be able to delete a child entry with a new configuration', function* () {
const firstConfig = {
parent: { entry: 'entryToDelete' },
};
yield run(`echo '${JSON.stringify(firstConfig)}' > firstConfig.json`);
yield run('comfy setall development firstConfig.json');
const { stdout: firstConfigOutput } = yield run('comfy get development');
expect(JSON.parse(firstConfigOutput)).toEqual(firstConfig);
const secondConfig = {
parent: { child: { entry: 'entry' } },
child: { entry: 'entry' },
};
yield run(`echo '${JSON.stringify(secondConfig)}' > secondConfig.json`);
yield run('comfy setall development secondConfig.json');
const { stdout: secondConfigOutput } = yield run('comfy get development');
expect(JSON.parse(secondConfigOutput)).toEqual(secondConfig);
});
});
| JavaScript | 0.000039 | @@ -92,20 +92,16 @@
be('
-Child Entrie
+Scenario
s',
@@ -136,24 +136,66 @@
eProject);%0A%0A
+ describe('Child Entries', () =%3E %7B%0A
it('shou
@@ -275,24 +275,28 @@
) %7B%0A
+
const firstC
@@ -297,32 +297,36 @@
firstConfig = %7B%0A
+
pare
@@ -353,24 +353,28 @@
oDelete' %7D,%0A
+
%7D;%0A%0A
@@ -373,32 +373,36 @@
%7D;%0A%0A
+
yield run(%60echo
@@ -456,32 +456,36 @@
json%60);%0A
+
yield run('comfy
@@ -525,32 +525,36 @@
son');%0A%0A
+
const %7B stdout:
@@ -611,32 +611,36 @@
ment');%0A
+
expect(JSON.pars
@@ -688,24 +688,28 @@
);%0A%0A
+
const second
@@ -711,32 +711,36 @@
econdConfig = %7B%0A
+
pare
@@ -786,16 +786,20 @@
+
child: %7B
@@ -817,36 +817,44 @@
try' %7D,%0A
-%7D;%0A%0A
+ %7D;%0A%0A
yield ru
@@ -918,32 +918,36 @@
json%60);%0A
+
yield run('comfy
@@ -980,32 +980,36 @@
Config.json');%0A%0A
+
const %7B
@@ -1075,32 +1075,36 @@
ment');%0A
+
expect(JSON.pars
@@ -1149,16 +1149,490 @@
onfig);%0A
+ %7D);%0A %7D);%0A%0A describe('Boolean serialization', () =%3E %7B%0A it('should not transform a %60false%60 bool to a %60%22false%22%60 string', function* () %7B%0A const config = %7B myEntry: false %7D;%0A%0A yield run(%60echo '$%7BJSON.stringify(config)%7D' %3E config.json%60);%0A yield run('comfy setall development config.json');%0A%0A const %7B stdout %7D = yield run('comfy get development');%0A expect(JSON.parse(stdout)).toEqual(config);%0A %7D);%0A
%7D);%0A
|
d14b044e1ebd2b87c60274aeec23e48301bf0e47 | improve term test | test/standalone/term.js | test/standalone/term.js | // https://github.com/chuckremes/nn-core/blob/master/spec/nn_term_spec.rb
var nano = require('../../');
var test = require('tape');
test('throw exception when seding on socket after term() called', function (t) {
t.plan(1);
var sock = nano.socket('pub');
sock.on('error', function (err) {
t.ok('error was thrown on send after term');
sock.close();
});
sock.send("Hello");
nano.term();
});
| JavaScript | 0.000003 | @@ -156,16 +156,17 @@
when se
+n
ding on
@@ -209,18 +209,16 @@
n (t) %7B%0A
-
t.plan
@@ -223,18 +223,16 @@
an(1);%0A%0A
-
var so
@@ -256,19 +256,53 @@
'pub');%0A
-%0A
+sock.bind('tcp://127.0.0.1:9999')%0A%0A
sock.o
@@ -337,27 +337,102 @@
- t.ok('error was
+t.equals(err.message,%0A 'Nanomsg library was terminated',%0A 'library termination error
thr
@@ -457,18 +457,16 @@
term');%0A
-
so
@@ -481,19 +481,15 @@
();%0A
-
%7D);%0A%0A
-
so
@@ -506,18 +506,16 @@
ello%22);%0A
-
nano.t
@@ -526,10 +526,8 @@
);%0A%0A%7D);%0A
-%0A%0A
|
7d1a708cbfccbc528ea817d5c38fce8eb6e6a072 | Fix apiClient middleware action issue | src/api-client.js | src/api-client.js | import Url from 'url'
import Superagent from 'superagent'
import { merge } from 'lodash'
export default function clientMiddleware(req, options) {
let client = new ApiClient(req, options)
return store => next => action => {
return next({ client, action })
}
}
const methods = ['get', 'post', 'put', 'patch', 'del']
export class ApiClient {
static defaults = {
server: {
protocol: 'http',
host: 'localhost',
pathname: '/'
},
client: {
pathname: '/'
}
}
constructor(req, options) {
this.options = merge({}, ApiClient.defaults, options)
methods.forEach(method => {
this[method] = this.genericMethod.bind(this, method)
})
}
genericMethod(method, path, options) {
if (!options) { options = {} }
let aborted = false
let dfd = deferred()
let request = Superagent[method](this.formatUrl(path))
if (options.params) {
request.query(options.params)
}
if (SERVER && req.get('cookie')) {
request.set('cookie', req.get('cookie'))
}
if (options.data) {
request.send(options.data)
}
else if (options.attach) {
let formData = new FormData()
let files = options.attach
for (let key in files) {
if (files.hasOwnProperty(key) && files[key] instanceof File) {
formData.append(`files`, files[key])
}
}
request.send(formData)
}
dfd.promise.abort = function() {
aborted = true
request.abort()
}
request.end((err, res) => {
if (!aborted) {
if (err) {
return dfd.reject((res && res.body) || err)
}
dfd.resolve(res.body)
}
})
return dfd.promise
}
formatUrl(path) {
const config = SERVER ? this.options.server : this.options.client
const adjustedPath = path[0] === '/' ? '/' : `/${path}`
if (config.base) {
config.pathname = config.base
}
const baseUrl = Url.format(config)
return Url.resolve(baseUrl, adjustedPath)
}
}
function deferred() {
let resolve, reject,
promise = new Promise((_resolve, _reject)=> {
resolve = _resolve
reject = _reject
})
return {
promise,
resolve,
reject
}
}
| JavaScript | 0.000009 | @@ -249,24 +249,51 @@
action =%3E %7B%0A
+ action.client = client%0A
return n
@@ -300,26 +300,14 @@
ext(
-%7B client,
action
- %7D
)%0A
|
1b7348124d31489aad9f74e8b5cd4ede25397e0f | Add delete stage route | src/api/routes.js | src/api/routes.js | 'use strict'
let express = require('express')
let middleware = {
auth: require('./middleware/auth'),
notFound: require('./middleware/not-found')
}
let controllers = {
pipelines: require('./controllers/pipelines'),
pipelineExecutions: require('./controllers/pipeline-executions'),
projects: require('./controllers/projects'),
user: require('./controllers/user'),
checks: require('./controllers/checks'),
stages: require('./controllers/stages')
}
module.exports = function(app) {
// Authentication Verification middleware
app.use('/api/*', middleware.auth)
// Authentication
app.post('/login', controllers.user.login)
app.all('/logout', controllers.user.logout)
// User
app.get('/api/user', controllers.user.getUser)
// Projects
app.get('/api/projects', controllers.projects.getProjects)
app.post('/api/projects', controllers.projects.createProject)
app.get('/api/projects/with-pipelines', controllers.projects.getProjectsWithPipelines)
app.get('/api/projects/:id', controllers.projects.getProject)
// Pipelines
app.get('/api/pipelines', controllers.pipelines.getList)
app.post('/api/pipelines', controllers.pipelines.createPipeline)
app.get('/api/pipelines/:id', controllers.pipelines.getPipeline)
app.get('/api/pipelines/:id/executions', controllers.pipelineExecutions.getListForPipeline)
app.post('/api/pipelines/:id/execute', controllers.pipelines.executePipeline)
// Pipeline Stages
app.get('/api/pipelines/:id/stages', controllers.stages.getListForPipeline)
app.get('/api/stage-types', controllers.stages.getAvailableTypes)
app.post('/api/stage/config', controllers.stages.setStageConfig)
// Pipeline Executions
// TODO: GET /api/pipeline-executions
app.get('/api/pipeline-executions/recent', controllers.pipelineExecutions.getRecent)
app.get('/api/pipeline-executions/:id/with-details', controllers.pipelineExecutions.getOneWithDetails)
// TODO: POST /api/pipeline-executions
// Pipeline Stage Executions
// Pipeline Execution Logs
// Health Checks
app.get('/api/checks', controllers.checks.getAll)
app.post('/api/check', controllers.checks.create)
// Static files
app.use(express.static('./node_modules/mc-core/ui-build/'))
// 404
app.use(middleware.notFound)
}
| JavaScript | 0.000001 | @@ -1583,24 +1583,25 @@
lableTypes)%0A
+%0A
app.post('
@@ -1654,16 +1654,85 @@
eConfig)
+%0A app.delete('/api/stage/:id', controllers.stages.deleteStageConfig)
%0A%0A // P
|
22dbc645d370d8421b2feebe28a3096b00125ec2 | Add (failing) test for stripping file paths from error messages | test/error-parser.js | test/error-parser.js | const assert = require('assert');
var ErrorParser = require("../lib/error-parser.js");
/**
* The first test in this suite will take some time to run, this is because
* its loading the `pos` library
*/
describe('ErrorParser', function() {
describe('parse', function() {
let parser = new ErrorParser();
let username = 'test-username';
beforeEach(function() {
// the parser expects the first line to be an input line
parser.parse(`${username}$`);
});
it('should flag errors correctly', function() {
// given
let message = "ERROR: x is undefined";
// when
let result = parser.parse(message);
// then
let expected = "ERROR: is undefined";
assert.equal(result, expected);
});
it('should flag a real stacktrace correctly', function() {
// given
let message = "2015-05-29T09:35:09.793Z - error: [api] TypeError: Cannot call method 'logger' of undefined stack=TypeError: Cannot call method 'logger' of undefined";
// when
let result = parser.parse(message);
// then
let expected = "2015-05-29T09:35:09.793Z - error: [api] TypeError: Cannot call method of undefined stack=TypeError: Cannot call method of undefined";
assert.equal(result, expected);
});
it('should flag errors when they start with a different username', function() {
// given
let message = "username2$ error";
// when
let result = parser.parse(message);
// then
assert.equal(result, message);
});
it('should not flag empty lines', function() {
// given
let message = "";
// when
let result = parser.parse(message);
// then
assert.equal(result, null);
});
it('should not flag input lines', function() {
// given
let message = `${username}$ test_command`;
// when
let result = parser.parse(message);
// then
assert.equal(result, null);
});
it('should not flag input lines even if they contain the word error', function() {
// given
let message = `${username}$ input line with the word error`;
// when
let result = parser.parse(message);
// then
assert.equal(result, null);
});
it('should not flag input lines where the username has error in it', function() {
// given
let message = "error-username$ input line";
parser = new ErrorParser();
// when
parser.parse('error-username$');
let result = parser.parse(message);
// then
assert.equal(result, null);
});
it('should not flag error output when an input line contained a blacklisted command', function() {
// given
let message = `${username}$ ls -la`;
parser = new ErrorParser();
// when
let result = parser.parse(message);
assert.equal(result, null);
result = parser.parse('-rw-r--r-- 1 username groupname 0 23 Oct 00:00 error.txt');
// then
assert.equal(result, null);
});
it('should resume flagging error output after a blacklisted command when a new input is received', function() {
// send blacklisted input - we don't care about the result, this has already been tested
let message = `${username}$ ls -la`;
let result = parser.parse(message);
// check error output while blacklisted command is running
message = '-rw-r--r-- 1 username groupname 0 23 Oct 00:00 error.txt'
result = parser.parse(message);
assert.equal(result, null);
// send non-blacklisted input - we don't care about the result, this has already been tested
message = `${username}$ some_other_command`;
result = parser.parse(message);
// ensure error output is now tracked again
message = "ERROR";
result = parser.parse(message);
let expected = "ERROR";
assert.equal(result, expected);
});
it('should not flag white space', function() {
// given
let message = `
\r\n
`;
// when
let result = parser.parse(message);
// then
assert.equal(result, null);
});
it('should not flag general output', function() {
// given
let message = "Normal output with nothing weird about it";
// when
let result = parser.parse(message);
// then
assert.equal(result, null);
});
});
});
| JavaScript | 0 | @@ -3906,32 +3906,717 @@
cted);%0A %7D);%0A%0A
+ it('should remove file paths from errors', function() %7B%0A // given%0A let message = %22PHP Parse error: syntax error, unexpected ';' in /Users/tallytarik/work/bert/test.php on line 1%22;%0A // when%0A let result = parser.parse(message);%0A // then%0A // TODO: this expected error message format would be ideal for searching, but also goes beyond the scope of /just/ removing the file path%0A // Either of the following two would be acceptable%0A let expected = %22PHP Parse error: syntax error, unexpected ';'%22;%0A // OR:%0A // let expected = %22PHP Parse error: syntax error, unexpected ';' in on line 1%22;%0A assert.equal(result, expected);%0A %7D);%0A%0A
it('should n
|
22fa94039a8583377fbb9d38eb286e5856dbf78b | Improve extends query tests | test/extends.test.js | test/extends.test.js | var path = require('path')
var fs = require('fs-extra')
var browserslist = require('../')
var mocked = []
function mock (name, exports) {
var dir = path.join(__dirname, '..', 'node_modules', name)
mocked.push(dir)
return fs.ensureDir(dir).then(() => {
var content = 'module.exports = ' + JSON.stringify(exports)
return fs.writeFile(path.join(dir, 'index.js'), content)
})
}
afterEach(() => {
return Promise.all(mocked.map(dir => fs.remove(dir))).then(() => {
mocked = []
})
})
it('uses package', () => {
return mock('browserslist-config-test', ['ie 11']).then(() => {
var result = browserslist(['extends browserslist-config-test', 'edge 12'])
expect(result).toEqual(['edge 12', 'ie 11'])
})
})
it('works with non-prefixed package with dangerousExtend', () => {
return mock('pkg', ['ie 11']).then(() => {
var result = browserslist(['extends pkg', 'edge 12'], {
dangerousExtend: true
})
expect(result).toEqual(['edge 12', 'ie 11'])
})
})
it('handles scoped packages', () => {
return mock('@scope/browserslist-config-test', ['ie 11']).then(() => {
var result = browserslist(['extends @scope/browserslist-config-test'])
expect(result).toEqual(['ie 11'])
})
})
it('handles scoped packages when package is @scope/browserslist-config', () => {
return mock('@scope/browserslist-config', ['ie 11']).then(() => {
var result = browserslist(['extends @scope/browserslist-config'])
expect(result).toEqual(['ie 11'])
})
})
it('recursively imports configs', () => {
return Promise.all([
mock('browserslist-config-a', ['extends browserslist-config-b', 'ie 9']),
mock('browserslist-config-b', ['ie 10'])
]).then(() => {
var result = browserslist(['extends browserslist-config-a'])
expect(result).toEqual(['ie 10', 'ie 9'])
})
})
it('handles relative queries in external packages with local overrides', () => {
return mock('browserslist-config-rel', ['ie 9-10']).then(() => {
var result = browserslist(['extends browserslist-config-rel', 'not ie 9'])
expect(result).toEqual(['ie 10'])
})
})
it('throws when external package does not resolve to an array', () => {
return mock('browserslist-config-wrong', { not: 'an array' }).then(() => {
expect(() => {
browserslist(['extends browserslist-config-wrong'])
}).toThrowError(/not an array/)
})
})
it('throws when package does not have browserslist-config- prefix', () => {
expect(() => {
browserslist(['extends thing-without-prefix'])
}).toThrowError(/needs `browserslist-config-` prefix/)
})
it('throws when extends package has "." in path', () => {
expect(() => {
browserslist(['extends browserslist-config-package/../something'])
}).toThrowError(/`.` not allowed/)
})
it('throws when extends package has node_modules in path', () => {
expect(() => {
browserslist(['extends browserslist-config-test/node_modules/a'])
}).toThrowError(/`node_modules` not allowed/)
})
| JavaScript | 0.000002 | @@ -725,24 +725,246 @@
%5D)%0A %7D)%0A%7D)%0A%0A
+it('uses file in package', () =%3E %7B%0A return mock('browserslist-config-test/ie', %5B'ie 11'%5D).then(() =%3E %7B%0A var result = browserslist(%5B'extends browserslist-config-test/ie'%5D)%0A expect(result).toEqual(%5B'ie 11'%5D)%0A %7D)%0A%7D)%0A%0A
it('works wi
|
8d48b736a14a55f521f93c37f2302581453ffab7 | use createEndpoint() | test/fileEndpoint.js | test/fileEndpoint.js | /* global describe, it*/
/* jslint node: true, esnext: true */
"use strict";
const fs = require('fs');
const path = require('path');
const assert = require('assert');
const endpointImpl = require('../lib/endpointImplementation');
describe('file endpoint implementation', function () {
const fileImpl = endpointImpl.implementations.file;
const myEndpoint = Object.create(endpointImpl.defaultEndpoint, {
value: {
value: "file:" + path.join(__dirname, 'fixtures', 'file1.txt')
},
direction: {
value: 'in'
}
});
const in1 = fileImpl.implementation(myEndpoint)();
//console.log(`in1: ${in1}`);
for (let request in in1) {
console.log(`request: ${request}`);
}
/*
let request = in1.next();
assert(request.stream !== undefined);
*/
});
| JavaScript | 0.000001 | @@ -283,18 +283,17 @@
n () %7B%0A%0A
-
+%09
const fi
@@ -337,18 +337,17 @@
.file;%0A%0A
-
+%09
const my
@@ -361,22 +361,8 @@
t =
-Object.create(
endp
@@ -374,23 +374,22 @@
mpl.
-default
+create
Endpoint
, %7B%0A
@@ -388,36 +388,25 @@
oint
-, %7B%0A value: %7B%0A value
+('e1', %7B%0A%09%09target
: %22f
@@ -462,66 +462,35 @@
xt')
-%0A %7D,%0A direction: %7B%0A value: 'in'%0A %7D%0A
+,%0A%09%09direction: 'in'%0A%09
%7D);%0A%0A
-
+%09
cons
@@ -537,18 +537,17 @@
nt)();%0A%0A
-
+%09
//consol
@@ -569,18 +569,17 @@
n1%7D%60);%0A%0A
-
+%09
for (let
@@ -597,20 +597,18 @@
in1) %7B%0A
-
+%09%09
console.
@@ -639,22 +639,19 @@
%60);%0A
- %7D%0A%0A /*%0A
+%09%7D%0A%0A%09/*%0A%09
-
let
@@ -672,18 +672,17 @@
next();%0A
-
+%09
assert
@@ -713,18 +713,17 @@
fined);%0A
-
+%09
*/%0A%0A%7D);%0A
|
1507ca2dc9360481181ffc4ed28c298f5f90f380 | remove only | test/git-checkout.js | test/git-checkout.js | describe.only("git-checkout, when GHM is in use,", function(){
beforeEach(function(done){
TEST_SUITE.setup(true, true, true, function(err){
if(err){
done(err);
}
else{
TEST_SUITE.git.__makeAddAndCommitFile("test", "test", done);
}
});
});
describe("when checking out a branch", function(){
it("should run", function(done){
TEST_SUITE.git.checkout("-b test", function(err, stdout, stderr){
if(err){
done(err);
}
else{
try{
stderr.should.equal("Switched to a new branch 'test'\npost-checkout\n\n");
done();
}
catch(err){
done(err);
}
}
});
});
});
describe("when checking out a file", function(){
it("should reset to old content if the file has changed", function(done){
TEST_SUITE.mkfile("test", "hmmmm", function(err){
if(err){
done(err);
}
else{
TEST_SUITE.git.checkout("-- test", function(err, stdout, stderr){
if(err){
done(err);
}
else{
try{
stderr.should.equal("post-checkout\n\n");
TEST_SUITE.getFileContents("test").should.equal("test\n");
done();
}
catch(err){
done(err);
}
}
});
}
});
});
});
}); | JavaScript | 0.000001 | @@ -5,13 +5,8 @@
ribe
-.only
(%22gi
|
05793a2a9489a999074e769220947d3734cbda6e | Add launch() convenience function | test/support/TestApp.js | test/support/TestApp.js | 'use strict';
import sinon from 'sinon'
import Promise from 'bluebird'
import { Dispatcher } from '../../'
class TestApp extends Dispatcher {
constructor() {
super()
this.log = sinon.spy();
this.config = {};
this.on = sinon.spy(this.on);
this.once = sinon.spy(this.once);
this.await = sinon.spy();
this._gather = sinon.createStubInstance(Promise);
this._send_with = sinon.createStubInstance(Promise);
this._send = {
with: sinon.stub().returns(this._send_with)
}
this._get = {
gather: sinon.stub().returns(this._gather),
send: sinon.stub().returns(this._send)
};
this.get = sinon.stub().returns(this._get);
}
}
export default TestApp;
| JavaScript | 0.000003 | @@ -692,16 +692,156 @@
;%0A%0A %7D%0A%0A
+ launch() %7B%0A return new Promise.mapSeries(%5B'init', 'load', 'startup', 'launch'%5D, (e) =%3E %7B%0A return this.emit(e).with();%0A %7D)%0A %7D%0A%0A
%7D%0A%0Aexpor
|
85eb691c41360e0652396fb9de41ec54aaa1dae8 | use new resource() function | test/journey-test.js | test/journey-test.js | var journey = require('../lib/journey'),
vows = require('../../vows/lib/vows');
var sys = require('sys'),
http = require('http'),
assert = require('assert'),
url = require('url');
var mock = {
mockRequest: function (method, path, headers) {
var uri = url.parse(path || '/', true);
return {
listeners: [],
method: method,
headers: headers || { accept: "application/json", "Content-Type":'application/json' },
url: uri,
setBodyEncoding: function (e) { this.bodyEncoding = e },
addListener: function (event, callback) {
this.listeners.push({ event: event, callback: callback });
if (event == 'body') {
var body = this.body;
this.body = '';
callback(body);
} else { callback() }
}
};
},
mockResponse: function () {
return {
body: null,
finished: false,
status: 200,
headers: [],
sendHeader: function (status, headers) {
this.status = status;
this.headers = headers;
},
sendBody: function (body) { this.body = body },
finish: function () { this.finished = true }
};
},
request: function (method, path, headers, body) {
return journey.server.handler(this.mockRequest(method, path, headers),
this.mockResponse(), body);
}
}
// Convenience functions to send mock requests
var get = function (p, h) { return mock.request('GET', p, h) }
var del = function (p, h) { return mock.request('DELETE', p, h) }
var post = function (p, h, b) { return mock.request('POST', p, h, b) }
var put = function (p, h, b) { return mock.request('PUT', p, h, b) }
var routes = function (map) {
map.route('GET', 'picnic/fail').to(map.resources["picnic"].fail);
map.get('home/room').to(map.resources["home"].room);
map.route('GET', /^(\w+)$/).
to(function (res, r) { return map.resources[r].index(res) });
map.route('GET', /^(\w+)\/([0-9]+)$/).
to(function (res, r, k) { return map.resources[r].get(res, k) });
map.route('PUT', /^(\w+)\/([0-9]+)$/, { payload: true }).
to(function (res, r, k) { return map.resources[r].update(res, k) });
map.route('POST', /^(\w+)$/, { payload: true }).
to(function (res, r, doc) { return map.resources[r].create(res, doc) });
map.route('DELETE', /^(\w+)\/([0-9]+)$/).
to(function (res, r, k) { return map.resources[r].destroy(res, k) });
map.route('GET', '/').to(function (res) { return map.resources["home"].index(res) });
};
journey.resources = {
"home": {
index: function (res) {
res.send([200, {"Content-Type":"text/html"}, "honey I'm home!"]);
},
},
"picnic": {
fail: function () {
throw "fail!";
}
},
"kitchen": {},
"recipies": {}
};
journey.ENV = 'test';
vows.tell('Journey', {
//
// SUCCESSFUL (2xx)
//
"A valid HTTP request": {
setup: function () { return get('/', { accept: "application/json" }) },
"returns a 200": function (res) {
assert.equal(res.status, 200);
assert.equal(res.body, "honey I'm home!");
assert.match(res.body, /honey/);
assert.ok(res.finished);
}
},
"A request with uri parameters": {
setup: function () {
// URI parameters get parsed into a javascript object, and are passed to the
// function handler like so:
journey.resources["home"].room = function (res, params) {
res.send([200, {"Content-Type":"text/html"}, JSON.stringify(params)]);
};
return get('/home/room?slippers=on&candles=lit');
},
"gets parsed into an object": function (res) {
var home = JSON.parse(res.body);
assert.equal(home.slippers, 'on');
assert.equal(home.candles, 'lit');
assert.equal(res.status, 200);
}
},
"A POST request": {
setup: function () {
// Here, we're sending a POST request; the input is parsed into an object, and passed
// to the function handler as a parameter.
// We expect Journey to respond with a 201 'Created', if the request was successful.
journey.resources["kitchen"].create = function (res, input) {
res.send(201, "cooking-time: " + (input['chicken'].length + input['fries'].length) + 'min');
};
return post('/kitchen', null, {"chicken":"roasted", "fries":"golden"})
},
"returns a 201": function (res) {
assert.equal(res.body, 'cooking-time: 13min');
assert.equal(res.status, 201);
}
},
//
// Representational State Transfer (REST)
//
//journey.resources["recipies"].index = function (params) {
//
//};
//get('/recipies').addCallback(function (res) {
// //var doc = JSON.parse(res.body);
// //assert.ok(doc.includes("recipies"));
// //assert.ok(doc.recipies.is(Array));
//});
//
// CLIENT ERRORS (4xx)
//
// Journey being a JSON only server, asking for text/html returns 'Bad Request'
"A request for text/html": {
setup: function () {
return get('/', { accept: "text/html" });
},
"returns a 400": function (res) { assert.equal(res.status, 400) }
},
// This request won't match any pattern, because of the '@',
// it's therefore considered invalid
"A request for text/html": {
setup: function () {
return get('/hello/@');
},
"returns a 400": function (res) {
assert.equal(res.status, 400);
}
},
// Trying to access an unknown resource will result in a 404 'Not Found',
// as long as the uri format is valid
"A request for an unknown resource": {
setup: function () {
return get('/unknown');
},
"returns a 404": function (res) {
assert.equal(res.status, 404);
}
},
// Here, we're trying to use the DELETE method on /
// Of course, we haven't allowed this, so Journey responds with a
// 405 'Method not Allowed', and returns the allowed methods
"A request with an unsupported method": {
setup: function () {
return del('/');
},
"returns a 405": function (res) {
assert.equal(res.status, 405);
assert.equal(res.headers.allow, 'GET');
}
},
//
// SERVER ERRORS (5xx)
//
// The code in `picnic.fail` throws an exception, so we return a
// 500 'Internal Server Error'
"A request to a controller with an error in it": {
setup: function () {
return get('/picnic/fail');
},
"returns a 500": function (res) {
assert.equal(res.status, 500);
}
}
});
journey.router.draw(routes);
| JavaScript | 0.000003 | @@ -2136,20 +2136,19 @@
resource
-s%5Br%5D
+(r)
.index(r
|
d0282aad4f2fed5a777ac9f99828e2e1c800dfca | Fix flowtype | src/background.js | src/background.js | // @flow
declare var chrome: any
import shouldCompress from './background/shouldCompress'
import patchContentSecurity from './background/patchContentSecurity'
import getHeaderValue from './background/getHeaderIntValue'
import parseUrl from './utils/parseUrl'
import deferredStateStorage from './utils/deferredStateStorage'
import defaultState from './defaults'
import type { AppState } from './types'
chrome.storage.sync.get((storedState: AppState) => {
const storage = deferredStateStorage()
let state: AppState
let pageUrl: string
let isWebpSupported
setState({ ...defaultState, ...storedState })
checkWebpSupport().then(isSupported => {
isWebpSupported = isSupported
})
async function checkWebpSupport() {
if (!self.createImageBitmap) return false
const webpData =
'data:image/webp;base64,UklGRh4AAABXRUJQVlA4TBEAAAAvAAAAAAfQ//73v/+BiOh/AAA='
const blob = await fetch(webpData).then(r => r.blob())
return createImageBitmap(blob).then(() => true, () => false)
}
/**
* Sync state.
*/
function setState(newState: AppState) {
if (!state || state.enabled !== newState.enabled) {
chrome.browserAction.setIcon({
path: newState.enabled
? 'assets/icon-128.png'
: 'assets/icon-128-disabled.png'
})
}
state = newState
}
/**
* Intercept image loading request and decide if we need to compress it.
*/
function onBeforeRequestListener({ url }) {
if (
shouldCompress({
imageUrl: url,
pageUrl,
proxyUrl: state.proxyUrl,
disabledHosts: state.disabledHosts,
enabled: state.enabled
})
) {
let redirectUrl = `${state.proxyUrl}?url=${encodeURIComponent(url)}`
if (!isWebpSupported) redirectUrl += '&jpeg=1'
return { redirectUrl }
}
}
/**
* Retrieve saved bytes info from response headers, update statistics in
* app storage and notify UI about state changes.
*/
function onCompletedListener({ responseHeaders }) {
const bytesSaved = getHeaderValue(responseHeaders, 'x-bytes-saved')
const bytesProcessed = getHeaderValue(responseHeaders, 'x-original-size')
if (bytesSaved !== false && bytesProcessed !== false) {
state.statistics.filesProcessed += 1
state.statistics.bytesProcessed += bytesProcessed
state.statistics.bytesSaved += bytesSaved
storage.set(state)
chrome.runtime.sendMessage(state)
}
}
/**
* Patch document's content security policy headers so that it will allow
* images loading from our compression proxy URL.
*/
function onHeadersReceivedListener({ responseHeaders }) {
return {
responseHeaders: patchContentSecurity(responseHeaders, state.proxyUrl)
}
}
chrome.runtime.onMessage.addListener(setState)
chrome.webRequest.onBeforeRequest.addListener(
onBeforeRequestListener,
{
urls: ['<all_urls>'],
types: ['image']
},
['blocking']
)
chrome.webRequest.onCompleted.addListener(
onCompletedListener,
{
urls: ['<all_urls>'],
types: ['image']
},
['responseHeaders']
)
chrome.webRequest.onHeadersReceived.addListener(
onHeadersReceivedListener,
{
urls: ['<all_urls>'],
types: ['main_frame', 'sub_frame']
},
['blocking', 'responseHeaders']
)
chrome.tabs.onActivated.addListener(({ tabId }) => {
chrome.tabs.get(tabId, tab => (pageUrl = parseUrl(tab.url).hostname))
})
})
| JavaScript | 0.000001 | @@ -948,16 +948,21 @@
return
+self.
createIm
|
0f17246e5374f1cf7be2bb44935e33e2f7f3a6fd | Use YUI JSON | lib/ymdp/javascripts/jquery/init.js | lib/ymdp/javascripts/jquery/init.js | /*
INITIALIZER CODE
*/
// Adds behaviors/observers to elements on the page
//
YMDP.Init.addBehaviors = function() {
// overwrite this function locally
};
// hide the loading screen and show the main body of the summary
YMDP.Init.show = function() {
Debug.log("YMDP.Init.show");
$('#utility').hide();
$('#error').hide();
$('#loading').hide();
$('#main').show();
};
// Local initializer. When your page starts up, this method will be called after fetching the user's guid and ymail wssid.
//
YMDP.Init.local = function() {
throw("This hasn't been overwritten.");
// overwrite this function locally
};
// To be run before any other initializers have run.
//
YMDP.Init.before = function() {
// overwrite this function locally
};
// Main startup code. Overwrite this function to execute after YMDP.Init.before and before YMDP.Init.after.
//
YMDP.Init.startup = function() {
Debug.log("init.startup");
// gets the user
YMDP.getGuid(function(guid) {
Reporter.reportCurrentView(guid);
callback = function() {
try {
YMDP.Init.local();
} catch(omg) {
Debug.error("Error in YMDP.Init.local", omg);
YMDP.showError();
}
};
YMDP.getUserState(callback, callback);
});
};
YMDP.Init.abTesting = function() {
// to enable abTesting in your view, overwrite this file locally.
//
// be sure to finish your post-Ajax callback with YMDP.Init.show()
//
YMDP.Init.show();
YMDP.Init.after();
};
// Finishing code. Runs after startup, executes translations and behaviors. Shows the page and then
// runs the A/B testing callback, which in turn will execute the last callbacks.
//
YMDP.Init.finish = function() {
Debug.log("init.finish for view " + View.name);
YMDP.showTranslations();
Debug.log("addBehaviors:");
YMDP.Init.addBehaviors();
Debug.log("abTesting:");
YMDP.Init.abTesting();
Debug.log("page_loaded = true:");
View.page_loaded = true;
Debug.log("finished init.finish for view " + View.name);
};
// Post-initalizer. Very last thing that runs, after content has been shown.
//
YMDP.Init.after = function() {
// overwrite this function locally
};
// Execute the before, startup and after methods. Do not overwrite. (Change YMDP.Init.startup to create a custom initializer.)
YMDP.init = function() {
Debug.log("OIB.init for view " + View.name, "<%= @message %>");
Logger.init();
Tags.init();
YMDP.Init.browser();
YMDP.Init.resources();
I18n.addLanguageToBody();
I18n.translateLoading();
I18n.translateError();
YMDP.Init.before();
YMDP.Init.startup();
};
YMDP.Init.browser = function() {
if ($.browser.webkit) {
$('body').addClass('webkit');
}
};
YMDP.Init.resources = function() {
Debug.log("about to call I18n.setResources");
I18n.availableLanguages = <%= supported_languages.to_json %>;
I18n.currentLanguage = OpenMailIntl.findBestLanguage(I18n.availableLanguages);
I18n.setResources();
Debug.log("finished calling I18n.setResources");
};
// Contains the last two callbacks, to show the page contents and run post-show function. Do not overwrite.
YMDP.Init.showAndFinish = function() {
Debug.log("YMDP.Init.showAndFinish");
YMDP.Init.show();
YMDP.Init.after();
};
| JavaScript | 0.000004 | @@ -2289,32 +2289,96 @@
= function() %7B%0A
+ YUI().use('json', function (Y) %7B%0A window.JSON = Y.JSON;%0A%0A
Debug.log(%22OIB
@@ -2427,16 +2427,18 @@
e %25%3E%22);%0A
+
Logger
@@ -2446,16 +2446,18 @@
init();%0A
+
Tags.i
@@ -2459,24 +2459,26 @@
ags.init();%0A
+
YMDP.Init.
@@ -2484,24 +2484,26 @@
.browser();%0A
+
YMDP.Init.
@@ -2511,24 +2511,26 @@
esources();%0A
+
I18n.addLa
@@ -2543,24 +2543,26 @@
ToBody();%0A
+
+
I18n.transla
@@ -2576,16 +2576,18 @@
ng();%0A
+
+
I18n.tra
@@ -2597,24 +2597,26 @@
ateError();%0A
+
YMDP.Init.
@@ -2621,24 +2621,26 @@
t.before();%0A
+
YMDP.Init.
@@ -2646,24 +2646,30 @@
.startup();%0A
+ %7D);%0A
%7D;%0A%0AYMDP.Ini
|
57b2df65a3b5f60e4626c5b3db3b2fc580de56b4 | Fix spawn arguments sent to the runner | src/bin/runner.js | src/bin/runner.js | import { spawn } from "child_process"
import { join } from "path"
const cwd = process.cwd()
export default
(defaultOptions) =>
(argv) => {
// get real args, after the node script
// by relying on yargs $0
const realArgs = process.argv.slice(process.argv.indexOf(argv.$0) + 1)
// get argv that are not recognized as command by yargs
const args = realArgs.filter((arg) => argv._.indexOf(arg) === -1)
spawn(
"node",
[
join(__dirname, "runner-cmd.js"),
join(cwd, argv.script),
// pass collected args, or default if there is none
...args.length ? args : defaultOptions,
],
{
stdio: "inherit",
env: {
...process.env,
BABEL_DISABLE_CACHE: process.env.BABEL_DISABLE_CACHE || 1,
DEBUG: process.env.DEBUG || "statinamic:*",
STATINAMIC_CONFIG:
process.env.STATINAMIC_CONFIG || join(cwd, argv.config),
},
}
)
// close current process with spawned code
// allow to exit(1) if spawned exited with 1
.on("close", process.exit)
}
| JavaScript | 0 | @@ -427,39 +427,28 @@
-spawn(%0A %22node%22,%0A
+const spawnArgs =
%5B%0A
-
@@ -485,26 +485,24 @@
js%22),%0A
-
join(cwd, ar
@@ -523,117 +523,89 @@
- // pass collected args, or default if there is none%0A ...args.length ? args : defaultOptions,%0A %5D
+...defaultOptions,%0A ...args,%0A %5D%0A%0A spawn(%0A %22node%22,%0A spawnArgs
,%0A
|
a0abea9dd8b112f2da6a2c395ebea055cf74df11 | version bump | dist/boily.js | dist/boily.js | /*!
* boily v4.1.2
* (c) 2016 KFlash
* Released under the MIT License.
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global.Boily = factory());
}(this, function () { 'use strict';
var boily = { foo: 123 };
// Correct version will be set with the 'rollup-replace plugin'
boily.version = 'VERSION';
// Flow example
function foo(one, two, three) {}
boily.flow = foo;
return boily;
}));
//# sourceMappingURL=boily.js.map
| JavaScript | 0.000001 | @@ -11,17 +11,17 @@
ly v4.1.
-2
+4
%0A * (c)
|
c244b8bc3d1b88aa07fc1e5814e4cb57f9932752 | change ver | src/buryPoint2.js | src/buryPoint2.js | /**
* @file: PoliceDog web performance script for client side
* @author by zhangxiang
* @update 2017.05
*/
(function(){
/**
* Browser compatibility:
* Some brower cannot handle the interface(window.performance), so we must add some code to compatibile some bowser
*
*/
if(window.addEventListener){
window.addEventListener('load', function(){
});
} else if(window.attachEvent) {
window.attachEvent('onload', function(){
});
} else {
if(window.onload) {
let loadFunc = window.onload;
window.onload = function(){
/**do some thing */
loadFunc();
}
} else {
window.onload = function(){
/**do something */
}
}
}
function getPerformance(){
let perf = null;
perf = window.performance ? window.performance : (window.wekitPerformance ? window.webkitPerformance : window.msPerformance);
return perf;
}
/**
* to count the static source situation
*/
function toAnalysisStaticResource(perf){
let entries = perf.getEntries();
let javascriptNum = 0, cssNum = 0, imgNum = 0, javascriptTime = 0, cssTime = 0, imgTime = 0;
entries.forEach(function(data, i){
//to count time of the different type of resource
switch (data.initiatorType) {
case 'script':
javascriptNum ++;
javascriptTime += data.responseEnd - data.startTime
break;
case 'css':
cssNum ++;
cssTime += data.responseEnd - data.startTime;
break;
case 'img':
imgNum ++;
imgTime += data.responseEnd - data.startTime;
break;
}
});
const staticSourceInfo = {
'num': entries.length,
'javascriptNum': javascriptNum,
'cssNum': cssNum,
'imgNum': imgNum,
'javascriptUseTime': javascriptTime,
'cssUseTime': cssTime,
'imgUsetime': imgTime
}
return staticSourceInfo;
}
policeReport['staticResource loadSituation'] = toAnalysisStaticResource(perf);
/**
* to count the DNS Query time
*/
let DNSquery = resource.domainLookupEnd - resource.domainLookupStart;
policeReport['DNS Query'] = DNSquery;
/**
*to count the TCP connect time
*/
let TCPconnect = resource.connectEnd - resource.connectStart;
policeReport['TCP Connect'] = TCPconnect;
/**
* to count the request time
*/
let requestTime = resource.requestEnd - resource.requestStart;
/**
* to count the response time
*/
let responseTime = resource.responseEnd - resource.responseStart;
policeReport['Request Time'] = responseTime;
/**
* 白屏时间
*/
let whiteTime = resource.responseStart - resource.navigationStart;
policeReport['WhiteScreen Time'] = whiteTime;
/**
* 解析 DOM 树耗费时间
*/
let DOMAnalysis = resource.domContentLoadedEventEnd - resource.navigationStart;
policeReport['DOM Analysis'] = DOMAnalysis;
/**
* load time
*/
let loadTime = resource.loadEventEnd - resource.navigationStart;
policeReport['Load Time'] = loadTime;
console.log(policeReport);
//分开 IE 与高级浏览器
})(); | JavaScript | 0.000003 | @@ -2313,31 +2313,25 @@
%0A %7D%0A%0A
-policeR
+r
eport%5B'stati
@@ -2512,39 +2512,33 @@
ookupStart;%0A
-policeR
+r
eport%5B'DNS Query
@@ -2673,31 +2673,25 @@
tStart;%0A
-policeR
+r
eport%5B'TCP C
@@ -2954,31 +2954,25 @@
eStart;%0A
-policeR
+r
eport%5B'Reque
@@ -3098,31 +3098,25 @@
nStart;%0A
-policeR
+r
eport%5B'White
@@ -3264,31 +3264,25 @@
nStart;%0A
-policeR
+r
eport%5B'DOM A
@@ -3414,23 +3414,17 @@
rt;%0A
-policeR
+r
eport%5B'L
|
08cce4aad15baa004f131a4a0ff9cc9896a1ef3c | Update version string to 2.5.4-pre.2 | version.js | version.js | (function (enyo, scope) {
/**
A library of UI widgets designed for use alongside Enyo core in the
development of smart TV applications.
@namespace moon
*/
var moon = scope.moon = scope.moon || {};
if (enyo && enyo.version) {
enyo.version.moonstone = "2.5.3-pre.7";
}
/**
* Global *design-time* configuration options for Moonstone
*
* @param {Boolean} accelerate `true` to prefer CSS transforms over position properties
* @type {Object}
*/
moon.config = enyo.mixin({
accelerate: false
}, moon.config);
})(enyo, this);
| JavaScript | 0.000001 | @@ -266,15 +266,15 @@
2.5.
-3
+4
-pre.
-7
+2
%22;%0A%09
|
2e082d4417fe44f3499b75e0fdd198f23dc97c3c | Add test to verify initialize behavior | test/reducer.spec.js | test/reducer.spec.js | import { reducer } from '../src'
import {
authenticateSucceeded,
authenticateFailed,
invalidateSession,
restore,
restoreFailed
} from '../src/actions'
describe('session reducer', () => {
it('returns default state when initialized', () => {
const expected = {
authenticator: null,
isAuthenticated: false,
data: {}
}
const state = reducer(undefined, {})
expect(state).toEqual(expected)
})
it('handles INVALIDATE_SESSION', () => {
const currentState = { isAuthenticated: true, data: { token: 'abcdefg' } }
const expected = {
authenticator: null,
isAuthenticated: false,
data: {}
}
const state = reducer(currentState, invalidateSession())
expect(state).toEqual(expected)
})
it('handles AUTHENTICATE_SUCCEEDED', () => {
const currentState = { isAuthenticated: false }
const expected = {
isAuthenticated: true,
authenticator: 'test',
data: { token: 'abcdefg' }
}
const state = reducer(
currentState,
authenticateSucceeded('test', { token: 'abcdefg' })
)
expect(state).toEqual(expected)
})
it('handles AUTHENTICATE_FAILED', () => {
const currentState = { isAuthenticated: false, data: {} }
const expected = { authenticator: null, isAuthenticated: false, data: {} }
const state = reducer(currentState, authenticateFailed())
expect(state).toEqual(expected)
})
it('handles RESTORE', () => {
const currentState = reducer(undefined, {})
const expected = {
authenticator: 'credentials',
isAuthenticated: true,
data: { token: '1234' }
}
const state = reducer(
currentState,
restore({ authenticator: 'credentials', token: '1234' })
)
expect(state).toEqual(expected)
})
it('handles RESTORE_FAILED', () => {
const currentState = reducer(undefined, {})
const expected = {
authenticator: null,
isAuthenticated: false,
data: {}
}
const state = reducer(currentState, restoreFailed())
expect(state).toEqual(expected)
})
})
| JavaScript | 0 | @@ -82,16 +82,30 @@
Failed,%0A
+ initialize,%0A
invali
@@ -437,32 +437,418 @@
expected)%0A %7D)%0A%0A
+ it('handles INITIALIZE', () =%3E %7B%0A const sessionData = %7B%0A authenticated: %7B%0A authenticator: 'credentials',%0A token: 'abcde'%0A %7D%0A %7D%0A const expected = %7B%0A authenticator: 'credentials',%0A isAuthenticated: false,%0A data: %7B token: 'abcde' %7D%0A %7D%0A%0A const state = reducer(null, initialize(sessionData))%0A%0A expect(state).toEqual(expected)%0A %7D)%0A%0A
it('handles IN
|
d6ab2e5e5f0ca5c8c59aa576a80aa07e737a7fe6 | load debugging | api/index.js | api/index.js | const express = require('express');
const bodyParser = require('body-parser');
const siteSession = require('./siteConfig').siteSession;
const router = require('./router');
const socket = require('./socket');
const cors = require('cors');
const app = express();
app.use(cors());
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
router(app);
const http = require('http').Server(app);
/*
const io = require('socket.io')(http);
socket(io);
*/
const PORT = 3500;
http.listen(PORT, function () {
console.log('Server listening on: ' + PORT);
});
| JavaScript | 0.000002 | @@ -411,11 +411,8 @@
p);%0A
-/*%0A
cons
@@ -461,11 +461,8 @@
io);
-%0A*/
%0A%0Aco
|
bade894ba774530e6593d128b503f14400d0d549 | add test, 4 failed now | test/test-context.js | test/test-context.js | 'use strict';
var assert = require('chai').assert,
testlib = require('../lib/test'),
context = require('../lib/context.js');
describe('context', function () {
it('.query should be a subtask', function (done) {
assert.equal(true, testlib.isSubtask(testlib.getMockContext().query));
done();
});
it('.param should be a subtask', function (done) {
assert.equal(true, testlib.isSubtask(testlib.getMockContext().param));
done();
});
it('.cookie should be a subtask', function (done) {
assert.equal(true, testlib.isSubtask(testlib.getMockContext().cookie));
done();
});
it('.data should be a subtask', function (done) {
assert.equal(true, testlib.isSubtask(testlib.getMockContext().data));
done();
});
it('.page should be a subtask', function (done) {
assert.equal(true, testlib.isSubtask(testlib.getMockContext().page));
done();
});
it('.react should be a subtask', function (done) {
assert.equal(true, testlib.isSubtask(testlib.getMockContext().react));
done();
});
it('.dreact should be a subtask', function (done) {
assert.equal(true, testlib.isSubtask(testlib.getMockContext().dreact));
done();
});
it('.task should be a subtask', function (done) {
assert.equal(true, testlib.isSubtask(testlib.getMockContext().task));
done();
});
});
| JavaScript | 0 | @@ -790,32 +790,193 @@
one();%0A %7D);%0A%0A
+ it('.module should be a subtask', function (done) %7B%0A assert.equal(true, testlib.isSubtask(testlib.getMockContext().module));%0A done();%0A %7D);%0A%0A
it('.page sh
|
2f8b7d983e764b13977e9d16b230e40793308e81 | Update test description | test/test-suspend.js | test/test-suspend.js | var StringBuilder = require('../src/string-builder');
var assert = require('chai').assert;
var sinon = require('sinon');
var jsonfile = require('jsonfile');
var file = './fixtures/data.json';
var fixtures = jsonfile.readFileSync(file);
describe('StringBuilder #suspend', function() {
it('Iterate over collection', function(){
var sb = new StringBuilder();
var sections = ['section-1', 'section-2', 'section-3'];
var expected = '<row>section-1 section-2 section-3 <row>';
sb.wrap('<', '>')
.cat('row')
.suspend()
.each(sections, function(section, index){
this.cat(section, ' ')
})
.suffix('\n')
.end(1)
.cat('row')
assert.equal(expected, sb.string());
});
});
| JavaScript | 0.000001 | @@ -291,31 +291,20 @@
it('
-Iterate over collection
+Suspend wrap
', f
|
361811758797996fbba4ade55e97e164f84ada36 | Fix DreamView to not load dreams on initialize. #17 | toast/public/assets/js/app.js | toast/public/assets/js/app.js | $(function() {
////////
// Views
////////
// Dream mini view
var DreamMiniView = Backbone.View.extend
(
{
tagName: "div",
className: "span3 center",
template: $("#dreamTemplate").html(),
render: function ()
{
var variables = {name: this.model.get('name'), count: this.model.get('count')};
var tmpl = _.template(this.template);
//this.$el.html(tmpl(this.model.toJSON())); // <-- fails here
//this.$el.html(tmpl(this.model.toJSON())); // <-- fails here
$(this.el).html(tmpl(this.model.toJSON())); // <-- this worked
return this;
}
}
);
var DreamView = Backbone.View.extend
(
{
el: "#thedream",
template: $("#theDreamTemplate").html(),
model: Dream,
initialize: function(options)
{
var url = '/dreams/get/' + options['name'];
this.model = new Dream([], {url: url});
this.listenTo( this.model, 'sync', this.render ); // Trigger render when model has been loaded
this.model.fetch
();
},
render: function()
{
//alert('here');
var tmpl = _.template(this.template);
//alert(this.model.toJSON());
$(this.el).html(tmpl(this.model.toJSON()));
}
}
);
// DreamList
var DreamListView = Backbone.View.extend
(
{
//el: $('#populardreams'), // attaches `this.el` to an existing element.
initialize: function(options)
{
var url = options["url"];
this.collection = new DreamList([], {url: url});
this.collection.fetch({type: "GET", reset: true});
_.bindAll(this, 'render'); // fixes loss of context for 'this' within methods
//this.render(); // not all views are self-rendering. This one is.
this.listenToOnce( this.collection, 'reset', this.render ); // Trigger render when list has been loaded
},
render: function()
{
var that = this;
var i = 0;
var div_row_fluid;
//alert(this.collection.toJSON());
_.each(
this.collection.models,
function (item)
{
if(i % 4 == 0)
{
div_row_fluid = $('<div class=\"row-fluid\"></div>');
$(this.el).append(div_row_fluid);
//$(this.el).append("<div class=\"row-fluid\">");
}
//$(that.el).append(item.render().el);
that.renderDream(div_row_fluid, item);
//if(i % 4 == 0)
//{
// $(this.el).append("</div>");
//}
//$(that.el).append(item.render().el);
i++;
},
this
);
},
renderDream: function(div_row_fluid, item)
{
var dreamMiniView = new DreamMiniView
(
{
model: item
}
);
//$(this.el).append(dreamMiniView.render().el);
div_row_fluid.append(dreamMiniView.render().el);
}
}
);
// Models & Collections
var Dream = Backbone.Model.extend();
var TopDreams = Backbone.Collection.extend({
model: Dream,
url: '/dreams/top',
parse: function(response) {
return response;
}
});
var RecentDreams = Backbone.Collection.extend({
model: Dream,
url: '/dreams/recent',
parse: function(response) {
return response;
}
});
// Router
var Router = Backbone.Router.extend({
routes: {
'': 'index',
'dreams': 'dreams'
}
});
// Views
var IndexView = Backbone.View.extend({
el: '#hook',
events: {
'click button#btn-submit': 'addDream'
},
initialize: function() {
_.bindAll(this, 'render', 'addDream');
var self = this;
},
render: function(tmpl, data) {
var self = this;
var template = _.template($("#tmpl_index").html(),
{});
this.$el.html( template );
// Hide the spinner after the template renders.
$('#spinner', self.el).hide();
return this;
},
addDream: function() {
console.log('Add dream!');
var self = this;
var dream = $('#dream', self.el).val();
$('#spinner', self.el).show();
// This should really be a model call.
$.getJSON('/dreams/add/' + dream, function(result) {
router.navigate('dreams', {trigger: true});
});
}
});
DreamsView = Backbone.View.extend({
el: '#hook',
template: '#tmpl_dreams',
initialize: function() {
_.bindAll(this, 'render');
var self = this;
self.dream = new Dream();
self.topDreams = new TopDreams();
self.recentDreams = new RecentDreams();
self.topDreams.fetch();
self.recentDreams.fetch();
// dependencies
self.topDreams.on('sync', self.render);
self.recentDreams.on('sync', self.render);
},
render: function() {
var self = this;
var template = _.template($(self.template).html(),
{dream: self.dream,
topDreams: self.topDreams.models,
recentDreams: self.recentDreams.models});
this.$el.html( template );
return this;
}
});
// Instantiations
var indexView = new IndexView();
var dreamsView = new DreamsView();
var router = new Router();
router.on('route:index', function() {
console.log('Load the index page!');
indexView.render();
});
router.on('route:dreams', function() {
console.log('Load the dreams page!');
dreamsView.render();
});
// Let's get this party started!
Backbone.history.start();
});
| JavaScript | 0 | @@ -4353,19 +4353,27 @@
'render'
+, 'load'
);%0A
-
@@ -4533,83 +4533,8 @@
s();
-%0A self.topDreams.fetch();%0A self.recentDreams.fetch();
%0A%0A
@@ -5066,32 +5066,211 @@
return this;%0A
+ %7D,%0A load: function() %7B%0A var self = this;%0A // Go fetch some dreams!%0A self.topDreams.fetch();%0A self.recentDreams.fetch();%0A
%7D%0A %7D)
@@ -5630,30 +5630,28 @@
dreamsView.
-render
+load
();%0A %7D);%0A
|
9cabfe315a8eb4a564afda1c72dc8717e3e8b678 | configure baseUrl comment | src/client/app.js | src/client/app.js | (function() {
var lib_path = '/res/lib/';
var config = {
paths: {
jquery: lib_path + 'jquery',
'jquery-ui': lib_path + 'jquery-ui',
'd3': lib_path + 'd3/d3',
FileSaver: lib_path + 'FileSaver',
caret: lib_path + 'caret',
autocomplete: lib_path + 'autocomplete',
Bacon: lib_path + 'Bacon',
}
}
config.urlArgs = (typeof local_config != 'undefined') && local_config.urlArgs;
if (window.is_node) {
// Testing path only
console.log('app: running under node');
config.baseUrl = '../src/';
window.rhizi_require_config = config;
} else {
// Main app path
require.config(config);
requirejs(['main'], function(main) {
console.log('starting rhizi logic');
main.main();
});
}
}());
| JavaScript | 0.000001 | @@ -656,16 +656,160 @@
else %7B%0A
+ // %5B!%5D no need to configure baseUrl, as in%0A // config.baseUrl = ...%0A // generated script URLs include the basepath of app.js%0A%0A
// M
|
e8255cf46ee77626e9eef1c2909899c9508173da | add `timeoutAfter` test with Promises | test/timeoutAfter.js | test/timeoutAfter.js | 'use strict';
var tape = require('../');
var tap = require('tap');
var concat = require('concat-stream');
var stripFullStack = require('./common').stripFullStack;
tap.test('timeoutAfter test', function (tt) {
tt.plan(1);
var test = tape.createHarness();
var tc = function (rows) {
tt.same(stripFullStack(rows.toString('utf8')), [
'TAP version 13',
'# timeoutAfter',
'not ok 1 timeoutAfter timed out after 1ms',
' ---',
' operator: fail',
' stack: |-',
' Error: timeoutAfter timed out after 1ms',
' [... stack stripped ...]',
' ...',
'',
'1..1',
'# tests 1',
'# pass 0',
'# fail 1'
].join('\n') + '\n');
};
test.createStream().pipe(concat(tc));
test('timeoutAfter', function (t) {
t.plan(1);
t.timeoutAfter(1);
});
});
| JavaScript | 0 | @@ -965,12 +965,1760 @@
%7D);%0A%7D);%0A
+%0Atap.test('timeoutAfter with Promises', function (tt) %7B%0A tt.plan(1);%0A%0A var test = tape.createHarness();%0A var tc = function (rows) %7B%0A tt.same(stripFullStack(rows.toString('utf8')), %5B%0A 'TAP version 13',%0A '# timeoutAfter with promises',%0A '# fulfilled promise',%0A 'not ok 1 fulfilled promise timed out after 1ms',%0A ' ---',%0A ' operator: fail',%0A ' stack: %7C-',%0A ' Error: fulfilled promise timed out after 1ms',%0A ' %5B... stack stripped ...%5D',%0A ' ...',%0A '# rejected promise',%0A 'not ok 2 rejected promise timed out after 1ms',%0A ' ---',%0A ' operator: fail',%0A ' stack: %7C-',%0A ' Error: rejected promise timed out after 1ms',%0A ' %5B... stack stripped ...%5D',%0A ' ...',%0A '',%0A '1..2',%0A '# tests 2',%0A '# pass 0',%0A '# fail 2'%0A %5D.join('%5Cn') + '%5Cn');%0A %7D;%0A%0A test.createStream().pipe(concat(tc));%0A%0A test('timeoutAfter with promises', function (t) %7B%0A t.plan(2);%0A%0A t.test('fulfilled promise', function (st) %7B%0A st.plan(1);%0A st.timeoutAfter(1);%0A%0A return new Promise(function (resolve) %7B%0A setTimeout(function () %7B%0A resolve();%0A %7D, 2);%0A %7D);%0A %7D);%0A%0A t.test('rejected promise', function (st) %7B%0A st.plan(1);%0A st.timeoutAfter(1);%0A%0A return new Promise(function (reject) %7B%0A setTimeout(function () %7B%0A reject();%0A %7D, 2);%0A %7D);%0A %7D);%0A %7D);%0A%7D);%0A
|
0b7b30bed0608f81a6a52b45481af0b7b6fe533c | Add correspondingCost handling to old model | model/submission/index.js | model/submission/index.js | 'use strict';
var Map = require('es6-map')
, memoize = require('memoizee/plain')
, defineStringLine = require('dbjs-ext/string/string-line')
, _ = require('mano').i18n.bind('Model: Submissions')
, defineDocument = require('../document');
module.exports = memoize(function (db) {
var StringLine = defineStringLine(db)
, Document = defineDocument(db);
var RejectReason = StringLine.createEnum('RejectReason', new Map([
["illegible", {
label: _("The document is unreadable")
}],
["invalid", {
label: _("The loaded document does not match the required document")
}],
["other", {
label: _("Other") + "..."
}]
]));
return db.Object.extend('Submission', {
document: { type: Document, nested: true },
approved: { type: db.Boolean, required: true, trueLabel: _("Valid"), falseLabel: _("Invalid") },
matchesOriginal: { type: db.Boolean, required: true },
rejectReasonType: { type: RejectReason, required: true, label: _("Reject document") },
rejectReasonMemo: { type: db.String, required: true, label: _("Explanation") },
rejectReason: { type: db.String, label: _("Reject document"), required: true,
value: function () {
var type = this.rejectReasonType;
if (type == null) return type;
if (type === 'other') return (this.rejectReasonMemo || null);
return this.database.RejectReason.meta[type].label;
}, selectField: 'rejectReasonType', otherField: 'rejectReasonMemo' },
isApproved: { type: db.Boolean, value: function () {
if (this.approved == null) return null;
if (this.approved) return true;
if (this.rejectReason == null) return null;
return false;
} },
validateWithOriginal: { type: db.Boolean, required: true, value: false }
});
}, { normalizer: require('memoizee/normalizers/get-1')() });
| JavaScript | 0 | @@ -250,24 +250,70 @@
Document =
+ require('../document')%0A , defineCost =
require('..
@@ -440,16 +440,43 @@
ment(db)
+%0A%09 , Cost = defineCost(db)
;%0A%0A%09var
@@ -939,16 +939,125 @@
id%22) %7D,%0A
+%09%09// If upload concerns payment receipt, this links cost it corresponds%0A%09%09correspondingCost: %7B type: Cost %7D,%0A
%09%09matche
@@ -1695,24 +1695,32 @@
: function (
+_observe
) %7B%0A%09%09%09if (t
@@ -1776,16 +1776,124 @@
proved)
+%7B%0A%09%09%09%09if (this.correspondingCost) %7B%0A%09%09%09%09%09return _observe(this.correspondingCost._isPaid) %7C%7C null;%0A%09%09%09%09%7D%0A%09%09%09%09
return t
@@ -1897,16 +1897,21 @@
n true;%0A
+%09%09%09%7D%0A
%09%09%09if (t
|
f1e916dbd7fe9ad3b5c2a4621b03a2dcbfa1fe10 | Update Mergemons | mods/mergemons/scripts.js | mods/mergemons/scripts.js | 'use strict';
exports.BattleScripts = {
init: function () {
let learnsets = Object.assign({}, this.data.Learnsets);
let dex = [];
for (let i in this.data.Pokedex) {
if (this.data.Pokedex[i].num <= 0) continue;
if (this.data.Pokedex[i].evos) continue;
if (!learnsets[i]) continue;
if (this.data.FormatsData[i].isUnreleased) continue;
if (this.data.FormatsData[i].tier && this.data.FormatsData[i].tier === 'Illegal') continue;
dex.push(i);
}
for (let i = 0; i < dex.length; i++) {
let pokemon = dex[i];
while (this.data.Pokedex[pokemon].prevo) {
pokemon = this.data.Pokedex[pokemon].prevo;
}
let target = dex[(i === 0 ? dex.length - 1 : i - 1)];
let merge = false;
do {
let learnset = learnsets[target].learnset;
for (let move in learnset) {
let source = learnset[move][0].charAt(0) + 'L0';
if (!(move in learnsets[pokemon].learnset)) this.modData('Learnsets', pokemon).learnset[move] = [source];
}
if (this.data.Pokedex[target].prevo) {
target = this.data.Pokedex[target].prevo;
} else if (!merge) {
merge = true;
target = dex[(i === dex.length - 1 ? 0 : i + 1)];
} else {
target = null;
}
} while (target && learnsets[target]);
}
},
};
| JavaScript | 0 | @@ -683,16 +683,142 @@
- 1)%5D;%0A
+%09%09%09while (this.data.Pokedex%5Bpokemon%5D.num === this.data.Pokedex%5Btarget%5D.num) %7B%0A%09%09%09%09target = dex%5Bdex.indexOf(target) - 1%5D;%0A%09%09%09%7D%0A
%09%09%09let m
@@ -1279,16 +1279,148 @@
+ 1)%5D;%0A
+%09%09%09%09%09while (this.data.Pokedex%5Bpokemon%5D.num === this.data.Pokedex%5Btarget%5D.num) %7B%0A%09%09%09%09%09%09target = dex%5Bdex.indexOf(target) + 1%5D;%0A%09%09%09%09%09%7D%0A
%09%09%09%09%7D el
|
30e41cadca5a4d23b8858eee2f030ed6def5c745 | Add test case for clear icon | tests/Select.spec.js | tests/Select.spec.js | import expect from 'expect.js';
import React from 'react';
import ReactDOM from 'react-dom';
import TestUtils, { Simulate } from 'react-addons-test-utils';
import Select, { Option } from 'rc-select';
import $ from 'jquery';
describe('Select', () => {
let instance;
let div;
beforeEach(() => {
div = document.createElement('div');
document.body.appendChild(div);
});
afterEach(() => {
ReactDOM.unmountComponentAtNode(div);
document.body.removeChild(div);
});
it('render to body works', (done) => {
instance = ReactDOM.render(
<Select
value="2"
>
<Option value="1">1</Option>
<Option value="2">2</Option>
</Select>,
div);
instance.setState({
open: true,
}, () => {
expect(instance.getPopupDOMNode().parentNode
.parentNode.parentNode.nodeName.toLowerCase()).to.be('body');
expect(instance.getPopupDOMNode().className).not.to.contain('hidden');
done();
});
});
it('allow number value', (done) => {
function onChange(v) {
expect(v).to.be(1);
done();
}
instance = ReactDOM.render(
<Select
onChange={onChange}
value={2}
>
<Option value={1}>1</Option>
<Option value={2}>2</Option>
</Select>,
div);
instance.setState({
open: true,
});
let activeItem = $(instance.getPopupDOMNode()).find('.rc-select-dropdown-menu-item-active')[0];
expect(activeItem.innerHTML).to.be('2');
activeItem = $(instance.getPopupDOMNode()).find('.rc-select-dropdown-menu-item')[0];
Simulate.click(activeItem);
});
it('should add css class of root dom node', () => {
instance = ReactDOM.render(
<Select className="forTest" openClassName="my-open" value="2">
<Option value="1">1</Option>
<Option value="2" disabled>2</Option>
</Select>, div);
expect(ReactDOM.findDOMNode(instance).className.indexOf('forTest') !== -1).to.be(true);
});
it('should default select the right option', (done) => {
instance = ReactDOM.render(
<Select defaultValue="2">
<Option value="1">1</Option>
<Option value="2">2</Option>
</Select>, div);
instance.setState({
open: true,
}, () => {
expect(instance.getPopupMenuComponent().instanceArray[0].props.selected).to.be(false);
expect(instance.getPopupMenuComponent().instanceArray[1].props.selected).to.be(true);
done();
});
});
it('should can select multiple items', (done) => {
instance = ReactDOM.render(
<Select multiple value={['1', '2']}>
<Option value="1">1</Option>
<Option value="2">2</Option>
<Option value="3">2</Option>
</Select>, div);
instance.setState({
open: true,
}, () => {
expect(instance.getPopupMenuComponent().instanceArray[0].props.selected).to.be(true);
expect(instance.getPopupMenuComponent().instanceArray[1].props.selected).to.be(true);
expect(instance.getPopupMenuComponent().instanceArray[2].props.selected).to.be(false);
done();
});
});
it('should have clear button', () => {
instance = ReactDOM.render(
<Select allowClear>
<Option value="1">1</Option>
<Option value="2">2</Option>
</Select>,
div);
expect(TestUtils.scryRenderedDOMComponentsWithClass(instance,
'rc-select-selection__clear').length).to.be(1);
});
it('should not response click event when select is disabled', (done) => {
instance = ReactDOM.render(
<Select disabled defaultValue="2">
<Option value="1">1</Option>
<Option value="2">2</Option>
</Select>, div);
Simulate.click(ReactDOM.findDOMNode(instance.refs.selection));
expect(instance.state.open).not.to.be.ok();
done();
});
it('should show selected value in singleMode when close', (done) => {
instance = ReactDOM.render(
<Select value="1">
<Option value="1">1</Option>
<Option value="2">2</Option>
</Select>, div);
expect($(ReactDOM.findDOMNode(instance))
.find('.rc-select-selection-selected-value').length).to.be(1);
done();
});
it('should show placeholder in singleMode when value is undefined', (done) => {
instance = ReactDOM.render(
<Select placeholder="aaa">
<Option value="1">1</Option>
<Option value="2">2</Option>
</Select>, div);
expect($(ReactDOM.findDOMNode(instance))
.find('.rc-select-selection__placeholder').length).to.be(1);
done();
});
describe('when open', function test() {
this.timeout(400000);
beforeEach((done) => {
div = document.createElement('div');
div.tabIndex = 0;
document.body.appendChild(div);
instance = ReactDOM.render(
<Select>
<Option value="1">1</Option>
<Option value="2">2</Option>
</Select>,
div);
Simulate.click(ReactDOM.findDOMNode(instance.refs.selection));
done();
});
afterEach(() => {
ReactDOM.unmountComponentAtNode(div);
});
it('should show not found', (done) => {
instance.getInputDOMNode().value = '4';
Simulate.change(instance.getInputDOMNode());
setTimeout(() => {
expect($(instance.getPopupDOMNode())
.find('.rc-select-dropdown-menu-item').length).to.be(1);
expect($(instance.getPopupDOMNode())
.find('.rc-select-dropdown-menu-item')[0].innerHTML).to.be('Not Found');
done();
}, 100);
});
it('should show search input in single selection trigger', (done) => {
expect($(instance.getInputDOMNode()).parents('.rc-select-open').length).to.be(1);
done();
});
});
});
| JavaScript | 0 | @@ -3114,11 +3114,366 @@
uld
-hav
+show clear button', () =%3E %7B%0A instance = ReactDOM.render(%0A %3CSelect value=%221%22 allowClear%3E%0A %3COption value=%221%22%3E1%3C/Option%3E%0A %3COption value=%222%22%3E2%3C/Option%3E%0A %3C/Select%3E,%0A div);%0A expect(TestUtils.scryRenderedDOMComponentsWithClass(instance,%0A 'rc-select-selection__clear')%5B0%5D.style.display).to.be('block');%0A %7D);%0A%0A it('should hid
e cl
@@ -3755,31 +3755,41 @@
_clear')
-.length
+%5B0%5D.style.display
).to.be(
1);%0A %7D)
@@ -3776,25 +3776,30 @@
play).to.be(
-1
+'none'
);%0A %7D);%0A%0A
|
60f306f38879867e4e837fcb5c05768445b9089c | add error inspect for tester | tests/_lib/tester.js | tests/_lib/tester.js | "use strict";
var _ = require('lodash');
var inspect = require('./inspect');
var Schema = require('./schema');
var tester = function (testCase) {
return function (test) {
testCase.schema.verifier(testCase.options).verify(testCase.value, function (err) {
if (testCase.expect) {
test.ok(!err, 'must be valid!');
} else if (!err) {
test.ok(false, 'must be inValid');
} else if (err instanceof Schema.ValidationError) {
test.ok(true);
_.each(testCase.vErr, function (v, k) {
test.ok(_.isEqual(err[k], v), k +': ' + inspect(v) + ' given: ' + inspect(err[k]));
});
err = null;
}
test.done(err);
});
};
};
module.exports = tester; | JavaScript | 0 | @@ -312,24 +312,140 @@
e valid!');%0A
+%09%09%09%09if (err instanceof Schema.ValidationError) %7B%0A%09%09%09%09%09console.log('%3E%3Eerror:', inspect(err));%0A%09%09%09%09%09err = null;%0A%09%09%09%09%7D%0A
%09%09%09%7D else if
|
27d9823492cd248b30c22c4eea4a2bbb158cdf30 | Remove trivial variable | modules/gulpease/index.js | modules/gulpease/index.js | const fs = require( 'fs' );
const spawnSync = require( 'child_process' ).spawnSync;
/**
Get the number of letters inside the text
@param text : string - Text where count the number of letters
@return {number} - Number of letters
*/
function letters( text ) {
return text.match( /\w/g ).length;
}
/**
Get the number of sentences inside the text
@param text : string - Text where count the number of sentences
@return {number} - Number of sentences
*/
function sentences( text ) {
var allCarriageReturn = text;
// For each end lines or sentences add a point and carrige return.
// Example:
// My mother going at home. He will go back friday. =>
// My mother going at home.
// He will go back friday.
allCarriageReturn = allCarriageReturn.replace( /(\n|\. )/g, ".\n" );
//Therefor the number of sentences is a number of the point preceded by
//another symbol. The separator line will ignored because it haven't
//nothing before. I believe that one sentence with less than three words is
//absurde.
return allCarriageReturn.match( /\w{3,}\s{0,}.$/gm ).length;
}
/**
Get the number of words inside the text
@param text : string - Text where count the number of words
@return {number} - Number of words
*/
function words( text ) {
return text.match( /\w+/g ).length;
}
exports.main = function ( path ) {
console.log( "Run gulpease script..." );
// The path MUST have above struct:
// res/section/all_file.tex
path += "res/sections/"; // Attach the location when all sections are store
var files = fs.readdirSync( path ); // Get all files
var dcDetex = "";
console.log( "Detected this files:" );
// Apply detex every files and append content at dcDetex
files.forEach( ( val, index, array ) => {
console.log( val );
var outSpawn = spawnSync( 'detex', [ path+val ] );
dcDetex += `${outSpawn.stdout}\n`;
});
// Remove all matched form dcDetex
var filter =
"enumerate|" +
"itemize|" +
"center|" +
"figure|" +
"longtable|" +
"description|" +
"tabular|" +
"table|" +
"math|" +
"name|" +
"p.*cm|" + // measure
"\s1.8\s|" +
"\s2.*c.*0\.9\s|" +
"\[.*\]|" +
"(l\s?)*(l\s?c)(c\s?)*\s{0,}|" + // latex format table
".*\.png$|" +
"\t";
// Convert filter string in a regex exp with global visibility
var e = new RegExp( filter, "gm" );
// Clean text catch
var cleanText = dcDetex.replace( e, "" );
console.log( `\nSentences: ${sentences( cleanText )}` );
console.log( `Letters: ${letters( cleanText )}` );
console.log( `Words: ${words( cleanText )}` );
var seToLe = 300 * sentences( cleanText ) - 10 * letters( cleanText );
var words = words( cleanText );
return 89 + ( seToLe ) / words;
}
| JavaScript | 0.02782 | @@ -2714,49 +2714,8 @@
);%0A
- var words = words( cleanText );%0A %0A
@@ -2744,13 +2744,26 @@
/ words
+( cleanText )
;%0A%7D %0A
|
29a0d3d1c8fa72322da34cf27e18b11ddc4e0430 | use __dirname instead of cwd | .babelrc.js | .babelrc.js | const cwd = process.cwd();
module.exports = {
"plugins": [
["transform-runtime", {
helpers: true,
polyfill: false,
regenerator: false
}],
"transform-es2015-modules-commonjs",
["check-es2015-constants", { "loose": true }],
["transform-es2015-arrow-functions", { "loose": true }],
["transform-es2015-block-scoped-functions", { "loose": true }],
["transform-es2015-block-scoping", { "loose": true }],
["transform-es2015-classes", { "loose": true }],
["transform-es2015-computed-properties", { "loose": true }],
["transform-es2015-destructuring", { "loose": true }],
["transform-es2015-duplicate-keys", { "loose": true }],
[`${cwd}/build/babel-transform-for-of-array`,{ "loose": true }],
["transform-es2015-function-name", { "loose": true }],
["transform-es2015-literals", { "loose": true }],
["transform-es2015-modules-commonjs", { "loose": true }],
["transform-es2015-object-super", { "loose": true }],
["transform-es2015-parameters", { "loose": true }],
["transform-es2015-shorthand-properties", { "loose": true }],
["transform-es2015-spread", { "loose": true }],
["transform-es2015-sticky-regex", { "loose": true }],
["transform-es2015-template-literals", { "loose": true }],
["transform-es2015-typeof-symbol", { "loose": true }],
["transform-es2015-unicode-regex", { "loose": true }],
["transform-object-rest-spread"]
],
"env": {
"test": {
"plugins": ["istanbul"]
}
}
}
| JavaScript | 0.000612 | @@ -3,27 +3,39 @@
nst
-cwd = process.cwd()
+buildDir = %60$%7B__dirname%7D/build%60
;%0A%0Am
@@ -769,18 +769,17 @@
%5B%60$%7B
-cwd%7D/
build
+Dir%7D
/bab
|
ca266ba478cb1115392a53c86b999eb3d54023f2 | Fix typo | .babelrc.js | .babelrc.js | module.exports = api => ({
presets: [
['@babel/env', {
...(api.env('test') ? {
targets: {
browsers: ['chrome >= 60', 'firefox >= 56'], // Test in these browsers is enough
}
} : {}),
}],
api("test") && ['@babel/react', { runtime: "automatic" }],
].filter(Boolean),
plugins: [
api.env('test') && ['istanbul', { exclude: ['test/**'] }],
].filter(Boolean),
});
| JavaScript | 0.999999 | @@ -234,16 +234,20 @@
%0A api
+.env
(%22test%22)
|
e81329526532e7562e29ed068c805e541c787d93 | Fix for CI failure due to PhantomJS incompatibility. | tests/test-helper.js | tests/test-helper.js | document.write('<div id="ember-testing-container"><div id="ember-testing"></div></div>');
Ember.testing = true;
window.startApp = require('appkit/tests/helpers/start-app')['default'];
window.isolatedContainer = require('appkit/tests/helpers/isolated-container')['default'];
function exists(selector) {
return !!find(selector).length;
}
function getAssertionMessage(actual, expected, message) {
return message || QUnit.jsDump.parse(expected) + " expected but was " + QUnit.jsDump.parse(actual);
}
function equal(actual, expected, message) {
message = getAssertionMessage(actual, expected, message);
QUnit.equal.call(this, actual, expected, message);
}
function strictEqual(actual, expected, message) {
message = getAssertionMessage(actual, expected, message);
QUnit.strictEqual.call(this, actual, expected, message);
}
window.exists = exists;
window.equal = equal;
window.strictEqual = strictEqual;
| JavaScript | 0 | @@ -915,12 +915,941 @@
trictEqual;%0A
+%0A// Fix for failures in PhantomJS due to Function not having bind() in that env.%0A//%0A// Polyfill from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind%0A//%0Aif (!Function.prototype.bind) %7B%0A Function.prototype.bind = function (oThis) %7B%0A if (typeof this !== %22function%22) %7B%0A // closest thing possible to the ECMAScript 5 internal IsCallable function%0A throw new TypeError(%22Function.prototype.bind - what is trying to be bound is not callable%22);%0A %7D%0A%0A var aArgs = Array.prototype.slice.call(arguments, 1), %0A fToBind = this, %0A FnNOP = function () %7B%7D,%0A FnBound = function () %7B%0A return fToBind.apply(this instanceof FnNOP && oThis ? this : oThis,%0A aArgs.concat(Array.prototype.slice.call(arguments)));%0A %7D;%0A%0A FnNOP.prototype = this.prototype;%0A FnBound.prototype = new FnNOP();%0A%0A return FnBound;%0A %7D;%0A%7D%0A
|
334e6b460376d1e7e01bfbf4c231ace5c67f3032 | Remove arrow functions for browser compatibility | src/connection.js | src/connection.js | var EventEmitter = require('eventemitter3');
var _ = require('lodash');
var ircLineParser = require('./irclineparser');
function Connection(options) {
EventEmitter.call(this);
this.options = options || {};
this.connected = false;
this.requested_disconnect = false;
this.auto_reconnect = options.auto_reconnect || false;
this.auto_reconnect_wait = options.auto_reconnect_wait || 4000;
this.auto_reconnect_max_retries = options.auto_reconnect_max_retries || 3;
this.reconnect_attempts = 0;
// When an IRC connection was successfully registered.
this.registered = false;
this.read_buffer = [];
this.reading_buffer = false;
this.read_command_buffer = [];
this.transport = null;
this._timers = [];
}
_.extend(Connection.prototype, EventEmitter.prototype);
module.exports = Connection;
Connection.prototype.debugOut = function(out) {
this.emit('debug', out);
};
Connection.prototype.registeredSuccessfully = function() {
this.registered = Date.now();
};
Connection.prototype.connect = function(options) {
var that = this;
var transport;
if (options) {
this.options = options;
}
options = this.options;
transport = this.transport = new options.transport(options);
if (!options.encoding || !this.setEncoding(options.encoding)) {
this.setEncoding('utf8');
}
// Some transports may emit extra events
transport.on('extra', function(/*event_name, argN*/) {
that.emit.apply(that, arguments);
});
transport.on('open', socketOpen);
transport.on('line', socketLine);
transport.on('close', socketClose);
transport.on('debug', out => this.debugOut(out));
transport.connect();
// Called when the socket is connected and ready to start sending/receiving data.
function socketOpen() {
that.debugOut('Socket fully connected');
that.reconnect_attempts = 0;
that.connected = true;
that.emit('socket connected');
}
function socketLine(line) {
that.debugOut('[incoming line] ' + line);
that.read_buffer.push(line);
that.processReadBuffer();
}
function socketClose(err) {
var was_connected = that.connected;
var should_reconnect = false;
var safely_registered = false;
var registered_ms_ago = Date.now() - that.registered;
// Some networks use aKills which kill a user after succesfully
// registering instead of a ban, so we must wait some time after
// being registered to be sure that we are connected properly.
safely_registered = that.registered !== false && registered_ms_ago > 5000;
that.debugOut('Socket closed. was_connected=' + was_connected + ' safely_registered=' + safely_registered + ' requested_disconnect='+that.requested_disconnect);
that.connected = false;
that.clearTimers();
that.emit('socket close', err);
if (that.requested_disconnect || !that.auto_reconnect) {
should_reconnect = false;
// If trying to reconnect, continue with it
} else if (that.reconnect_attempts && that.reconnect_attempts < that.auto_reconnect_max_retries) {
should_reconnect = true;
// If we were originally connected OK, reconnect
} else if (was_connected && safely_registered) {
should_reconnect = true;
} else {
should_reconnect = false;
}
if (should_reconnect) {
that.reconnect_attempts++;
that.emit('reconnecting', {
attempt: that.reconnect_attempts,
max_retries: that.auto_reconnect_max_retries,
wait: that.auto_reconnect_wait
});
} else {
that.emit('close', err ? true : false);
that.reconnect_attempts = 0;
}
if (should_reconnect) {
that.debugOut('Scheduling reconnect');
that.setTimeout(function() {
that.connect();
}, that.auto_reconnect_wait);
}
}
};
Connection.prototype.write = function(data, callback) {
if (!this.connected || this.requested_disconnect) {
return 0;
}
return this.transport.writeLine(data, callback);
};
/**
* Create and keep track of all timers so they can be easily removed
*/
Connection.prototype.setTimeout = function(/*fn, length, argN */) {
var that = this;
var tmr = null;
var callback = arguments[0];
arguments[0] = function() {
_.pull(that._timers, tmr);
callback.apply(null, arguments);
};
tmr = setTimeout.apply(null, arguments);
this._timers.push(tmr);
return tmr;
};
Connection.prototype.clearTimeout = function(tmr) {
clearTimeout(tmr);
_.pull(this._timers, tmr);
};
Connection.prototype.clearTimers = function() {
this._timers.forEach(function(tmr) {
clearTimeout(tmr);
});
this._timers = [];
};
/**
* Close the connection to the IRCd after forcing one last line
*/
Connection.prototype.end = function(data, callback) {
var that = this;
this.debugOut('Connection.end() connected=' + this.connected + ' with data=' + !!data);
if (this.connected && data) {
// Once the last bit of data has been sent, then re-run this function to close the socket
this.write(data, function() {
that.end();
});
return;
}
this.requested_disconnect = true;
if (this.transport) {
this.transport.close();
}
};
Connection.prototype.setEncoding = function(encoding) {
this.debugOut('Connection.setEncoding() encoding=' + encoding);
if (this.transport) {
return this.transport.setEncoding(encoding);
}
};
/**
* Process the buffered messages recieved from the IRCd
* Will only process 4 lines per JS tick so that node can handle any other events while
* handling a large buffer
*/
Connection.prototype.processReadBuffer = function(continue_processing) {
// If we already have the read buffer being iterated through, don't start
// another one.
if (this.reading_buffer && !continue_processing) {
return;
}
var lines_per_js_tick = 4;
var processed_lines = 0;
var line;
var message;
this.reading_buffer = true;
while (processed_lines < lines_per_js_tick && this.read_buffer.length > 0) {
line = this.read_buffer.shift();
if (!line) {
continue;
}
message = ircLineParser(line);
if (!message) {
// A malformed IRC line
continue;
}
this.emit('raw', line);
this.emit('message', message);
processed_lines++;
}
// If we still have items left in our buffer then continue reading them in a few ticks
if (this.read_buffer.length > 0) {
this.setTimeout(() => {
this.processReadBuffer(true);
}, 1);
} else {
this.reading_buffer = false;
}
};
| JavaScript | 0.000001 | @@ -1696,19 +1696,37 @@
g',
-out =%3E this
+function (out) %7B%0A that
.deb
@@ -1735,16 +1735,23 @@
Out(out)
+;%0A %7D
);%0A%0A
@@ -6250,24 +6250,45 @@
urn;%0A %7D%0A%0A
+ var that = this;%0A
var line
@@ -6972,13 +6972,18 @@
out(
-() =%3E
+function()
%7B%0A
@@ -6995,18 +6995,18 @@
th
-is
+at
.process
|
8259ef083fbca90166e5d136471e2357cd91918a | Update UDPefef | benchmark.js | benchmark.js | 'use strict'
/**
* Created by tungtouch on 2/9/15.
*/
var cluster = require('cluster');
var numCPUs = require('os').cpus().length;
var dgram = require('dgram');
var message = new Buffer("Some bytes hello world bo bo bo world HEHEHEHE ahhaha hohoho hehe:");
var client = dgram.createSocket("udp4");
var async = require('async');
var max = 1000;
var numCluster = 100;
var arr = [];
for (var i = 0; i < max; i++) {
arr.push(i);
}
var a = 0;
//[2GB]128.199.126.250 [8GB]128.199.109.202
var q = async.queue(function(index, cb){
setTimeout(function () {
client.send(message, 0, message.length, 4444, "128.199.126.250", function (err) {
console.log("Request : ", a++);
if(err){
console.log('ERROR :', err);
}
cb(err);
});
}, 20);
});
if (cluster.isMaster) {
// Fork workers.
for (var m = 0; m < numCluster; m++) {
console.log("Starting Benchmark!", m);
cluster.fork();
}
cluster.on('exit', function(worker, code, signal) {
console.log('worker ' + worker.process.pid + ' died');
});
} else {
// Workers can share any TCP connection
// In this case its a HTTP server
q.push(arr);
}
| JavaScript | 0 | @@ -621,22 +621,22 @@
28.199.1
-26.250
+09.202
%22, funct
|
176d80dab80e74c6cda1498d2dc6c929b54321c5 | Update build script to build development. | bin/build.js | bin/build.js | #!/usr/bin/env node
var shell = require('shelljs');
shell.exec('node ./node_modules/brunch/bin/brunch build --production');
process.exit(0);
| JavaScript | 0 | @@ -106,21 +106,8 @@
uild
- --production
');%0A
|
1461591ea397cf1f7b1b482a0b900e25223b4bae | Add progress message | bin/index.js | bin/index.js | #!/usr/bin/env node
var exec = require('child_process').exec;
var fs = require('fs');
var os = require("os");
var isWindows = os.type() == "Windows_NT";
if (isWindows)
var scm = "scm";
else
var scm = "lscm";
// some requests print a lot of information
// increase the buffer to handle the size of these requests
var maxBuffer = 1000 * 1000 * 1024;
var user = process.env.RTC_USER;
var password = process.env.RTC_PASSWORD;
var defaultAuthor = process.env.AUTHOR;
var defaultDomain = process.env.DOMAIN;
var componentOption = process.env.COMPONENT ? "-C " + process.env.COMPONENT : "";
if (!defaultAuthor || !defaultDomain) {
console.log("You must set AUTHOR and DOMAIN environment variables");
} else {
var userPass = "";
if (user) {
userPass = ' -u ' + user + ' -P ' + password + " ";
}
if (process.argv[2] == "continue")
walkThroughHistory();
else
discardChanges(makeFirstCommit);
}
function convertToEmail(name) {
// convert the name from "John Doe" to "john.doe@domain"
return [name.toLowerCase().split(/\s+/).join('.'), '@', defaultDomain].join('');
}
function gitAddAndCommit(uuid, next) {
// list the changes for this UUID so we can get the full work item comment
echoAndExec(null, scm + ' list changes ' + uuid + userPass + ' -j', {
maxBuffer: maxBuffer
}, function (err, stdout, stderr) {
if (err) throw err;
// console.log(stdout);
var jazzResponse = JSON.parse(stdout);
var change = jazzResponse.changes[0];
var comment = createCommitMessage(change);
var name = (change.author || defaultAuthor);
var email = convertToEmail(name);
var author = name + ' <' + email + '>';
var modified = new Date(change.modified).toISOString();
echoAndExec(null, 'git add -A', {
maxBuffer: maxBuffer
}, function (err, stdout, stderr) {
if (err) throw err;
var env = process.env;
env["GIT_COMMITTER_EMAIL"] = email;
env["GIT_COMMITTER_NAME"] = name;
env["GIT_COMMITTER_DATE"] = modified;
// commit these changes
echoAndExec(comment, ['git commit',
'-F -',
'--author="' + author + '"',
'--date=' + modified,
'--allow-empty'].join(' '), {
maxBuffer: maxBuffer,
env: env
}, next);
});
});
}
function processHistoryItem(history, index) {
if (index >= history.length) return;
var uuid = history[index].uuid;
// accept changes from RTC
echoAndExec(null, scm + ' accept ' + uuid + userPass + ' --overwrite-uncommitted', {
maxBuffer: maxBuffer
}, function (err, stdout, stderr) {
if (err) throw err;
console.log(stdout);
gitAddAndCommit(uuid, function(err, stdout, stderr) {
if (err) throw err;
// process the next item
processHistoryItem(history, index + 1);
});
});
}
function createCommitMessage(change) {
// convert <No comment> to an empty string.
var comment = change.comment.replace(/<No comment>/, ''),
message;
if (change.workitems && change.workitems.length > 0) {
// message is in a format similar to "12345 The work item description"
message = [change.workitems[0]['workitem-number'],
change.workitems[0]['workitem-label']].join(' ');
// if there is a comment, append it to the message as a new paragraph
if (comment) {
message = [message, comment].join('\n\n');
}
} else {
message = comment;
}
return message;
}
/*
1. Grab the history of change sets from RTC.
2. If the message has been cut off, query to RTC to get the full message.
3. Add the changes to git.
4. Commit the change to git using the message from RTC.
5. Accept the next changeset from RTC.
6. Repeat from step 2.
*/
function discardChanges(callback) {
echoAndExec(null, scm + ' show history -j -m 100 ' + componentOption + userPass, {
maxBuffer: maxBuffer
}, function(err, stdout, stderr) {
if (err) throw err;
// console.log(stdout);
// get the response and reverse all the change sets in it
var jazzResponse = JSON.parse(stdout),
changes = jazzResponse.changes;
// cannot discard the first change
if (changes.length === 1) {
return callback(changes);
}
// to be safe, we can discard all but the first changeset, which might be
// the last element in the array
var uuids = changes.slice(0, -1).map(function (change) {
return change.uuid;
});
echoAndExec(null, scm + ' discard ' + userPass + ' --overwrite-uncommitted ' + uuids.join(' '), {
maxBuffer: maxBuffer
}, function(err, stdout, stderr) {
if (err) throw err;
console.log(stdout);
// recurse and attempt to discard more changes
discardChanges(callback);
});
});
}
function makeFirstCommit(changes) {
echoAndExec(null, 'git init', function(err) {
if (err) throw err;
gitAddAndCommit(changes[0].uuid, function(err, stdout, stderr) {
if (err) throw err;
walkThroughHistory();
});
});
}
function walkThroughHistory() {
echoAndExec(null, scm + ' show status -i in:cbC -j ' + userPass, {
maxBuffer: maxBuffer
}, function (err, stdout, stderr) {
if (err) throw err;
// console.log(stdout);
var jazzResponse = JSON.parse(stdout);
// get the RTC change set history and reverse it to get it in
// chronological order
var orderedHistory = jazzResponse.workspaces[0].components[0]['incoming-baselines'].reverse().reduce(function(history, baseline) {
return history.concat(baseline.changes.reverse());
}, []);
orderedHistory = orderedHistory.concat(jazzResponse.workspaces[0].components[0]['incoming-changes'].reverse());
processHistoryItem(orderedHistory, 0);
});
}
function echoAndExec(input, cmd, options, callback) {
console.log(cmd);
var child = exec(cmd, options, callback);
if (input)
child.stdin.write(input);
child.stdin.end();
return child;
}
| JavaScript | 0.000001 | @@ -2433,16 +2433,204 @@
rom RTC%0A
+ console.log(%22%5Cn=======================================%22);%0A console.log(%22Processing change set %22 + (index+1) + %22 of %22 + history.length + %22 (%22 + (history.length - index - 1) + %22 left)%22);%0A
echoAn
|
615ef66f622e9364c3f53a965d8ccc370db88458 | Remove data from context once we're done with it | bin/index.js | bin/index.js | #!/usr/bin/env node
var program = require('commander')
, fs = require('fs')
, path = require('path')
, util = require('util')
, extend = require('extend')
, Handlebars = require('handlebars');
program
.version('0.0.0')
.usage('[options] <file ...>')
.option('-o, --output [file]', 'write JSON output to a file')
.parse(process.argv);
var tests = []
, context = {};
tests.add = function (spec) {
var key = (spec.description + '-' + spec.it).toLowerCase();
for (var i = 0; i < 20; i++) {
var name = key + '-' + ('0' + i).slice(-2);
if (!tests.hasOwnProperty(name)) {
if (program.output) {
var patchFile = __dirname + '/../patch/' + path.basename(program.output);
if (fs.existsSync(path.resolve(patchFile))) {
var patch = require(patchFile);
if (patch.hasOwnProperty(name)) {
spec = extend(true, spec, patch[name]);
}
}
}
tests.push(spec);
break;
}
}
};
var isFunction = function (object) {
return !!(object && object.constructor && object.call && object.apply);
};
var isEmptyObject = function (object) {
return !Object.keys(object).length;
};
var extractHelpers = function (data) {
var helpers = {};
if (!data || typeof data !== 'object') {
return false;
}
Object.keys(data).forEach(function (el) {
if (isFunction(data[el])) {
helpers[el] = { javascript: '' + data[el] };
}
});
return isEmptyObject(helpers) ? false : helpers;
};
global.Handlebars = Handlebars;
global.handlebarsEnv = Handlebars.create();
global.beforeEach = function (next) {
next();
};
global.CompilerContext = {
compile: function (template, options) {
// Push template unto context
context.template = template;
return function (data, options) {
if (options && options.hasOwnProperty('data')) {
data = extend(true, data, options.data);
}
// Push template data unto context
context.data = data;
if (options && options.hasOwnProperty('helpers')) {
// Push helpers unto context
context.helpers = options.helpers;
}
};
},
compileWithPartial: function(template, options) {
// Push template unto context
context.template = template;
}
};
global.describe = function (description, next) {
// Push suite description unto context
context.description = description;
next();
};
global.it = function (description, next) {
// Push test spec unto context
context.it = description;
next();
};
global.equal = global.equals = function (actual, expected, message) {
var spec = {
description : context.description
, it : context.it
, template : context.template
, data : context.data
, expected : expected
};
if (context.hasOwnProperty('helpers')) {
spec.helpers = extractHelpers(context.helpers);
}
tests.add(spec);
};
global.shouldCompileTo = function (string, hashOrArray, expected) {
shouldCompileToWithPartials(string, hashOrArray, false, expected);
};
global.shouldCompileToWithPartials = function (string, hashOrArray, partials, expected, message) {
compileWithPartials(string, hashOrArray, partials, expected, message);
};
global.compileWithPartials = function(string, hashOrArray, partials, expected, message) {
var helpers = false;
if (util.isArray(hashOrArray)) {
data = hashOrArray[0];
helpers = extractHelpers(hashOrArray[1]);
partials = hashOrArray[2];
} else {
data = hashOrArray;
}
var spec = {
description : context.description
, it : context.it
, template : string
, data : data
};
if (partials) spec.partials = partials;
if (helpers) spec.helpers = helpers;
if (expected) spec.expected = expected;
if (message) spec.message = '' + message;
tests.add(spec);
};
global.shouldThrow = function (callback, error, message) {
callback();
var spec = {
description : context.description
, it : context.it
, template : context.template
, exception : true
};
if (message) spec.message = '' + message;
tests.add(spec);
};
var input = path.resolve(program.args[0]);
fs.exists(input, function (exists) {
if (exists) {
require(input);
var output = JSON.stringify(tests, null, '\t');
if (!program.output) {
return console.log(output);
}
var outputFile = path.resolve(program.output);
fs.writeFile(outputFile, output, function (err) {
if (err) {
console.log(err);
} else {
console.log('JSON saved to ' + program.output);
}
});
} else {
console.log('The input file does not exist');
}
});
| JavaScript | 0.000014 | @@ -2792,24 +2792,118 @@
ted%0A %7D;%0A%0A
+ // Remove template and data from context%0A delete context.template;%0A delete context.data;%0A%0A
if (contex
@@ -2985,16 +2985,44 @@
lpers);%0A
+ delete context.helpers;%0A
%7D%0A%0A t
@@ -4223,24 +4223,86 @@
rue%0A %7D;%0A%0A
+ // Remove template from context%0A delete context.template;%0A%0A
if (messag
|
47358c6fc5a1c53d5f1bbf29a7de3b2b9d90673c | Fix typo | bin/konga.js | bin/konga.js | #!/usr/bin/env node bin
var argv = require('minimist')(process.argv.slice(2));
var child_process = require('child_process');
var spawn = child_process.spawn
var path = require('path')
var _ = require('lodash');
var Sails = require('sails');
if (argv._[0] === 'help') {
console.log("Usage:");
logHelp()
process.exit()
}
else if (argv._[0] === 'play')
{
var port = process.env.PORT || argv.port
console.log("------------------------------------------------------")
console.log("Playing Konga!")
console.log("------------------------------------------------------")
console.log("")
console.log(argv)
var args = ["app.js","--prod"]
if(port) args.push("--port=" + port)
console.log(args)
var cmd = spawn('node',
args,
{cwd : path.join(__dirname,".."), stdio: "inherit"});
cmd.on('exit', function(code){
console.log("Exiting",code);
});
}
else if(argv._[0] === 'prepare') {
Sails.log("Preparing database...")
if(!process.env.DB_ADAPTER && !argv.adapter) {
Sails.log.error("No db adapter defined. Set --adapter {mongo || mysql || postgres || sql-srv}")
return process.exit(1);
}
if(!process.env.DB_URI && !argv.uri) {
Sails.log.error("No db connection string is defined. Set --uri {db_connection_string}")
return process.exit(1);
}
process.env.DB_ADAPTER = process.env.DB_ADAPTER || argv.adapter;
process.env.DB_URI = process.env.DB_URI || argv.uri;
process.env.PORT = _.isString(argv.port) || _.isNumber(argv.port) ? argv.port : 1339;
require("../makedb")(function(err) {
if(err) return process.exit();
Sails.load({
environment: 'development',
port: process.env.PORT,
hooks: {
grunt: false
}
}, function callback(error, sails) {
if(error) {
sails.log.error("Failed to prepare database:",error)
return process.exit(1);
}
sails.log("Database migrations complete!")
process.exit()
});
});
}
else
{
console.log(argv)
console.log("Unknown command. Try one of:");
logHelp()
}
function logHelp() {
console.log("==============================");
console.log("konga play | Start Konga.");
console.log("==============================");
process.exit()
} | JavaScript | 0.999999 | @@ -1957,16 +1957,17 @@
complete
+d
!%22)%0A
|
41e8395374c2a56e6699112c93e43c778ec91ba7 | use math module in group | src/core/group.js | src/core/group.js | import { mat4 } from 'gl-matrix';
import { obj_to_vec } from '../misc/utils.js';
import { zero_vector, unit_vector } from '../misc/defaults.js';
class Group {
constructor(options = {}) {
this.position = options.position || Object.assign({}, zero_vector);
this.rotation = options.rotation || Object.assign({}, zero_vector);
this.scale = options.scale || Object.assign({}, unit_vector);
this.origin = options.origin || Object.assign({}, zero_vector);
this.entities = [];
this.skip = false;
}
add(entity) {
entity.parent = this;
this.entities.push(entity);
}
update() {
if (this.skip) {
return;
}
const model_view_matrix = mat4.identity(mat4.create());
mat4.translate(model_view_matrix, model_view_matrix, obj_to_vec(this.position));
const origin = obj_to_vec(this.origin);
const rev_origin = obj_to_vec({
x: -this.origin.x,
y: -this.origin.y,
z: -this.origin.z
});
mat4.translate(model_view_matrix, model_view_matrix, rev_origin);
mat4.rotate(model_view_matrix, model_view_matrix, this.rotation.x, [1, 0, 0]);
mat4.rotate(model_view_matrix, model_view_matrix, this.rotation.y, [0, 1, 0]);
mat4.rotate(model_view_matrix, model_view_matrix, this.rotation.z, [0, 0, 1]);
mat4.translate(model_view_matrix, model_view_matrix, origin);
mat4.scale(model_view_matrix, model_view_matrix, obj_to_vec(this.scale));
this.model_view_matrix = model_view_matrix;
this.entities.forEach((entity) => {
entity.update();
});
// this.material_desc = new materials[this.material];
}
render(ticks) {
!this.skip && this.entities.forEach((entity) => {
entity.render(ticks);
});
}
}
export { Group }
| JavaScript | 0.000004 | @@ -5,17 +5,17 @@
rt %7B mat
-4
+h
%7D from
@@ -19,17 +19,17 @@
om '
-gl-matrix
+./math.js
';%0Ai
@@ -677,16 +677,21 @@
atrix =
+math.
mat4.ide
@@ -696,16 +696,21 @@
dentity(
+math.
mat4.cre
@@ -717,24 +717,29 @@
ate());%0A
+math.
mat4.transla
@@ -971,24 +971,29 @@
%7D);%0A%0A
+math.
mat4.transla
@@ -1046,24 +1046,29 @@
rigin);%0A
+math.
mat4.rotate(
@@ -1130,32 +1130,37 @@
%5B1, 0, 0%5D);%0A
+math.
mat4.rotate(mode
@@ -1222,24 +1222,29 @@
1, 0%5D);%0A
+math.
mat4.rotate(
@@ -1310,24 +1310,29 @@
0, 1%5D);%0A
+math.
mat4.transla
@@ -1385,16 +1385,21 @@
n);%0A
+math.
mat4.sca
|
b57d4b1e4a6af512ca9fddb91f466df28fed5c8b | end is negative's bug | src/core/index.js | src/core/index.js | /**
* @file index
* @author Cuttle Cong
* @date 2018/2/26
* @description
*/
import defaultPlugin from './plugins/default'
import highlight from './utils/highlight'
import markdown from './utils/markdown'
import parseUrl from './utils/parseQuerystring'
import each from 'lodash/each'
export default class Telescope {
static fromUrl(url = '') {
const { plugins, ...data } = parseUrl(url)
return new this(data)
}
static styleGetter = {
'github|gh': require('github-markdown-css/github-markdown.css'),
'bootstrap3|bs': require('./styles/bootstrap3.css')
}
static hlStyleGetter = {
'school-book|sb': require('highlight.js/styles/school-book.css'),
'solarized-dark|sd': require('highlight.js/styles/solarized-dark.css'),
'github-gist|gg': require('highlight.js/styles/github-gist.css'),
'github|gh': require('highlight.js/styles/github.css'),
}
options = {
type: 'md',
style: 'github',
hlStyle: 'github',
range: [],
plugins: [
require('./plugins/github'),
defaultPlugin,
]
}
constructor(options = {}) {
const plugins = options.plugins || []
this.options = Object.assign({}, this.options, options, {
plugins: plugins.concat(this.options.plugins).filter(x => typeof x === 'function')
})
this.initializePlugin()
}
initializePlugin() {
const polyfill = defaultPlugin(this)
this.defaultPlugin = polyfill
this.plugins = this.options.plugins.map(plugin => {
return {
...polyfill,
...plugin(this)
}
})
}
/**
*
* @param url
* @returns html {string}
*/
async see(url) {
const matchedPlugin = this.plugins.find(plugin =>
plugin.condition(url)
)
url = await matchedPlugin.urlTransform(url)
const response = await matchedPlugin.fetch(url)
let value, text
switch (response.contentType) {
case 'code':
case 'javascript':
case 'css':
let range = this.options.range
text = await response.text()
if (!Array.isArray(range)) {
range = [range]
}
let [start, end] = range
if (parseInt(start) == start && start != 0) {
const lines = text.split('\n')
// neg
if (typeof end !== 'undefined' && -end === Math.abs(end)) {
end = lines.length - 1 + end
}
text = lines.slice(start - 1, end).join('\n')
}
value = await matchedPlugin.renderCode(text, response)
break
case 'image':
value = await matchedPlugin.renderImage(response)
// @todo blob
break
case 'md':
default:
text = await response.text()
value = await matchedPlugin.renderMarkdown(text, response)
}
return {
value,
contentType: response.contentType,
url: response.url,
}
}
}
function overrideGetter(ref, path) {
const styleGetter = ref[path]
const getter = {}
each(styleGetter, (value, name) => {
const keys = name.split('|')
keys.forEach(key => {
key = key.trim()
if (key) {
getter[key] = styleGetter[name]
}
})
})
ref[path] = getter
}
overrideGetter(Telescope, 'styleGetter')
overrideGetter(Telescope, 'hlStyleGetter')
| JavaScript | 0.998293 | @@ -2343,16 +2343,17 @@
h - 1 +
++
end%0A
|
ac2832e4544c9b2c98c324505865eb7a4796c3a2 | Revert to previous readyState logic per @scottjehl comments and this: https://github.com/mobify/mobifyjs/blob/526841be5509e28fc949038021799e4223479f8d/src/capture.js#L128 | src/core/ready.js | src/core/ready.js | //>>excludeStart("exclude", pragmas.exclude);
define([ "shoestring" ], function(){
//>>excludeEnd("exclude");
/**
* Bind callbacks to be run when the DOM is "ready".
*
* @param {function} fn The callback to be run
* @return shoestring
* @this shoestring
*/
shoestring.ready = function( fn ){
if( ready && fn ){
fn.call( doc );
}
else if( fn ){
readyQueue.push( fn );
}
else {
runReady();
}
return [doc];
};
// TODO necessary?
shoestring.fn.ready = function( fn ){
shoestring.ready( fn );
return this;
};
// Empty and exec the ready queue
var ready = false,
readyQueue = [],
runReady = function(){
if( !ready ){
while( readyQueue.length ){
readyQueue.shift().call( doc );
}
ready = true;
}
};
// If DOM is already ready at exec time, depends on the browser.
// From: https://github.com/mobify/mobifyjs/blob/526841be5509e28fc949038021799e4223479f8d/src/capture.js#L128
if (doc.readyState !== "loading") {
runReady();
} else {
doc.addEventListener( "DOMContentLoaded", runReady, false );
doc.addEventListener( "readystatechange", runReady, false );
win.addEventListener( "load", runReady, false );
}
//>>excludeStart("exclude", pragmas.exclude);
});
//>>excludeEnd("exclude");
| JavaScript | 0.000001 | @@ -949,16 +949,66 @@
28%0A%09if (
+doc.attachEvent ? doc.readyState === %22complete%22 :
doc.read
|
2aef9c4164e2578ee6a3669e5a981dcfc153d347 | Add some logging | src/core/scope.js | src/core/scope.js | 'use strict';
const d = require('./util').log;
const clone = require('clone');
function createScope(obj, parentScope) {
d('Creating new scope...');
d(obj);
d(parentScope);
obj = clone(obj) || {};
Object.defineProperty(obj, '__parent__', {
value: parentScope
});
d('new obj __parent__');
d(obj.__parent__);
d('/createScope');
return obj;
}
function findInScope(scope, identifier, fullIdentifier, parent) {
let idSplit = identifier.split('.');
let temp = idSplit.shift();
// hold full original identifier for use during look up in parent
// if it's already initialized (which happens only on the first call), leave it be
fullIdentifier = fullIdentifier || identifier;
// storing parent scope since a child node might not have a __parent__ property
// so we memoize the parent a level above and use that in the recursive calls
// so that we can come out of the child object and resume checking up the parents
parent = scope.__parent__ || parent;
d('findInScope:');
d(scope);
d(temp);
d(idSplit);
d('/findInScope');
if (0 === Object.keys(scope).length) throw new ReferenceError(fullIdentifier + ' is not defined');
if (idSplit.length && scope.hasOwnProperty(temp)) return findInScope(scope[temp], idSplit.join('.'), fullIdentifier, parent);
if (!idSplit.length && scope.hasOwnProperty(temp)) return scope[temp];
return findInScope(scope.__parent__ || parent, fullIdentifier, fullIdentifier, parent);
}
function setInScope(scope, identifier, value) {
d('SetInScope');
d(identifier);
d(value.toString());
d(scope);
d('/SetInScope');
scope[identifier] = value;
return true;
}
module.exports = {
setInScope: setInScope,
createScope: createScope,
findInScope: findInScope
};
| JavaScript | 0.000001 | @@ -1341,32 +1341,88 @@
nProperty(temp))
+ %7B%0A d('Found item in scope');%0A d(scope%5Btemp%5D);%0A
return scope%5Bte
@@ -1426,16 +1426,20 @@
%5Btemp%5D;%0A
+ %7D%0A
return
@@ -1613,28 +1613,109 @@
;%0A
-d(value.toString());
+if ('function' === typeof value) d(value.toString());%0A else d(value);%0A%0A scope%5Bidentifier%5D = value;%0A
%0A d
@@ -1748,37 +1748,8 @@
);%0A%0A
- scope%5Bidentifier%5D = value;%0A
re
|
239a18047e7cbe10524da890af2690c3cb76e671 | Update join.js | tests/useful/join.js | tests/useful/join.js | import join from '../../src/commands/useful/join';
describe('join/join-server', () => {
it('should join execute joinServer and respond with with a success message', done => {
function reply(res) {
res.should.equal(`To invite me to your server, click the link below and select a server.
Only users with **Manage Server** permission in that server are able to invite me to it.
You may remove some of the permissions if you wish, but be warned it may break current and upcoming features.
https://discordapp.com/oauth2/authorize?&client_id=123&scope=bot&permissions=268823767`);
done();
}
return join.join({}, {message: {reply}});
});
});
| JavaScript | 0.000001 | @@ -573,17 +573,17 @@
ons=
-268823767
+403041495
%60);%0A
|
0d57e6ba0d3b4fc9cfb2e694f804dbab0a7fdfe8 | Disable caching | thumbhub/thumbhub.js | thumbhub/thumbhub.js | var express = require('express'),
fs = require('fs'),
path = require('path'),
url = require('url'),
request = require('request'),
dns = require('dns'),
jimp = require('jimp'),
tmp = require("tmp"),
common;
var metahub_srv = "bokeh-metahub.service.consul."
var photohub_srv = "bokeh-photohub-3000.service.consul."
var thumbhub_srv = "bokeh-thumbhub.service.consul."
function pickupSRV(name, cb) {
dns.resolveSrv(name, function (err, results) {
if (results instanceof Array) {
// Pickup a random result from the different resolved names
result = results[Math.floor(Math.random()*results.length)];
cb(result);
}
});
}
function getMetaData(hash, cb) {
pickupSRV(metahub_srv, function(record) {
var myurl = 'http://' + record.name + ':' + record.port + '/photos/' + hash;
console.log("Requesting Metahub: "+ myurl);
request({uri: myurl}).on('response', function(response) {
var str = '';
response.on('data', function (chunk) { str += chunk; });
response.on('end', function () {
var resp = JSON.parse(str);
if (resp) {
myPhoto = resp['photos'][0];
type = myPhoto['type'];
url = myPhoto['url'];
cb(false, url, type);
} else {
console.log('Bad response from Metahub');
cb('error', '', '');
}
});
}).on('error', function (error) {
console.log('Error while requesting Metahub');
cb('error', '', '');
});
});
}
function getPhoto(hash, path, cb) {
pickupSRV(photohub_srv, function(record) {
var myurl = 'http://' + record.name + ':' + record.port + '/photos/hash/' + hash;
console.log('Uploading photo from PhotoHub: '+myurl);
// Set timout for 42sec
request({url: myurl, agentOptions: { timeout: 420000 }})
.on('error', function(err) {
cb(err);
})
.on('response', function(response) {
console.log("Reply from photohub: " + response.statusCode);
response.on('end', function () {
console.log("Written file: " + path);
cb('');
});
}).pipe(fs.createWriteStream(path));
});
}
module.exports = function(config){
var app = express(),
staticFiles = config.staticFiles,
common = require('./common')(config);
// app.get(/.+\.(jpg|bmp|jpeg|gif|png|tif)$/i, function(req, res, next){
app.get(/.+$/i, function(req, res, next){
var hashPath, filePath, fstream;
var hash = path.basename(req.path);
console.log("Got request for " + config.urlRoot + req.path);
getMetaData(hash, function (e, p, type) {
if (e) {
console.log("Unable to get MIME type on MetaHub");
return common.error(req, res, next, 404, 'File not found', err);
}
console.log("Got from MetaHub type: " + type);
hashPath = staticFiles + "/" + hash + path.extname(p);
fs.stat(hashPath, function(err){
if (err){
console.log("Thumb not found: " + hashPath);
filePath = staticFiles + "/" + p;
getPhoto(hash, filePath, function (err) {
if (err) {
console.log("Cannot download: " + err);
return common.error(req, res, next, 404, 'File not found', err);
}
jimp.read(filePath, function(err1, img) {
if (err1) {
console.log("Cannot read: " + err1);
return common.error(req, res, next, 404, 'File not found', err1);
}
img.resize(256, jimp.AUTO);
img.write(hashPath, function(err3, i) {
if (err3) {
console.log("Cannot write final thumb: " + hashPath + " err3: " + err3);
return common.error(req, res, next, 404, 'File not found', err3);
}
console.log("Successfully created thumb: " + hashPath);
fs.unlink(filePath);
fstream = fs.createReadStream(hashPath);
return fstream.pipe(res);
});
});
});
} else {
fstream = fs.createReadStream(hashPath);
fstream.on('error', function(err){
console.log("Cannot read thumb: " + hashPath);
return common.error(req, res, next, 404, 'File not found', err);
});
return fstream.pipe(res);
}
});
});
});
return app;
} | JavaScript | 0.000001 | @@ -2714,19 +2714,20 @@
%09%09%09%09if (
-err
+true
)%7B%0A%09%09%09%09%09
|
2392ad25ecc293c07fc9820c488f17dce3ab9748 | Revert null check removal | src/diff/props.js | src/diff/props.js | import { IS_NON_DIMENSIONAL } from '../constants';
import options from '../options';
/**
* Diff the old and new properties of a VNode and apply changes to the DOM node
* @param {import('../internal').PreactElement} dom The DOM node to apply
* changes to
* @param {object} newProps The new props
* @param {object} oldProps The old props
* @param {boolean} isSvg Whether or not this node is an SVG node
*/
export function diffProps(dom, newProps, oldProps, isSvg) {
let keys = Object.keys(newProps).sort();
for (let i = 0; i < keys.length; i++) {
let k = keys[i];
if (k!=='children' && k!=='key' && (!oldProps || ((k==='value' || k==='checked') ? dom : oldProps)[k]!==newProps[k])) {
setProperty(dom, k, newProps[k], oldProps[k], isSvg);
}
}
for (let i in oldProps) {
if (i!=='children' && i!=='key' && !(i in newProps)) {
setProperty(dom, i, null, oldProps[i], isSvg);
}
}
}
let CAMEL_REG = /-?(?=[A-Z])/g;
/**
* Set a property value on a DOM node
* @param {import('../internal').PreactElement} dom The DOM node to modify
* @param {string} name The name of the property to set
* @param {*} value The value to set the property to
* @param {*} oldValue The old value the property had
* @param {boolean} isSvg Whether or not this DOM node is an SVG node or not
*/
function setProperty(dom, name, value, oldValue, isSvg) {
let v;
if (name==='class' || name==='className') name = isSvg ? 'class' : 'className';
if (name==='style') {
/* Possible golfing activities for setting styles:
* - we could just drop String style values. They're not supported in other VDOM libs.
* - assigning to .style sets .style.cssText - TODO: benchmark this, might not be worth the bytes.
* - assigning also casts to String, and ignores invalid values. This means assigning an Object clears all styles.
*/
let s = dom.style;
if (typeof value==='string') {
s.cssText = value;
}
else {
if (typeof oldValue==='string') s.cssText = '';
else {
// remove values not in the new list
for (let i in oldValue) {
if (value==null || !(i in value)) s.setProperty(i.replace(CAMEL_REG, '-'), '');
}
}
for (let i in value) {
v = value[i];
if (oldValue==null || v!==oldValue[i]) {
s.setProperty(i.replace(CAMEL_REG, '-'), typeof v==='number' && IS_NON_DIMENSIONAL.test(i)===false ? (v + 'px') : v);
}
}
}
}
else if (name==='dangerouslySetInnerHTML') {
return;
}
// Benchmark for comparison: https://esbench.com/bench/574c954bdb965b9a00965ac6
else if (name[0]==='o' && name[1]==='n') {
let useCapture = name !== (name=name.replace(/Capture$/, ''));
let nameLower = name.toLowerCase();
name = (nameLower in dom ? nameLower : name).substring(2);
if (value) {
if (!oldValue) dom.addEventListener(name, eventProxy, useCapture);
}
else {
dom.removeEventListener(name, eventProxy, useCapture);
}
(dom._listeners || (dom._listeners = {}))[name] = value;
}
else if (name!=='list' && name!=='tagName' && !isSvg && (name in dom)) {
dom[name] = value==null ? '' : value;
}
else if (value==null || value===false) {
if (name!==(name = name.replace(/^xlink:?/, ''))) dom.removeAttributeNS('http://www.w3.org/1999/xlink', name.toLowerCase());
else dom.removeAttribute(name);
}
else if (typeof value!=='function') {
if (name!==(name = name.replace(/^xlink:?/, ''))) dom.setAttributeNS('http://www.w3.org/1999/xlink', name.toLowerCase(), value);
else dom.setAttribute(name, value);
}
}
/**
* Proxy an event to hooked event handlers
* @param {Event} e The event object from the browser
* @private
*/
function eventProxy(e) {
return this._listeners[e.type](options.event ? options.event(e) : e);
}
| JavaScript | 0 | @@ -817,16 +817,30 @@
'key' &&
+ (!newProps %7C%7C
!(i in
@@ -849,16 +849,17 @@
wProps))
+)
%7B%0A%09%09%09se
|
262fcdc40ed7775f13dbe593f0ecf120cf181a62 | remove dummy/debugger rectangle | source/main.js | source/main.js | import init from './app/init';
init((ctx, { ts, dts }, { w, h, hw, hh }) => {
ctx.fillStyle = '#f0f';
ctx.fillRect(hw - 50, hh - 50, 100, 100);
});
| JavaScript | 0.001009 | @@ -80,77 +80,39 @@
-ctx.fillStyle = '#f0f';%0A ctx.fillRect(hw - 50, hh - 50, 100, 100);
+// do stuff with particles here
%0A%7D);
|
eea25ff052d2dfd33c4b6f52a182d8352220f9ae | Fix setPositionVisible on dropdown when in mobile. | source/assets/javascripts/locastyle/_dropdown.js | source/assets/javascripts/locastyle/_dropdown.js | var locastyle = locastyle || {};
locastyle.dropdown = (function() {
'use strict';
function init() {
unbind();
bindClickOnTriggers();
bindClickOutsideTriggers();
}
function unbind() {
$("[data-ls-module=dropdown] > a:first-child").off("click.ls");
$("body").off("click.ls");
}
function bindClickOnTriggers() {
$("[data-ls-module=dropdown] > a:first-child").on("click.ls", function(evt) {
evt.preventDefault();
var $target = $($(this).parents("[data-ls-module=dropdown]"));
locastyle.dropdown.toggleDropdown($target);
locastyle.dropdown.closeDropdown($target);
setPositionVisible($target);
evt.stopPropagation();
});
}
function bindClickOutsideTriggers() {
$("body").on("click.ls", function(){
locastyle.dropdown.closeDropdown();
});
}
function toggleDropdown($target) {
$target.toggleClass("ls-active");
locastyle.topbarCurtain.hideCurtains();
}
function closeDropdown(el) {
$("[data-ls-module=dropdown]").not(el).removeClass("ls-active");
}
function setPositionVisible($target){
var $main = $('.ls-main');
if($main.get(0).scrollWidth > $main.width()){
$($target).addClass('ls-pos-right')
}
}
return {
init: init,
unbind: unbind,
toggleDropdown: toggleDropdown,
closeDropdown: closeDropdown
}
}());
| JavaScript | 0 | @@ -1121,16 +1121,12 @@
$('
-.ls-main
+body
');%0A
|
479faa17acc3f90fbef034caa2a7e6aed6f2241d | Improve metric stack chart colors | core/app/scripts/services/keyed-color-pools.js | core/app/scripts/services/keyed-color-pools.js | /*
* Copyright 2014 the original author or 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.
*/
/* global glowroot, angular, $ */
glowroot.factory('keyedColorPools', [
function () {
var fixedPool = ['#edc240', '#afd8f8', '#cb4b4b', '#4da74d', '#9440ed'];
var dynamicPool = fixedPool.slice(0);
var variation = 0;
function getColor(i) {
if (i < dynamicPool.length) {
return dynamicPool[i];
}
// this color generation code is copied from jquery.flot.js
var c = $.color.parse(fixedPool[i % fixedPool.length] || '#666');
if (i % fixedPool.length === 0 && i) {
if (variation >= 0) {
if (variation < 0.5) {
variation = -variation - 0.2;
} else {
variation = 0;
}
} else {
variation = -variation;
}
}
var color = c.scale('rgb', 1 + variation);
dynamicPool.push(color);
return color;
}
function create() {
var colors = {};
var used = {};
function nextAvailable() {
for (var i = 0; i < dynamicPool.length; i++) {
var color = dynamicPool[i];
if (!used[color]) {
return color;
}
}
return getColor(dynamicPool.length);
}
return {
reset: function (keys) {
var preservedColors = {};
used = {};
angular.forEach(keys, function (key) {
var color = colors[key];
if (color) {
preservedColors[key] = color;
used[color] = true;
}
});
colors = preservedColors;
angular.forEach(keys, function (key) {
if (!colors[key]) {
var color = nextAvailable();
colors[key] = color;
used[color] = true;
}
});
},
keys: function () {
return Object.keys(colors);
},
add: function (key) {
var color = colors[key];
if (color) {
return color;
}
color = nextAvailable();
colors[key] = color;
used[color] = true;
return color;
},
get: function (key) {
return colors[key];
},
remove: function (key) {
var color = colors[key];
if (color) {
delete colors[key];
delete used[color];
}
}
};
}
return {
create: create
};
}
]);
| JavaScript | 0.000001 | @@ -13,16 +13,21 @@
ght 2014
+-2015
the ori
@@ -737,14 +737,14 @@
, '#
-afd8f8
+9dc2df
', '
@@ -838,17 +838,17 @@
ation =
-0
+1
;%0A%0A f
@@ -983,19 +983,21 @@
code is
-cop
+modif
ied from
@@ -1075,18 +1075,8 @@
gth%5D
- %7C%7C '#666'
);%0A
@@ -1119,36 +1119,32 @@
&& i) %7B%0A
-if (
variation %3E= 0)
@@ -1141,18 +1141,16 @@
ion
-%3E= 0) %7B%0A
+-= 0.3;%0A
@@ -1178,34 +1178,32 @@
.5) %7B%0A
-
variation = -var
@@ -1200,135 +1200,12 @@
ion
++
=
--variation - 0.2;%0A %7D else %7B%0A variation = 0;%0A %7D%0A %7D else %7B%0A variation = -variation
+1
;%0A
@@ -1256,12 +1256,8 @@
gb',
- 1 +
var
|
d316dfea2036cb175b6bb2044a4aca49627e931a | Edit MySpec test suite | spec/MySpec.js | spec/MySpec.js | describe("MyClass", function() {
it("should be true", function() {
expect(true).toBeTruthy();
});
});
| JavaScript | 0 | @@ -74,19 +74,20 @@
expect(
-tru
+fals
e).toBeT
|
58249e6f72fc7e45b932bd469e5ae1b69f4a0df1 | Create file upload (#114) | addon/components/uni-file-upload.js | addon/components/uni-file-upload.js | import Ember from 'ember';
import layout from '../templates/components/uni-file-upload';
const { Component } = Ember;
export default Component.extend({
layout,
accept: null,
renderFile: false,
label: '',
filename: '',
handleFile() {},
actions: {
triggerInputFile() {
this.$('.uni-file-upload').click();
},
handleFile(event) {
let reader = new FileReader();
let [file] = event.target.files;
reader.onload = () => {
this.set('filename', file.name);
this.get('handleFile')(file, reader.result);
};
if (file) {
reader.readAsDataURL(file);
}
}
}
});
| JavaScript | 0 | @@ -147,16 +147,51 @@
xtend(%7B%0A
+ classNames: %5B'uni-file-upload'%5D,%0A
layout
|
c407a7b2ac32d7fae985dc94bc4a2b109c6b76f0 | update Switcher | src/Switcher/Switcher.js | src/Switcher/Switcher.js | /**
* @file Switcher component
* @author liangxiaojun([email protected])
*/
import React, {Component} from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import IconButton from '../IconButton';
import CircularLoading from '../CircularLoading';
import Theme from '../Theme';
import Util from '../_vendors/Util';
class Switcher extends Component {
static Size = {
DEFAULT: '',
SMALL: 'small'
};
static Theme = Theme;
constructor(props, ...restArgs) {
super(props, ...restArgs);
this.state = {
value: !!props.value
};
}
clickHandler = e => {
const {disabled, isLoading, beforeChange, onClick} = this.props;
if (disabled || isLoading) {
return;
}
onClick && onClick(e);
const value = !this.state.value,
callback = () => {
this.setState({
value
}, () => {
const {onChange} = this.props;
onChange && onChange(value, e);
});
};
if (beforeChange) {
beforeChange(value) !== false && callback();
} else {
callback();
}
};
componentWillReceiveProps(nextProps) {
if (nextProps.value !== this.state.value) {
this.setState({
value: !!nextProps.value
});
}
}
render() {
const {className, style, theme, disabled, isLoading, size, labelVisible} = this.props,
{value} = this.state,
switcherClassName = classNames('switcher', {
activated: value,
small: size === Switcher.Size.SMALL,
[`theme-${theme}`]: theme,
[className]: className
});
return (
<div className={switcherClassName}
style={style}
disabled={disabled || isLoading}
onClick={this.clickHandler}>
{
labelVisible ?
<div className="switcher-label"></div>
:
null
}
<IconButton className="switcher-slider-wrapper"
disableTouchRipple={disabled || isLoading}>
<div className="switcher-slider">
{
isLoading ?
<CircularLoading/>
:
null
}
</div>
</IconButton>
</div>
);
}
}
Switcher.propTypes = {
/**
* The CSS class name of the root element.
*/
className: PropTypes.string,
/**
* Override the styles of the root element.
*/
style: PropTypes.object,
/**
* The Switcher theme.
*/
theme: PropTypes.oneOf(Util.enumerateValue(Theme)),
/**
* If true,the switcher will be in active status.
*/
value: PropTypes.bool,
/**
* Disables the switcher if set to true.
*/
disabled: PropTypes.bool,
/**
* If true,the switcher will be have loading effect.
*/
isLoading: PropTypes.bool,
labelVisible: PropTypes.bool,
/**
* The size of switcher.The value can be small or default.
*/
size: PropTypes.oneOf(Util.enumerateValue(Switcher.Size)),
/**
* Callback function fired when the switcher touch-tapped.
*/
onClick: PropTypes.func,
/**
* Callback function fired before the switcher touch-tapped.
*/
beforeChange: PropTypes.func,
/**
* Callback function fired when the switcher touch-tapped.
*/
onChange: PropTypes.func
};
Switcher.defaultProps = {
theme: Theme.DEFAULT,
value: false,
disabled: false,
isLoading: false,
labelVisible: false,
size: Switcher.Size.DEFAULT
};
export default Switcher; | JavaScript | 0 | @@ -353,16 +353,71 @@
s/Util';
+%0Aimport ComponentUtil from '../_vendors/ComponentUtil';
%0A%0Aclass
@@ -1344,183 +1344,174 @@
-componentWillReceiveProps(nextProps) %7B%0A if (nextProps.value !== this.state.value) %7B%0A this.setState(%7B%0A value: !!nextProps.value%0A %7D);
+static getDerivedStateFromProps(props, state) %7B%0A return %7B%0A prevProps: props,%0A value: ComponentUtil.getDerivedState(props, state, 'value')
%0A
@@ -1512,24 +1512,25 @@
')%0A %7D
+;
%0A %7D%0A%0A
@@ -4125,8 +4125,9 @@
witcher;
+%0A
|
181a90e284f73ee862de323cdf569e94cd9e6440 | Update gruntfile.js | samples/grunt/gruntfile.js | samples/grunt/gruntfile.js | /*
Copyright (c) Microsoft. All rights reserved.
Licensed under the MIT license. See LICENSE file in the project root for full license information.
*/
module.exports = function(grunt) {
grunt.loadNpmTasks("grunt-typescript");
grunt.initConfig({
typescript: {
base: {
src: "scripts/**/*.ts",
dest: "www",
options: {
base: "scripts",
noImplicitAny: false,
noEmitOnError: true,
removeComments: false,
sourceMap: true,
target: "es5"
}
}
}
});
grunt.registerTask('default', ['typescript','build']);
grunt.registerTask('build', function () {
var cordovaBuild = require('taco-team-build'),
done = this.async();
var platformsToBuild = process.platform == "darwin" ? ["ios"] : ["android", "windows", "wp8"], // Darwin == OSX
buildArgs = {
android: ["--release", "--ant"], // Warning: Omit the extra "--" when referencing platform
ios: ["--release", "--device"], // specific preferences like "-- --ant" for Android
windows: ["--release"], // or "-- --win" for Windows. You may also encounter a
wp8: ["--release"] // "TypeError" after adding a flag Android doesn't recognize
}; // when using Cordova < 4.3.0. This is fixed in 4.3.0.
cordovaBuild.buildProject(platformsToBuild, buildArgs)
.then(function() {
return cordovaBuild.packageProject(platformsToBuild);
})
.done(done);
});
};
| JavaScript | 0.000001 | @@ -1064,15 +1064,43 @@
%22--
-ant
+device%22,%22--gradleArg=--no-daemon
%22%5D,
-
/
@@ -1199,24 +1199,52 @@
%22--device%22%5D,
+
// spec
@@ -1325,18 +1325,46 @@
release%22
+, %22--device%22
%5D,
+
@@ -1456,17 +1456,37 @@
release%22
-%5D
+, %22--device%22%5D
@@ -1495,16 +1495,24 @@
+
// %22Type
@@ -1578,16 +1578,44 @@
%7D;
+
|
cb8d299e570a5222f78247f4c2512f7166bf7d13 | add some stories | spark/components/awards/react/SprkAward-story.js | spark/components/awards/react/SprkAward-story.js | import React from 'react';
import { storiesOf } from '@storybook/react';
import { SprkAward } from '@sparkdesignsystem/spark-react';
storiesOf('Award', module)
.add('test', () => (
<SprkAward
heading="Award Component Heading"
idString="award-1"
disclaimerText="
This is an example of disclaimer content.
The aria-expanded='true' attribute will be
viewable in the DOM on the toggle link when
this content is shown. When this content is
hidden the aria-expanded attribute will have
the value of false. This helps accessibilty
devices in understanding that the link is a
control for expandable content.
"
disclaimerTitle="My Disclaimer"
images={[{
href:
'#nogo',
src:
'https://www.sparkdesignsystem.com/assets/toolkit/images/spark-placeholder.jpg',
alt:
'Spark Placeholder Logo',
analyticsString:
'award-1',
element:
'a',
},
{
href:
'#nogo',
src:
'https://www.sparkdesignsystem.com/assets/toolkit/images/spark-placeholder.jpg',
alt:
'Spark Placeholder Logo',
analyticsString:
'award-2',
element:
'a',
},
]}
/>
)); | JavaScript | 0 | @@ -772,32 +772,24 @@
href:
-%0A
'#nogo',%0A
@@ -794,32 +794,24 @@
src:
-%0A
'https://ww
@@ -888,32 +888,24 @@
alt:
-%0A
'Spark Plac
@@ -939,32 +939,24 @@
yticsString:
-%0A
'award-1',%0A
@@ -975,64 +975,30 @@
ent:
-%0A 'a',%0A %7D,%0A %7B%0A href:%0A
+ 'a',%7D,%0A %7Bhref:
'#n
@@ -1015,24 +1015,16 @@
src:
-%0A
'https:
@@ -1109,24 +1109,16 @@
alt:
-%0A
'Spark
@@ -1160,24 +1160,16 @@
sString:
-%0A
'award-
@@ -1192,30 +1192,13 @@
ent:
-%0A 'a',%0A
+ 'a',
%7D,%0A
|
fc0eadb0cb8c161cf02f7fd4be6653f8677c29c9 | Fix questions post | www/app/features/labelEffects/labelEffects.js | www/app/features/labelEffects/labelEffects.js | 'use strict';
/**
* @ngdoc function
* @name gapFront.controller:LabelEffectsCtrl
* @description
* # LabelEffectsCtrl
* Controller of the gapFront
*/
angular.module('gapFront')
.controller('LabelEffectsCtrl', function ($scope, IntegrationService, APIService, DrugService) {
$scope.effects = [];
$scope.selectedSymptom = '';
$scope.adverseEffects = [];
$scope.displayedStuff = [];
$scope.percentAnswered = function(){
return $scope.getPercentage() + '% of possible side effects addressed'
};
$scope.count = 1;
$scope.total = 0;
var initLabelEffects = function (params) {
$scope.selectedDrug = DrugService.getSelectedDrug();
var query = 'patient.drug.medicinalproduct:' + $scope.selectedDrug.brand_name;
APIService.aggregateDrugEvent(query, 50, 'patient.reaction.reactionmeddrapt.exact').then(addFdaList, serviceError)
};
IntegrationService.registerIntegrationMethod('initLabelEffects', initLabelEffects);
$scope.fetchDrugEffects = function () {
$scope.adverseEffects = [];
$scope.displayedStuff = [];
APIService.getDrugsApi().get($scope.selectedDrug.brand_name).then(updateList, serviceError)
};
function addFdaList(resp) {
var res = resp.results;
for (var i in res) {
$scope.effects.push(res[i].term);
}
$scope.fetchDrugEffects();
}
function updateList(resp) {
$scope.adverseEffects = resp.drug.effects;
$scope.total = $scope.adverseEffects.length;
addDisplayedStuff();
}
function addDisplayedStuff() {
var k = genRandomInt(0, $scope.adverseEffects.length);
var effect = $scope.adverseEffects.splice(k, 1)[0];
var sentence = findMatchingSentence($scope.selectedDrug.object, effect);
$scope.displayedStuff.push({effect: effect, sentence: sentence});
}
function genRandomInt(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
function serviceError(error) {
}
function findMatchingSentence(drugObject, effect) {
var textToSearch = [];
if (drugObject['boxed_warnings']) {
textToSearch.push.apply(textToSearch, drugObject['boxed_warnings']);
}
if (drugObject['warnings_and_precautions']) {
textToSearch.push.apply(textToSearch, drugObject['warnings_and_precautions']);
}
if (drugObject['user_safety_warnings']) {
textToSearch.push.apply(textToSearch, drugObject['user_safety_warnings']);
}
if (drugObject['precautions']) {
textToSearch.push.apply(textToSearch, drugObject['precautions']);
}
if (drugObject['warnings']) {
textToSearch.push.apply(textToSearch, drugObject['warnings']);
}
if (drugObject['general_precautions']) {
textToSearch.push.apply(textToSearch, drugObject['general_precautions']);
}
if (drugObject['warnings_and_precautions']) {
textToSearch.push.apply(textToSearch, drugObject['warnings_and_precautions']);
}
if (drugObject['adverse_reactions']) {
textToSearch.push.apply(textToSearch, drugObject['adverse_reactions']);
}
var i, j;
var found = false;
if (Array.isArray(textToSearch)) {
textToSearch = textToSearch.join('.');
}
var splitText = textToSearch.split('.');
for (i = 0; i < splitText.length; i++) {
if (splitText[i].match(effect)) {
found = true;
break;
}
}
if (found == true) {
return (splitText.slice(i-1, i+1).join('.'));
} else {
var idx = Math.floor(Math.random() * splitText.length);
return (splitText.slice(idx-1, idx+1).join('.'));
}
}
// Called every time you finish one question
$scope.completeIndex = function (index, accurate) {
$scope.count += 1;
var term = $scope.displayedStuff.splice(index, 1)[0];
if ($scope.adverseEffects.length > 0) addDisplayedStuff();
if (accurate) {
var post = {drug_name: $scope.selectedDrug.brand_name, effect: term, response: accurate};
APIService.getEffectsApi().post(post).then(serviceError, serviceError);
}
};
$scope.adverseTooltip = "Add a new adverse affect not currently reported";
$scope.addSelectedSymptom = function () {
var elem = $('#selsym')[0];
var value = elem.value;
if (contains($scope.symptoms, value) && !effectsContain(value)) {
$scope.effects.push({medical_term: value, layman_term: value, checked: true});
$scope.selectedSymptom = '';
elem.value = '';
}
};
$scope.getPercentage = function () {
var div = ($scope.count - 1) / $scope.total;
var percent = div * 100;
return Math.floor(percent);
};
function effectsContain(obj) {
var a = $scope.effects;
for (var i = 0; i < a.length; i++) {
if (a[i].medical_term == obj) {
return true;
}
}
return false;
}
function contains(a, obj) {
for (var i = 0; i < a.length; i++) {
if (a[i] === obj) {
return true;
}
}
return false;
}
});
| JavaScript | 0.000129 | @@ -4004,24 +4004,51 @@
accurate) %7B%0A
+ console.log(term);%0A
var
@@ -4110,16 +4110,23 @@
ct: term
+.effect
, respon
|
fe69034bc7d1f04b130d668f278ea63964ffc77e | add mouse over | www/static_src/scripts/services/mapService.js | www/static_src/scripts/services/mapService.js | import 'leaflet';
import 'topojson';
import angular from 'angular';
require('../../../../node_modules/leaflet.vectorgrid/dist/Leaflet.VectorGrid.js');
class mapService {
constructor(ajaxService) {
'ngInject';
this.ajaxService = ajaxService;
}
initialize() {
this.map = L.map('map', {
center: [0, 0],
zoom: 2
});
var basemap = L.tileLayer('http://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png', {
attribution: '© <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a> © <a href="http://cartodb.com/attributions">CartoDB</a>',
subdomains: 'abcd',
maxZoom: 19
});
this.map.addLayer(basemap);
this.ajaxService
.getInstances()
.then(result => {
_.forEach(result.instances, instance => {
let latLngs = L.GeoJSON.coordsToLatLngs(instance.bbox.coordinates[0]);
let layer = instance.layers[0];
let tileLayer = L.vectorGrid.protobuf(layer.url, {
bbox: L.latLngBounds(latLngs),
vectorTileLayerStyles: {
// all tilesplash layer is named 'vectile' internally
vectile: {
weight: 3,
fillColor: '#449bf6',
fillOpacity: 0.7,
fill: true
}
}
});
this.map.addLayer(tileLayer);
});
});
}
}
mapService.$inject = ['ajaxService'];
angular.module('OpenDataDiscovery').service('mapService', mapService);
export default mapService;
| JavaScript | 0.000001 | @@ -1317,85 +1317,655 @@
%7D
-%0A %7D);%0A%0A this.map.addLayer(tileLayer);%0A %7D);%0A %7D);
+,%0A onMouseOver: this._onMouseOver.bind(this),%0A onMouseOut: this._onMouseOut.bind(this),%0A onMouseMove: this._onMouseMove.bind(this)%0A %7D);%0A%0A this.map.addLayer(tileLayer);%0A %7D);%0A %7D);%0A %7D%0A%0A _onMouseOver(e) %7B%0A this.map.closePopup();%0A%0A this.currentPopup = L.popup(%7B%0A offset: L.point(0, -1),%0A closeButton: false%0A %7D)%0A .setLatLng(e.latlng)%0A .setContent('test')%0A .openOn(this.map);%0A %7D%0A%0A _onMouseOut(e) %7B%0A this.map.closePopup();%0A delete this.currentPopup;%0A %7D%0A%0A _onMouseMove(e) %7B%0A if (this.currentPopup) %7B%0A this.currentPopup.setLatLng(e.latlng);%0A %7D
%0A %7D
|
488da56a757282dec675f67fcffbfb3b25f30bce | support array of lua lines | src/rule.js | src/rule.js | import { Criteria } from './criteria.js';
import { Behavior } from './behavior.js';
export class Rule {
constructor(name, criteria, criteriaMustSatisfy, behaviors, children, skipBehaviors, valueMap, depth) {
this.name = name;
this.criteria = criteria;
this.criteriaMustSatisfy = criteriaMustSatisfy;
this.behaviors = behaviors;
this.children = children;
this.skipBehaviors = skipBehaviors;
this.valueMap = valueMap;
this.depth = depth;
}
process() {
let result = '\n' + this.pad(this.depth) + '-- ' + this.name + ' rule ####';
let criteriaNames = this.criteriaNames(this.criteria) ? this.criteriaNames(this.criteria) : 'none';
result += '\n' + this.pad(this.depth) + '-- criteria: ' + criteriaNames;
if (this.anyCriteriaForRuleRegistered(this.criteria)) {
result += '\n' + this.pad(this.depth) + 'if ' + this.processCriteria(this.criteria, this.valueMap) + ' then';
} else {
if (this.criteriaNamesNotRegistered(this.criteria)) {
console.error('Criteria not registered: ' + this.criteriaNamesNotRegistered(this.criteria));
}
}
if (this.behaviors && typeof this.behaviors !== 'undefined' && this.behaviors.length > 0) {
result += this.pad(this.depth + 1) +
this.processBehaviors(this.behaviors, this.valueMap, this.skipBehaviors) + '\n';
}
let that = this;
this.children.forEach(function (childRule) {
let rule = new Rule(
childRule.name,
childRule.criteria,
childRule.criteriaMustSatisfy,
childRule.behaviors,
childRule.children,
that.skipBehaviors,
that.valueMap,
that.depth + 1
);
result += rule.process();
});
if (this.anyCriteriaForRuleRegistered(this.criteria)) {
result += this.pad(this.depth) + 'end\n';
}
return result;
}
anyCriteriaForRuleRegistered(criteria) {
if (!criteria) return false;
let anyCriteriaRegistered = false;
criteria.forEach((criteria) => {
if (Criteria.isRegistered(criteria.name)) {
anyCriteriaRegistered = true;
}
});
return anyCriteriaRegistered;
}
criteriaNames(criteria) {
if (!criteria) return '';
let criteriaNameArray = [];
criteria.forEach((criteria) => {
criteriaNameArray.push(criteria.name);
});
return criteriaNameArray.join(this.criteriaJoiner());
}
criteriaNamesNotRegistered(criteria) {
if (!criteria) return;
let criteriaNameArray = [];
criteria.forEach((criteria) => {
if (!Criteria.isRegistered(criteria.name)) {
criteriaNameArray.push(criteria.name);
}
});
return criteriaNameArray.join(', ');
}
processCriteria(criteria, valueMap) {
if (!criteria) return null;
let criteriaArray = [];
criteria.forEach((criteria) => {
if (Criteria.isRegistered(criteria.name)) {
let item = new Criteria(criteria.name, criteria.options, valueMap);
criteriaArray.push(item.process());
}
});
return criteriaArray.join(this.criteriaJoiner());
}
processBehaviors(behaviors, valueMap, skipBehaviors) {
if (!behaviors) return null;
let behaviorArray = [];
behaviors.forEach((behavior) => {
let item = new Behavior(behavior.name, behavior.options, valueMap);
if (skipBehaviors.includes(behavior.name)) {
behaviorArray.push('-- ' + behavior.name + ' behavior (skipped)');
} else {
behaviorArray.push('-- ' + behavior.name + ' behavior');
let behaviourResult = item.process();
if (behaviourResult) {
behaviorArray.push(behaviourResult);
}
}
});
return '\n' + this.pad(this.depth+1) + behaviorArray.join('\n' + this.pad(this.depth+1));
}
criteriaJoiner() {
switch (this.criteriaMustSatisfy) {
case 'all': {
return ' and '
}
case 'any': {
return ' or '
}
}
}
pad(count) {
if (!count || count <0) {count=0}
return (new Array(count + 1)).join('\t');
}
} | JavaScript | 0 | @@ -4041,24 +4041,195 @@
urResult) %7B%0A
+ if (Array.isArray(behaviourResult)) %7B%0A behaviorArray = %5B...behaviorArray, ...behaviourResult%5D;%0A %7D else %7B%0A
@@ -4273,16 +4273,38 @@
esult);%0A
+ %7D%0A
|
f5c61e997d8e49b0398954199d298b66b6d98dd2 | Fix linting errors | src/send.js | src/send.js | import { busy, scheduleRetry } from './actions';
import { JS_ERROR } from './constants';
import type { Config, OfflineAction, ResultAction } from './types';
const complete = (
action: ResultAction,
success: boolean,
payload: {}
): ResultAction => ({
...action,
payload,
meta: { ...action.meta, success, completed: true }
});
const send = (action: OfflineAction, dispatch, config: Config, retries = 0) => {
const metadata = action.meta.offline;
dispatch(busy(true));
return config
.effect(metadata.effect, action)
.then(result => {
const commitAction = metadata.commit || {
...config.defaultCommit,
meta: { ...config.defaultCommit.meta, offlineAction: action }
};
try {
dispatch(complete(commitAction, true, result));
} catch (e) {
dispatch(complete({ type: JS_ERROR, payload: e }, false));
}
})
.catch(async error => {
const rollbackAction = metadata.rollback || {
...config.defaultRollback,
meta: { ...config.defaultRollback.meta, offlineAction: action }
};
// discard
let mustDiscard = true
try {
mustDiscard = await config.discard(error, action, retries)
} catch(e) {
console.warn(e)
}
if (!mustDiscard) {
const delay = config.retry(action, retries);
if (delay != null) {
dispatch(scheduleRetry(delay));
return;
}
}
dispatch(complete(rollbackAction, false, error));
});
};
export default send;
| JavaScript | 0.000075 | @@ -1124,16 +1124,17 @@
d = true
+;
%0A t
@@ -1204,16 +1204,17 @@
retries)
+;
%0A %7D
@@ -1219,16 +1219,17 @@
%7D catch
+
(e) %7B%0A
@@ -1249,16 +1249,17 @@
.warn(e)
+;
%0A %7D
|
49eb704692bdadeae6da08aa9b3ff52c981e9adb | Make slider slide automatically | assets/js/app.js | assets/js/app.js | $(document).ready(function() {
$('#menu .toggle').click(function (event) {
$(this).closest('header').find('nav').slideToggle(300)
event.preventDefault()
})
function PopupCenter(url, title, w, h) {
var dualScreenLeft = window.screenLeft != undefined ? window.screenLeft : screen.left
var dualScreenTop = window.screenTop != undefined ? window.screenTop : screen.top
var width = window.innerWidth ? window.innerWidth : document.documentElement.clientWidth ? document.documentElement.clientWidth : screen.width
var height = window.innerHeight ? window.innerHeight : document.documentElement.clientHeight ? document.documentElement.clientHeight : screen.height
var left = ((width / 2) - (w / 2)) + dualScreenLeft
var top = ((height / 2) - (h / 2)) + dualScreenTop
var newWindow = window.open(url, title, 'scrollbars=yes, width=' + w + ', height=' + h + ', top=' + top + ', left=' + left)
if (window.focus) {
newWindow.focus()
}
}
$('#video').fitVids()
$('#slider .container').unslider()
$('#page aside > span').click(function (event) {
$(this).nextAll('nav').slideToggle(300)
$(this).toggleClass('on')
})
$('#toggle-overlay a, section .spread').click(function (event) {
$('#overlay').animate({
top: '0%'
}, 400, function () {
$('body').addClass('no-scroll')
})
event.preventDefault()
})
$('#overlay .toggle').click(function () {
$('#overlay').animate({
top: '100%'
}, 400, function () {
$('body').removeClass('no-scroll')
})
})
$('#overlay .social a').click(function (event) {
var url = $(this).attr('href')
PopupCenter(url, 'Share', '600', '600')
event.preventDefault()
})
if ($('#news')) {
$.ajax({
type: 'GET',
url: 'http://davehakkens.nl/tag/preciousplastic/feed/',
success: function (xml) {
$(xml).find('item').each(function (index) {
var article = $('<article />')
var title = $(this).find('title').text()
var description = $($(this).find('description').text())[1]
var url = $(this).find('link').text()
var preview = $($(this).find('description').text()).find('.wp-post-image')
var figure = $('<figure></figure>')
figure.append(preview)
article.append(figure)
article.append('<a href="' + url + '" class="title">' + title + '</a>')
var descText = $(description).text()
if (descText.indexOf('-source') == -1 && descText.indexOf(title) == -1) {
article.append('<p>' + descText + '</p>')
}
var news = $('#news .container:first-child')
news.find('.loading').hide()
news.append(article)
if (index == 2) {
return false;
}
})
}
})
}
if ($().accordion) {
$('#page dl').accordion()
}
if ($().isotope) {
var grid = $('.extras').isotope({
itemSelector: '.item'
})
$('.filter nav a').click(function (e) {
var group = $(this).attr('href').split('#')[1]
var isActive = $(this).hasClass('active')
grid.isotope({
filter: isActive ? '*' : '.' + group
})
if( !isActive ) {
$(this).closest('nav').find('.active').removeClass('active')
}
$(this).toggleClass('active')
e.preventDefault()
})
}
//var canonical = $('head link[rel="canonical"]').attr('href')
var canonical = 'http://preciousplastic.com'
var url = encodeURIComponent(canonical)
var counts = [
{
url: 'api.facebook.com/method/links.getStats?urls=' + url + '&format=json',
field: 'share_count'
}
]
for (var api of counts) {
$.ajax({
type: 'GET',
url: 'https://' + api.url,
success: function (response) {
var count = parseInt(response[0][api.field])
var previous = parseInt($('#overlay .total span').text())
$('#overlay .total span').html(previous + count)
}
})
}
})
| JavaScript | 0.000001 | @@ -1041,16 +1041,40 @@
nslider(
+%7B%0A autoplay: true%0A %7D
)%0A%0A $('
|
e990e83ca5e95d3945be263ead3c4744c14688b9 | check against non-configured stage type before apply color | app/scripts/modules/delivery/executionBar.controller.js | app/scripts/modules/delivery/executionBar.controller.js | 'use strict';
angular.module('spinnaker.delivery.executionBar.controller', [
'spinnaker.pipelines.config',
'ui.router',
])
.controller('executionBar', function($scope, $filter, $stateParams, pipelineConfig, $state) {
var controller = this;
controller.getStageWidth = function() {
return 100 / $scope.execution.stageSummaries.length + '%';
};
controller.getStageColor = function(stage) {
var stageConfig = pipelineConfig.getStageConfig(stage.type);
if (stageConfig.executionBarColorProvider && stageConfig.executionBarColorProvider(stage)) {
return stageConfig.executionBarColorProvider(stage);
}
return $scope.scale[$scope.filter.stage.colorOverlay](
stage[$scope.filter.stage.colorOverlay].toLowerCase()
);
};
controller.getStageOpacity = function(stage) {
if (!!$scope.filter.stage.solo.facet &&
stage[$scope.filter.stage.solo.facet].toLowerCase() !==
$scope.filter.stage.solo.value) {
return 0.5;
} else {
return 0.8;
}
};
controller.showingDetails = function(stage) {
var param = $stateParams.stage ? parseInt($stateParams.stage) : 0;
return $scope.execution.id === $stateParams.executionId && $scope.execution.stageSummaries.indexOf(stage) === param;
};
controller.styleStage = function(stage) {
return {
'background-color': controller.getStageColor(stage),
opacity: controller.getStageOpacity(stage),
};
};
controller.toggleDetails = function(executionId, stageIndex) {
var stageSummary = $scope.execution.stageSummaries[stageIndex],
masterIndex = stageSummary.masterStageIndex;
if ($state.includes('**.execution', {executionId: executionId, stage: stageIndex})) {
$state.go('^');
} else {
if ($state.includes('**.execution')) {
$state.go('^.execution', {executionId: executionId, stage: stageIndex, step: masterIndex});
} else {
$state.go('.execution', {executionId: executionId, stage: stageIndex, step: masterIndex});
}
}
};
controller.getLabelTemplate = function(stage) {
var target = stage.masterStage || stage;
var config = pipelineConfig.getStageConfig(target.type);
if (config && config.executionLabelTemplateUrl) {
return config.executionLabelTemplateUrl;
} else {
return 'scripts/modules/pipelines/config/stages/core/executionBarLabel.html';
}
};
});
| JavaScript | 0 | @@ -491,32 +491,47 @@
if (stageConfig
+ && stageConfig
.executionBarCol
|
be46eb73747805567d5e251051524f3952ed7ada | Add tests for _meta and _metaid | tests/bookmarks.spec.js | tests/bookmarks.spec.js | /* Copyright 2015 Open Ag Data Alliance
*
* 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';
var Promise = require('bluebird');
var debug = require('debug')('oada-conformance:bookmarks.spec');
var test = require('./test');
var auth = require('./auth.js');
var resources = require('./resources.js');
var config = require('../config.js').get('bookmarks');
var Formats = require('oada-formats');
var formats = new Formats();
var packs = require('../config.js').get('options:oadaFormatsPackages') || [];
packs.forEach(function(pack) {
formats.use(require(pack));
});
test.describe('bookmarks', function(t) {
// Have to get token corrensponding to config.login user
return auth.getAuth(config.login).then(function(token) {
t.test('is valid', function(t) {
var bookmarks = resources.get('bookmarks', token);
return formats
.model('application/vnd.oada.bookmarks.1+json')
.call('validate', bookmarks.get('body'))
.nodeify(function(err) {
t.error(err, 'matches schema');
})
.catch(function() {});
});
// TODO: Is this required? Maybe the previous test handles this?
t.todo('is a resource', function(t) {
var bookmarks = resources.get('bookmarks', token).get('body');
var id = bookmarks.get('_id');
return id
.tap(function(id) {
t.ok(id, '/bookmarks has an `_id` field');
})
.tap(function(id) {
var resource = resources.get(id, token).get('body');
return Promise.join(bookmarks, resource,
function(bookmarks, resource) {
t.deepEqual(resource, bookmarks,
'/bookmarks equals corresponding resource');
});
});
});
// TODO: Rewrite to run tests as documents are retrieved
// currently gets *all* documents and then tests them
t.test('has valid subdocuments', function(t) {
return resources.getAll('bookmarks', token, function(id, res) {
t.notEqual(res.body, undefined, 'has a body: ' + id);
if (res.body && res.body._id) {
var skip = false;
return formats
.model(res.type)
.call('validate', res.body)
.catch(Formats.MediaTypeNotFoundError, function(e) {
debug('Model for ' + e.message + ' not found');
skip = e.message;
})
.nodeify(function(err) {
t.error(err, 'matches schema: ' + id, {
skip: skip
});
})
.catch(function() {});
/* TODO: Fails because of rev. How to handle?
.then(function() {
return resources.get(res.body._id, token);
})
.get('body')
.nodeify(function(err, body) {
t.deepEqual(res.body, body,
'matches /resources doc: ' + id);
})
.catch(function() {});
*/
}
});
});
t.todo('has CORS enabled');
});
});
| JavaScript | 0.000005 | @@ -2848,24 +2848,206 @@
body._id) %7B%0A
+ // TODO: _meta schema?%0A t.ok(res.body._meta, 'has a _meta: ' + id);%0A t.ok(res.body._meta._metaid, 'has a _metaid: ' + id);%0A%0A
|
3e39a32199f7c00339a5cf594c6cb9f3489b6c2f | update cartridge directory name | test/directoryStructureSpec.js | test/directoryStructureSpec.js | var path = require('path');
var chai = require('chai');
chai.use(require('chai-fs'));
chai.should();
const ROOT_DIR = path.join(process.cwd());
describe('As a dev', function() {
describe('When testing cartridge directory structure', function() {
var pathToTest;
it('then _cartridge folder should exist', function() {
pathToTest = path.join(ROOT_DIR, '_config');
pathToTest.should.be.a.directory();
})
it('then _config folder should exist', function() {
pathToTest = path.join(ROOT_DIR, '_config');
pathToTest.should.be.a.directory();
})
it('then _source folder should exist', function() {
pathToTest = path.join(ROOT_DIR, '_source');
pathToTest.should.be.a.directory();
})
});
}); | JavaScript | 0.000002 | @@ -376,37 +376,40 @@
in(ROOT_DIR, '_c
-onfig
+artridge
');%0A
@@ -821,8 +821,9 @@
%7D);%0A%0A%7D);
+%0A
|
c9f53411b6145cf41893c835c4893f7a02d0c980 | set the extractor's spec expectation straight w.r.t. the amount of spacing in the error message | test/extract/extractor.spec.js | test/extract/extractor.spec.js | "use strict";
const expect = require('chai').expect;
const extractor = require('../../src/extract/extractor');
const cjsFixtures = require('../extractor-fixtures/cjs.json');
const es6Fixtures = require('../extractor-fixtures/es6.json');
const amdFixtures = require('../extractor-fixtures/amd.json');
const tsFixtures = require('../extractor-fixtures/ts.json');
function runFixture(pFixture) {
it(pFixture.title, () => {
expect(
extractor(
pFixture.input.fileName,
{
baseDir: pFixture.input.baseDir,
moduleSystems: pFixture.input.moduleSystems
}
)
).to.deep.equal(
pFixture.expected
);
});
}
describe('CommonJS - ', () => cjsFixtures.forEach(runFixture));
describe('ES6 - ', () => es6Fixtures.forEach(runFixture));
describe('AMD - ', () => amdFixtures.forEach(runFixture));
describe('TypeScript - ', () => tsFixtures.forEach(runFixture));
describe('Error scenarios - ', () => {
it('Does not raise an exception on syntax errors (because we\'re on the loose parser)', () => {
expect(
() => extractor("test/extractor-fixtures/syntax-error.js")
).to.not.throw("Extracting dependencies ran afoul of... Unexpected token (1:3)");
});
it('Raises an exception on non-existing files', () => {
expect(
() => extractor("non-existing-file.js")
).to.throw(
"Extracting dependencies ran afoul of... ENOENT: no such file or directory, open 'non-existing-file.js'"
);
});
});
| JavaScript | 0 | @@ -1523,16 +1523,21 @@
ul of...
+%5Cn%5Cn
ENOENT:
@@ -1591,16 +1591,18 @@
file.js'
+%5Cn
%22%0A
|
25b2162f8283e3e500c70b521cf7f794f44e0774 | Disable FOREIGN_KEY_CHECKS before sync | test/helpers/fixtures/index.js | test/helpers/fixtures/index.js | var fixtures = require('node-require-directory')(__dirname);
exports.load = function(specificFixtures) {
return exports.unload().then(function() {
if (typeof specificFixtures === 'string') {
specificFixtures = [specificFixtures];
}
var promises = [];
Object.keys(fixtures).filter(function(key) {
if (key === 'index') {
return false;
}
if (specificFixtures && specificFixtures.indexOf(key) === -1) {
return false;
}
return true;
}).forEach(function(key) {
var promise = fixtures[key].load().then(function(instances) {
exports[key] = instances;
}).catch(function(e) {
console.error('Load fixtures', e);
});
promises.push(promise);
});
return Promise.all(promises);
});
};
exports.unload = function() {
return sequelize.sync({ force: true });
};
| JavaScript | 0.000001 | @@ -629,80 +629,8 @@
es;%0A
- %7D).catch(function(e) %7B%0A console.error('Load fixtures', e);%0A
@@ -715,81 +715,300 @@
%7D)
-;%0A%7D;%0A%0Aexports.unload = function() %7B%0A return sequelize.sync(%7B force: true
+.catch(function(err) %7B%0A console.error(err.stack);%0A %7D);%0A%7D;%0A%0Aexports.unload = function() %7B%0A return sequelize.query('SET FOREIGN_KEY_CHECKS = 0').then(function() %7B%0A return sequelize.sync(%7B force: true %7D);%0A %7D).then(function() %7B%0A return sequelize.query('SET FOREIGN_KEY_CHECKS = 1');%0A
%7D);
|
1526cf8f4f7885f1baa8e7d2a95a69692bd2f896 | set fixed distance from axis to bars | mptracker/static/votesimilaritychart.js | mptracker/static/votesimilaritychart.js | (function() {
"use strict";
app.render_votesimilaritychart = function(options) {
var margin = {top: 20, right: 20, bottom: 30, left: 60},
width = options.container.width() - margin.left - margin.right,
height = 300 - margin.top - margin.bottom;
var data = options.vote_similarity_list;
var x = d3.scale.ordinal()
.rangeRoundBands([0, width], .1);
var y = d3.scale.linear()
.range([height, 0]);
var yAxis = d3.svg.axis()
.scale(y)
.orient("left")
.ticks(10, "%");
var svg = d3.select(options.container[0]).append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
x.domain(d3.range(data.length));
y.domain([0, 1]);
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Similaritate");
svg.selectAll(".bar")
.data(data)
.enter().append("rect")
.attr("class", "bar")
.attr("x", function(d, n) { return x(n); })
.attr("width", x.rangeBand())
.attr("y", function(d) { return y(d.similarity); })
.attr("height", function(d) { return height - y(d.similarity); })
.attr("fill", function(d) { return app.PARTY_COLOR[d.party_short_name]; })
.on("click", clicked)
.append("svg:title")
.text(function(d) { return d.name; });
function clicked(d) {
window.location.href = '/persoane/' + d.person_slug;
}
};
})();
| JavaScript | 0 | @@ -135,16 +135,40 @@
t: 60%7D,%0A
+ axis_padding = 5,%0A
wi
@@ -926,188 +926,81 @@
.
-call(yAxis)%0A .append(%22text%22)%0A .attr(%22transform%22, %22rotate(-90)%22)%0A .attr(%22y%22, 6)%0A .attr(%22dy%22, %22.71em%22)%0A .style(%22text-anchor%22, %22end%22)%0A .text(%22Similaritate%22
+attr(%22transform%22, %22translate(%22 + -axis_padding + %22,0)%22)%0A .call(yAxis
);%0A%0A
@@ -1093,24 +1093,24 @@
ss%22, %22bar%22)%0A
-
.attr(
@@ -1142,16 +1142,23 @@
urn x(n)
+ - x(0)
; %7D)%0A
|
589960f23524f2466ecce2e973bb3a25014beb7a | make sure chart is shown, even on narrow pages | mptracker/static/votesimilaritychart.js | mptracker/static/votesimilaritychart.js | (function() {
"use strict";
app.render_votesimilaritychart = function(options) {
var margin = {top: 20, right: 20, bottom: 30, left: 60},
axis_padding = 5,
width = options.container.width() - margin.left - margin.right,
height = 300 - margin.top - margin.bottom;
var data = options.vote_similarity_list;
var x = d3.scale.ordinal()
.rangeRoundBands([0, width], .1);
var y = d3.scale.linear()
.range([height, 0]);
var yAxis = d3.svg.axis()
.scale(y)
.orient("left")
.ticks(10, "%");
var svg = d3.select(options.container[0]).append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
x.domain(d3.range(data.length));
y.domain([0, 1]);
svg.append("g")
.attr("class", "y axis")
.attr("transform", "translate(" + -axis_padding + ",0)")
.call(yAxis);
svg.selectAll(".bar")
.data(data)
.enter().append("rect")
.attr("class", "bar")
.attr("x", function(d, n) { return x(n) - x(0); })
.attr("width", x.rangeBand())
.attr("y", function(d) { return y(d.similarity); })
.attr("height", function(d) { return height - y(d.similarity); })
.attr("fill", function(d) { return app.PARTY_COLOR[d.party_short_name]; })
.on("click", clicked)
.append("svg:title")
.text(function(d) { return d.name; });
function clicked(d) {
window.location.href = '/persoane/' + d.person_slug;
}
};
})();
| JavaScript | 0 | @@ -323,16 +323,61 @@
_list;%0A%0A
+ width = d3.max(%5Bwidth, data.length + 1%5D);%0A%0A
var x
|
638689e0ad177e722249cc07758490d789db4451 | Add parsing unit tests | test/lib/parsers/javascript.js | test/lib/parsers/javascript.js | 'use strict';
var test = require('tap').test,
parse = require('../../../lib/parsers/javascript');
function toComment(fn, filename) {
return parse({
file: filename || 'test.js',
source: fn instanceof Function ? '(' + fn.toString() + ')' : fn
});
}
test('parse - unknown tag', function (t) {
t.equal(toComment(function () {
/** @unknown */
})[0].tags[0].title, 'unknown');
t.end();
});
test('parse - error', function (t) {
t.deepEqual(toComment(function () {
/** @param {foo */
})[0].errors, [
{ message: 'Braces are not balanced' },
{ message: 'Missing or invalid tag name' }]);
t.end();
});
| JavaScript | 0.000001 | @@ -113,16 +113,17 @@
oComment
+s
(fn, fil
@@ -197,71 +197,496 @@
ce:
-fn instanceof Function ? '(' + fn.toString() + ')' : fn%0A %7D
+'(' + fn.toString() + ')'%0A %7D);%0A%7D%0A%0Atest('parse - leading comment', function (t) %7B%0A t.deepEqual(toComments(function () %7B%0A /** one */%0A /** two */%0A function two() %7B%7D%0A %7D).map(function (c) %7B%0A return c.description;%0A %7D), %5B'one', 'two'%5D);%0A t.end();%0A%7D);%0A%0Atest('parse - trailing comment', function (t) %7B%0A t.deepEqual(toComments(function () %7B%0A /** one */%0A function one() %7B%7D%0A /** two */%0A %7D).map(function (c) %7B%0A return c.description;%0A %7D), %5B'one', 'two'%5D);%0A t.end(
);%0A%7D
+);
%0A%0Ate
@@ -737,32 +737,33 @@
.equal(toComment
+s
(function () %7B%0A
@@ -892,16 +892,17 @@
oComment
+s
(functio
|
80269989131cf02b7a512d5fa58582f4ebf20123 | Update showHidePassword.js | script/showHidePassword.js | script/showHidePassword.js | // show/hide password in forms
const nodeList = document.getElementsByTagName("input");
let isShown = false;
[...nodeList].forEach(node => {
if(!isShown && node.getAttribute("type") === "password"){
node.setAttribute('type', 'text');
isShown = true
} else {
node.setAttribute('type', 'password');
}
})
| JavaScript | 0 | @@ -1,8 +1,33 @@
+/*jshint esversion: 6 */%0A
// show/
|
e0cb20aed9ddde8510c5042c20e89c189c1f2a72 | Fix other regexp in createTempFile() test | test/ringo/utils/files_test.js | test/ringo/utils/files_test.js | var assert = require("assert");
var files = require('ringo/utils/files');
var fs = require('fs');
const PARENT = '/home/ringo/';
const CHILD = 'Projects';
const RELATIVE_CHILD = './' + CHILD;
const FOO = 'foo';
exports.testResolveUri = function () {
// Should work the same for both normal and relative child notations.
assert.strictEqual(PARENT + CHILD, files.resolveUri(PARENT, CHILD));
assert.strictEqual(PARENT + CHILD, files.resolveUri(PARENT, RELATIVE_CHILD));
assert.strictEqual(PARENT + FOO, files.resolveUri(PARENT, CHILD, FOO));
assert.strictEqual(PARENT + FOO, files.resolveUri(PARENT, RELATIVE_CHILD, FOO));
// but ignore parent if child starts with "/"
assert.strictEqual(PARENT, files.resolveUri(PARENT, PARENT));
};
exports.testResolveId = function () {
// Parent is ignored unless child starts with "./" or "../"
assert.strictEqual(CHILD, files.resolveId(PARENT, CHILD));
assert.strictEqual(PARENT + CHILD, files.resolveId(PARENT, RELATIVE_CHILD));
assert.strictEqual(PARENT, files.resolveId(PARENT, PARENT));
};
exports.testCreateTempFile = function () {
var tempFile = files.createTempFile('ringo');
assert.isNotNull(tempFile); // Creation w/ prefix only.
assert.isTrue(/[\/\\]ringo\w*\.tmp$/.test(tempFile));
fs.remove(tempFile);
tempFile = files.createTempFile('ringo', '.js');
assert.isNotNull(tempFile); // Creation incl. suffix.
assert.isTrue(/^.*\/ringo.*\.js$/.test(tempFile));
fs.remove(tempFile);
assert.throws(function () files.createTempFile('ri'), java.lang.
IllegalArgumentException); // Prefix must be at least 3 chars long.
};
| JavaScript | 0.000009 | @@ -1440,19 +1440,21 @@
ue(/
-%5E.*%5C/
+%5B%5C/%5C%5C%5D
ringo
-.
+%5Cw
*%5C.j
|
d046f11c20397c7683518bf36b1ce98d5e176a63 | Make checkbox labels clickable again | src/filterForm.js | src/filterForm.js | import React, {Component, PropTypes} from 'react';
class FilterForm extends Component {
constructor(props) {
super(props);
this.values = {
certificate: [
'DGNP-Gold',
'Green Globe',
'GCB Green Member',
'FSC-Papier',
],
foodImpact: [
'Gering',
'Mittel',
'Hoch'
],
rating: [
'Gering',
'Mittel',
'Hoch'
],
};
this.handleCheckboxClick = this.handleCheckboxClick.bind(this);
}
handleCheckboxClick(e) {
this.props.handleCheckboxClick(
this.props.name,
e.target.getAttribute('value')
);
}
render() {
const name = this.props.name;
const values = this.values[name];
return (
<div className="form">
{
values.map((value, i) => {
return (
<div key={i}>
<input
onClick={this.handleCheckboxClick}
type="checkbox"
value={value}
name={name}
id={`${name}_${i}`}
/>
<label htmlFor={`checkbox${i}`}>{value}</label>
</div>
);
})
}
</div>
);
}
}
export default FilterForm;
| JavaScript | 0.000004 | @@ -813,16 +813,63 @@
i) =%3E %7B%0A
+ const checkboxId = %60$%7Bname%7D_$%7Bi%7D%60;%0A
@@ -1103,30 +1103,26 @@
id=%7B
-%60$%7Bname%7D_$%7Bi%7D%60
+checkboxId
%7D%0A
@@ -1170,17 +1170,16 @@
or=%7B
-%60
checkbox
$%7Bi%7D
@@ -1174,21 +1174,18 @@
checkbox
-$%7Bi%7D%60
+Id
%7D%3E%7Bvalue
|
0fab2689f7308fab09b9bf0e1f7ea570da6b6ce8 | Disable suspected test to confirm if it pass without it | test/test-canonical-fs-uris.js | test/test-canonical-fs-uris.js | 'use strict'
const tabs = require('sdk/tabs')
const { prefs } = require('sdk/simple-prefs')
const fs = require('../lib/protocols.js').fs.createInstance()
const gw = require('../lib/gateways.js')
const self = require('sdk/self')
const testpage = self.data.url('linkify-demo.html')
const mdownPath = 'ipfs/QmSrCRJmzE4zE1nAfWPbzVfanKQNBhp7ZWmMnEdbiLvYNh/mdown#sample.md'
const sripage = 'fs:/' + mdownPath
const parent = require('sdk/remote/parent')
parent.remoteRequire('../lib/child-main.js', module)
const {Cc, Ci} = require('chrome')
const ioservice = Cc['@mozilla.org/network/io-service;1'].getService(Ci.nsIIOService)
ioservice.newURI('fs:/ipns/foo', null, null)
exports['test mdownPath load via http handler'] = function (assert, done) {
tabs.open({
url: gw.publicUri.spec + mdownPath,
onReady: (tab) => {
tab.close(done)
}
})
}
exports['test newURI'] = function (assert) {
prefs.fsUris = true
assert.equal(fs.newURI('fs:/ipns/foo', null, null).spec, 'fs:/ipns/foo', 'keeps fs:/ uris as-is')
}
exports['test newChannel'] = function (assert) {
prefs.fsUris = true
gw.redirectEnabled = false
let uri = fs.newURI('fs:///ipns/foo', null, null)
let chan = fs.newChannel(uri)
assert.equal(chan.originalURI.spec, 'fs:/ipns/foo', "keeps fs: URI as channel's originalURI")
// double and triple slashes lead to gateway redirects, which cause CORS troubles -> check normalization
assert.equal(chan.URI.spec, gw.publicUri.spec + 'ipns/foo', 'redirect off, channel has normalized http urls')
gw.redirectEnabled = true
chan = fs.newChannel(uri)
assert.equal(chan.URI.spec, gw.customUri.spec + 'ipns/foo', 'redirect on, channel has normalized http urls')
}
// https://github.com/lidel/ipfs-firefox-addon/issues/3
exports['test subresource loading'] = function (assert, done) {
prefs.fsUris = true
gw.redirectEnabled = false
tabs.open({
url: testpage,
onReady: (tab) => {
// first load somehow doesn't have protocol handlers registered. so load resource:// first, then redirect to fs:/ page
if (tab.url !== sripage) {
tab.url = sripage
return
}
let worker = tab.attach({
contentScript: `
let obs = new MutationObserver(function(mutations) {
let result = (document.querySelector("#ipfs-markdown-reader") instanceof HTMLHeadingElement)
self.port.emit("test result", {result: result})
})
obs.observe(document.body,{childList: true})
`
})
worker.port.on('test result', (msg) => {
assert.equal(msg.result, true, 'subresource loaded successfully')
tab.close(done)
})
}
})
}
require('./prefs-util.js').isolateTestCases(exports)
require('sdk/test').run(exports)
| JavaScript | 0 | @@ -7,16 +7,19 @@
trict'%0A%0A
+//
const ta
@@ -39,24 +39,24 @@
'sdk/tabs')%0A
-
const %7B pref
@@ -189,24 +189,27 @@
teways.js')%0A
+//
const self =
@@ -229,16 +229,19 @@
/self')%0A
+//
const te
@@ -284,16 +284,19 @@
.html')%0A
+//
const md
@@ -375,16 +375,19 @@
ple.md'%0A
+//
const sr
@@ -684,198 +684,8 @@
l)%0A%0A
-exports%5B'test mdownPath load via http handler'%5D = function (assert, done) %7B%0A tabs.open(%7B%0A url: gw.publicUri.spec + mdownPath,%0A onReady: (tab) =%3E %7B%0A tab.close(done)%0A %7D%0A %7D)%0A%7D%0A%0A
expo
@@ -1582,16 +1582,19 @@
ssues/3%0A
+/*%0A
exports%5B
@@ -2493,17 +2493,20 @@
%7D%0A %7D)%0A
-
%7D
+%0A*/
%0A%0Arequir
|
35a67c4637533df09191e234aede2f19d059d83d | update gh | scripts/github-commands.js | scripts/github-commands.js | module.exports = function(robot) {
'use strict';
var slackMsgs = require('./slackMsgs.js');
/* set Github Account */
var GitHubApi = require("github");
//var Trello = require(https://api.trello.com/1/client.js?key=51def9cb08cf171cd0970d8607ad8f97);
var github = new GitHubApi({
/* optional */
// debug: true,
// protocol: "https",
// host: "api.github.com", // should be api.github.com for GitHub
// //thPrefix: "/api/v3", // for some GHEs; none for GitHub
// headers: {
// "user-agent": "My-Cool-GitHub-App" // GitHub is happy with a unique user agent
// },
// Promise: require('bluebird'),
// followRedirects: false, // default: true; there's currently an issue with non-get redirects, so allow ability to disable follow-redirects
// timeout: 5000
});
/* oauth autentication using github personal token */
github.authenticate({
"type": "oauth",
"token": process.env.HUBOT_GITHUB_TOKEN
})
/* basic autentication using github's username & password */
// github.authenticate({
// type: "basic",
// username: '',
// password: ''
// });
robot.on('github-webhook-event', function(data){
// console.log(data);
var room, adapter, payload;
room = "random";
adapter = robot.adapterName;
payload = data.body;
console.log(payload.target_url);
switch(data.eventType){
case 'push':
if (adapter == 'slack'){
let msg = slackMsgs.githubEvent();
msg.attachments[0].pretext = `<www.google.com|[andreasBot:master]> 1 new commit by andreash92:`;
msg.attachments[0].title = '';
msg.attachments[0].text = '';
robot.messageRoom(room, msg);
} else {
robot.messageRoom(room, "push event");
}
break;
case 'deployment':
robot.messageRoom(room, "deployment event");
break;
case 'deployment_status':
if (adapter == 'slack'){
let msg = slackMsgs.githubEvent();
msg.attachments[0].title = `Deployment ${payload.deployment_status}`;
msg.attachments[0].pretext = '';
msg.attachments[0].text = `<${payload.target_url}|[andreasBot:master]> 1 new commit by andreash92:`;
robot.messageRoom(room, msg);
} else {
robot.messageRoom(room, "deployment_status event");
}
break;
default:
robot.messageRoom(room, `event: ${data.eventType}`);
break;
}
})
robot.respond(/gh hook/i, function(res_r) {
github.repos.createHook({
"owner":"andreash92",
"repo":"andreasBot",
"name":"andreasBot-hook",
"config": {
"url": "https://andreasbot.herokuapp.com/hubot/github-hooks",
"content_type": "json"
}},
function(err, res){
if (err){
robot.logger.error(err);
return 0;
}
robot.logger.info(res);
});
})
robot.respond(/gh followers (.*)/i, function(res_r) {
var username = res_r.match[1];
github.users.getFollowersForUser({
"username": username},
function(err, res){
if (err){
res_r.send('Error: ' + JSON.parse(err).message);
return false;
}
var jsonsize = Object.keys(res.data).length;
let menu = slackMsgs.menu();
let login;
for (var i = 0; i < jsonsize; i++) {
login = res.data[i].login;
menu.attachments[0].actions[0]['options'].push({"text":login,"value":login});
//TODO: maybe sort them before display
}
menu.attachments[0].text = "Followers of "+ "*" + username + "*";
menu.attachments[0].fallback = '';
menu.attachments[0].callback_id = 'followers_cb_id';
menu.attachments[0].actions[0].name=' ';
menu.attachments[0].actions[0].text=' ';
res_r.reply(menu);
});
})
}
| JavaScript | 0.000001 | @@ -1773,24 +1773,362 @@
ployment': %0A
+%09%09%09%09if (adapter == 'slack')%7B%0A%09%09%09%09%09let msg = slackMsgs.githubEvent();%0A%09%09%09%09%09msg.attachments%5B0%5D.title = %60Deployment $%7Bpayload.deployment_status%7D%60;%0A%09%09%09%09%09msg.attachments%5B0%5D.pretext = '';%0A%09%09%09%09%09msg.attachments%5B0%5D.text = %60%3C$%7Bpayload.target_url%7D%7C%5BandreasBot:master%5D%3E 1 new commit by andreash92:%60;%0A%09%09%09%09%09robot.messageRoom(room, msg);%09%0A%09%09%09%09%7D else %7B%0A%09
%09%09%09%09robot.me
@@ -2161,24 +2161,29 @@
t event%22);%09%0A
+%09%09%09%09%7D
%09%09%09%09break;%0A%09
|
f13a009b679930d8b0bf9c24be105eed4e13f870 | No await, no async | src/test.js | src/test.js | import fs from 'fs';
import { all, promisify, reject, resolve } from 'bluebird';
import {
either,
evolve,
filter,
inc,
startsWith,
tryCatch
} from 'ramda';
import { compileES6 } from './compiler';
import { getLocaleStrings } from './i18n';
import { emitError, emitInfo, emitSuccess } from './input';
import { inspect } from './module';
import { compileSources } from './run';
import { createVM, runAndGetAlerts } from './vm';
const readFile = promisify(fs.readFile);
/**
* Compiles the app files and returns an instance of a V8 object.
*
* @return {Promise<Object => Promise>}
*/
async function compileApp() {
const { name } = await readFile('package.json', 'utf-8')
| JSON.parse;
const [source, modules] = await compileSources();
const strings = await getLocaleStrings();
return context =>
runAndGetAlerts({ name, source }, context, strings, modules);
}
/**
* Compiles the test source.
*
* @return {Promise}
*/
async function compileTest() {
const source = await (readFile('test/index.js', 'utf-8')
.catchThrow(new Error('no tests provided')))
| compileES6;
const localTestModules = inspect(source).modules
| filter(either(startsWith('./'), startsWith('../')));
if (localTestModules.length > 0) {
return reject(new Error('only external modules can be required in testsuite. Found '
+ localTestModules.join(', ')));
}
return source;
}
/**
* Executes the tests and returns a promise with computed results.
* @param {Object => Promise} runWithContext - Pre-compiled application
* @param {(String, Function)[]} tests - The test cases
* @return {Promise}
*/
async function runTests(runWithContext, tests) {
if (tests.length === 0) {
return emitInfo('no tests to run');
}
const loop = async ([test, ...rest], report = { passing: 0, failing: 0 }) => {
if (!test) {
const message = `${report.passing} passing, ${report.failing} failing`;
if (report.failing > 0) {
return reject(new Error(message));
}
return emitSuccess(message);
}
const [description, implementation] = test;
return runWithContext
| tryCatch(implementation & resolve, reject)
| (future => future
.then(~emitSuccess(description)
.return(report | evolve({ passing: inc })))
.catch(err =>
emitError(`${description}:\n${err.stack}\n`)
.return(report | evolve({ failing: inc })))
.then(loop(rest, _)));
};
await emitInfo(`${tests.length} test case(s) found`);
return loop(tests);
}
/**
* If possible, run the tests. Compile the tests to ES5 and the app sources to
* V8 objects, then run the tests in the VM linking the compiled object to it.
*
* @return {Promise}
*/
export default async () => {
const [source, runWithContext] = await all([compileTest(), compileApp()]);
const tests = [];
const vm = createVM();
const test = (...args) => tests.push(args);
vm.freeze(test, 'test');
vm.run(source, 'test/index.js');
return runTests(runWithContext, tests);
};
| JavaScript | 0.999079 | @@ -1832,22 +1832,16 @@
t loop =
- async
(%5Btest,
|
d2b8c1c6c0d45b967694533cf879a3ddb08e89b0 | Adding test file path as argument of the rtcBot run command's arguments. | tools/rtcbot/test.js | tools/rtcbot/test.js | // Copyright (c) 2014 The WebRTC project authors. All Rights Reserved.
//
// Use of this source code is governed by a BSD-style license
// that can be found in the LICENSE file in the root of the source
// tree. An additional intellectual property rights grant can be found
// in the file PATENTS. All contributing project authors may
// be found in the AUTHORS file in the root of the source tree.
//
// This script loads the test file in the virtual machine and runs it in a
// context that only exposes a test variable with methods for testing and to
// spawn bots.
//
// Note: an important part of this script is to keep nodejs-isms away from test
// code and isolate it from implementation details.
var fs = require('fs');
var vm = require('vm');
var BotManager = require('./botmanager.js');
function Test(botType) {
// TODO(houssainy) set the time out.
this.timeout_ = setTimeout(
this.fail.bind(this, "Test timeout!"),
10000);
this.botType_ = botType;
}
Test.prototype = {
log: function () {
console.log.apply(console.log, arguments);
},
abort: function (error) {
var error = new Error(error || "Test aborted");
console.log(error.stack);
process.exit(1);
},
assert: function (value, message) {
if (value !== true) {
this.abort(message || "Assert failed.");
}
},
fail: function () {
this.assert(false, "Test failed.");
},
done: function () {
clearTimeout(this.timeout_);
console.log("Test succeeded");
process.exit(0);
},
// Utility method to wait for multiple callbacks to be executed.
// functions - array of functions to call with a callback.
// doneCallback - called when all callbacks on the array have completed.
wait: function (functions, doneCallback) {
var result = new Array(functions.length);
var missingResult = functions.length;
for (var i = 0; i != functions.length; ++i)
functions[i](complete.bind(this, i));
function complete(index, value) {
missingResult--;
result[index] = value;
if (missingResult == 0)
doneCallback.apply(null, result);
}
},
spawnBot: function (name, doneCallback) {
// Lazy initialization of botmanager.
if (!this.botManager_)
this.botManager_ = new BotManager();
this.botManager_.spawnNewBot(name, this.botType_, doneCallback);
},
}
function runTest(testfile) {
console.log("Running test: " + testfile);
var script = vm.createScript(fs.readFileSync(testfile), testfile);
script.runInNewContext({ test: new Test(process.argv[2]) });
}
runTest("./test/webrtc_video_streaming.js");
| JavaScript | 0.999995 | @@ -2368,16 +2368,25 @@
runTest(
+botType,
testfile
@@ -2548,23 +2548,15 @@
est(
-process.argv%5B2%5D
+botType
) %7D)
@@ -2572,41 +2572,39 @@
est(
-%22./test/webrtc_video_streaming.js%22
+process.argv%5B2%5D, process.argv%5B3%5D
);%0A
|
21c4caf2f703f182cb79956edd2c23c762bf20c3 | Resolve paths with path.resolve | tools/server/boot.js | tools/server/boot.js | var Fiber = require("fibers");
var fs = require("fs");
var path = require("path");
var Future = require(path.join("fibers", "future"));
var _ = require('underscore');
var sourcemap_support = require('source-map-support');
// This code is duplicated in tools/main.js.
var MIN_NODE_VERSION = 'v0.10.28';
if (require('semver').lt(process.version, MIN_NODE_VERSION)) {
process.stderr.write(
'Meteor requires Node ' + MIN_NODE_VERSION + ' or later.\n');
process.exit(1);
}
// read our control files
var serverJsonPath = path.resolve(process.argv[2]);
var serverDir = path.dirname(serverJsonPath);
var serverJson = JSON.parse(fs.readFileSync(serverJsonPath, 'utf8'));
var configJson =
JSON.parse(fs.readFileSync(path.resolve(serverDir, 'config.json'), 'utf8'));
// Set up environment
__meteor_bootstrap__ = {
startup_hooks: [],
serverDir: serverDir,
configJson: configJson };
__meteor_runtime_config__ = { meteorRelease: configJson.meteorRelease };
// connect (and some other NPM modules) use $NODE_ENV to make some decisions;
// eg, if $NODE_ENV is not production, they send stack traces on error. connect
// considers 'development' to be the default mode, but that's less safe than
// assuming 'production' to be the default. If you really want development mode,
// set it in your wrapper script (eg, run-app.js).
if (!process.env.NODE_ENV)
process.env.NODE_ENV = 'production';
// Map from load path to its source map.
var parsedSourceMaps = {};
// Read all the source maps into memory once.
_.each(serverJson.load, function (fileInfo) {
if (fileInfo.sourceMap) {
var rawSourceMap = fs.readFileSync(
path.resolve(serverDir, fileInfo.sourceMap), 'utf8');
// Parse the source map only once, not each time it's needed. Also remove
// the anti-XSSI header if it's there.
var parsedSourceMap = JSON.parse(rawSourceMap.replace(/^\)\]\}'/, ''));
// source-map-support doesn't ever look at the sourcesContent field, so
// there's no point in keeping it in memory.
delete parsedSourceMap.sourcesContent;
var url;
if (fileInfo.sourceMapRoot) {
// Add the specified root to any root that may be in the file.
parsedSourceMap.sourceRoot = path.join(
fileInfo.sourceMapRoot, parsedSourceMap.sourceRoot || '');
}
parsedSourceMaps[fileInfo.path] = parsedSourceMap;
}
});
var retrieveSourceMap = function (pathForSourceMap) {
if (_.has(parsedSourceMaps, pathForSourceMap))
return { map: parsedSourceMaps[pathForSourceMap] };
return null;
};
sourcemap_support.install({
// Use the source maps specified in program.json instead of parsing source
// code for them.
retrieveSourceMap: retrieveSourceMap,
// For now, don't fix the source line in uncaught exceptions, because we
// haven't fixed handleUncaughtExceptions in source-map-support to properly
// locate the source files.
handleUncaughtExceptions: false
});
Fiber(function () {
_.each(serverJson.load, function (fileInfo) {
var code = fs.readFileSync(path.resolve(serverDir, fileInfo.path));
var Npm = {
require: function (name) {
if (! fileInfo.node_modules) {
return require(name);
}
var nodeModuleDir =
path.resolve(serverDir, fileInfo.node_modules, name);
if (fs.existsSync(nodeModuleDir)) {
return require(nodeModuleDir);
}
try {
return require(name);
} catch (e) {
// Try to guess the package name so we can print a nice
// error message
var filePathParts = fileInfo.path.split(path.sep);
var packageName = filePathParts[1].replace(/\.js$/, '');
// XXX better message
throw new Error(
"Can't find npm module '" + name +
"'. Did you forget to call 'Npm.depends' in package.js " +
"within the '" + packageName + "' package?");
}
}
};
var getAsset = function (assetPath, encoding, callback) {
var fut;
if (! callback) {
fut = new Future();
callback = fut.resolver();
}
// This assumes that we've already loaded the meteor package, so meteor
// itself (and weird special cases like js-analyze) can't call
// Assets.get*. (We could change this function so that it doesn't call
// bindEnvironment if you don't pass a callback if we need to.)
var _callback = Package.meteor.Meteor.bindEnvironment(function (err, result) {
if (result && ! encoding)
// Sadly, this copies in Node 0.10.
result = new Uint8Array(result);
callback(err, result);
}, function (e) {
console.log("Exception in callback of getAsset", e.stack);
});
if (!fileInfo.assets || !_.has(fileInfo.assets, assetPath)) {
_callback(new Error("Unknown asset: " + assetPath));
} else {
var filePath = path.join(serverDir, fileInfo.assets[assetPath]);
fs.readFile(filePath, encoding, _callback);
}
if (fut)
return fut.wait();
};
var Assets = {
getText: function (assetPath, callback) {
return getAsset(assetPath, "utf8", callback);
},
getBinary: function (assetPath, callback) {
return getAsset(assetPath, undefined, callback);
}
};
// \n is necessary in case final line is a //-comment
var wrapped = "(function(Npm, Assets){" + code + "\n})";
// It is safer to use the absolute path as different tooling, such as
// node-inspector, can get confused on relative urls.
var absoluteFilePath = __dirname + "/" + fileInfo.path;
var func = require('vm').runInThisContext(wrapped, absoluteFilePath, true);
func.call(global, Npm, Assets); // Coffeescript
});
// run the user startup hooks.
_.each(__meteor_bootstrap__.startup_hooks, function (x) { x(); });
// find and run main()
// XXX hack. we should know the package that contains main.
var mains = [];
var globalMain;
if ('main' in global) {
mains.push(main);
globalMain = main;
}
_.each(Package, function (p, n) {
if ('main' in p && p.main !== globalMain) {
mains.push(p.main);
}
});
if (! mains.length) {
process.stderr.write("Program has no main() function.\n");
process.exit(1);
}
if (mains.length > 1) {
process.stderr.write("Program has more than one main() function?\n");
process.exit(1);
}
var exitCode = mains[0].call({}, process.argv.slice(3));
// XXX hack, needs a better way to keep alive
if (exitCode !== 'DAEMON')
process.exit(exitCode);
}).run();
| JavaScript | 0.000021 | @@ -5595,16 +5595,29 @@
ePath =
+path.resolve(
__dirnam
@@ -5621,16 +5621,9 @@
name
- + %22/%22 +
+,
fil
@@ -5632,16 +5632,17 @@
nfo.path
+)
;%0A va
|
55a6a8293050a481d419f5875df6d6381e16a178 | test run async | src/test.js | src/test.js | import defRules from './rules'
import * as util from './util'
const allDevices = Object.keys(util.devices).map(key => util.devices[key])
const severity = function (val) {
switch (val) {
case 0:
case 'off':
return 'off'
case 1:
case 'warn':
return 'warn'
case 2:
case 'error':
return 'error'
default:
throw new Error(`react-a11y: invalid severity ${val}`)
}
}
const normalize = function (opts = 'off') {
if ( Array.isArray(opts) ) {
opts[0] = severity(opts[0])
return opts
} else {
return [ severity(opts) ]
}
}
export default class Suite {
constructor (React, ReactDOM, options) {
this.options = options
this.React = React
this.ReactDOM = ReactDOM
if (!this.React && !this.React.createElement) {
throw new Error('Missing parameter: React')
}
const {
plugins = []
} = this.options
// prepare all rules by including every plugin and saving their rules
// namespaced like plugin/rule
this.rules = plugins
.map(function (name) {
try {
const mod = require(`react-a11y-plugin-${name}`)
const rules = 'default' in mod ? mod.default.rules : mod.rules
return Object.keys(rules).reduce((acc, key) => ({
...acc
, [`${name}/${key}`]: rules[key]
}), {})
} catch (err) {
throw new Error(`Could not find react-a11y-plugin-${name}`)
}
})
.reduce((acc, next) => ({ ...acc, ...next }), defRules)
}
test (tagName, props, children, done) {
Object.keys(this.options.rules)
.forEach(function (key) {
const rule = this.rules[key]
// ensure that the rule exists
if ( !rule ) {
throw new Error(`react-a11y: rule ${key} not found, `
+ 'maybe you\'re missing a plugin?')
}
// get options for rule
const [
sev
, ...options
] = normalize(this.options.rules[key])
if ( sev !== 'off' ) {
const ctx = {
options
, React: this.React
, ReactDOM: this.ReactDOM
}
rule.reduce(function (prev, defn) {
// only fail once per rule
// so check if previous test failed
// already, if this is true, they havn't-
if ( !prev ) {
return prev
}
const {
tagName: tagNames
, msg
, url
, test
, affects = allDevices
} = defn
// filter by tagName
if ( Array.isArray(tagNames) ) {
if ( tagNames.indexOf(tagName) < 0 ) {
return prev
}
} else if ( tagNames ) {
if ( tagName !== tagNames ) {
return prev
}
}
// perform the test
const pass = test(tagName, props, children, ctx)
if ( !pass ) {
done({
tagName
, msg
, props
, children
, severity: sev
, rule: key
, affects
})
}
return prev && pass
}, true)
}
}.bind(this))
}
}
| JavaScript | 0.000002 | @@ -2200,16 +2200,22 @@
.reduce(
+async
function
@@ -2216,16 +2216,17 @@
nction (
+p
prev, de
@@ -2372,16 +2372,52 @@
havn't-%0A
+ const prev = await prev%0A
@@ -3011,16 +3011,22 @@
t pass =
+ await
test(ta
|
5836293913a76dc0a1a4f5c18fa84e6b7bed16ae | Fix code bug in test | test/unit/testExecutionPlan.js | test/unit/testExecutionPlan.js | 'use strict';
var jf = require('../../'),
expect = require('chai').expect;
const testFilePath = './' + Math.random() + '.json';
var testValue1 = { msg: "test value 1" };
var testValue2 = { msg: "test value 2" };
describe('Chained operation ', function () {
it('can be branched.', function (done) {
let init =
jf.filed( testFilePath )
.io( function( obj, filePath){} )
.pass( function(){
let rootPart =
jf.filed( testFilePath )
.copy( function(){ return './' + Math.random() + '.json'; }, function( err ){ console.log(err) } )
.filter( ( obj, filePath ) => { filePath != testFilePath } );
rootPart
.io( function( obj, filePath ) { return testValue1; } )
.pass( function( obj, filePath ){
expect( obj ).to.eql( testValue1 );
} ).exec();
rootPart
.io( function( obj, filePath ) { return testValue2; } )
.pass( function( obj, filePath ){
expect( obj ).to.eql( testValue2 );
} ).exec();
})
.exec();
setTimeout(
function() {
done();
},
100
);
});
});
| JavaScript | 0.00001 | @@ -623,18 +623,16 @@
ath ) =%3E
- %7B
filePat
@@ -648,18 +648,16 @@
FilePath
- %7D
);%0A%0A
|
6fe1d2e648eea075c5c55d92735925db9b929ad2 | Add a method to post to GH commit status | src/github-api.js | src/github-api.js | import './babel-maybefill';
import url from 'url';
import _ from 'lodash';
import request from 'request-promise';
import parseLinkHeader from 'parse-link-header';
import pkg from '../package.json';
import {asyncMap} from './promise-array';
import createLRU from 'lru-cache';
const d = require('debug')('serf:github-api');
export function getNwoFromRepoUrl(repoUrl) {
let u = url.parse(repoUrl);
return u.path.slice(1);
}
export async function gitHub(uri, token=null) {
let tok = token || process.env.GITHUB_TOKEN;
d(`Fetching GitHub URL: ${uri}`);
let ret = request({
uri: uri,
headers: {
'User-Agent': `${pkg.name}/${pkg.version}`,
'Accept': 'application/vnd.github.v3+json',
'Authorization': `token ${tok}`
},
json: true
});
let result = await ret;
return { result, headers: ret.response.headers };
}
const githubCache = createLRU({
max: 1000
});
export async function cachedGitHub(uri, token=null, maxAge=null) {
let ret = githubCache.get(uri);
if (ret) return ret;
ret = await gitHub(uri, token);
githubCache.set(uri, ret, maxAge);
return ret;
}
export function filterBoringRefs(refs) {
return _.filter(refs, (ref) => {
if (ref.name.match(/__gh/)) return false;
if (ref.name.match(/\/merge$/i)) return false;
return true;
});
}
export async function githubPaginate(uri, token=null, maxAge=null) {
let next = uri;
let ret = [];
do {
let {headers, result} = await cachedGitHub(next, token, maxAge);
ret = ret.concat(result);
if (!headers['link']) break;
let links = parseLinkHeader(headers['link']);
next = 'next' in links ? links.next.url : null;
} while (next);
return ret;
}
export function fetchAllRefs(nwo) {
return githubPaginate(`https://api.github.com/repos/${nwo}/git/refs?per_page=100`, null, 60*1000);
}
export async function fetchAllRefsWithInfo(nwo) {
let refs = filterBoringRefs(await fetchAllRefs(nwo));
let commitInfo = await asyncMap(
_.map(refs, (ref) => ref.object.url),
async (x) => {
return (await cachedGitHub(x)).result;
});
_.each(refs, (ref) => {
ref.object.commit = commitInfo[ref.object.url];
});
return refs;
}
| JavaScript | 0 | @@ -462,28 +462,39 @@
, token=null
+, body=null
) %7B%0A
-
let tok =
@@ -575,22 +575,15 @@
let
-ret = request(
+opts =
%7B%0A
@@ -769,19 +769,113 @@
n: true%0A
-
%7D
+;%0A%0A if (body) %7B%0A opts.body = body;%0A opts.method = 'post';%0A %7D%0A%0A let ret = request(opts
);%0A%0A le
@@ -2291,12 +2291,256 @@
urn refs;%0A%7D%0A
+%0Aexport function postCommitStatus(nwo, sha, state, description, target_url, context, token=null) %7B%0A let body = %7B state, target_url, description, context %7D;%0A return gitHub(%60https://api.github.com/repos/$%7Bnwo%7D/statuses/$%7Bsha%7D%60, token, body);%0A%7D%0A
|
237df1fb0602c5616b195a23366a965a88cf2d2e | Fix code fragments printing. | src/util.js | src/util.js | import fs from 'fs';
import path from 'path';
import mkdirp from 'mkdirp';
import yaml from 'js-yaml';
import chalk from 'chalk';
import striptags from 'striptags';
import escapeHtml from 'escape-html';
import IntlMessageFormat from 'intl-messageformat';
import { DateTimeFormat } from 'intl';
import createFormatCache from 'intl-format-cache';
import _ from 'lodash';
/* eslint-disable no-console */
const ERROR_COLOR = '#c00';
/**
* Remove extension from file name.
*
* @param {string} filename
* @return {string}
*/
export function removeExtension(filename) {
return filename.replace(/\.\w+$/, '');
}
/**
* Returns extension of a file (without the leading dot).
*
* @param {string} filename
* @return {string}
*/
export function getExtension(filename) {
return path.extname(filename).substring(1);
}
/**
* Read text file.
*
* @param {string} filepath
* @return {string}
*/
export function readFile(filepath) {
return fs.readFileSync(filepath, { encoding: 'utf8' });
}
/**
* Save text to a file (create all folders if necessary).
*
* @param {string} filepath
* @param {string} content
* @return {string}
*/
export function writeFile(filepath, content) {
mkdirp.sync(path.dirname(filepath));
return fs.writeFileSync(filepath, content, { encoding: 'utf8' });
}
/**
* Read YAML file.
*
* @param {string} filepath
* @return {string}
*/
export function readYamlFile(filepath) {
try {
return yaml.safeLoad(readFile(filepath));
}
catch (e) {
console.log(`Cannot read YAML file ${filepath}:`, e);
}
}
/**
* Prepare fields list in short format to _.orderBy()
* @param {Array} shortFields ['foo', '-bar']
* @return {Array}
*/
export function formatFieldsForSortByOrder(shortFields) {
return _.unzip(shortFields.map((field) => {
if (field[0] === '-') {
return [field.substr(1), 'desc'];
}
return [field, 'asc'];
}));
}
/**
* Returns HTML meta tag.
*
* @param {string} name Meta name.
* @param {string} content Meta value.
* @return {string}
*/
export function meta(name, content) {
content = cleanHtml(content);
return `<meta name="${name}" content="${content}">`;
}
/**
* Returns HTML meta tag for Open Graph.
*
* @param {string} name Meta name.
* @param {string} content Meta value.
* @return {string}
*/
export function og(name, content) {
content = cleanHtml(content);
return `<meta property="${name}" content="${content}">`;
}
/**
* Return the content of the first paragraph in a given HTML.
*
* @param {string} text
* @return {string}
*/
export function getFirstParagraph(text) {
let m = text.match(/<p[^>]*>(.*?)<\/p>/i);
return m && m[1];
}
/**
* Return the URL of the first image in a given HTML.
*
* @param {string} text
* @return {string}
*/
export function getFirstImage(text) {
let m = text.match(/<img\s+src=["']([^"']+)["']/i);
return m && m[1];
}
/**
* Remove HTML and escape special characters.
*
* @param {string} text
* @return {string}
*/
export function cleanHtml(text) {
return escapeHtml(striptags(text)).trim();
}
/**
* Print an error message to console.
*
* @param {string} message
*/
export function printError(message) {
console.error(chalk.red.bold(message));
}
/**
* Format a message to use in HTML.
*
* @param {string} message
* @return {string}
*/
export function formatErrorHtml(message) {
return _.escape(message).replace(/\n/g, '<br>');
}
/**
* Print an error message to a console and return formatted HTML document.
*
* @param {string} message
* @param {string} [file] Source file path.
* @param {number} [line] Line to highlight in a source file.
* @return {string}
*/
export function errorHtml(message, file, line) {
printError(message);
let code = '';
if (file && line) {
code = codeFragment(readFile(file), line);
}
return `
<title>Error</title>
<body style="background:${ERROR_COLOR}; color:#fff; font-family:Helvetica">
<h1>Fledermaus error</h1>
<p>${formatErrorHtml(message)}</p>
<pre>${code}</pre>
</body>
`;
}
/**
* Print an error message to a console and return formatted HTML string.
*
* @param {string} message
* @return {string}
*/
export function errorInlineHtml(message, { block } = {}) {
printError(message);
let html = `<b style="color:${ERROR_COLOR}; font-family:Helvetica">${formatErrorHtml(message)}</b>`;
if (block) {
html = `<p>${html}</p>`;
}
return html;
}
/**
* Print code fragment with line numbers.
*
* @param {string} code
* @param {number} line Line to highlight.
* @return {string}
*/
export function codeFragment(code, line) {
const contextLines = 2;
let lines = code.split('\n');
let begin = Math.max(line - contextLines, 1);
let end = Math.min(line + contextLines, lines.length);
lines = lines.slice(begin - 1, end);
lines = lines.map((str, index) => {
let currentLineNum = index + begin;
return [
currentLineNum === line ? '>' : ' ',
_.padStart(currentLineNum, 3),
'|',
str,
].join(' ');
});
return lines.join('\n');
}
/**
* Print message immidiately and show execution time on process exit.
*
* @param {string} message
*/
export function start(message) {
console.log(message);
let startTime = new Date().getTime();
process.on('exit', () => {
let time = new Date().getTime() - startTime;
let minutes = Math.floor(time / 1000 / 60) % 60;
let seconds = Math.floor(time / 1000) % 60;
console.log(
'Done in', (minutes ? `${minutes}m ` : '') + (seconds ? `${seconds}s` : '') +
(!minutes && !seconds ? 'a moment' : '')
);
});
}
/**
* Intl message formatter.
*
* @param {string} format Format string.
* @param {string} lang Language.
*/
export const getMessageFormat = createFormatCache(IntlMessageFormat);
/**
* Intl date/time formatter.
*
* @param {string} lang Language.
* @param {Object} format Format.
*/
export const getDateTimeFormat = createFormatCache(DateTimeFormat);
| JavaScript | 0.000005 | @@ -3759,21 +3759,29 @@
(file),
+Number(
line)
+)
;%0A%09%7D%0A%09re
@@ -3965,20 +3965,30 @@
%09%3Cpre%3E$%7B
+_.escape(
code
+)
%7D%3C/pre%3E%0A
|
68b2e7e38ca5624855d451fd3e18d68f0e21b32e | increase random assigned memory | src/util.js | src/util.js | import { OPERATORS } from '@/const';
export function getRandom(min, max) {
const minCeil = Math.ceil(min);
const maxFloor = Math.floor(max);
return Math.floor(Math.random() * ((maxFloor - minCeil) + 1)) + minCeil;
}
export function generateProcessValues() {
const operators = Object.values(OPERATORS);
return {
memory: getRandom(2, 10),
timeMax: getRandom(5, 8),
operation: {
operand1: getRandom(1, 50),
operator: operators[getRandom(0, operators.length - 1)],
operand2: getRandom(1, 50),
},
};
}
| JavaScript | 0.000001 | @@ -345,13 +345,13 @@
dom(
-2, 10
+6, 25
),%0A
|
c4c11a06806a9b198999111b8f0afc45030e831d | write weather to file | edison-cli.js | edison-cli.js | /**
* Edison CLI to provide time-saving Bash calls via NPM
*/
var util = require('util'),
exec = require('child_process').exec,
request = require("request"),
moment = require("moment"),
child = require('child_process'),
async = require('async');
var EdisonCLI = function () {};
EdisonCLI.prototype = {
/**
* Automatically starts blinking Edison's pin 13
*/
blink: function(interval, pin, next){
var Cylon = require('cylon');
Cylon.robot({
connections: {
edison: { adaptor: 'intel-iot' }
},
devices: {
led: { driver: 'led', pin: pin }
},
work: function(my) {
console.log("Hit CNTRL+C to exit at any time.")
every((interval).second(), my.led.toggle);
}
}).start();
},
/**
* Automatically runs an API call to get the weather.
*/
weather: function(key, state, city, next){
// Build the API string.
var url = "http://api.wunderground.com/api/" + key + "/forecast/q/" + state + "/" + city + ".json";
request({
url: url,
json: true
}, function (error, response, body) {
if (!error && response.statusCode === 200) {
//var bodyparse = JSON.parse(body);
var result = JSON.stringify(body,null, 4);
//var observation = bodyparse.response.current_observation;
//var entries = "temp: " + observation.temp_f + " wind mph: " + observation.wind_mph;
next(null, result);
} else {
next("There was an error. Did you provide an API key? Is your Edison online? Try running edison status to check!");
}
});
},
/**
* Automatically runs a program to get the weather.
*/
status: function(next){
// Check and see if Edison is online or not.
require('dns').resolve('www.google.com', function(err) {
if (err)
next("You are not online, try running \'edison wifi\'");
else
next(null, "You are online!");
});
},
/**
* Execute an upgrade on LibMRAA.
*/
updateLibMRAA: function(next){
async.parallel([
async.apply(exec, 'echo \"src maa-upm http://iotdk.intel.com/repos/1.1/intelgalactic\" > /etc/opkg/intel-iotdk.conf'),
async.apply(exec, 'opkg update'),
async.apply(exec, 'opkg upgrade')
],
function (err, results) {
if(err){
next("You may already have the latest libMRAA. Try running opkg update then opkg upgrade to see.");
} else {
next(null, "Success!");
}
});
},
/**
* Scan for a Wi-Fi network
*/
scanWiFi: function(next){
var spawn = require('child_process').spawn,
ssh = spawn('configure_edison', ["--wifi"],{stdio: 'inherit'});
}
/**
* Automatically turns Edison into an iBeacon
*/
/*
beacon: function(next){
var bleno = require('bleno');
console.log('bleno - iBeacon');
bleno.on('stateChange', function(state) {
console.log('on -> stateChange: ' + state);
if (state === 'poweredOn') {
bleno.startAdvertisingIBeacon('e2c56db5dffb48d2b060d0f5a71096e0', 0, 0, -59);
} else {
bleno.stopAdvertising();
}
});
bleno.on('advertisingStart', function() {
console.log('on -> advertisingStart');
});
bleno.on('advertisingStop', function() {
console.log('on -> advertisingStop');
});
},
enableBluetoothSmart: function(next){
var command = spawn('sh', ['/enable_bluetooth.sh']);
var output = [];
command.on('close', function(code) {
next();
});
}*/
};
module.exports = new EdisonCLI();
| JavaScript | 0.000026 | @@ -1118,51 +1118,8 @@
) %7B%0A
-%09%09 %09//var bodyparse = JSON.parse(body);%0A
%09%09
@@ -1164,16 +1164,17 @@
ll, 4);%0A
+%0A
%09%09 %09/
@@ -1178,191 +1178,350 @@
%09//
-var observation = bodyparse.response.current_observation;%0A%09%09 //var entries = %22temp: %22 + observation.temp_f + %22 wind mph: %22 + observation.wind_mph;%0A%09%09 next(null, result);
+ write the output to a file.%0A%09%09 %09var outputFilename = '/weather.json';%0A%0A%09%09%09%09fs.writeFile(outputFilename, result, function(err) %7B%0A%09%09%09%09 if(err)%0A%09%09%09%09 next(%22There was an error writing the weather output to a file.%22);%0A%09%09 %09%09%09else%0A%09%09 %09%09 next(null, %22Weather saved to %5C'weather.json%5C', use %5C'cat weather.json%5C' to view it.%22);%0A%09%09%09%09%7D);
%0A%09%09
|
a268c9fc2dcee44170bca34bf7c0af14b0f2f81b | update trigger function try-catch style | src/util.js | src/util.js | /**
* Utilties
*/
// export default for holding the Vue reference
const exports = {}
export default exports
/**
* warn
*
* @param {String} msg
* @param {Error} [err]
*
*/
export function warn (msg, err) {
if (window.console) {
console.warn('[vue-validator] ' + msg)
if (err) {
console.warn(err.stack)
}
}
}
/**
* empty
*
* @param {Array|Object} target
* @return {Boolean}
*/
export function empty (target) {
if (target === null) { return true }
if (Array.isArray(target)) {
if (target.length > 0) { return false }
if (target.length === 0) { return true }
} else if (exports.Vue.util.isPlainObject(target)) {
for (let key in target) {
if (exports.Vue.util.hasOwn(target, key)) { return false }
}
}
return true
}
/**
* each
*
* @param {Array|Object} target
* @param {Function} iterator
* @param {Object} [context]
*/
export function each (target, iterator, context) {
if (Array.isArray(target)) {
for (let i = 0; i < target.length; i++) {
iterator.call(context || target[i], target[i], i)
}
} else if (exports.Vue.util.isPlainObject(target)) {
const hasOwn = exports.Vue.util.hasOwn
for (let key in target) {
if (hasOwn(target, key)) {
iterator.call(context || target[key], target[key], key)
}
}
}
}
/**
* pull
*
* @param {Array} arr
* @param {Object} item
* @return {Object|null}
*/
export function pull (arr, item) {
let index = exports.Vue.util.indexOf(arr, item)
return ~index ? arr.splice(index, 1) : null
}
/**
* attr
*
* @param {Element} el
* @param {String} name
* @return {String|null}
*/
export function attr (el, name) {
return el ? el.getAttribute(name) : null
}
/**
* trigger
*
* @param {Element} el
* @param {String} event
*/
export function trigger (el, event) {
let e = document.createEvent('HTMLEvents')
e.initEvent(event, true, false)
// Due to Firefox bug, events fired on disabled
// non-attached form controls can throw errors
try {
el.dispatchEvent(e)
} catch(e) {}
}
| JavaScript | 0.000003 | @@ -2018,20 +2018,16 @@
%0A try %7B
-%0A
el.disp
@@ -2042,18 +2042,16 @@
t(e)
-%0A
%7D catch
(e)
@@ -2046,16 +2046,17 @@
%7D catch
+
(e) %7B%7D%0A%7D
|
eecf8f0fb24140cbd16a31f1043e705363e46246 | Test travis fail build | src/wall.js | src/wall.js | // --- Application objects ----------------------------------------------------
class WallClient {
constructor(host, port, path) {
this.clientId = WallClient.generateClientId();
var client = new Paho.MQTT.Client(host, port, path, this.clientId);
var connectOptions = {};
client.onMessageArrived = (message) => {
//console.log("Message arrived ", message);
this.onMessage(message.destinationName, message.payloadString, message.retained);
};
client.onConnectionLost = (error) => {
console.info("Connection lost ", error);
this.onError(`Connection lost (${error.errorMessage})`, true);
}
connectOptions.onSuccess = () => {
console.info("Connect success");
this.onConnected();
}
connectOptions.onFailure = (error) => {
console.error("Connect fail ", error);
this.onError("Fail to connect", true);
}
client.connect(connectOptions);
this.client = client;
this.currentTopic = null;
this.onConnected = $.noop();
this.onMessage = $.noop();
this.onError = $.noop();
}
static generateClientId() {
var time = Date.now() % 1000;
var rnd = Math.round(Math.random() * 1000);
return `wall-${time}-${rnd}`;
}
subscribe (topic, fn) {
// unsubscribe current topic (if exists)
if (this.currentTopic !== null) {
var oldTopic = this.currentTopic;
this.client.unsubscribe(oldTopic, {
onSuccess: () => {
console.info("Unsubscribe '%s' success", oldTopic);
},
onFailure: (error) => {
console.error("Unsubscribe '%s' failure", oldTopic, error);
},
});
}
// subscribe new topic
this.client.subscribe(topic, {
onSuccess: (r) => {
console.info("Subscribe '%s' success", topic, r);
fn();
},
onFailure: (r) => {
console.error("subscribe '%s' failure", topic, r);
this.onError("Subscribe failure");
}
});
this.currentTopic = topic;
}
toString () {
var str = this.client.host;
if (this.client.port != 80) {
str += ":" + this.client.port;
}
return str;
}
}
// --- UI ---------------------------------------------------------------------
var UI = {};
UI.setTitle = function (topic) {
document.title = "MQTT Wall" + (topic ? (" for " + topic) : "");
};
UI.toast = function (message, type = "info", persistent = false) {
var toast = $("<div class='toast-item'>")
.text(message)
.addClass(type)
.hide()
.appendTo("#toast")
.fadeIn();
if (persistent != true) {
toast.delay(5000).slideUp().queue(function () { this.remove(); });
} else {
$("<span> – <a href='javascript:;'>reload</a></span>")
.find("a").click(function () { location.reload(); }).end()
.appendTo(toast);
}
};
class MessageLine {
constructor(topic, $parent){
this.topic = topic;
this.$parent = $parent;
this.init();
}
init() {
this.$root = $("<div class='message'>");
$("<h2>")
.text(this.topic)
.appendTo(this.$root);
this.$payload = $("<p>").appendTo(this.$root);
this.$root.appendTo(this.$parent);
}
set isRetained(value) {
this.$root.toggleClass("r", value);
}
set isSystemPayload(value) {
this.$payload.toggleClass("sys", value);
}
highlight() {
this.$payload
.stop()
.css({backgroundColor: "#0CB0FF"})
.animate({backgroundColor: "#fff"}, 2000);
}
update(payload, retained) {
this.isRetained = retained;
if (payload == "")
{
payload = "NULL";
this.isSystemPayload = true;
}
else
{
this.isSystemPayload = false;
}
this.$payload.text(payload);
this.highlight();
}
}
class MessageContainer {
constructor($parent) {
this.$parent = $parent;
this.init();
}
init() {
this.reset();
}
reset() {
this.lines = {};
this.$parent.html("");
}
update (topic, payload, retained) {
if (this.lines[topic] === undefined) {
this.lines[topic] = new MessageLine(topic, this.$parent);
}
this.lines[topic].update(payload, retained);
}
}
class Footer {
set clientId(value) {
$("#status-client").text(value);
}
set host(value) {
$("#status-host").text("ws://" + value);
}
set state(value) {
var className = ["connecting", "connected", "fail"];
var text = ["connecting...", "connected", "not connected"];
$("#status-state").removeClass().addClass(className[value]);
$("#status-state span").text(text[value]);
}
}
// --- Main -------------------------------------------------------------------
var client = new WallClient(config.server.host, config.server.port, config.server.path);
var messages = new MessageContainer($("#messages"));
var footer = new Footer();
footer.clientId = client.clientId;
footer.host = client.toString();
footer.state = 0;
client.onConnected = () => {
load();
footer.state = 1;
UI.toast("Connected to host " + client.toString());
}
client.onError = (description, isFatal) => {
UI.toast(description, "error", isFatal);
if (isFatal) footer.state = 2;
}
client.onMessage = (topic, msg, retained) => {
messages.update(topic, msg, retained);
}
function load() {
var topic = $("#topic").val();
client.subscribe(topic, function () {
UI.setTitle(topic);
location.hash = "#" + topic;
});
messages.reset();
}
$("#topic").keypress(function(e) {
if(e.which == 13) {
load();
}
});
// URL hash
if (location.hash != "") {
$("#topic").val(location.hash.substr(1));
} else {
$("#topic").val(config.defaultTopic);
}
| JavaScript | 0 | @@ -81,16 +81,18 @@
%0A%0D%0Aclass
+xx
WallCli
|
d778353f111fbc75e3d80cf2f043b6d568cf5212 | rename bindActionOnSet to onSet | src/html/scope.js | src/html/scope.js | function Scope(templateName, _parent, params, holder) {
if (!templates[templateName]) {
console.error("unknown template ", templateName);
}
this.template = templates[templateName].cloneNode(true); // deep
this._parent = _parent;
this.params = params;
this.cleanUp = [];
if (_parent)
for (var key in params)
this.bindData(key, _parent, params[key]); // params format is {localPath: parentPath}
templateScripts[templateName].call(this.template, this, this.template); //provide template as argument as well as reciever for ease of use in callbacks
if (holder) {
holder.innerHTML = '';
holder.appendChild(this.template);
}
}
Scope.prototype = {
// bind a path on this scope to a path on another object
bindData: function(path, other, otherPath) {
this.cleanUp.push(dataBinding.mutual(
other, otherPath,
this, path
));
},
// bind computed attribute
bindComputed: function(path, action) {
var that = this;
this.cleanUp.push(dataBinding.computedProperty(this, action, function(x) {
that[path] = x;
}));
},
// bind a path on this scope to an attribute of an html element in the scope, identified by selector
bindElement: function(selector, attribute, path) {
if (isFunction(path)) // bind computed property
this.bindElementComputed(selector, attribute, path);
else {
var element = this.template.querySelector(selector);
if (!element) console.error("selector " + selector + " not found");
bindElementAttributePathToObjectPath(element, attribute, this, path);
}
},
// build a new scope with the named template, link properties as specified in params, insert into holder identified by selector
bindTemplate: function(selector, templateName, params) {
var holder = this.template.querySelector(selector);
holder.innerHTML = '';
var that = this;
setTimeout(function() { // resolve this after binding elements in current scope, to prevent css selector reaching into child template
new Scope(templateName, that, params, holder);
}, 1);
},
// bind an array full of objects to a list of html scope instances
bindArray: function(selector, templateName, params, path) {
var fetchArray = dataBinding.walkAndGet(this, path);
var that = this;
// the function which builds each scope for the array members
// array within here is immutable
function subScope($index, array) {
var scope = new Scope(templateName, that, params);
scope.arrayScopeSetIndex($index, path);
return scope;
}
var holder = this.template.querySelector(selector);
// bind setting the array, each time, bind the array values / length changeing functions
this.cleanUp.push(bindArrayPathToHTML(holder, subScope, this, path));
//var currentArray = dataBinding.walkAndGet(this, path)();
//onSet(currentArray);
},
bindElementComputed: function(selector, attribute, action) {
// create a key name ( a single step path )
var path = dataBinding.makePrivateKey(selector + '|' + attribute);
// bind the computed property to the key name
var setAttribute = dataBinding.walkAndSet(this.template.querySelector(selector), attribute);
this.cleanUp.push(dataBinding.computedProperty(this, action, setAttribute));
},
bindActionOnSet: function(path, action) {
this.cleanUp.push(dataBinding.addOnSet(this, path, action));
},
//to be used when a scope representing an array item changes it's index
arrayScopeSetIndex: function($index, arrayPath) {
if (this.$index == $index)
return;
this.$index = $index;
//remove old listItemBinding
if (this.removeIndexBinding)
this.removeIndexBinding();
// bindListItem
var that = this,
_parent = this._parent;
this.removeIndexBinding = dataBinding.addOnSet(_parent, arrayPath + '.' + $index, function(x) {
that.$listItem = x;
});
},
$: function(selector) {
return new ChainableSelector(selector, this);
},
on: function(selector, eventName, callback) {
this.template.querySelector(selector).addEventListener(eventName, callback);
}
};
var alias = {
array: 'bindArray',
attr: 'bindElement',
tpl: 'bindTemplate',
computed: 'bindComputed'
};
for (var key in alias)
Scope.prototype[key] = Scope.prototype[alias[key]];
function isFunction(obj) {
return !!(obj && obj.constructor && obj.call && obj.apply);
}
| JavaScript | 0.000026 | @@ -3304,19 +3304,9 @@
,%0A
-bindActionO
+o
nSet
@@ -3799,17 +3799,16 @@
nding =
-d
ataBindi
|
3f7d4fab6862abd8bfce270d3f9bdb83205582e8 | Add tests for link adding for simple graph | src/index.test.js | src/index.test.js | var expect = require("chai").expect;
var graph = require("./index");
describe("Graph", function () {
var graphs = [
{
obj: graph.UndirectedUnweightedGraph,
name: "Undirected Unweighted Graph", type: {weighted: false, directed: false}
},
{
obj: graph.UndirectedWeightedGraph,
name: "Undirected Weighted Graph", type: {weighted: true, directed: false}
},
{
obj: graph.DirectedUnweightedGraph,
name: "Directed Unweighted Graph", type: {weighted: false, directed: true}
},
{
obj: graph.DirectedWeightedGraph,
name: "Directed Weighted Graph", type: {weighted: true, directed: true}
}
];
describe("Create and Type", function () {
graphs.forEach(function (test) {
it("Create " + test.name, function(){
var g = test.obj();
expect(g.type()).to.deep.equal(test.type);
})
});
});
describe("Add and has node", function(){
graphs.forEach(function (test) {
var g = test.obj();
it("Add node in " + test.name, function(){
expect(g.addNode("One", [1])).to.be.true;
expect(g.addNode("One", [2])).to.be.false;
expect(g.addNode("Two", [2])).to.be.true;
});
it("Has node in " + test.name, function(){
expect(g.hasNode("One")).to.be.true;
expect(g.hasNode("Three")).to.be.false;
expect(g.hasNode("Two")).to.be.true;
});
it("Node value is correct for " + test.name, function(){
expect(g.nodeValue("One")).to.be.deep.equal([1]);
expect(g.nodeValue("One")).to.be.not.deep.equal([2]);
expect(g.nodeValue("Two")).to.be.deep.equal([2]);
expect(g.nodeValue("Three")).to.be.undefined;
});
});
});
});
| JavaScript | 0.000001 | @@ -1981,13 +1981,1002 @@
%7D);%0A
+%0A describe(%22Add and has link%22, function()%7B%0A it(%22Add link in unweighted undirected graph%22, function()%7B%0A var g = graph.UndirectedUnweightedGraph();%0A g.addNode(%22One%22, 1);%0A g.addNode(%22Two%22, 2);%0A g.addNode(%22Three%22, 3);%0A g.addLink(%22One%22, %22Two%22);%0A expect(g.hasLink(%22One%22, %22Two%22)).to.be.true;%0A expect(g.hasLink(%22Two%22, %22One%22)).to.be.true;%0A expect(g.hasLink(%22One%22, %22Three%22)).to.be.false;%0A expect(g.hasLink(%22One%22, %22Four%22)).to.be.false;%0A // Weight%0A expect(g.linkWeight(%22One%22, %22Two%22)).to.be.equal(1);%0A expect(g.linkWeight(%22Two%22, %22One%22)).to.be.equal(1);%0A expect(g.linkWeight(%22Two%22, %22Three%22)).to.be.undefined;%0A%0A // Exceptions%0A expect(function()%7Bg.addLink(%22Four%22, %22One%22)%7D).to.throw(Error, %22'Four' is not found.%22);%0A expect(function()%7Bg.addLink(%22One%22, %22WWW%22)%7D).to.throw(Error, %22'WWW' is not found.%22);%0A%0A %7D)%0A %7D)%0A%0A
%7D);%0A%0A
|
854686fac0c37feb0968f80ce567a2f3463b2105 | remove catch all route | src/indexRoute.js | src/indexRoute.js | import {getEnv} from "./getEnv";
import {version} from "../package.json";
const IMAGE_QUALITY = getEnv("IMAGE_QUALITY").optional(50).number();
const CACHE_TTL = getEnv("CACHE_TTL").optional(3600000).number();
const WIDTH_POST = getEnv("WIDTH_POST").optional(1024).number();
const WIDTH_THREAD = getEnv("WIDTH_THREAD").optional(1280).number();
export const createIndexRoute = async (webserver) => {
webserver.use((req, res) => {
res.status(200).type("text/plain").send(`ROUTES
/thread/{threadId}
/thread/{threadId}.png
/thread/{threadId}/{pageNo}
/thread/{threadId}/{pageNo}.png
/post/{postId}
/post/{postId}.png
FORMAT
png
QUALITY
${IMAGE_QUALITY}
CACHE TTL
${CACHE_TTL}
POST WIDTH
${WIDTH_POST}
THREAD WIDTH
${WIDTH_THREAD}
VERSION
${version}
SOURCE
https://github.com/BreadfishPlusPlus/Screenshot`);
});
return;
};
| JavaScript | 0.001225 | @@ -411,12 +411,17 @@
ver.
-use(
+get(%22/%22,
(req
@@ -880,16 +880,100 @@
%0A %7D);
+%0A%0A webserver.use((req, res) =%3E %7B%0A res.status(404).send(%22400 + 4%22);%0A %7D);
%0A ret
|
ba5b5cabc38165ebcb443ad57f81b13191311a19 | Use afterClean event. | src/inlineMode.js | src/inlineMode.js | 'use strict';
// Creates a <br>.
function br () {
return document.createElement('br')
}
function onKeydown (e) {
if (e.keyCode === 13)
e.preventDefault()
}
function onInput () {
var first
this.selection.save()
this.sanitizer.clean(this.elem)
// Remove all whitespace at the beginning of the element.
first = this.elem.firstChild
while (this.node.isText(first) && !first.data) {
this.elem.removeChild(first)
first = this.elem.firstChild
}
// Append a <br> if need be.
if (!this.elem.textContent)
this.elem.appendChild(br())
this.selection.restore()
}
/**
* insertSpaces() is a Sanitizer filter which inserts spaces between
* elements; this is so that, when pasting, "<p>One</p><p>Two</p>"" gets
* turned into "One Two", not "OneTwo".
*
* @param {Element} elem
*/
function insertSpaces (elem) {
var text
if (!this.selection.isMarker(elem) && elem.parentNode === this.elem &&
elem.previousSibling) {
text = document.createTextNode(' ')
this.elem.insertBefore(text, elem)
}
}
function InlineMode (Quill) {
this.elem = Quill.elem
this.off = Quill.off.bind(Quill)
// Store bound event handlers for later removal.
this.onInput = onInput.bind(Quill)
this.insertSpaces = insertSpaces.bind(Quill)
this.elem.addEventListener('keydown', onKeydown)
Quill.on('input', this.onInput)
Quill.sanitizer.addFilter(this.insertSpaces)
// Remove all (presumably) unwanted elements present on initialization
// by simulating input.
this.onInput()
}
InlineMode.prototype.destroy = function () {
this.elem.removeEventListener('keydown', onKeydown)
this.off('input', this.onInput)
delete this.off
delete this.elem
return null
}
InlineMode.plugin = 'inline'
module.exports = InlineMode
| JavaScript | 0 | @@ -185,20 +185,8 @@
() %7B
-%0A var first
%0A%0A
@@ -243,16 +243,85 @@
.elem)%0A%0A
+ this.selection.restore()%0A%7D%0A%0Afunction afterClean () %7B%0A var first%0A%0A%0A
// Rem
@@ -372,16 +372,49 @@
lement.%0A
+ // FIXME: doesn't really work.%0A
first
@@ -483,16 +483,23 @@
rst.data
+.trim()
) %7B%0A
@@ -662,36 +662,8 @@
r())
-%0A%0A this.selection.restore()
%0A%7D%0A%0A
@@ -1292,16 +1292,59 @@
(Quill)%0A
+ this.afterClean = afterClean.bind(Quill)%0A
this.i
@@ -1463,24 +1463,66 @@
his.onInput)
+%0A Quill.on('afterclean', this.afterClean)
%0A%0A Quill.sa
@@ -1810,16 +1810,58 @@
onInput)
+%0A this.off('afterclean', this.afterClean)
%0A%0A dele
|
3da06e1ba7c9497607fd5439fb6124d2336e43eb | Add comment. | src/item/Group.js | src/item/Group.js | /*
* Paper.js
*
* This file is part of Paper.js, a JavaScript Vector Graphics Library,
* based on Scriptographer.org and designed to be largely API compatible.
* http://paperjs.org/
* http://scriptographer.org/
*
* Distributed under the MIT license. See LICENSE file for details.
*
* Copyright (c) 2011, Juerg Lehni & Jonathan Puckey
* http://lehni.org/ & http://jonathanpuckey.com/
*
* All rights reserved.
*/
var Group = this.Group = Item.extend({
/** @lends Group# */
// DOCS: document new Group(item, item...);
/**
* Creates a new Group item and places it at the top of the active layer.
*
* @param {Item[]} [children] An array of children that will be added to the
* newly created group.
*
* @example {@paperscript split=true height=200}
* // Create a group containing two paths:
* var path = new Path(new Point(100, 100), new Point(100, 200));
* var path2 = new Path(new Point(50, 150), new Point(150, 150));
*
* // Create a group from the two paths:
* var group = new Group([path, path2]);
*
* // Set the stroke color of all items in the group:
* group.strokeColor = 'black';
*
* // Move the group to the center of the view:
* group.position = view.center;
*
* @example {@paperscript split=true height=320}
* // Click in the view to add a path to the group, which in turn is rotated
* // every frame:
* var group = new Group();
*
* function onMouseDown(event) {
* // Create a new circle shaped path at the position
* // of the mouse:
* var path = new Path.Circle(event.point, 5);
* path.fillColor = 'black';
*
* // Add the path to the group's children list:
* group.addChild(path);
* }
*
* function onFrame(event) {
* // Rotate the group by 1 degree from
* // the centerpoint of the view:
* group.rotate(1, view.center);
* }
*
* @class A Group is a collection of items. When you transform a Group, its
* children are treated as a single unit without changing their relative
* positions.
* @extends Item
* @constructs Group
*/
initialize: function(items) {
this.base();
// Allow Group to have children and named children
this._children = [];
this._namedChildren = {};
this.addChildren(!items || !Array.isArray(items)
|| typeof items[0] !== 'object' ? arguments : items);
},
_changed: function(flags) {
if (flags & (ChangeFlag.HIERARCHY | ChangeFlag.CLIPPING)) {
// Clear cached clip item whenever hierarchy changes
delete this._clipItem;
}
},
_getClipItem: function() {
// Allow us to set _clipItem to null when none is found and still return
// it as a defined value without searching again
if (this._clipItem !== undefined)
return this._clipItem;
for (var i = 0, l = this._children.length; i < l; i++) {
var child = this._children[i];
if (child._clipMask)
return this._clipItem = child;
}
return this._clipItem = null;
},
/**
* Specifies whether the group item is to be clipped.
* When setting to {@code true}, the first child in the group is
* automatically defined as the clipping mask.
*
* @type Boolean
* @bean
*/
isClipped: function() {
return !!this._getClipItem();
},
setClipped: function(clipped) {
var child = this.getFirstChild();
if (child)
child.setClipMask(clipped);
return this;
},
draw: function(ctx, param) {
var clipItem = this._getClipItem();
if (clipItem)
Item.draw(clipItem, ctx, param);
for (var i = 0, l = this._children.length; i < l; i++) {
var item = this._children[i];
if (item != clipItem)
Item.draw(item, ctx, param);
}
}
});
| JavaScript | 0 | @@ -2874,16 +2874,106 @@
ld;%0A%09%09%7D%0A
+%09%09// Make sure we're setting _clipItem to null so it won't be searched for%0A%09%09// nex time.%0A
%09%09return
|
a9c50da9f3e6a09f47e995dcd152bbbf41043c57 | Fix import | scripts/update-location.js | scripts/update-location.js | #!/usr/bin/env node
let { existsSync, dirname } = require('fs')
let { writeFile, mkdir } = require('fs').promises
let { join } = require('path')
let dotenv = require('dotenv')
let MyError = require('./lib/my-error')
let read = require('./lib/read')
let get = require('./lib/get')
dotenv.config()
const FILE = join(__dirname, 'location', 'last.json')
async function loadLatLng () {
return get('https://evilmartians.com/locations/ai')
}
async function loadName (latLng, lang) {
let geodata = await get(
'https://maps.googleapis.com/maps/api/geocode/json' +
`?latlng=${ latLng.latitude },${ latLng.longitude }` +
`&language=${ lang }` +
`&key=${ process.env.GMAPS_TOKEN }`
)
if (!geodata.results[0]) {
console.error(geodata)
throw new MyError('Bad responce from Google')
}
let address = geodata.results[0].address_components
let country = address.find(i => i.types.includes('country'))
let city = address.find(i => i.types.includes('locality'))
if (country.short_name === 'JP') {
if (address.find(i => i.short_name === 'Tōkyō-to')) {
city = { long_name: lang === 'ru' ? 'Токио' : 'Tokyo' }
}
} else if (country.short_name === 'US') {
country = { long_name: lang === 'ru' ? 'США' : 'USA' }
}
if (!city) {
city = address.find(i => i.types.includes('administrative_area_level_1'))
}
if (city.long_name === 'New York' && lang === 'ru') {
city.long_name = 'Нью-Йорк'
}
return { country: country.long_name, city: city.long_name }
}
async function loadNames (latLng) {
let [ru, en] = await Promise.all([
loadName(latLng, 'ru'),
loadName(latLng, 'en')
])
return { ...latLng, ru, en }
}
async function wasNotChanged (cur) {
if (!existsSync(FILE)) return false
let last = JSON.parse(await read(FILE))
if (cur.latitude === last.latitude && cur.longitude === last.longitude) {
process.stdout.write('Location was not changed\n')
return true
} else {
return false
}
}
async function save (location) {
if (!existsSync(dirname(FILE))) {
await mkdir(dirname(FILE))
}
await writeFile(FILE, JSON.stringify(location, null, 2))
}
loadLatLng()
.then(async latLng => {
if (await wasNotChanged(latLng)) return
let location = await loadNames(latLng)
process.stdout.write(`${ location.en.city }, ${ location.en.country }\n`)
process.stdout.write(`${ location.ru.city }, ${ location.ru.country }\n`)
await save(location)
})
.catch(MyError.print)
| JavaScript | 0.000002 | @@ -24,52 +24,8 @@
t %7B
-existsSync, dirname %7D = require('fs')%0Alet %7B
writ
@@ -74,16 +74,62 @@
t %7B join
+, dirname %7D = require('path')%0Alet %7B existsSync
%7D = req
@@ -130,28 +130,26 @@
= require('
-path
+fs
')%0Alet doten
|
ef5421530011e231f3693e33947108b37583d0f6 | Remove unused parameter | src/js/options.js | src/js/options.js | 'use strict';
import $ from 'jquery';
import Promise from 'bluebird';
const getTeamIcon = function(config) {
// TODO: jQuery捨てるときにPromiseをreturnしないようにしてresolve/rejectをそれぞれreturn/throwを使って置き換える
return new Promise(function(resolve, reject) {
$.ajax({
type: 'GET',
url: 'https://api.esa.io/v1/teams/' + config.teamName,
data: {
access_token: config.token,
},
}).then(function(response) {
config.teamIcon = response.icon;
resolve(config);
}, reject);
});
};
const saveConfig = function(config) {
chrome.storage.sync.set(config, function() {
showMessage('Saved!(\\( ⁰⊖⁰)/)', true);
});
};
const notifyInvalidConfig = function(config) {
let teamName = $('.options__team-name').val();
let token = $('.options__token').val();
showMessage('invalid teamname or token (\\( ˘⊖˘)/)', false);
};
const showMessage = function(message, succeeded) {
let messageDom = $('.options__message');
$('.message').show();
messageDom.removeClass('message__body-color-success');
messageDom.removeClass('message__body-color-failure');
messageDom.text(message);
if (succeeded) {
messageDom.addClass('message__body-color-success');
setTimeout(function() {
$('.message').fadeOut('normal', function() {
messageDom.text('');
});
}, 2000);
} else {
messageDom.addClass('message__body-color-failure');
}
};
const toggleButton = function(disabled) {
$('.options__save').prop('disabled', disabled);
$('.options__save').text(disabled ? 'Saving...' : 'Save Options');
};
$(function() {
let defaultConfig = { teamName: '', token: '' };
chrome.storage.sync.get(defaultConfig, function(config) {
$('.options__team-name').val(config.teamName);
$('.options__token').val(config.token);
});
$('.options__save').on('click', function() {
toggleButton(true);
let config = {
teamName: $('.options__team-name').val(),
token: $('.options__token').val(),
};
(async function(config) {
let updatedConfig = await getTeamIcon(config);
saveConfig(updatedConfig);
})(config)
.catch(notifyInvalidConfig)
.finally(function() {
toggleButton(false);
});
});
});
| JavaScript | 0.000002 | @@ -684,30 +684,24 @@
= function(
-config
) %7B%0A let te
|
2f31ff8d0df6577a875189e52bbfae92c40cd3aa | Add Brazilian Portuguese | src/lang/index.js | src/lang/index.js | 'use strict';
import da from './da';
import de from './de';
import en from './en';
import fr from './fr';
import ja from './ja';
import ko from './ko';
import ru from './ru';
import zh_cn from './zh_cn';
export { da, de, en, fr, ja, ko, ru, zh_cn };
export default { da, de, en, fr, ja, ko, ru, zh_cn };
| JavaScript | 0.999929 | @@ -169,16 +169,45 @@
'./ru';%0A
+import pt_br from './pt_br';%0A
import z
@@ -266,24 +266,31 @@
o, ru, zh_cn
+, pt_br
%7D;%0Aexport d
@@ -331,12 +331,19 @@
u, zh_cn
+, pt_br
%7D;%0A
|
ec6ae3fe32a1d22e1d4004b5dad0e9af9b6438d2 | support additional headers | src/lib/rpcapi.js | src/lib/rpcapi.js | import 'whatwg-fetch';
const url = "http://localhost:1920";
const headers = {
'Content-Type': 'application/json'
};
let requestSeq = 1;
export function rpc(name, params) {
const data = {
"jsonrpc": "2.0",
"method": name,
"params": params,
"id": requestSeq++
};
return fetch(url, {method: 'POST', headers: headers, body: JSON.stringify(data)})
.then((response) => response.json())
} | JavaScript | 0 | @@ -60,17 +60,21 @@
;%0Aconst
-h
+baseH
eaders =
@@ -172,16 +172,25 @@
, params
+, headers
) %7B%0A
@@ -361,24 +361,51 @@
headers:
+ Object.assign(baseHeaders,
headers
, body:
@@ -396,16 +396,17 @@
headers
+)
, body:
|
dd770446bee0d9fe1b279835fdcc9c73d2b53012 | Update bignum.js | bignum/bignum.js | bignum/bignum.js | var numVals = {}
numVals.add = function(key, value)
{
numVals[key] = value + "";
}
for( var i = 0; i < 10; i++ )
{
var val = i + 48;
numVals.add(i, val);
}
for( var i = 0; i < 26; i++ )
{
var val = i + 65;
var char = String.fromCharCode(val);
numVals.add(char, val);
numVals.add(i + 10, val);
}
function number( positive, value )
{
this.positive = positive;
this.value = value + "";
this.isHex = false;
this.toString = function()
{
var sign = this.positive ? "+" : "-";
return sign + this.value;
}
}
//note: does not handle hex.
number.prototype.biggerThan( otherNumber, inclusive )
{
if( this.positive && !otherNumber.positive ){ return true; }
else if( !this.positive && otherNumber.positive ){ return false; }
else if( !this.positive && !otherNumber.positive )
{
var tempNumber = new number( true, this.value );
var tempOtherNumber = new number( true, otherNumber.value );
return tempOtherNumber.biggerThan(tempNumber);
}
else
{
if( this.value.length > otherNumber.value.length )
{
return true;
}
else if( this.value.length < otherNumber.value.length )
{
return true;
}
else
{
for(var i = 0; i < this.value.length; i++)
{
if( parseInt(this.value[i]) > parseInt(otherNumber.value[i]))
{
return true;
}
if( parseInt(this.value[i]) < parseInt(otherNumber.value[i]))
{
return false;
}
}
if( inclusive == undefined ||){ return false; }
if( inclusive == true ){ return true; }
}
}
}
number.prototype.smallerThan( otherNumber , inclusive)
{
return otherNumber.biggerThan(this, inclusive);
}
number.prototype.biggerThanOrEqual( otherNumber )
{
return this.biggerThan( otherNumber, true );
}
number.prototype.smallerThanOrEqual( otherNumber )
{
return this.smallerThan( otherNumber, true );
}
//note: only works for positive numbers for now.
number.prototype.plus( otherNumber )
{
var thisLastDigit = this.value.length;
var thatLastDigit = otherNumber.value.length;
var carried = 0;
var finalString = "";
var tempThis = "0" + this.value;
otherNumber = "0" + otherNumber.value;
var padding = thisLastDigit - thatLastDigit;
var paddingString = getPaddingString(Math.abs(padding));
if(padding > 0)
{
otherNumber = paddingString + otherNumber;
}
else
{
tempThis = paddingString + tempThis;
}
for(var i = Math.min(thisLastDigit, thatLastDigit) + Math.abs(padding); i > -1; i--)
{
var newNum = tempThis.charCodeAt(i) + otherNumber.value.charCodeAt(i) + carried - 96;
if(newNum >= 10)
{
carried = ( newNum - (newNum % 10) ) / 10;
newNum = newNum % 10;
}
else
{
carried = 0;
}
finalString = newNum + finalString + "";
}
if(finalString[0] == "0"){ finalString = finalString.substr(1); }
return new number( true, finalString );
}
//todo: do this next
//note: only works for positive numbers for now.
//lies. This is not yet done.
number.prototype.minus( otherNumber )
{
var thisLastDigit = this.value.length;
var thatLastDigit = otherNumber.value.length;
var carried = 0;
var finalString = "";
var positive = this.biggerThan(otherNumber);
var tempThis = "0" + this.value;
otherNumber = "0" + otherNumber.value;
var padding = thisLastDigit - thatLastDigit;
var paddingString = getPaddingString(Math.abs(padding));
if(padding > 0)
{
otherNumber = paddingString + otherNumber;
}
else
{
tempThis = paddingString + tempThis;
}
for(var i = Math.min(thisLastDigit, thatLastDigit) + Math.abs(padding); i > -1; i--)
{
var newNum = tempThis.charCodeAt(i) + otherNumber.value.charCodeAt(i) + carried - 96;
if(newNum >= 10)
{
carried = ( newNum - (newNum % 10) ) / 10;
newNum = newNum % 10;
}
else
{
carried = 0;
}
finalString = newNum + finalString + "";
}
if(finalString[0] == "0"){ finalString = finalString.substr(1); }
return new number( true, finalString );
}
//note: note implemented. Use newton-raphson division algorithm?
number.prototype.divideBy(divisor)
{
if(divisor.value == "0")
{
alert("You cannot divide by 0!!!");
}
return { quotient: this, remainder: 5 };
}
number.prototype.getHex()
{
var hexString = "";
var quotient = new number(this.positive, this.value);
var divisor = new number( true, 16 );
for(var i = 0; i < this.value.length; i++)
{
var result = quotient.divideBy( divisor );
quotient = result.quotient;
hexString = numVals[result.remainder] + hexString;
}
return hexString;
}
function complexNumber( realPositive, realValue, iPositive, iValue)
{
this.real = new number( realPositive, realValue );
this.i = new number( iPositive, iValue );
this.toString = function()
{
var realSign = this.real.positive ? "+" : "-";
var iSign = this.i.positive ? "+" : "-";
return realSign + this.real.value + iSign + this.i.value + "i";
}
}
| JavaScript | 0.000001 | @@ -1625,32 +1625,34 @@
iggerThanOrEqual
+To
( otherNumber )%0A
@@ -1737,16 +1737,18 @@
nOrEqual
+To
( otherN
|
6f6d9bd5a8f79a42d3893d179c6eefe734d3f679 | Simplify chokidar event handler | bin/6to5/file.js | bin/6to5/file.js | var sourceMap = require("source-map");
var chokidar = require("chokidar");
var util2 = require("../../lib/6to5/util");
var path = require("path");
var util = require("./util");
var fs = require("fs");
var _ = require("lodash");
module.exports = function (commander, filenames) {
var results = [];
var buildResult = function () {
var map = new sourceMap.SourceMapGenerator({
file: commander.outFile || "stdout"
});
var code = "";
var offset = 0;
_.each(results, function (result) {
var filename = result.filename;
code += result.code + "\n";
if (result.map) {
var consumer = new sourceMap.SourceMapConsumer(result.map);
map._sources.add(filename);
map.setSourceContent(filename, result.actual);
consumer.eachMapping(function (mapping) {
map._mappings.push({
generatedLine: mapping.generatedLine + offset,
generatedColumn: mapping.generatedColumn,
originalLine: mapping.originalLine,
originalColumn: mapping.originalColumn,
source: filename
});
});
offset = code.split("\n").length;
}
});
if (commander.sourceMapsInline || (!commander.outFile && commander.sourceMaps)) {
code += "\n" + util2.sourceMapToComment(map);
}
return {
map: map,
code: code
};
};
var output = function () {
var result = buildResult();
if (commander.outFile) {
if (commander.sourceMaps) {
var mapLoc = commander.outFile + ".map";
result.code = util.addSourceMappingUrl(result.code, mapLoc);
fs.writeFileSync(mapLoc, JSON.stringify(result.map));
}
fs.writeFileSync(commander.outFile, result.code);
} else {
console.log(result.code);
}
};
var stdin = function () {
var code = "";
process.stdin.setEncoding("utf8");
process.stdin.on("readable", function () {
var chunk = process.stdin.read();
if (chunk !== null) code += chunk;
});
process.stdin.on("end", function() {
results.push(util.transform(commander.filename, code));
output();
});
};
var walk = function () {
var _filenames = [];
results = [];
_.each(filenames, function (filename) {
if (!fs.existsSync(filename)) return;
var stat = fs.statSync(filename);
if (stat.isDirectory()) {
var dirname = filename;
_.each(util.readdirFilter(filename), function (filename) {
_filenames.push(path.join(dirname, filename));
});
} else {
_filenames.push(filename);
}
});
_.each(_filenames, function (filename) {
results.push(util.compile(filename));
});
output();
};
var files = function () {
walk();
if (commander.watch) {
var watcher = chokidar.watch(filenames, {
persistent: true,
ignoreInitial: true
});
_.each(["add", "change", "unlink"], function (type) {
watcher.on(type, function (filename) {
console.log(type, filename);
walk();
});
});
}
};
if (filenames.length) {
files();
} else {
stdin();
}
};
| JavaScript | 0.000615 | @@ -2962,106 +2962,35 @@
%7D)
-;%0A%0A _.each(%5B%22add%22, %22change%22, %22unlink%22%5D, function (type) %7B%0A watcher.on(type, function (
+.on(%22all%22, function (type,
file
@@ -2989,34 +2989,32 @@
pe, filename) %7B%0A
-
console.
@@ -3042,26 +3042,24 @@
-
walk();%0A
@@ -3050,28 +3050,16 @@
walk();%0A
- %7D);%0A
%7D)
|
a23773a500a5d9a2a98754cfd2f4f3249cffb695 | Rebuild prior to validation | bin/presidium.js | bin/presidium.js | #! /usr/bin/env node
var yargs = require('yargs');
var config = require('../src/config');
var presidium = require('../src/presidium');
var conf = config.load('_config.yml');
var argv = yargs.usage('$0 command')
.command('requirements', 'Install jekyll gems and npm dependencies', function (yargs) {
presidium.requirements(conf);
})
.command('clean', 'Clean build directory', function (yargs) {
presidium.clean(conf);
})
.command('install', 'Install jekyll gems and npm dependencies', function (yargs) {
presidium.install(conf);
})
.command('generate', 'Generate site sources', function (yargs) {
presidium.generate(conf);
})
.command('build', 'Build site', function (yargs) {
presidium.generate(conf);
presidium.build(conf);
})
.command('validate', 'Validate generated site', function (yargs) {
presidium.validate(conf)
})
.command('watch', 'Watch for content and media updates', function (yargs) {
presidium.watch(conf)
})
.command('develop', 'Watch presidium sources (for development)', function (yargs) {
presidium.develop(conf)
})
.command('serve', 'Serve site', function (yargs) {
presidium.serve(conf);
})
.command('start', 'Build and serve', function (yargs) {
presidium.clean(conf);
presidium.generate(conf);
presidium.watch(conf);
presidium.serve(conf);
})
.command('gh-pages', 'Publish to Github Pages', function (yargs) {
presidium.clean(conf);
presidium.generate(conf);
presidium.build(conf);
presidium.ghPages(conf);
})
.demand(1, 'must provide a valid command')
.help('h').alias('h', 'help')
.argv;
| JavaScript | 0 | @@ -873,32 +873,128 @@
ction (yargs) %7B%0A
+ presidium.clean(conf);%0A presidium.generate(conf);%0A presidium.build(conf);%0A
presidiu
|
fde0b36912a78604ed4932af737ac3263dd2b129 | add missing propType "extra" | src/line-chart.js | src/line-chart.js | import * as array from 'd3-array'
import * as scale from 'd3-scale'
import * as shape from 'd3-shape'
import PropTypes from 'prop-types'
import React, { PureComponent } from 'react'
import { StyleSheet, View } from 'react-native'
import Svg from 'react-native-svg'
import Path from './animated-path'
import { Constants } from './util'
class LineChart extends PureComponent {
state = {
width: 0,
height: 0,
}
_onLayout(event) {
const { nativeEvent: { layout: { height, width } } } = event
this.setState({ height, width })
}
_createLine(dataPoints, yAccessor, xAccessor) {
const { curve } = this.props
return shape.line()
.x(xAccessor)
.y(yAccessor)
.defined(value => typeof value === 'number')
.curve(curve)
(dataPoints)
}
render() {
const {
dataPoints,
strokeColor,
dashArray,
shadowColor,
style,
animate,
animationDuration,
showGrid,
numberOfTicks,
contentInset: {
top = 0,
bottom = 0,
left = 0,
right = 0,
},
gridMax,
gridMin,
renderDecorator,
extras,
renderExtra,
} = this.props
const { width, height } = this.state
if (dataPoints.length === 0) {
return <View style={ style }/>
}
const extent = array.extent([ ...dataPoints, gridMax, gridMin ])
const ticks = array.ticks(extent[ 0 ], extent[ 1 ], numberOfTicks)
//invert range to support svg coordinate system
const y = scale.scaleLinear()
.domain(extent)
.range([ height - bottom, top ])
const x = scale.scaleLinear()
.domain([ 0, dataPoints.length - 1 ])
.range([ left, width - right ])
const line = this._createLine(
dataPoints,
value => y(value),
(value, index) => x(index),
)
const shadow = this._createLine(
dataPoints,
value => y(value) + 3,
(value, index) => x(index),
)
return (
<View style={style}>
<View style={{ flex: 1 }} onLayout={event => this._onLayout(event)}>
{
showGrid &&
ticks.map((tick, index) => (
<View
key={index}
style={[ styles.grid, { top: y(tick) } ]}
/>
))
}
<Svg style={{ flex: 1 }}>
<Path
d={line}
stroke={strokeColor}
fill={'none'}
strokeWidth={2}
strokeDasharray={dashArray}
animate={animate}
animationDuration={animationDuration}
/>
<Path
d={shadow}
stroke={shadowColor}
fill={'none'}
strokeWidth={5}
strokeDasharray={dashArray}
animate={animate}
animationDuration={animationDuration}
/>
{ dataPoints.map((value, index) => renderDecorator({ x, y, value, index, width, height })) }
{ extras.map((item, index) => renderExtra({ x, y, item, index, width, height })) }
</Svg>
</View>
</View>
)
}
}
LineChart.propTypes = {
dataPoints: PropTypes.arrayOf(PropTypes.number).isRequired,
strokeColor: PropTypes.string,
fillColor: PropTypes.string,
dashArray: PropTypes.arrayOf(PropTypes.number),
style: PropTypes.any,
shadowColor: PropTypes.string,
animate: PropTypes.bool,
animationDuration: PropTypes.number,
curve: PropTypes.func,
contentInset: PropTypes.shape({
top: PropTypes.number,
left: PropTypes.number,
right: PropTypes.number,
bottom: PropTypes.number,
}),
numberOfTicks: PropTypes.number,
showGrid: PropTypes.bool,
gridMin: PropTypes.number,
gridMax: PropTypes.number,
renderDecorator: PropTypes.func,
renderExtra: PropTypes.func,
}
LineChart.defaultProps = {
strokeColor: '#22B6B0',
width: 100,
height: 100,
curve: shape.curveCardinal,
contentInset: {},
numberOfTicks: 10,
showGrid: true,
gridMin: 0,
gtidMax: 0,
extras: [],
renderDecorator: () => {
},
renderExtra: () => {
},
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
grid: Constants.gridStyle,
surface: {
backgroundColor: 'transparent',
},
intersection: {
position: 'absolute',
bottom: 0,
left: 0,
right: 0,
},
})
export default LineChart
| JavaScript | 0 | @@ -4708,24 +4708,53 @@
pes.number,%0A
+ extras: PropTypes.array,%0A
renderDe
|
8d25eb87fe34e0178e4d18f0d698289abecd7be1 | Reset settings functionality added | src/main/index.js | src/main/index.js | const {
electron,
globalShortcut,
app,
BrowserWindow,
Tray,
Menu,
shell,
ipcMain,
dialog
} = require('electron');
const settings = require('electron-settings');
const path = require('path');
const url = require('url');
const fs = require('fs');
const stripJsonComments = require('strip-json-comments');
let mainWindow, aboutWindow, tray, forceQuit = false;
//Load the default JSBeautify settings
let beautifyOptions = JSON.parse(
stripJsonComments(
fs.readFileSync(
path.join(__dirname, '../static/jsbeautifyrc.json'),
'utf8'
)
)
);
/**
* Create the main settings window
*/
function createWindow () {
mainWindow = new BrowserWindow({
width: 600,
height: 600,
show: false,
resizable: false,
minimizable: false,
maximizable: false,
skipTaskbar: true
});
mainWindow.webContents.openDevTools();
mainWindow.loadURL(url.format({
pathname: path.join(__dirname, '../renderer/views/preferences.html'),
protocol: 'file:',
slashes: true
}));
mainWindow.on('close', e => {
if (!forceQuit) {
e.preventDefault();
mainWindow.hide();
}
});
}
/**
* Initial load/set up of user settings
*/
function handleSettings() {
let all_settings = settings.getAll();
}
/**
* Create and show the about window
*/
function handleAboutWindow() {
if (!aboutWindow) {
aboutWindow = new BrowserWindow({
width: 250,
height: 400,
resizable: false,
minimizable: false,
maximizable: false,
skipTaskbar: true,
title: '',
show: false
});
aboutWindow.loadURL(url.format({
pathname: path.join(__dirname, '../renderer/views/about.html'),
protocol: 'file:',
slashes: true
}));
aboutWindow.once('ready-to-show', () => {
aboutWindow.show();
});
aboutWindow.on('closed', () => {
aboutWindow = null;
});
} else {
aboutWindow.focus();
}
}
/**
* Show the preferences window
*/
function handlePreferencesWindow() {
mainWindow.show();
}
/**
* Sets up the tray icon and it's context menu
*/
function setupTray() {
//Use the approapriate icon per OS
if (process.platform !== 'darwin') {
tray = new Tray(path.join(__dirname, '../static/win_icon.ico'));
} else {
tray = new Tray(path.join(__dirname, '../static/tray_icon_gray.png'));
tray.setPressedImage(path.join(__dirname, '../static/tray_icon_color.png'));
}
//A nice tooltip
tray.setToolTip('QuickFix');
//Create the context menu
let contextMenu = Menu.buildFromTemplate([
{label: 'Preferences...', type: 'normal', click: handlePreferencesWindow},
{label: 'About QuickFix', type: 'normal', click: handleAboutWindow},
{type: 'separator'},
{label: 'Quit', type: 'normal', role: 'quit'}
]);
//Apply the menu
tray.setContextMenu(contextMenu);
}
/**
* Loads settings from flat file storage
*/
function loadSettings() {
//Get app data path
let userDataPath = app.getPath('userData');
//Check if the folder exists
fs.exists(userDataPath, exists => {
//If it doesn't, create it and put the default options there
if (!exists) {
fs.createReadStream(path.join(__dirname, '../static/jsbeautifyrc.json')).pipe(fs.createWriteStream(path.join(userDataPath, 'jsbeautifyrc.json')));
} else {
//If the folder exists, check if the settings file exists
fs.exists(path.join(userDataPath, 'jsbeautifyrc.json'), fileExists => {
if (!fileExists) {
//If it doesn't, put the default there
fs.createReadStream(path.join(__dirname, '../static/jsbeautifyrc.json')).pipe(fs.createWriteStream(path.join(userDataPath, 'jsbeautifyrc.json')));
} else {
//If it does, read the settings that are there
beautifyOptions = JSON.parse(
stripJsonComments(
fs.readFileSync(
path.join(userDataPath, 'jsbeautifyrc.json'),
'utf8'
)
)
);
}
});
}
});
}
/**
* Sets up ipcMain callbacks
*/
function ipcSetup() {
//Settings reset
ipcMain.addListener('reset-settings', () => {
dialog.showMessageBox(mainWindow, {
title: 'Warning',
icon: path.join(__dirname, '../static/original_icon.png'),
message: 'Are you sure you want to reset your settings to default?',
type: 'warning',
defaultId: 1,
cancelId: 1,
buttons: ['Yes', 'Cancel']
}, res => {
console.log(res);
});
});
}
/**
* Set up our application
*/
app.on('ready', () => {
loadSettings();
createWindow();
handleSettings();
setupTray();
ipcSetup();
const ret = globalShortcut.register('CommandOrControl+B', () => {
mainWindow.webContents.send('shortcut-hit', 'ping');
});
if (process.platform === 'darwin') {
app.dock.hide();
}
});
/**
* Use force to remove the preferences window
*/
app.on('before-quit', () => {
forceQuit = true;
});
/**
* Prevent app from closing when all windows are closed
*/
app.on('window-all-closed', () => {
//😎
}); | JavaScript | 0 | @@ -3760,24 +3760,42 @@
t are there%0A
+ try %7B%0A
be
@@ -3834,16 +3834,18 @@
+
stripJso
@@ -3865,24 +3865,26 @@
+
fs.readFileS
@@ -3884,24 +3884,26 @@
adFileSync(%0A
+
@@ -3964,24 +3964,26 @@
+
'utf8'%0A
@@ -3983,34 +3983,38 @@
'%0A
-)%0A
+ )%0A
)%0A
@@ -4021,18 +4021,83 @@
-);
+ );%0A %7D catch(e) %7B%0A console.log(e);%0A %7D
%0A
@@ -4575,25 +4575,325 @@
-console.log(res);
+if (res === 0) %7B%0A let userDataPath = app.getPath('userData');%0A fs.unlink(path.join(userDataPath, 'jsbeautifyrc.json'), () =%3E %7B%0A fs.createReadStream(path.join(__dirname, '../static/jsbeautifyrc.json')).pipe(fs.createWriteStream(path.join(userDataPath, 'jsbeautifyrc.json')));%0A %7D);%0A %7D
%0A
|
d202f3baea0fdb7f69f9131430f44d99b9b20d14 | add flow types to makeAreaSlug | modules/hanson-format/make-area-slug.js | modules/hanson-format/make-area-slug.js | import kebabCase from 'lodash/kebabCase'
export function makeAreaSlug(name) {
return kebabCase((name || '').replace("'", '')).toLowerCase()
}
| JavaScript | 0 | @@ -1,8 +1,17 @@
+// @flow%0A
import k
@@ -77,17 +77,33 @@
lug(name
-)
+: string): string
%7B%0A%09retu
|
fb541c65383729737577febde46dcdf93f4043d8 | add small speed up to action calls | src/Actions.js | src/Actions.js | import Rx from 'rx';
import invariant from 'invariant';
import assign from 'object.assign';
import debugFactory from 'debug';
import waitFor from './waitFor';
const debug = debugFactory('thundercats:actions');
const protectedProperties = [
'displayName',
'constructor'
];
export function getActionNames(ctx) {
return Object.getOwnPropertyNames(ctx.constructor.prototype)
.filter(name => {
return (
protectedProperties.indexOf(name) === -1 &&
name.indexOf('_') === -1 &&
typeof ctx[name] === 'function'
);
});
}
export const ActionCreator = {
create(name, map) {
let observers = [];
let actionStart = new Rx.Subject();
function action(value) {
/* istanbul ignore else */
if (typeof map === 'function') {
value = map(value);
}
actionStart.onNext(value);
observers.forEach((observer) => {
observer.onNext(value);
});
return value;
}
action.displayName = name;
action.observers = observers;
assign(action, Rx.Observable.prototype, Rx.Subject.prototype);
action.hasObservers = function hasObservers() {
return observers.length > 0 ||
actionStart.hasObservers();
};
action.waitFor = function() {
return actionStart
.flatMap(payload => waitFor(...arguments).map(() => payload));
};
Rx.Observable.call(action, observer => {
observers.push(observer);
return new Rx.Disposable(() => {
observers.splice(observers.indexOf(observer), 1);
});
});
debug('action %s created', action.displayName);
return action;
},
createManyOn(ctx, actions) {
invariant(
Array.isArray(actions),
'createActions requires an array but got %s',
actions
);
let actionsBag = actions.reduce(function(ctx, action) {
invariant(
action &&
typeof action === 'object',
'createActions requires items in array to be objects but ' +
'was supplied with %s',
action
);
invariant(
typeof action.name === 'string',
'createActions requires objects to have a name key, but got %s',
action.name
);
/* istanbul ignore else */
if (action.map) {
invariant(
typeof action.map === 'function',
'createActions requires objects with map field to be a function ' +
'but was given %s',
action.map
);
}
ctx[action.name] = ActionCreator.create(action.name, action.map);
return ctx;
}, {});
return assign(ctx, actionsBag);
}
};
export default class Actions {
constructor(actionNames) {
if (actionNames) {
invariant(
Array.isArray(actionNames) &&
actionNames.every(actionName => typeof actionName === 'string'),
'%s should get an array of strings but got %s',
actionNames
);
}
let actionDefinitions = getActionNames(this)
.map(name => ({ name: name, map: this[name] }));
if (actionNames) {
actionDefinitions =
actionDefinitions.concat(actionNames.map(name => ({ name })));
}
// istanbul ignore else
if (actionDefinitions && actionDefinitions.length) {
ActionCreator.createManyOn(this, actionDefinitions);
}
}
}
| JavaScript | 0 | @@ -709,82 +709,8 @@
) %7B%0A
- /* istanbul ignore else */%0A if (typeof map === 'function') %7B%0A
@@ -730,24 +730,16 @@
(value);
-%0A %7D
%0A%0A
@@ -2989,24 +2989,16 @@
itions =
-%0A
actionD
@@ -3015,16 +3015,25 @@
.concat(
+%0A
actionNa
@@ -3055,20 +3055,53 @@
(%7B name
- %7D))
+, map: Rx.helpers.identity %7D))%0A
);%0A %7D
|
e45e949947e1986e89ee5bbad86b4095636fe45b | add log to get out the problems on travis integation tests | src/services/user/services/AdminUsers.js | src/services/user/services/AdminUsers.js | /* eslint-disable no-param-reassign */
/* eslint-disable class-methods-use-this */
const { BadRequest, Forbidden } = require('@feathersjs/errors');
const { authenticate } = require('@feathersjs/authentication').hooks;
const moment = require('moment');
const logger = require('../../../logger');
const { createMultiDocumentAggregation } = require('../utils/aggregations');
const {
hasSchoolPermission,
} = require('../../../hooks');
const { userModel } = require('../model');
const getCurrentUserInfo = (id) => userModel.findById(id)
.select('schoolId')
.lean()
.exec();
const getCurrentYear = (ref, schoolId) => ref.app.service('schools')
.get(schoolId, {
query: { $select: ['currentYear'] },
})
.then(({ currentYear }) => currentYear.toString());
class AdminUsers {
constructor(roleName) {
this.roleName = roleName;
this.docs = {};
}
async find(params) {
return this.getUsers(undefined, params);
}
async get(id, params) {
return this.getUsers(id, params);
}
async getUsers(_id, params) {
try {
const { query: clientQuery = {}, account } = params;
const currentUserId = account.userId.toString();
// fetch base data
const { schoolId } = await getCurrentUserInfo(currentUserId);
const schoolYearId = await getCurrentYear(this, schoolId);
const query = {
schoolId,
roles: this.role._id,
schoolYearId,
sort: clientQuery.$sort || clientQuery.sort,
select: [
'consentStatus',
'consent',
'classes',
'firstName',
'lastName',
'email',
'createdAt',
'importHash',
'birthday',
],
skip: clientQuery.$skip || clientQuery.skip,
limit: clientQuery.$limit || clientQuery.limit,
};
if (_id) query._id = _id;
if (clientQuery.consentStatus) query.consentStatus = clientQuery.consentStatus;
if (clientQuery.classes) query.classes = clientQuery.classes;
if (clientQuery.createdAt) query.createdAt = clientQuery.createdAt;
if (clientQuery.firstName) query.firstName = clientQuery.firstName;
if (clientQuery.lastName) query.lastName = clientQuery.lastName;
return new Promise((resolve, reject) => userModel.aggregate(createMultiDocumentAggregation(query)).option({
collation: { locale: 'de', caseLevel: true },
}).exec((err, res) => {
if (err) reject(err);
else resolve(res[0]);
// else if (_id) resolve(res[0].data[0] || {});
// else resolve(res[0]);
}));
} catch (err) {
if ((err || {}).code === 403) {
throw new Forbidden('You have not the permission to execute this.', err);
}
throw new BadRequest('Can not fetch data.', err);
}
}
async create(data, params) {
return this.app.service('usersModel').create(data);
}
async update(id, data, params) {
return this.app.service('usersModel').update(id, data);
}
async patch(id, data, params) {
return this.app.service('usersModel').patch(id, data);
}
async remove(id, params) {
const { _ids } = params.query;
if (id) {
return this.app.service('usersModel').remove(id);
}
return this.app.service('usersModel').remove(null, { query: { _id: { $in: _ids } } });
}
async setup(app) {
this.app = app;
this.role = (await this.app.service('roles').find({
query: { name: this.roleName },
})).data[0];
}
}
const formatBirthdayOfUsers = ({ result: { data: users } }) => {
users.forEach((user) => { user.birthday = moment(user.birthday).format('DD.MM.YYYY'); });
};
const adminHookGenerator = (kind) => ({
before: {
all: [authenticate('jwt')],
find: [hasSchoolPermission(`${kind}_LIST`)],
get: [hasSchoolPermission(`${kind}_LIST`)],
create: [hasSchoolPermission(`${kind}_CREATE`)],
update: [hasSchoolPermission(`${kind}_EDIT`)],
patch: [hasSchoolPermission(`${kind}_EDIT`)],
remove: [hasSchoolPermission(`${kind}_DELETE`)],
},
after: {
find: [formatBirthdayOfUsers],
},
});
module.exports = {
AdminUsers,
adminHookGenerator,
};
| JavaScript | 0 | @@ -2320,117 +2320,112 @@
s%5B0%5D
-);%0A%09%09%09%09// else if (_id) resolve(res%5B0%5D.data%5B0%5D %7C%7C %7B%7D);%0A%09%09%09%09// else resolve(res%5B0%5D);%0A%09%09%09%7D));%0A%09%09%7D catch (err) %7B
+ %7C%7C %7B%7D);%0A%09%09%09%7D));%0A%09%09%7D catch (err) %7B%0A%09%09%09logger.error('------------------------------Spezial error:', err);
%0A%09%09%09
|
6e5da323ca2ad20b79779af5eb2a2838bab73d17 | Remove App.js from tests | src/App.test.js | src/App.test.js | /*jshint ignore: start*/
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
it('renders without crashing', () => {
const div = document.createElement('div');
ReactDOM.render(<App />, div);
ReactDOM.unmountComponentAtNode(div);
});
| JavaScript | 0.000001 | @@ -83,33 +83,8 @@
om';
-%0Aimport App from './App';
%0A%0Ait
|
22ec30abcef58a0e9216892edea6af4995caec0a | Update autoClear.js | service/autoClear.js | service/autoClear.js | /**
* Created by chriscai on 2014/10/14.
*/
var MongoClient = require('mongodb').MongoClient;
var log4js = require('log4js'),
logger = log4js.getLogger();
var url = global.MONGODB.url;
var mongoDB;
// Use connect method to connect to the Server
MongoClient.connect(url, function(err, db) {
if(err){
logger.error("failed connect to mongodb");
}else {
logger.info("Connected correctly to mongodb");
}
mongoDB = db;
});
var maxAge = GLOBAL.pjconfig.maxAge ;
// 5 天前的数据
var beforeDate = 1000 * 60 * 60 *24 * maxAge ;
var autoClearStart = function (){
logger.info('start auto clear data before '+ beforeDate +' and after 7d will clear again');
mongoDB.collections(function (error,collections){
collections.forEach(function (collection ,key ){
if(collection.s.name.indexOf("badjs")<0) {
return ;
}
logger.info("start clear " + collection.s.name);
collection.deleteMany({ date : { $lt : new Date(new Date - beforeDate)}} , function (err , result){
if(err){
logger.info("clear error " + err);
}else {
logger.info("clear success id=" + collection.s.name);
}
})
})
});
}
module.exports = function (){
var afterDate = new Date;
afterDate.setDate(afterDate.getDate()+1);
afterDate.setHours(04);
// autoClearStart();
var afterTimestamp = afterDate - new Date ;
logger.info(afterTimestamp + "s should clear");
var start = function (){
autoClearStart();
setInterval(function (){
autoClearStart();
} , 86400000 * maxAge );
};
//明天凌晨4点,启动
setTimeout(function (){
start();
}, afterTimestamp);
}
| JavaScript | 0.000001 | @@ -502,9 +502,17 @@
%0A//
-5
+%E6%B8%85%E7%90%86 maxAge
%E5%A4%A9%E5%89%8D%E7%9A%84
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.