commit stringlengths 40 40 | old_file stringlengths 4 150 | new_file stringlengths 4 150 | old_contents stringlengths 0 3.26k | new_contents stringlengths 1 4.43k | subject stringlengths 15 501 | message stringlengths 15 4.06k | lang stringclasses 4
values | license stringclasses 13
values | repos stringlengths 5 91.5k | diff stringlengths 0 4.35k |
|---|---|---|---|---|---|---|---|---|---|---|
5bf7c484a2d325e433105264fad62395a06ae3f5 | test/browserScriptTests.js | test/browserScriptTests.js | 'use strict';
let assert = require('assert'),
path = require('path'),
parser = require('../lib/support/browserScript');
const TEST_SCRIPTS_FOLDER = path.resolve(__dirname, 'browserscripts', 'testscripts');
describe('#parseBrowserScripts', function() {
it('should parse valid scripts', function() {
return parser.findAndParseScripts(TEST_SCRIPTS_FOLDER)
.then((scriptsByCategory) => {
const categoryNames = Object.keys(scriptsByCategory);
assert.deepEqual(categoryNames, ['testscripts']);
const testscriptsCategory = scriptsByCategory.testscripts;
const scriptNames = Object.keys(testscriptsCategory);
assert.deepEqual(scriptNames, ['scriptTags']);
assert.notEqual(testscriptsCategory.script, '');
});
});
it('should get scripts for all categories', function() {
return parser.getScriptsForCategories(parser.allScriptCategories)
.then((scriptsByCategory) => {
const categoryNames = Object.keys(scriptsByCategory);
assert.deepEqual(categoryNames, ['browser', 'pageinfo', 'timings']);
});
});
});
| 'use strict';
let assert = require('assert'),
path = require('path'),
parser = require('../lib/support/browserScript');
const TEST_SCRIPTS_FOLDER = path.resolve(__dirname, 'browserscripts', 'testscripts');
describe('#parseBrowserScripts', function() {
it('should parse valid scripts', function() {
return parser.findAndParseScripts(TEST_SCRIPTS_FOLDER, 'custom')
.then((scriptsByCategory) => {
const categoryNames = Object.keys(scriptsByCategory);
assert.deepEqual(categoryNames, ['testscripts']);
const testscriptsCategory = scriptsByCategory.testscripts;
const scriptNames = Object.keys(testscriptsCategory);
assert.deepEqual(scriptNames, ['scriptTags']);
assert.notEqual(testscriptsCategory.script, '');
});
});
it('should get scripts for all categories', function() {
return parser.getScriptsForCategories(parser.allScriptCategories)
.then((scriptsByCategory) => {
const categoryNames = Object.keys(scriptsByCategory);
assert.deepEqual(categoryNames, ['browser', 'pageinfo', 'timings']);
});
});
});
| Fix api usage in script parse test. | Fix api usage in script parse test.
| JavaScript | apache-2.0 | sitespeedio/browsertime,sitespeedio/browsertime,sitespeedio/browsertime,tobli/browsertime,sitespeedio/browsertime | ---
+++
@@ -8,7 +8,7 @@
describe('#parseBrowserScripts', function() {
it('should parse valid scripts', function() {
- return parser.findAndParseScripts(TEST_SCRIPTS_FOLDER)
+ return parser.findAndParseScripts(TEST_SCRIPTS_FOLDER, 'custom')
.then((scriptsByCategory) => {
const categoryNames = Object.keys(scriptsByCategory);
|
665cf3ad4235befb89c1f414239bf041896fac75 | tests/commands/tgrTests.js | tests/commands/tgrTests.js | var tgr = require("__buttercup/classes/commands/command.tgr.js");
/*
module.exports = {
failMe: {
failmeplease: function(test) {
console.log(tgr);
test.fail();
test.done();
}
}
};
*/
| var tgr = require("__buttercup/classes/commands/command.tgr.js");
module.exports = {
errors: {
groupNotFoundThrowsError: function (test) {
var command = new tgr();
var fakeSearching = {
findGroupByID: function (a, b) {
return false;
}
};
command.injectSearching(fakeSearching);
test.throws(function() {
command.execute({ }, 1, 'a');
}, 'Group not found for ID', 'An error was thrown when no group found');
test.done();
}
}
};
| Add test around group not being found | Add test around group not being found
| JavaScript | mit | perry-mitchell/buttercup-core,buttercup-pw/buttercup-core,buttercup/buttercup-core,buttercup-pw/buttercup-core,buttercup/buttercup-core,buttercup/buttercup-core,perry-mitchell/buttercup-core | ---
+++
@@ -1,12 +1,22 @@
var tgr = require("__buttercup/classes/commands/command.tgr.js");
-/*
+
module.exports = {
- failMe: {
- failmeplease: function(test) {
- console.log(tgr);
- test.fail();
+ errors: {
+ groupNotFoundThrowsError: function (test) {
+ var command = new tgr();
+
+ var fakeSearching = {
+ findGroupByID: function (a, b) {
+ return false;
+ }
+ };
+
+ command.injectSearching(fakeSearching);
+
+ test.throws(function() {
+ command.execute({ }, 1, 'a');
+ }, 'Group not found for ID', 'An error was thrown when no group found');
test.done();
}
}
};
-*/ |
b86ed23f1b7949ed0bd5dbfe23cb883f9fcbe652 | tests/commands/cmmTests.js | tests/commands/cmmTests.js | var cmm = require("__buttercup/classes/commands/command.cmm.js");
module.exports = {
setUp: function(cb) {
this.command = new cmm();
(cb)();
},
callbackInjected: {
callsToCallback: function(test) {
var callbackCalled = false;
var callback = function(comment) {
callbackCalled = true;
};
this.command.injectCommentCallback(callback);
this.command.execute({}, "");
test.strictEqual(callbackCalled, true, "Calls into callback");
test.done();
}
}
};
| var cmm = require("__buttercup/classes/commands/command.cmm.js");
module.exports = {
setUp: function(cb) {
this.command = new cmm();
(cb)();
},
callbackInjected: {
callsToCallback: function(test) {
var callbackCalled = false;
var callback = function(comment) {
callbackCalled = true;
};
this.command.injectCommentCallback(callback);
this.command.execute({}, "");
test.strictEqual(callbackCalled, true, "Calls into callback");
test.done();
},
callsToCallbackWithCommentTestCaseOne: function(test) {
var providedComment = "I am the first test case";
var callbackCalled = false;
var callback = function(comment) {
if (comment === providedComment) {
callbackCalled = true;
}
};
this.command.injectCommentCallback(callback);
this.command.execute({}, providedComment);
test.strictEqual(callbackCalled, true, "Calls into callback with correct comment (test case one)");
test.done();
}
}
};
| Test that the comment is correct (test case one) | Test that the comment is correct (test case one)
| JavaScript | mit | perry-mitchell/buttercup-core,buttercup/buttercup-core,buttercup-pw/buttercup-core,buttercup/buttercup-core,perry-mitchell/buttercup-core,buttercup/buttercup-core,buttercup-pw/buttercup-core | ---
+++
@@ -18,6 +18,23 @@
test.strictEqual(callbackCalled, true, "Calls into callback");
test.done();
+ },
+
+ callsToCallbackWithCommentTestCaseOne: function(test) {
+ var providedComment = "I am the first test case";
+
+ var callbackCalled = false;
+ var callback = function(comment) {
+ if (comment === providedComment) {
+ callbackCalled = true;
+ }
+ };
+
+ this.command.injectCommentCallback(callback);
+ this.command.execute({}, providedComment);
+
+ test.strictEqual(callbackCalled, true, "Calls into callback with correct comment (test case one)");
+ test.done();
}
}
}; |
efd1f74fd489f016323f8cf205fcdf7289e610ce | tests/helpers/start-app.js | tests/helpers/start-app.js | import Ember from 'ember';
import Application from '../../app';
import config from '../../config/environment';
export default function startApp(attrs) {
let application;
// use defaults, but you can override
let attributes = Ember.assign({}, config.APP, attrs);
Ember.run(() => {
application = Application.create(attributes);
application.setupForTesting();
application.injectTestHelpers();
});
return application;
}
| import Ember from 'ember';
import Application from '../../app';
import config from '../../config/environment';
export default function startApp(attrs) {
let application;
let attributes = Ember.merge({}, config.APP);
attributes = Ember.merge(attributes, attrs); // use defaults, but you can override
Ember.run(() => {
application = Application.create(attributes);
application.setupForTesting();
application.injectTestHelpers();
});
return application;
}
| Revert assign for 2.4 failures | Revert assign for 2.4 failures
| JavaScript | mit | thoov/ember-websockets,thoov/ember-websockets | ---
+++
@@ -5,8 +5,8 @@
export default function startApp(attrs) {
let application;
- // use defaults, but you can override
- let attributes = Ember.assign({}, config.APP, attrs);
+ let attributes = Ember.merge({}, config.APP);
+ attributes = Ember.merge(attributes, attrs); // use defaults, but you can override
Ember.run(() => {
application = Application.create(attributes); |
d9f20891fe1f8a3af1558613b4f27c3c3c412913 | contribs/gmf/apps/appmodule.js | contribs/gmf/apps/appmodule.js | /**
* This file provides the "app" namespace, which is the
* application's main namespace. And it defines the application's Angular
* module.
*/
goog.provide('app');
goog.require('gmf');
/**
* @type {!angular.Module}
*/
app.module = angular.module('app', [gmf.module.name]);
| /**
* This file provides the "app" namespace, which is the
* application's main namespace. And it defines the application's Angular
* module.
*/
goog.provide('app');
goog.require('gmf');
goog.require('goog.Uri');
/**
* @type {!angular.Module}
*/
app.module = angular.module('app', [gmf.module.name]);
app.module.config(['$compileProvider', function($compileProvider) {
var uri = goog.Uri.parse(location);
if (!uri.getQueryData().containsKey('debug')) {
// Disable the debug info
$compileProvider.debugInfoEnabled(false);
}
}]);
| Remove debug information when we are not in debug mode | Remove debug information when we are not in debug mode
| JavaScript | mit | kalbermattenm/ngeo,Jenselme/ngeo,kalbermattenm/ngeo,adube/ngeo,adube/ngeo,Jenselme/ngeo,ger-benjamin/ngeo,ger-benjamin/ngeo,camptocamp/ngeo,camptocamp/ngeo,pgiraud/ngeo,camptocamp/ngeo,adube/ngeo,Jenselme/ngeo,camptocamp/ngeo,pgiraud/ngeo,kalbermattenm/ngeo,pgiraud/ngeo,Jenselme/ngeo,camptocamp/ngeo,adube/ngeo,ger-benjamin/ngeo | ---
+++
@@ -6,9 +6,18 @@
goog.provide('app');
goog.require('gmf');
+goog.require('goog.Uri');
/**
* @type {!angular.Module}
*/
app.module = angular.module('app', [gmf.module.name]);
+
+app.module.config(['$compileProvider', function($compileProvider) {
+ var uri = goog.Uri.parse(location);
+ if (!uri.getQueryData().containsKey('debug')) {
+ // Disable the debug info
+ $compileProvider.debugInfoEnabled(false);
+ }
+}]); |
bf7420c9c60c3124d5fa096c79a5b5b13e011032 | src/component/utils/DraftDOMTypes.js | src/component/utils/DraftDOMTypes.js | /**
* (c) Facebook, Inc. and its affiliates. Confidential and proprietary.
*
* Types for things in the DOM used in Draft.js. These should eventaully be
* added to the flow DOM lib itself.
*
* @emails oncall+draft_js
* @flow strict
* @format
*/
'use strict';
// https://developer.mozilla.org/en-US/docs/Web/API/Selection
export type SelectionObject = {
/**
* Returns the Node in which the selection begins. Can return null if
* selection never existed in the document (e.g., an iframe that was
* never clicked on). */
anchorNode: ?Node,
anchorOffset: number,
focusNode: ?Node,
focusOffset: number,
isCollapsed: boolean,
rangeCount: number,
type: string,
removeAllRanges(): void,
getRangeAt: (index: number) => Range,
extend?: (node: Node, offset?: number) => void,
addRange: (range: Range) => void,
// ...etc. This is a non-exhaustive definition.
};
| /**
* (c) Meta Platforms, Inc. and affiliates. Confidential and proprietary.
*
* Types for things in the DOM used in Draft.js. These should eventaully be
* added to the flow DOM lib itself.
*
* @emails oncall+draft_js
* @flow strict
* @format
*/
'use strict';
// https://developer.mozilla.org/en-US/docs/Web/API/Selection
export type SelectionObject = {
/**
* Returns the Node in which the selection begins. Can return null if
* selection never existed in the document (e.g., an iframe that was
* never clicked on). */
anchorNode: ?Node,
anchorOffset: number,
focusNode: ?Node,
focusOffset: number,
isCollapsed: boolean,
rangeCount: number,
type: string,
removeAllRanges(): void,
getRangeAt: (index: number) => Range,
extend?: (node: Node, offset?: number) => void,
addRange: (range: Range) => void,
// ...etc. This is a non-exhaustive definition.
};
| Update copyright comments in JS files (part 13) | Update copyright comments in JS files (part 13)
Reviewed By: bhamodi
Differential Revision: D32686335
fbshipit-source-id: a0b6f1b26ff95ebe642625109aad34329b4ed7d7
| JavaScript | mit | facebook/draft-js | ---
+++
@@ -1,5 +1,5 @@
/**
- * (c) Facebook, Inc. and its affiliates. Confidential and proprietary.
+ * (c) Meta Platforms, Inc. and affiliates. Confidential and proprietary.
*
* Types for things in the DOM used in Draft.js. These should eventaully be
* added to the flow DOM lib itself. |
db288cfa6cf660c58e0228ba2271dd4fcf7243be | blueprints/app/files/.eslintrc.js | blueprints/app/files/.eslintrc.js | module.exports = {
root: true,
parserOptions: {
ecmaVersion: 6,
sourceType: 'module'
},
extends: 'eslint:recommended',
env: {
browser: true
},
rules: {
}
};
| module.exports = {
root: true,
parserOptions: {
ecmaVersion: 2017,
sourceType: 'module'
},
extends: 'eslint:recommended',
env: {
browser: true
},
rules: {
}
};
| Configure ESLint to parse ES2017 by default | Configure ESLint to parse ES2017 by default | JavaScript | mit | akatov/ember-cli,pzuraq/ember-cli,buschtoens/ember-cli,kategengler/ember-cli,cibernox/ember-cli,fpauser/ember-cli,romulomachado/ember-cli,gfvcastro/ember-cli,balinterdi/ember-cli,kellyselden/ember-cli,trentmwillis/ember-cli,HeroicEric/ember-cli,kanongil/ember-cli,jrjohnson/ember-cli,twokul/ember-cli,Turbo87/ember-cli,elwayman02/ember-cli,patocallaghan/ember-cli,twokul/ember-cli,trentmwillis/ember-cli,balinterdi/ember-cli,thoov/ember-cli,ember-cli/ember-cli,gfvcastro/ember-cli,patocallaghan/ember-cli,jgwhite/ember-cli,Turbo87/ember-cli,trentmwillis/ember-cli,fpauser/ember-cli,ef4/ember-cli,calderas/ember-cli,ef4/ember-cli,calderas/ember-cli,jgwhite/ember-cli,romulomachado/ember-cli,cibernox/ember-cli,mike-north/ember-cli,kanongil/ember-cli,thoov/ember-cli,ef4/ember-cli,pzuraq/ember-cli,rtablada/ember-cli,rtablada/ember-cli,kanongil/ember-cli,ef4/ember-cli,trentmwillis/ember-cli,Turbo87/ember-cli,elwayman02/ember-cli,calderas/ember-cli,akatov/ember-cli,akatov/ember-cli,mike-north/ember-cli,HeroicEric/ember-cli,kategengler/ember-cli,jrjohnson/ember-cli,twokul/ember-cli,buschtoens/ember-cli,akatov/ember-cli,raycohen/ember-cli,twokul/ember-cli,jgwhite/ember-cli,sivakumar-kailasam/ember-cli,fpauser/ember-cli,kellyselden/ember-cli,gfvcastro/ember-cli,rtablada/ember-cli,thoov/ember-cli,cibernox/ember-cli,kellyselden/ember-cli,fpauser/ember-cli,asakusuma/ember-cli,thoov/ember-cli,sivakumar-kailasam/ember-cli,HeroicEric/ember-cli,sivakumar-kailasam/ember-cli,gfvcastro/ember-cli,romulomachado/ember-cli,pzuraq/ember-cli,Turbo87/ember-cli,kanongil/ember-cli,kellyselden/ember-cli,patocallaghan/ember-cli,jgwhite/ember-cli,ember-cli/ember-cli,ember-cli/ember-cli,patocallaghan/ember-cli,mike-north/ember-cli,cibernox/ember-cli,pzuraq/ember-cli,rtablada/ember-cli,mike-north/ember-cli,romulomachado/ember-cli,HeroicEric/ember-cli,asakusuma/ember-cli,calderas/ember-cli,sivakumar-kailasam/ember-cli,raycohen/ember-cli | ---
+++
@@ -1,7 +1,7 @@
module.exports = {
root: true,
parserOptions: {
- ecmaVersion: 6,
+ ecmaVersion: 2017,
sourceType: 'module'
},
extends: 'eslint:recommended', |
dd18d0bd88cca645e6273d87a8dd48a05a76e6ab | src/components/Header/Header.test.js | src/components/Header/Header.test.js | import React from 'react';
import { shallow } from 'enzyme';
import Header from './Header';
describe('Component: Header', () => {
const props = {};
it('renders without crashing', () => {
expect(shallow(<Header {...props} />)).toHaveLength(1);
});
it('Add event form is closed by default', () => {
const header = shallow(<Header {...props} />);
const modalContainer1 = header.find('#modal-container');
const modalContainerDisplay1 = modalContainer1.node.props.style.display;
expect(modalContainerDisplay1).toBe('none');
header.setState({ addEventModalOpen: true });
const modalContainer2 = header.find('#modal-container');
const modalContainerDisplay2 = modalContainer2.node.props.style.display;
expect(modalContainerDisplay2).toBe('block');
});
it('Add event form is managed by state', () => {
const header = shallow(<Header {...props} />);
header.setState({ addEventModalOpen: true });
expect(header.find('AddEvent')).toHaveLength(1);
});
});
| import React from 'react';
import { shallow, mount } from 'enzyme';
import { MemoryRouter } from 'react-router';
import Header from './Header';
describe('Component: Header', () => {
const props = {};
it('renders without crashing', () => {
expect(shallow(<Header {...props} />)).toHaveLength(1);
});
it('Add event form is closed by default', () => {
const header = mount(<MemoryRouter><Header {...props} /></MemoryRouter>);
expect(header.find('#modal-container').length).toBe(0);
expect(header.find('AddEvent')).toHaveLength(0);
header.find("button").simulate('click')
expect(header.find('#modal-container').length).toBe(1);
expect(header.find('AddEvent')).toHaveLength(1);
});
});
| Fix Header Tests - now need to be wrapped in a router | Fix Header Tests - now need to be wrapped in a router
| JavaScript | mit | ResistanceCalendar/resistance-calendar-frontend,dorono/resistance-calendar-frontend,dorono/resistance-calendar-frontend,ResistanceCalendar/resistance-calendar-frontend | ---
+++
@@ -1,6 +1,6 @@
import React from 'react';
-import { shallow } from 'enzyme';
-
+import { shallow, mount } from 'enzyme';
+import { MemoryRouter } from 'react-router';
import Header from './Header';
describe('Component: Header', () => {
@@ -11,26 +11,14 @@
});
it('Add event form is closed by default', () => {
- const header = shallow(<Header {...props} />);
+ const header = mount(<MemoryRouter><Header {...props} /></MemoryRouter>);
- const modalContainer1 = header.find('#modal-container');
- const modalContainerDisplay1 = modalContainer1.node.props.style.display;
+ expect(header.find('#modal-container').length).toBe(0);
+ expect(header.find('AddEvent')).toHaveLength(0);
- expect(modalContainerDisplay1).toBe('none');
+ header.find("button").simulate('click')
- header.setState({ addEventModalOpen: true });
-
- const modalContainer2 = header.find('#modal-container');
- const modalContainerDisplay2 = modalContainer2.node.props.style.display;
-
- expect(modalContainerDisplay2).toBe('block');
- });
-
- it('Add event form is managed by state', () => {
- const header = shallow(<Header {...props} />);
-
- header.setState({ addEventModalOpen: true });
-
+ expect(header.find('#modal-container').length).toBe(1);
expect(header.find('AddEvent')).toHaveLength(1);
});
}); |
cf7df05d1cf5559a43d76491643686316ab3b121 | app.js | app.js | import express from 'express';
import logger from 'morgan';
import bodyParser from 'body-parser';
import passport from 'passport';
import http from 'http';
import routes from './server/routes';
import models from './server/models';
const app = express();
const port = parseInt(process.env.PORT, 10) || 8080;
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(passport.initialize());
app.use(passport.session());
routes(app);
const server = http.createServer(app);
server.listen(port, () => console.log('The server is running on port 8080'));
module.exports = server;
| import express from 'express';
import logger from 'morgan';
import bodyParser from 'body-parser';
import passport from 'passport';
import http from 'http';
import routes from './server/routes';
import models from './server/models';
models.sequelize.sync();
const app = express();
const port = parseInt(process.env.PORT, 10) || 8080;
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(passport.initialize());
app.use(passport.session());
routes(app);
const server = http.createServer(app);
server.listen(port, () => console.log('The server is running on port 8080'));
module.exports = server;
| Synchronize tables not yet in the database | Synchronize tables not yet in the database
| JavaScript | mit | 3m3kalionel/PostIt,3m3kalionel/PostIt | ---
+++
@@ -5,6 +5,8 @@
import http from 'http';
import routes from './server/routes';
import models from './server/models';
+
+models.sequelize.sync();
const app = express();
const port = parseInt(process.env.PORT, 10) || 8080; |
982f13ed0531ad77a4760d9a2fdd70f5f31b0c79 | app.js | app.js | var express = require('express'),
bodyParser = require('body-parser'),
app = express(),
server = require('http').Server(app),
router = express.Router(),
request = require('request'),
config = require('./config/config');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use('/', router);
server.listen(config.port, config.host);
router.post('/', function(req, res) {
if (req.body.token === config.slackToken) {
var payload = {};
req.body.text.split("--").forEach(function(i) {
if (/message=(.*)/.test(i)) payload.message = i.match(/message=(.*)/)[1].trim();
else if (/wb=(.*)/.test(i)) payload.wb = i.match(/wb=(.*)/)[1].trim();
});
if (payload.message) {
request.post({url:config.wbAPI + '/api/v1/event', form: payload}, function(err){
if (!err) res.json({text: "ok"});
});
} else {
res.json({text: "No message supplied!"});
}
} else {
res.json({text: "Access denied"});
}
});
| var express = require('express'),
bodyParser = require('body-parser'),
app = express(),
server = require('http').Server(app),
router = express.Router(),
request = require('request'),
config = require('./config/config');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use('/', router);
server.listen(config.port, config.host);
router.post('/', function(req, res) {
if (req.body.token === config.slackToken) {
var payload = {};
var text = req.body.text;
text.split("--").forEach(function(i) {
if (/message=(.*)/.test(i)) payload.message = i.match(/message=(.*)/)[1].trim();
else if (/wb=(.*)/.test(i)) payload.wb = i.match(/wb=(.*)/)[1].trim();
});
if (!payload.message) {
if (/wb-event ([a-zA-Z0-9].*)/.test(text)) payload.message = text.match(/message=(.*)/)[1].trim();
else res.json({text: "No message supplied!"});
} else {
request.post({url:config.wbAPI + '/api/v1/event', form: payload}, function(err){
if (!err) res.json({text: "ok"});
});
}
} else {
res.json({text: "Access denied"});
}
});
| Simplify event command for single message parameter | Simplify event command for single message parameter
| JavaScript | mit | hjamesw93/wallboarder-slack-event | ---
+++
@@ -16,17 +16,20 @@
if (req.body.token === config.slackToken) {
var payload = {};
- req.body.text.split("--").forEach(function(i) {
+ var text = req.body.text;
+
+ text.split("--").forEach(function(i) {
if (/message=(.*)/.test(i)) payload.message = i.match(/message=(.*)/)[1].trim();
else if (/wb=(.*)/.test(i)) payload.wb = i.match(/wb=(.*)/)[1].trim();
});
- if (payload.message) {
+ if (!payload.message) {
+ if (/wb-event ([a-zA-Z0-9].*)/.test(text)) payload.message = text.match(/message=(.*)/)[1].trim();
+ else res.json({text: "No message supplied!"});
+ } else {
request.post({url:config.wbAPI + '/api/v1/event', form: payload}, function(err){
if (!err) res.json({text: "ok"});
});
- } else {
- res.json({text: "No message supplied!"});
}
} else {
res.json({text: "Access denied"}); |
0f111be9c52fcac4df8e2fbc983fed87754716c7 | app.js | app.js | require('./config/config');
var express = require('express'),
app = express(),
DockerRemote = require(__services + 'docker_remote');
app.get('/', function(req, res){
// DockerRemote.stats('999f3c428c18').then(function(stats){
// console.log(stats);
// });
DockerRemote.containers().then(function(containers){
console.log(containers);
});
res.send('hello world');
});
app.listen(3000);
console.log('Server listening on port 3000');
| require('./config/config');
var express = require('express'),
app = express(),
DockerRemote = require(__services + 'docker_remote');
app.get('/containers', function(req, res){
DockerRemote.containers().then(function(containers){
res.json(containers);
});
});
app.get('/containers/:id/stats', function(req, res){
if(req.params.id === undefined || req.params.id === null) {
res.status(500).json({ error: 'container id missing' });
} else {
DockerRemote.stats(req.params.id).then(function(stats){
res.json(stats);
});
}
});
app.listen(3000);
console.log('Server listening on port 3000');
| Create routes endpoints for stats and containers list | Create routes endpoints for stats and containers list
| JavaScript | mit | davidcunha/wharf,davidcunha/wharf | ---
+++
@@ -4,16 +4,20 @@
app = express(),
DockerRemote = require(__services + 'docker_remote');
-app.get('/', function(req, res){
- // DockerRemote.stats('999f3c428c18').then(function(stats){
- // console.log(stats);
- // });
+app.get('/containers', function(req, res){
+ DockerRemote.containers().then(function(containers){
+ res.json(containers);
+ });
+});
- DockerRemote.containers().then(function(containers){
- console.log(containers);
- });
-
- res.send('hello world');
+app.get('/containers/:id/stats', function(req, res){
+ if(req.params.id === undefined || req.params.id === null) {
+ res.status(500).json({ error: 'container id missing' });
+ } else {
+ DockerRemote.stats(req.params.id).then(function(stats){
+ res.json(stats);
+ });
+ }
});
app.listen(3000); |
cc98ff7f0b9a4dff9d0c40ffa49afb4c1593927a | lib/db.js | lib/db.js | const mongoose = require('mongoose');
mongoose.connect('localhost', 'muffin');
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'Connection error:'));
module.exports = db;
| const mongoose = require('mongoose');
mongoose.connect('localhost', 'muffin');
const db = mongoose.connection;
db.on('error', function(message) {
console.error('Couldn\'t connect to DB: ' + message );
process.kill(0);
});
module.exports = db;
| Kill process if DB not reachable | Kill process if DB not reachable
| JavaScript | mit | muffin/server,kunni80/server | ---
+++
@@ -1,8 +1,11 @@
const mongoose = require('mongoose');
mongoose.connect('localhost', 'muffin');
+const db = mongoose.connection;
-const db = mongoose.connection;
-db.on('error', console.error.bind(console, 'Connection error:'));
+db.on('error', function(message) {
+ console.error('Couldn\'t connect to DB: ' + message );
+ process.kill(0);
+});
module.exports = db; |
17b4a496321c91bfd428c694c0735d1ad91da0e4 | leaderboard.js | leaderboard.js | const LEADERBOARD_SIZE = 10;
class leaderboard {
constructor () {
this.db = fbApp.database();
}
refreshScores (callback) {
this.db.ref('leaderboard').orderByValue().limitToLast(LEADERBOARD_SIZE).once('value', (snapshot) => {
var board = [];
snapshot.forEach((data) => {
board.push({user: data.key, score: data.val()});
});
board.reverse();
callback(board);
});
}
updateScore (username, score) {
this.db.ref('leaderboard/' + username).on('value', (snapshot) => {
this.db.ref('leaderboard/' + username).set(Math.max(score, snapshot.val()));
});
}
updatePassedLevel (username, levelNumber) {
this.db.ref('passedLevels/' + username + '/' + levelNumber.toString()).set(1);
}
getPassedLevels (username, callback) {
this.db.ref('passedLevels/' + username + '/').orderByKey().once('value', (snapshot) => {
var levels = [];
snapshot.forEach((data) => {
levels.push(data.key * 1);
});
callback(levels);
});
}
} | const LEADERBOARD_SIZE = 10;
class Leaderboard {
constructor () {
this.db = fbApp.database();
}
refreshScores (callback) {
this.db.ref('leaderboard').orderByValue().limitToLast(LEADERBOARD_SIZE).once('value', (snapshot) => {
var board = [];
snapshot.forEach((data) => {
board.push({user: data.key, score: data.val()});
});
board.reverse();
callback(board);
});
}
updateScore (username, score) {
this.db.ref('leaderboard/' + username).on('value', (snapshot) => {
this.db.ref('leaderboard/' + username).set(Math.max(score, snapshot.val()));
});
}
updatePassedLevel (username, levelNumber) {
this.db.ref('passedLevels/' + username + '/' + levelNumber.toString()).set(1);
}
getPassedLevels (username, callback) {
this.db.ref('passedLevels/' + username + '/').orderByKey().once('value', (snapshot) => {
var levels = [];
snapshot.forEach((data) => {
levels.push(data.key * 1);
});
callback(levels);
});
}
getUserInfo (username, callback) {
this.getPassedLevels(username, (levels) => {
this.db.ref('leaderboard/' + username).on('value', (snapshot) => {
callback({score: snapshot.val(), levels: levels});
});
})
}
} | Add userinfo getter, fix typo in class name | [LEADERBOARD/USERDATA] Add userinfo getter, fix typo in class name
| JavaScript | mit | BecauseWeCanStudios/dots-connect,BecauseWeCanStudios/dots-connect | ---
+++
@@ -1,6 +1,6 @@
const LEADERBOARD_SIZE = 10;
-class leaderboard {
+class Leaderboard {
constructor () {
this.db = fbApp.database();
@@ -37,4 +37,12 @@
});
}
+ getUserInfo (username, callback) {
+ this.getPassedLevels(username, (levels) => {
+ this.db.ref('leaderboard/' + username).on('value', (snapshot) => {
+ callback({score: snapshot.val(), levels: levels});
+ });
+ })
+ }
+
} |
dd7d7b3de7231cc86fef4a3395fe8957e3ff9d38 | cypress/integration/sample_spec.js | cypress/integration/sample_spec.js | describe('Mini test', function() {
it('should work', function () {
cy.visit("https://lga-1543-install-and-integra.staging.checklegalaid.service.gov.uk/start")
cy.contains('Choose the area you most need help with')
cy.contains('Debt').click()
cy.contains('Choose the option that best describes your debt problem')
cy.get(':nth-child(1) > .cla-scope-options-list-item-link').click()
cy.contains('Legal aid is available for this type of problem')
cy.contains('Check if you qualify financially').click()
// About you page form
cy.setRadioInput('have_partner', 'Yes')
cy.setRadioInput('in_dispute', 'No') // Depends on have_partner being set to 'Yes'
cy.setRadioInput('on_benefits', 'Yes')
cy.setRadioInput('have_children')
cy.setRadioInput('have_dependants')
cy.setRadioInput('own_property')
cy.setRadioInput('is_employed')
cy.setRadioInput('is_self_employed')
cy.setRadioInput('aged_60_or_over')
cy.setRadioInput('have_savings')
cy.setRadioInput('have_valuables')
// cy.get("#submit-button").click();
});
})
| describe('Mini test', function() {
it('should work', function () {
cy.visit("https://lga-1543-install-and-integra.staging.checklegalaid.service.gov.uk/start")
cy.contains('Choose the area you most need help with')
cy.contains('Debt').click()
cy.contains('Choose the option that best describes your debt problem')
cy.get(':nth-child(1) > .cla-scope-options-list-item-link').click()
cy.contains('Legal aid is available for this type of problem')
cy.contains('Check if you qualify financially').click()
// About you form
cy.setRadioInput('have_partner', 'No')
cy.setRadioInput('on_benefits', 'Yes')
cy.setRadioInput('have_children', 'Yes')
cy.setTextInput('num_children', '4')
cy.setRadioInput('have_dependants', 'No')
cy.setRadioInput('own_property', 'Yes')
cy.setRadioInput('is_employed', 'No')
cy.setRadioInput('is_self_employed', 'No')
cy.setRadioInput('aged_60_or_over', 'No')
cy.setRadioInput('have_savings', 'Yes')
cy.setRadioInput('have_valuables', 'No')
cy.get("#submit-button").click();
});
})
| Complete happy path for About You form | Complete happy path for About You form | JavaScript | mit | ministryofjustice/cla_public,ministryofjustice/cla_public,ministryofjustice/cla_public,ministryofjustice/cla_public | ---
+++
@@ -11,20 +11,21 @@
cy.contains('Legal aid is available for this type of problem')
cy.contains('Check if you qualify financially').click()
- // About you page form
- cy.setRadioInput('have_partner', 'Yes')
- cy.setRadioInput('in_dispute', 'No') // Depends on have_partner being set to 'Yes'
+ // About you form
+ cy.setRadioInput('have_partner', 'No')
cy.setRadioInput('on_benefits', 'Yes')
- cy.setRadioInput('have_children')
- cy.setRadioInput('have_dependants')
- cy.setRadioInput('own_property')
- cy.setRadioInput('is_employed')
- cy.setRadioInput('is_self_employed')
- cy.setRadioInput('aged_60_or_over')
- cy.setRadioInput('have_savings')
- cy.setRadioInput('have_valuables')
+ cy.setRadioInput('have_children', 'Yes')
+ cy.setTextInput('num_children', '4')
+ cy.setRadioInput('have_dependants', 'No')
+ cy.setRadioInput('own_property', 'Yes')
+ cy.setRadioInput('is_employed', 'No')
+ cy.setRadioInput('is_self_employed', 'No')
+ cy.setRadioInput('aged_60_or_over', 'No')
+ cy.setRadioInput('have_savings', 'Yes')
+ cy.setRadioInput('have_valuables', 'No')
+ cy.get("#submit-button").click();
- // cy.get("#submit-button").click();
+
});
}) |
1c380d16f4a446c856a6c90c4209081c1ac0047c | bin/github-backup.js | bin/github-backup.js | "use strict";
var backup = require("../lib/backup");
function main(argv) {
var args = argv.slice(2);
if (args.length !== 2) {
console.error("Usage: github-backup username path");
process.exit(-1);
}
backup.publicUserRepos(args[0], args[1]).catch(function(err) {
console.error("Unhandled error:", err);
}).done();
}
main(process.argv);
| #!/usr/bin/env node
"use strict";
var backup = require("../lib/backup");
function main(argv) {
var args = argv.slice(2);
if (args.length !== 2) {
console.error("Usage: github-backup username path");
process.exit(-1);
}
backup.publicUserRepos(args[0], args[1]).catch(function(err) {
console.error("Unhandled error:", err);
}).done();
}
main(process.argv);
| Add hashbang so command line works. | Add hashbang so command line works.
| JavaScript | mit | ericlathrop/github-backup | ---
+++
@@ -1,3 +1,4 @@
+#!/usr/bin/env node
"use strict";
var backup = require("../lib/backup"); |
32c6bd3a692f093cd772003f56a97b5ebba687bb | lib/local-db.js | lib/local-db.js | module.exports = function(configLocalDb) {
var childProcess = require('child_process');
function isoDate() {
return (new Date()).toISOString().slice(0, 16).replace(/T|:/g, '-');
}
function dumpLocalDB() {
var localDumpDir = 'syncdb/sql';
var localDumpName = 'local-db-' + isoDate() + '.sql';
var localDumpFile = localDumpDir + '/' + localDumpName;
var localDump = 'mysqldump -u ' + configLocalDb.user
+ ' -p' + configLocalDb.password + ' ' + configLocalDb.name
+ ' > ' + localDumpFile;
if (childProcess.spawnSync(localDump).status !== 0) {
console.log('dump failed');
process.exit(1);
}
return localDumpFile;
}
function populateLocalDB(dumpFile) {
var localPopulate = 'mysql -u ' + configLocalDb.user
+ ' -p' + configLocalDb.password + ' ' + configLocalDb.name
+ ' < ' + dumpFile;
if (childProcess.spawnSync(localPopulate).status !== 0) {
console.log('populating failed');
process.exit(1);
}
}
return {
dump: dumpLocalDB,
populate: populateLocalDB
};
}
| module.exports = function(configLocalDb) {
var childProcess = require('child_process');
var fs = require('fs');
function isoDate() {
return (new Date()).toISOString().slice(0, 16).replace(/T|:/g, '-');
}
function dumpLocalDB(callback) {
var localDumpDir = 'syncdb/sql';
var localDumpName = 'local-db-' + isoDate() + '.sql';
var localDumpFile = localDumpDir + '/' + localDumpName;
var mysqldump = childProcess.spawn('mysqldump', [
'-u', configLocalDb.user,
'-p' + configLocalDb.password, // sic, password is attached w/o space!
configLocalDb.name
]);
mysqldump.on('close', function(code) {
if (code !== 0) {
callback(new Error('Local mysqldump failed!'));
} else {
callback();
}
});
mysqldump.stdout.pipe(fs.createWriteStream(localDumpFile));
}
function populateLocalDB(dumpFile, callback) {
var mysql = childProcess.spawn('mysql', [
'-u', configLocalDb.user,
'-p' + configLocalDb.password,
configLocalDb.name
]);
mysql.on('close', function(code) {
if (code !== 0) {
callback(new Error('Local database population failed!'));
} else {
callback();
}
});
fs.createReadStream(dumpFile).pipe(mysql.stdin);
}
return {
dump: dumpLocalDB,
populate: populateLocalDB
};
}
| Use asynchronous child_process and fs apis | Use asynchronous child_process and fs apis
so that we don’t have to exit the process from this module;
instead, take callbacks and call them with errors like good
javascript hackers do.
| JavaScript | isc | wolfgangschoeffel/syncdb,wolfgangschoeffel/syncdb | ---
+++
@@ -1,36 +1,53 @@
module.exports = function(configLocalDb) {
var childProcess = require('child_process');
+ var fs = require('fs');
function isoDate() {
+
return (new Date()).toISOString().slice(0, 16).replace(/T|:/g, '-');
}
- function dumpLocalDB() {
+ function dumpLocalDB(callback) {
+
var localDumpDir = 'syncdb/sql';
var localDumpName = 'local-db-' + isoDate() + '.sql';
var localDumpFile = localDumpDir + '/' + localDumpName;
- var localDump = 'mysqldump -u ' + configLocalDb.user
- + ' -p' + configLocalDb.password + ' ' + configLocalDb.name
- + ' > ' + localDumpFile;
- if (childProcess.spawnSync(localDump).status !== 0) {
- console.log('dump failed');
- process.exit(1);
- }
+ var mysqldump = childProcess.spawn('mysqldump', [
+ '-u', configLocalDb.user,
+ '-p' + configLocalDb.password, // sic, password is attached w/o space!
+ configLocalDb.name
+ ]);
- return localDumpFile;
+ mysqldump.on('close', function(code) {
+ if (code !== 0) {
+ callback(new Error('Local mysqldump failed!'));
+ } else {
+ callback();
+ }
+ });
+
+ mysqldump.stdout.pipe(fs.createWriteStream(localDumpFile));
}
- function populateLocalDB(dumpFile) {
- var localPopulate = 'mysql -u ' + configLocalDb.user
- + ' -p' + configLocalDb.password + ' ' + configLocalDb.name
- + ' < ' + dumpFile;
+ function populateLocalDB(dumpFile, callback) {
- if (childProcess.spawnSync(localPopulate).status !== 0) {
- console.log('populating failed');
- process.exit(1);
- }
+ var mysql = childProcess.spawn('mysql', [
+ '-u', configLocalDb.user,
+ '-p' + configLocalDb.password,
+ configLocalDb.name
+ ]);
+
+ mysql.on('close', function(code) {
+ if (code !== 0) {
+ callback(new Error('Local database population failed!'));
+ } else {
+ callback();
+ }
+ });
+
+ fs.createReadStream(dumpFile).pipe(mysql.stdin);
}
return { |
40b68377716852e3cff5b0b248c168def9e8f410 | lib/markdown.js | lib/markdown.js | import unified from 'unified';
import parse from 'remark-parse';
import remark2react from 'remark-react';
export function convertMarkdownToReact(markdown) {
const content = unified()
.use(parse)
.use(remark2react)
.processSync(markdown).result;
return content;
} | import unified from 'unified';
import parse from 'remark-parse';
import remark2react from 'remark-react';
import CodeSnippet from '../components/CodeSnippet';
export function convertMarkdownToReact(markdown) {
const content = unified()
.use(parse)
.use(remark2react, {
remarkReactComponents: {
pre: CodeSnippet,
},
})
.processSync(markdown).result;
return content;
} | Add code snippets with copy to clipboard | Add code snippets with copy to clipboard
| JavaScript | mit | dracula/dracula.github.io | ---
+++
@@ -1,11 +1,16 @@
import unified from 'unified';
import parse from 'remark-parse';
import remark2react from 'remark-react';
+import CodeSnippet from '../components/CodeSnippet';
export function convertMarkdownToReact(markdown) {
const content = unified()
.use(parse)
- .use(remark2react)
+ .use(remark2react, {
+ remarkReactComponents: {
+ pre: CodeSnippet,
+ },
+ })
.processSync(markdown).result;
return content; |
b54cc4400e8c450e502a735af831db6fbe8a9b65 | lib/readfile.js | lib/readfile.js | var path = require('path');
var yaml = require('js-yaml');
var fs = require('fs');
module.exports = function(file) {
// check for existence first
if (!fs.existsSync(file)) {
throw new Error(file + ' doesn\'t exist');
}
var ext = path.extname(file);
// YAML file
if (ext.match(/ya?ml/)) {
var res = fs.readFileSync(file, 'utf8');
return yaml.safeLoad(res);
}
// JS / JSON / CoffeeScript
if (ext.match(/json|js|coffee|ls/)) {
return require(file);
}
// unknown
throw new Error(file + ' is an unsupported filetype');
};
| var path = require('path');
var fs = require('fs');
module.exports = function(file) {
// check for existence first
if (!fs.existsSync(file)) {
throw new Error(file + ' doesn\'t exist');
}
var ext = path.extname(file);
// YAML file
if (ext.match(/ya?ml/)) {
var res = fs.readFileSync(file, 'utf8');
return require('js-yaml').safeLoad(res);
}
// JS / JSON / CoffeeScript
if (ext.match(/json|js|coffee|ls/)) {
return require(file);
}
// unknown
throw new Error(file + ' is an unsupported filetype');
};
| Speed up build time when there are no yaml files | Speed up build time when there are no yaml files
js-yaml module takes a while to load. Moving it inside condition can speed up loading of readfile.js by ~7000 times. | JavaScript | mit | SolomoN-ua/load-grunt-config,firstandthird/load-grunt-config,SolomoN-ua/load-grunt-config,firstandthird/load-grunt-config | ---
+++
@@ -1,5 +1,4 @@
var path = require('path');
-var yaml = require('js-yaml');
var fs = require('fs');
module.exports = function(file) {
@@ -14,7 +13,7 @@
// YAML file
if (ext.match(/ya?ml/)) {
var res = fs.readFileSync(file, 'utf8');
- return yaml.safeLoad(res);
+ return require('js-yaml').safeLoad(res);
}
// JS / JSON / CoffeeScript |
bb83106480c6b5e6cbf521a1b31a442910efe625 | lib/validate.js | lib/validate.js | var fs = require('fs');
exports.directory = function(path) {
var stats;
try {
stats = fs.statSync(path);
} catch (err) {
if (err.code === 'ENOENT') {
throw new Error('No such directory ' + path);
}
}
if (!stats.isDirectory()) {
throw new Error(path + ' is not a directory');
}
};
exports.file = function(path) {
var stats;
try {
stats = fs.statSync(path);
} catch (err) {
if (err.code === 'ENOENT') {
throw new Error('No such file ' + path);
} else {
throw err;
}
}
if (!stats.isFile()) {
throw new Error(path + ' is not a file');
}
};
| var fs = require('fs');
exports.directory = function(path) {
var stats;
try {
stats = fs.statSync(path);
} catch (err) {
if (err.code === 'ENOENT') {
throw new Error('No such directory ' + path);
} else {
throw new Error(err.message);
}
}
if (!stats.isDirectory()) {
throw new Error(path + ' is not a directory');
}
};
exports.file = function(path) {
var stats;
try {
stats = fs.statSync(path);
} catch (err) {
if (err.code === 'ENOENT') {
throw new Error('No such file ' + path);
} else {
throw err;
}
}
if (!stats.isFile()) {
throw new Error(path + ' is not a file');
}
};
| Throw errors that are not ENOENT | Throw errors that are not ENOENT
| JavaScript | mit | vgno/requirejs-module-build | ---
+++
@@ -8,6 +8,8 @@
} catch (err) {
if (err.code === 'ENOENT') {
throw new Error('No such directory ' + path);
+ } else {
+ throw new Error(err.message);
}
}
|
5cba93d251ac38cac14a7665e8454839e1285f01 | routes/index.js | routes/index.js | var express = require('express');
var Global = require('../global');
var search = require('../commands/search');
var router = express.Router();
router.get('/*', function(req, res) {
var response = '';
var arg = req.body.text;
console.log(req.body); //TODO delete
console.log(req.body.token); //TODO delete
//validate token
if(req.body.token === Global.authToken) {
switch(req.body.command) {
case '/searchin':
response = search(arg, res);
break;
default:
res.status('500');
res.json({
text: 'Unknown command'
});
}
} else {
res.status('403');
res.json({
text: 'Invalid token'
});
}
});
router.post('/*', function(req, res) {
res.status('405');
res.json({
text: 'Method not allowed'
});
});
module.exports = router;
| var express = require('express');
var Global = require('../global');
var search = require('../commands/search');
var router = express.Router();
router.get('/*', function(req, res) {
var response = '';
var arg = req.query.text;
console.log(req.query); //TODO delete
console.log(req.query.token); //TODO delete
//validate token
if(req.query.token === Global.authToken) {
switch(req.query.command) {
case '/searchin':
response = search(arg, res);
break;
default:
res.status('500');
res.json({
text: 'Unknown command'
});
}
} else {
res.status('403');
res.json({
text: 'Invalid token'
});
}
});
router.post('/*', function(req, res) {
res.status('405');
res.json({
text: 'Method not allowed'
});
});
module.exports = router;
| Switch back to using query instead of body | Switch back to using query instead of body
| JavaScript | apache-2.0 | woz5999/SlackCommandAPI | ---
+++
@@ -6,12 +6,12 @@
router.get('/*', function(req, res) {
var response = '';
- var arg = req.body.text;
-console.log(req.body); //TODO delete
-console.log(req.body.token); //TODO delete
+ var arg = req.query.text;
+console.log(req.query); //TODO delete
+console.log(req.query.token); //TODO delete
//validate token
- if(req.body.token === Global.authToken) {
- switch(req.body.command) {
+ if(req.query.token === Global.authToken) {
+ switch(req.query.command) {
case '/searchin':
response = search(arg, res);
break; |
b94fb5e74f3408313325113ca95eaf0c19bee2ab | routes/healthchecks.js | routes/healthchecks.js | exports.ping = function ping (req, res) {
return res.send('OK', 200);
}
var package = require('../package.json')
exports.status = function status (req, res) {
return res.json({
status: 'OK',
pid: process.pid,
app: process.title,
uptime: process.uptime(),
version: package.version
}, 200);
}
| exports.ping = function ping (req, res) {
return res.send('OK', 200);
}
var package = require('../package.json')
exports.status = function status (req, res) {
return res.json({
status: 'OK',
pid: process.pid,
app: process.title,
host: process.env.SMF_ZONENAME,
uptime: process.uptime(),
version: package.version
}, 200);
}
| Put the zonename into the healthcheck output | Put the zonename into the healthcheck output
| JavaScript | isc | sundayliu/npm-www,sundayliu/npm-www,sundayliu/npm-www | ---
+++
@@ -9,6 +9,7 @@
status: 'OK',
pid: process.pid,
app: process.title,
+ host: process.env.SMF_ZONENAME,
uptime: process.uptime(),
version: package.version
}, 200); |
c520687f9294b8049b8712b9f6dc2eeea783e4b0 | kurahenPremium.user.js | kurahenPremium.user.js | // ==UserScript==
// @name Kurahen Premium
// @namespace karachan.org
// @version 1.0
// @include http://www.karachan.org/*
// @include http://karachan.org/*
// @exclude http://www.karachan.org/*/src/*
// @exclude http://karachan.org/*/src/*
// ==/UserScript==
(function () {
'use strict';
var KurahenPremium = function () {
};
KurahenPremium.prototype.changeBoardTitle = function (newTitle) {
document.title = newTitle;
document.getElementsByClassName('boardTitle')[0].innerHTML = newTitle;
};
})();
| // ==UserScript==
// @name Kurahen Premium
// @namespace karachan.org
// @version 1.0
// @include http://www.karachan.org/*
// @include http://karachan.org/*
// @exclude http://www.karachan.org/*/src/*
// @exclude http://karachan.org/*/src/*
// ==/UserScript==
(function () {
'use strict';
var KurahenPremium = function () {
};
KurahenPremium.prototype.changeBoardTitle = function (newTitle) {
document.title = newTitle;
document.getElementsByClassName('boardTitle')[0].innerHTML = newTitle;
};
KurahenPremium.prototype.setCookie = function (name, value) {
document.cookie = encodeURIComponent(name) + '=' + encodeURIComponent(value) + '; path=/; max-age=2592000';
};
})();
| Add method for setting cookies | Add method for setting cookies
| JavaScript | mit | Kurahen-Premium/Kurahen-Premium,Kurahen-Premium/Kurahen-Premium,Kurahen-Premium/Kurahen-Premium | ---
+++
@@ -19,4 +19,8 @@
document.getElementsByClassName('boardTitle')[0].innerHTML = newTitle;
};
+ KurahenPremium.prototype.setCookie = function (name, value) {
+ document.cookie = encodeURIComponent(name) + '=' + encodeURIComponent(value) + '; path=/; max-age=2592000';
+ };
+
})(); |
c9eead4bf625425883016d85530eecc0e131e614 | web.js | web.js | var tinymce = require('./index.js');
module.exports = tinymce;
require('./plugins/autoresize/plugin.js');
require('./plugins/table/plugin.js');
require('./plugins/paste/plugin.js');
require('./plugins/noparsing/plugin.js'); | var tinymce = require('./index.js');
module.exports = tinymce;
require('./plugins/autoresize/plugin.js');
require('./plugins/table/plugin.js');
require('./plugins/paste/plugin.js');
require('./plugins/noparsing/plugin.js');
module.exports.shopifyConfig.content_style = `
/**
* Rich Text Editor
* Manages style within the editor iframe
**/
html, body {
cursor: text;
}
body {
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
font-size: 15px;
line-height: 1.5;
margin: 0;
}
h1, h2, h3, h4, h5, h6, p {
margin: 0 0 1em 0;
line-height: 1.4;
}
table {
width: 100%;
}
table, td, th {
border: 1px dashed #CCC;
}
`;
| Add content CSS inline to settings | Add content CSS inline to settings
| JavaScript | lgpl-2.1 | Shopify/tinymce | ---
+++
@@ -5,3 +5,34 @@
require('./plugins/table/plugin.js');
require('./plugins/paste/plugin.js');
require('./plugins/noparsing/plugin.js');
+
+module.exports.shopifyConfig.content_style = `
+/**
+ * Rich Text Editor
+ * Manages style within the editor iframe
+ **/
+
+html, body {
+ cursor: text;
+}
+
+body {
+ font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
+ font-size: 15px;
+ line-height: 1.5;
+ margin: 0;
+}
+
+h1, h2, h3, h4, h5, h6, p {
+ margin: 0 0 1em 0;
+ line-height: 1.4;
+}
+
+table {
+ width: 100%;
+}
+
+table, td, th {
+ border: 1px dashed #CCC;
+}
+`; |
6a4c7c89d8dac192d4375d2745dcadb33abad190 | server/config/paths.js | server/config/paths.js | const http = require('http');
const createPath = filePath => http.resolve(__dirname, '..', filePath);
const paths = {
indexHtml: createPath('server/public/index.html'),
publicDir: createPath('server/public'),
};
module.exports = paths;
| const path = require('path');
const createPath = filePath => path.resolve(__dirname, '..', filePath);
const paths = {
indexHtml: createPath('server/public/index.html'),
publicDir: createPath('server/public'),
};
module.exports = paths;
| Use path module instead of http | Use path module instead of http
| JavaScript | mit | commandzpdx/habit-calendar,commandzpdx/habit-calendar,didju/didju,didju/didju | ---
+++
@@ -1,6 +1,6 @@
-const http = require('http');
+const path = require('path');
-const createPath = filePath => http.resolve(__dirname, '..', filePath);
+const createPath = filePath => path.resolve(__dirname, '..', filePath);
const paths = {
indexHtml: createPath('server/public/index.html'), |
9bc0c2437809c434291b97317fdcf4c628517f0d | server/lib/passport.js | server/lib/passport.js | import passport from 'passport';
import LocalStrategy from 'passport-local';
import {User} from '../models';
import log from './logger';
import settings from '../settings';
passport.serializeUser((user, done) => {
done(null, user._id);
});
passport.deserializeUser((userId, done) => {
User.findById(userId, (err, user) => {
if (err) {
return done(err.message, null);
}
if (!user) {
return done(null, false);
}
done(null, user);
});
});
passport.passportLocal = new LocalStrategy(
{
usernameField: 'email',
passwordField: 'password',
},
(email, password, done) => {
const _email = email.toLowerCase();
User.findOne({email: _email}, (err, user) => {
if (err) { return done(err); }
if (!user) { return done(null, false, { message: 'Unknown user with email ' + _email }); }
user.authenticate(password, (err, ok) => {
if (err) { return done(err); }
if (ok) {
return done(null, user);
}
return done(null, false, { message: 'Invalid password' });
});
});
}
);
passport.use(passport.passportLocal);
export default passport;
| /* eslint no-param-reassign: 0 */
import passport from 'passport';
import LocalStrategy from 'passport-local';
import {User} from '../models';
passport.serializeUser((user, done) => {
done(null, user._id);
});
passport.deserializeUser((userId, done) => {
User.findById(userId, (err, user) => {
if (err) {
return done(err.message, null);
}
if (!user) {
return done(null, false);
}
done(null, user);
});
});
passport.passportLocal = new LocalStrategy(
{
usernameField: 'email',
passwordField: 'password',
},
(email, password, done) => {
email = email.toLowerCase();
User.findOne({email: email}, (err, user) => {
if (err) { return done(err); }
if (!user) { return done(null, false, { message: 'Unknown user with email ' + email }); }
user.authenticate(password, (err, ok) => {
if (err) { return done(err); }
if (ok) {
return done(null, user);
}
return done(null, false, { message: 'Invalid password' });
});
});
}
);
passport.use(passport.passportLocal);
export default passport;
| Allow reassigning to function parameters here | Allow reassigning to function parameters here
Should probably turn this off globally.
| JavaScript | agpl-3.0 | strekmann/samklang,strekmann/samklang | ---
+++
@@ -1,10 +1,9 @@
+/* eslint no-param-reassign: 0 */
+
import passport from 'passport';
import LocalStrategy from 'passport-local';
import {User} from '../models';
-import log from './logger';
-import settings from '../settings';
-
passport.serializeUser((user, done) => {
done(null, user._id);
@@ -28,11 +27,11 @@
passwordField: 'password',
},
(email, password, done) => {
- const _email = email.toLowerCase();
+ email = email.toLowerCase();
- User.findOne({email: _email}, (err, user) => {
+ User.findOne({email: email}, (err, user) => {
if (err) { return done(err); }
- if (!user) { return done(null, false, { message: 'Unknown user with email ' + _email }); }
+ if (!user) { return done(null, false, { message: 'Unknown user with email ' + email }); }
user.authenticate(password, (err, ok) => {
if (err) { return done(err); } |
ba59fd569c751b8a72288e281ed026a95d486555 | generators/respec.js | generators/respec.js |
var phantom = require("phantomjs")
, execFile = require("child_process").execFile
, jn = require("path").join
, u = require("url")
, querystring = require("querystring")
, r2hPath = jn(__dirname, "../node_modules/respec/tools/respec2html.js")
;
exports.generate = function (url, params, cb) {
url = u.parse(url);
// respec use ";" as query string separators
var qs = querystring.parse(url.query, ";")
for (var k in params) if (params.hasOwnProperty(k)) qs[k] = params[k];
url.search = querystring.stringify(qs, ";");
url = u.format(url);
console.log("Generating", url);
// Phantom's own timeouts are never reaching us for some reason, so we do our own
var timedout = false;
var tickingBomb = setTimeout(
function () {
timedout = true;
cb({ status: 500, message: "Processing timed out." });
}
, 10000
);
execFile(
phantom.path
, ["--ssl-protocol=any", r2hPath, url]
, function (err, stdout, stderr) {
if (timedout) return;
clearTimeout(tickingBomb);
if (err) return cb({ status: 500, message: err + "\n" + (stderr || "") });
cb(null, stdout);
}
);
};
|
var phantom = require("phantomjs")
, execFile = require("child_process").execFile
, jn = require("path").join
, u = require("url")
, querystring = require("querystring")
, r2hPath = jn(__dirname, "../node_modules/respec/tools/respec2html.js")
;
exports.generate = function (url, params, cb) {
url = u.parse(url);
// respec use ";" as query string separators
var qs = querystring.parse(url.query, ";")
for (var k in params) if (params.hasOwnProperty(k)) qs[k] = params[k];
url.search = querystring.stringify(qs, ";");
url = u.format(url);
console.log("Generating", url);
// Phantom's own timeouts are never reaching us for some reason, so we do our own
var timedout = false;
var tickingBomb = setTimeout(
function () {
timedout = true;
cb({ status: 500, message: "Processing timed out." });
}
, 10000
);
execFile(
phantom.path
, ["--ssl-protocol=any", r2hPath, url]
, { maxBuffer: 400*1024 } // default * 2
, function (err, stdout, stderr) {
if (timedout) return;
clearTimeout(tickingBomb);
if (err) return cb({ status: 500, message: err + "\n" + (stderr || "") });
cb(null, stdout);
}
);
};
| Increase the buffer to satisfy appmanifest | Increase the buffer to satisfy appmanifest
| JavaScript | mit | w3c/spec-generator,w3c/spec-generator,w3c/spec-generator | ---
+++
@@ -27,6 +27,7 @@
execFile(
phantom.path
, ["--ssl-protocol=any", r2hPath, url]
+ , { maxBuffer: 400*1024 } // default * 2
, function (err, stdout, stderr) {
if (timedout) return;
clearTimeout(tickingBomb); |
9f970f2def42e8aacff84fc85575a1f6655848f8 | js/locales/bootstrap-datetimepicker.kr.js | js/locales/bootstrap-datetimepicker.kr.js | /**
* Korean translation for bootstrap-datetimepicker
* Gu Youn <http://github.com/guyoun>
*/
;(function($){
$.fn.datetimepicker.dates['kr'] = {
days: ["일요일", "월요일", "화요일", "수요일", "목요일", "금요일", "토요일", "일요일"],
daysShort: ["일", "월", "화", "수", "목", "금", "토", "일"],
daysMin: ["일", "월", "화", "수", "목", "금", "토", "일"],
months: ["1월", "2월", "3월", "4월", "5월", "6월", "7월", "8월", "9월", "10월", "11월", "12월"],
monthsShort: ["1월", "2월", "3월", "4월", "5월", "6월", "7월", "8월", "9월", "10월", "11월", "12월"],
suffix: [],
meridiem: []
};
}(jQuery));
| /**
* Korean translation for bootstrap-datetimepicker
* Gu Youn <http://github.com/guyoun>
* Baekjoon Choi <http://github.com/Baekjoon>
*/
;(function($){
$.fn.datetimepicker.dates['kr'] = {
days: ["일요일", "월요일", "화요일", "수요일", "목요일", "금요일", "토요일", "일요일"],
daysShort: ["일", "월", "화", "수", "목", "금", "토", "일"],
daysMin: ["일", "월", "화", "수", "목", "금", "토", "일"],
months: ["1월", "2월", "3월", "4월", "5월", "6월", "7월", "8월", "9월", "10월", "11월", "12월"],
monthsShort: ["1월", "2월", "3월", "4월", "5월", "6월", "7월", "8월", "9월", "10월", "11월", "12월"],
suffix: [],
meridiem: ["오전", "오후"],
today: "오늘",
};
}(jQuery));
| Add Korean translation "today, meridiem" | Add Korean translation "today, meridiem"
| JavaScript | apache-2.0 | rento41/bootstrap-datetimepicker,XanderDwyl/bootstrap-datetimepicker-1,foxythemes/bootstrap-datetimepicker,davidpatters0n/bootstrap-datetimepicker,rento41/bootstrap-datetimepicker,lincome/bootstrap-datetimepicker-1,cnbin/bootstrap-datetimepicker,jperkelens/bootstrap-datetimepicker,XanderDwyl/bootstrap-datetimepicker-1,tanyunshi/bootstrap-datetimepicker,yesmeck/bootstrap-datetimepicker,kimgronqvist/bootstrap-datetimepicker,kimgronqvist/bootstrap-datetimepicker,foxythemes/bootstrap-datetimepicker,pedropenna/bootstrap-datetimepicker,pedropenna/bootstrap-datetimepicker,smalot/bootstrap-datetimepicker,PeterDaveHello/bootstrap-datetimepicker-1,Youraiseme/bootstrap-datetimepicker,spiritinlife/bootstrap-datetimepicker,Quji/bootstrap-datetimepicker,jperkelens/bootstrap-datetimepicker,lincome/bootstrap-datetimepicker-1,charmfocus/bootstrap-datetimepicker,PeterDaveHello/bootstrap-datetimepicker-1,jperkelens/bootstrap-datetimepicker,toyang/bootstrap-datepicker-zh-cn,Quji/bootstrap-datetimepicker,ETroll/bootstrap-datetimepicker,Youraiseme/bootstrap-datetimepicker,yake987/bootstrap-datetimepicker,ETroll/bootstrap-datetimepicker,pixeljunkie/bootstrap-datetimepicker,lincome/bootstrap-datetimepicker-1,ljx213101212/bootstrap-datetimepicker,andrewblake1/bootstrap-datetimepicker,XanderDwyl/bootstrap-datetimepicker-1,yake987/bootstrap-datetimepicker,lvlin-kooboo/bootstrap-datetimepicker,jaredkwright/bootstrap-datetimepicker,rento41/bootstrap-datetimepicker,ljx213101212/bootstrap-datetimepicker,Quji/bootstrap-datetimepicker,pedropenna/bootstrap-datetimepicker,Polyconseil/bootstrap-datetimepicker,toyang/bootstrap-datepicker-zh-cn,yesmeck/bootstrap-datetimepicker,spiritinlife/bootstrap-datetimepicker,andrewblake1/bootstrap-datetimepicker,tanyunshi/bootstrap-datetimepicker,foxythemes/bootstrap-datetimepicker,andrewblake1/bootstrap-datetimepicker,charmfocus/bootstrap-datetimepicker,lvlin-kooboo/bootstrap-datetimepicker,davidpatters0n/bootstrap-datetimepicker,Youraiseme/bootstrap-datetimepicker,lvlin-kooboo/bootstrap-datetimepicker,pixeljunkie/bootstrap-datetimepicker,charmfocus/bootstrap-datetimepicker,kimgronqvist/bootstrap-datetimepicker,Polyconseil/bootstrap-datetimepicker,davidpatters0n/bootstrap-datetimepicker,smalot/bootstrap-datetimepicker,ljx213101212/bootstrap-datetimepicker,cnbin/bootstrap-datetimepicker,yesmeck/bootstrap-datetimepicker,AuspeXeu/bootstrap-datetimepicker,AuspeXeu/bootstrap-datetimepicker,yake987/bootstrap-datetimepicker,Polyconseil/bootstrap-datetimepicker,AuspeXeu/bootstrap-datetimepicker,spiritinlife/bootstrap-datetimepicker,cnbin/bootstrap-datetimepicker,pixeljunkie/bootstrap-datetimepicker,tanyunshi/bootstrap-datetimepicker,toyang/bootstrap-datepicker-zh-cn,smalot/bootstrap-datetimepicker,PeterDaveHello/bootstrap-datetimepicker-1,jaredkwright/bootstrap-datetimepicker,ETroll/bootstrap-datetimepicker,jaredkwright/bootstrap-datetimepicker | ---
+++
@@ -1,6 +1,7 @@
/**
* Korean translation for bootstrap-datetimepicker
* Gu Youn <http://github.com/guyoun>
+ * Baekjoon Choi <http://github.com/Baekjoon>
*/
;(function($){
$.fn.datetimepicker.dates['kr'] = {
@@ -10,6 +11,7 @@
months: ["1월", "2월", "3월", "4월", "5월", "6월", "7월", "8월", "9월", "10월", "11월", "12월"],
monthsShort: ["1월", "2월", "3월", "4월", "5월", "6월", "7월", "8월", "9월", "10월", "11월", "12월"],
suffix: [],
- meridiem: []
+ meridiem: ["오전", "오후"],
+ today: "오늘",
};
}(jQuery)); |
e4067132b064816b89f53192cf36bd201e1137c7 | app/middlewares/timeout-limits.js | app/middlewares/timeout-limits.js | module.exports = function timeoutLimits (metadataBackend) {
return function timeoutLimitsMiddleware (req, res, next) {
const { user, authenticated } = res.locals;
metadataBackend.getUserTimeoutRenderLimits(user, function (err, timeoutRenderLimit) {
if (err) {
return next(err);
}
const userLimits = {
timeout: authenticated ? timeoutRenderLimit.render : timeoutRenderLimit.renderPublic
};
res.locals.userLimits = userLimits;
next();
});
};
};
| module.exports = function timeoutLimits (metadataBackend) {
return function timeoutLimitsMiddleware (req, res, next) {
const { user, authenticated } = res.locals;
metadataBackend.getUserTimeoutRenderLimits(user, function (err, timeoutRenderLimit) {
if (req.profiler) {
req.profiler.done('getUserTimeoutLimits');
}
if (err) {
return next(err);
}
const userLimits = {
timeout: authenticated ? timeoutRenderLimit.render : timeoutRenderLimit.renderPublic
};
res.locals.userLimits = userLimits;
next();
});
};
};
| Add profile to user limit middleware | Add profile to user limit middleware
| JavaScript | bsd-3-clause | CartoDB/CartoDB-SQL-API,CartoDB/CartoDB-SQL-API | ---
+++
@@ -3,6 +3,10 @@
const { user, authenticated } = res.locals;
metadataBackend.getUserTimeoutRenderLimits(user, function (err, timeoutRenderLimit) {
+ if (req.profiler) {
+ req.profiler.done('getUserTimeoutLimits');
+ }
+
if (err) {
return next(err);
} |
8a983910adf08af5cdf8fd2fbbb8019db90c4d4c | database/database.js | database/database.js | const Sequelize = require('sequelize');
let db;
if (process.env.DATABASE_URL) {
db = new Sequelize(process.env.DATABASE_URL, {
dialect: 'postgres',
protocol:'postgres',
port: match[4],
host: match[3],
logging: true
});
} else {
db = new Sequelize('postgres', 'postgres', ' ', {
dialect: 'postgres',
port: 5432,
});
}
module.exports = { database: db, Sequelize };
| const Sequelize = require('sequelize');
let db;
if (process.env.DATABASE_URL) {
db = new Sequelize(process.env.DATABASE_URL, {
dialect: 'postgres',
protocol: 'postgres',
port: 5432,
host: 'ec2-23-21-76-49.compute-1.amazonaws.com',
logging: true,
});
} else {
db = new Sequelize('postgres', 'postgres', ' ', {
dialect: 'postgres',
port: 5432,
});
}
module.exports = { database: db, Sequelize };
| Connect to heroku postgres in production | Connect to heroku postgres in production
| JavaScript | mit | bwuphan/raptor-ads,bwuphan/raptor-ads,Darkrender/raptor-ads,Velocies/raptor-ads,Velocies/raptor-ads,wolnewitz/raptor-ads,wolnewitz/raptor-ads,Darkrender/raptor-ads | ---
+++
@@ -5,10 +5,10 @@
if (process.env.DATABASE_URL) {
db = new Sequelize(process.env.DATABASE_URL, {
dialect: 'postgres',
- protocol:'postgres',
- port: match[4],
- host: match[3],
- logging: true
+ protocol: 'postgres',
+ port: 5432,
+ host: 'ec2-23-21-76-49.compute-1.amazonaws.com',
+ logging: true,
});
} else {
db = new Sequelize('postgres', 'postgres', ' ', { |
4e942b154ccac0ed5619c19f806c8066718d4be8 | demo/js/main.js | demo/js/main.js | require.config({
urlArgs: "bust=v"+(new Date().getTime()), // Comment out/remove to enable caching
baseUrl: "js/",
paths: {
colt: 'libs/colt.0.2.5'
}
});
define(['colt'], function (Colt) {
// Define all of the modules
Colt.modules = [
'modules/static',
'modules/modone',
'modules/modtwo',
'modules/modthree'
];
// Initialize application
Colt.init();
}); | require.config({
urlArgs: "bust=v"+(new Date().getTime()), // Comment out/remove to enable caching
baseUrl: "js/",
paths: {
colt: 'libs/colt.0.2.7'
}
});
define(['colt'], function (Colt) {
// Define all of the modules
Colt.modules = [
'modules/static',
'modules/modone',
'modules/modtwo',
'modules/modthree'
];
// Initialize application
Colt.init();
}); | Fix colt reference version number | Fix colt reference version number
| JavaScript | mit | Fluidbyte/ColtJS | ---
+++
@@ -2,7 +2,7 @@
urlArgs: "bust=v"+(new Date().getTime()), // Comment out/remove to enable caching
baseUrl: "js/",
paths: {
- colt: 'libs/colt.0.2.5'
+ colt: 'libs/colt.0.2.7'
}
});
|
57271878c0107ce50add73b7c9305a91ff3d79bc | core/server/data/db/connection.js | core/server/data/db/connection.js | var knex = require('knex'),
config = require('../../config'),
dbConfig = config.database,
knexInstance;
function configure(dbConfig) {
var client = dbConfig.client,
pg;
if (client === 'pg' || client === 'postgres' || client === 'postgresql') {
try {
pg = require('pg');
} catch (e) {
pg = require('pg.js');
}
// By default PostgreSQL returns data as strings along with an OID that identifies
// its type. We're setting the parser to convert OID 20 (int8) into a javascript
// integer.
pg.types.setTypeParser(20, function (val) {
return val === null ? null : parseInt(val, 10);
});
}
if (client === 'sqlite3') {
dbConfig.useNullAsDefault = false;
}
return dbConfig;
}
if (!knexInstance && dbConfig && dbConfig.client) {
knexInstance = knex(configure(dbConfig));
}
module.exports = knexInstance;
| var knex = require('knex'),
config = require('../../config'),
dbConfig = config.database,
knexInstance;
function configure(dbConfig) {
var client = dbConfig.client,
pg;
if (client === 'pg' || client === 'postgres' || client === 'postgresql') {
try {
pg = require('pg');
} catch (e) {
pg = require('pg.js');
}
// By default PostgreSQL returns data as strings along with an OID that identifies
// its type. We're setting the parser to convert OID 20 (int8) into a javascript
// integer.
pg.types.setTypeParser(20, function (val) {
return val === null ? null : parseInt(val, 10);
});
}
if (client === 'sqlite3') {
dbConfig.useNullAsDefault = dbConfig.useNullAsDefault || false;
}
return dbConfig;
}
if (!knexInstance && dbConfig && dbConfig.client) {
knexInstance = knex(configure(dbConfig));
}
module.exports = knexInstance;
| Make it possible to override `useNullAsDefault` | Make it possible to override `useNullAsDefault`
refs #6623, #6637
- this was supposed to be in the original
| JavaScript | mit | epicmiller/pages,dbalders/Ghost,adam-paterson/blog,NovaDevelopGroup/Academy,letsjustfixit/Ghost,Gargol/Ghost,novaugust/Ghost,rizkyario/Ghost,JohnONolan/Ghost,mohanambati/Ghost,jorgegilmoreira/ghost,lf2941270/Ghost,tidyui/Ghost,SkynetInc/steam,AlexKVal/Ghost,AlexKVal/Ghost,javorszky/Ghost,olsio/Ghost,syaiful6/Ghost,Xibao-Lv/Ghost,sebgie/Ghost,petersucks/blog,olsio/Ghost,ManRueda/manrueda-blog,rizkyario/Ghost,acburdine/Ghost,stridespace/Ghost,janvt/Ghost,jomahoney/Ghost,daimaqiao/Ghost-Bridge,lukekhamilton/Ghost,daimaqiao/Ghost-Bridge,Kaenn/Ghost,lf2941270/Ghost,disordinary/Ghost,JohnONolan/Ghost,cwonrails/Ghost,ignasbernotas/nullifer,obsoleted/Ghost,Elektro1776/javaPress,MadeOnMars/Ghost,novaugust/Ghost,klinker-apps/ghost,chevex/undoctrinate,daimaqiao/Ghost-Bridge,pollbox/ghostblog,ManRueda/manrueda-blog,sebgie/Ghost,e10/Ghost,mohanambati/Ghost,novaugust/Ghost,ngosinafrica/SiteForNGOs,mohanambati/Ghost,Xibao-Lv/Ghost,jomahoney/Ghost,sunh3/Ghost,rizkyario/Ghost,Kaenn/Ghost,kaychaks/kaushikc.org,NovaDevelopGroup/Academy,leninhasda/Ghost,Kikobeats/Ghost,bitjson/Ghost,sunh3/Ghost,BlueHatbRit/Ghost,e10/Ghost,Elektro1776/javaPress,singular78/Ghost,cwonrails/Ghost,hnarayanan/narayanan.co,adam-paterson/blog,lukekhamilton/Ghost,leonli/ghost,bitjson/Ghost,singular78/Ghost,vainglori0us/urban-fortnight,SkynetInc/steam,Gargol/Ghost,klinker-apps/ghost,acburdine/Ghost,leonli/ghost,sebgie/Ghost,syaiful6/Ghost,kevinansfield/Ghost,janvt/Ghost,hnarayanan/narayanan.co,Kikobeats/Ghost,disordinary/Ghost,vainglori0us/urban-fortnight,leonli/ghost,TryGhost/Ghost,jorgegilmoreira/ghost,BlueHatbRit/Ghost,jorgegilmoreira/ghost,ErisDS/Ghost,vainglori0us/urban-fortnight,veyo-care/Ghost,TryGhost/Ghost,petersucks/blog,epicmiller/pages,bosung90/Ghost,ballPointPenguin/Ghost,dbalders/Ghost,ErisDS/Ghost,stridespace/Ghost,stridespace/Ghost,letsjustfixit/Ghost,Kaenn/Ghost,Kikobeats/Ghost,dbalders/Ghost,GroupxDev/javaPress,MadeOnMars/Ghost,tidyui/Ghost,cwonrails/Ghost,letsjustfixit/Ghost,bosung90/Ghost,singular78/Ghost,GroupxDev/javaPress,ErisDS/Ghost,NovaDevelopGroup/Academy,ignasbernotas/nullifer,pollbox/ghostblog,javorszky/Ghost,ivantedja/ghost,ngosinafrica/SiteForNGOs,ballPointPenguin/Ghost,GroupxDev/javaPress,Elektro1776/javaPress,obsoleted/Ghost,ManRueda/manrueda-blog,kevinansfield/Ghost,leninhasda/Ghost,veyo-care/Ghost,kaychaks/kaushikc.org,JohnONolan/Ghost,kevinansfield/Ghost,TryGhost/Ghost,acburdine/Ghost | ---
+++
@@ -23,7 +23,7 @@
}
if (client === 'sqlite3') {
- dbConfig.useNullAsDefault = false;
+ dbConfig.useNullAsDefault = dbConfig.useNullAsDefault || false;
}
return dbConfig; |
a600c85cda889b79f55d7d62992a90a54d9467a4 | packages/core/src/cache-tweets.js | packages/core/src/cache-tweets.js | import Twitter from 'twitter'
import S3TweetRepository from './lib/s3-tweet-repository'
import slscrypt from '../node_modules/serverless-crypt/dists/slscrypt'
const tweetRepository = new S3TweetRepository(process.env.TWEET_CACHE_BUCKET_NAME)
const handler = (event, context, callback) => {
return createTwitterClient(process.env.TWITTER_REST_BASE_URL)
.then(client => {
const params = {
screen_name: 'RealTimeWWII',
trim_user: true,
exclude_replies: true,
include_rts: false,
count: 200,
tweet_mode: 'extended'
}
return client.get('statuses/user_timeline', params)
})
.then(tweets => tweetRepository.saveLatestTweets(tweets))
.catch(err => callback(err))
}
const createTwitterClient = async (twitterRestBaseUrl) => {
return new Twitter({
consumer_key: await slscrypt.get('twitter_consumer_key'),
consumer_secret: await slscrypt.get('twitter_consumer_secret'),
access_token_key: await slscrypt.get('twitter_access_token_key'),
access_token_secret: await slscrypt.get('twitter_access_token_secret'),
rest_base: twitterRestBaseUrl
})
}
export {handler}
| import Twitter from 'twitter'
import S3TweetRepository from './lib/s3-tweet-repository'
import slscrypt from '../node_modules/serverless-crypt/dists/slscrypt'
const tweetRepository = new S3TweetRepository(process.env.TWEET_CACHE_BUCKET_NAME)
const createParams = () => {
return {
screen_name: 'RealTimeWWII',
trim_user: true,
exclude_replies: true,
include_rts: false,
count: 200,
tweet_mode: 'extended'
}
}
const handler = async (event, context, callback) => {
try {
const client = await createTwitterClient(process.env.TWITTER_REST_BASE_URL)
const tweets = await client.get('statuses/user_timeline', createParams())
await tweetRepository.saveLatestTweets(tweets)
} catch (err) {
callback(err)
}
}
const createTwitterClient = async (twitterRestBaseUrl) => {
return new Twitter({
consumer_key: await slscrypt.get('twitter_consumer_key'),
consumer_secret: await slscrypt.get('twitter_consumer_secret'),
access_token_key: await slscrypt.get('twitter_access_token_key'),
access_token_secret: await slscrypt.get('twitter_access_token_secret'),
rest_base: twitterRestBaseUrl
})
}
export {handler}
| Convert promise chain to async await. | Convert promise chain to async await.
| JavaScript | apache-2.0 | ceilfors/realtime-ww2-alexa | ---
+++
@@ -4,21 +4,25 @@
const tweetRepository = new S3TweetRepository(process.env.TWEET_CACHE_BUCKET_NAME)
-const handler = (event, context, callback) => {
- return createTwitterClient(process.env.TWITTER_REST_BASE_URL)
- .then(client => {
- const params = {
- screen_name: 'RealTimeWWII',
- trim_user: true,
- exclude_replies: true,
- include_rts: false,
- count: 200,
- tweet_mode: 'extended'
- }
- return client.get('statuses/user_timeline', params)
- })
- .then(tweets => tweetRepository.saveLatestTweets(tweets))
- .catch(err => callback(err))
+const createParams = () => {
+ return {
+ screen_name: 'RealTimeWWII',
+ trim_user: true,
+ exclude_replies: true,
+ include_rts: false,
+ count: 200,
+ tweet_mode: 'extended'
+ }
+}
+
+const handler = async (event, context, callback) => {
+ try {
+ const client = await createTwitterClient(process.env.TWITTER_REST_BASE_URL)
+ const tweets = await client.get('statuses/user_timeline', createParams())
+ await tweetRepository.saveLatestTweets(tweets)
+ } catch (err) {
+ callback(err)
+ }
}
const createTwitterClient = async (twitterRestBaseUrl) => { |
f2f33e935ded1cc6368c30e94933c8c985dbc599 | eloquent_js/chapter08/ch08_ex01.js | eloquent_js/chapter08/ch08_ex01.js | function reliableMultiply(a, b) {
for (;;) {
try {
return primitiveMultiply(a, b);
} catch (error) {
if (!(error instanceof MultiplicatorUnitFailure)) {
throw error;
}
}
}
}
| function reliableMultiply(a, b) {
for (;;) {
try {
primitiveMultiply(a, b);
break;
} catch(e) {
if (!e instanceof MultiplicatorUnitFailure) {
throw e;
}
}
}
}
| Add chapter 8, exercise 1 | Add chapter 8, exercise 1
| JavaScript | mit | bewuethr/ctci | ---
+++
@@ -1,11 +1,12 @@
function reliableMultiply(a, b) {
- for (;;) {
- try {
- return primitiveMultiply(a, b);
- } catch (error) {
- if (!(error instanceof MultiplicatorUnitFailure)) {
- throw error;
- }
- }
- }
+ for (;;) {
+ try {
+ primitiveMultiply(a, b);
+ break;
+ } catch(e) {
+ if (!e instanceof MultiplicatorUnitFailure) {
+ throw e;
+ }
+ }
+ }
} |
2c6455c95974f70fc3960a09d0d701ecb9dccb91 | web/static/js/components/room.js | web/static/js/components/room.js | import React, { Component } from "react"
import UserList from "./user_list"
import CategoryColumn from "./category_column"
import IdeaSubmissionForm from "./idea_submission_form"
class Room extends Component {
constructor(props) {
super(props)
this.state = { ideas: [] }
this.handleIdeaSubmission = this.handleIdeaSubmission.bind(this)
this._setupRoomChannelEventHandlers()
}
_setupRoomChannelEventHandlers() {
this.props.roomChannel.on("new_idea_received", newIdea => {
this.setState({ ideas: [...this.state.ideas, newIdea] })
})
}
handleIdeaSubmission(idea) {
this.props.roomChannel.push("new_idea", { body: idea })
}
render() {
return (
<section className="room">
<div className="ui three column padded grid category-columns-wrapper">
<CategoryColumn category="happy" ideas={ this.state.ideas }/>
<CategoryColumn category="sad" ideas={ [] }/>
<CategoryColumn category="confused" ideas={ [] }/>
</div>
<UserList users={ this.props.users } />
<IdeaSubmissionForm onIdeaSubmission={ this.handleIdeaSubmission }/>
</section>
)
}
}
Room.propTypes = {
roomChannel: React.PropTypes.object.isRequired,
users: React.PropTypes.array.isRequired,
}
export default Room
| import React, { Component } from "react"
import UserList from "./user_list"
import CategoryColumn from "./category_column"
import IdeaSubmissionForm from "./idea_submission_form"
class Room extends Component {
constructor(props) {
super(props)
this.state = { ideas: [] }
this.handleIdeaSubmission = this.handleIdeaSubmission.bind(this)
this._setupRoomChannelEventHandlers()
}
_setupRoomChannelEventHandlers() {
this.props.roomChannel.on("new_idea_received", newIdea => {
this.setState({ ideas: [...this.state.ideas, newIdea] })
})
}
handleIdeaSubmission(idea) {
this.props.roomChannel.push("new_idea", { body: idea })
}
render() {
return (
<section className="room">
<div className="ui equal width padded grid category-columns-wrapper">
<CategoryColumn category="happy" ideas={ this.state.ideas }/>
<CategoryColumn category="sad" ideas={ [] }/>
<CategoryColumn category="confused" ideas={ [] }/>
</div>
<UserList users={ this.props.users } />
<IdeaSubmissionForm onIdeaSubmission={ this.handleIdeaSubmission }/>
</section>
)
}
}
Room.propTypes = {
roomChannel: React.PropTypes.object.isRequired,
users: React.PropTypes.array.isRequired,
}
export default Room
| Use equal width grid to so that, in the future, we can use four column retro formats without changing the code | Use equal width grid to so that, in the future, we can use four column retro formats without changing the code
| JavaScript | mit | tnewell5/remote_retro,stride-nyc/remote_retro,stride-nyc/remote_retro,samdec11/remote_retro,tnewell5/remote_retro,stride-nyc/remote_retro | ---
+++
@@ -25,7 +25,7 @@
render() {
return (
<section className="room">
- <div className="ui three column padded grid category-columns-wrapper">
+ <div className="ui equal width padded grid category-columns-wrapper">
<CategoryColumn category="happy" ideas={ this.state.ideas }/>
<CategoryColumn category="sad" ideas={ [] }/>
<CategoryColumn category="confused" ideas={ [] }/> |
392008c4f5907d15dfd87434944be3842ef175e1 | Logger.js | Logger.js | var std = require('std')
// TODO Send email on error
module.exports = std.Class(function() {
var defaults = {
name: 'Logger'
}
this._init = function(opts) {
opts = std.extend(opts, defaults)
this._name = opts.name
this._emailQueue = []
}
this.log = function() {
this._consoleLog(std.slice(arguments))
}
this.error = function(err, message) {
var messageParts = [this._name, new Date().getTime(), message, err.message, err.stack]
this._consoleLog(messageParts)
this._queueEmail(messageParts)
}
this._queueEmail = function(messageParts) {
this._emailQueue.push(messageParts)
this._scheduleEmailDispatch()
}
var joinParts = function(arr) { return arr.join(' | ') }
this._consoleLog = function(messageParts) {
console.log(joinParts(messageParts))
}
this._scheduleEmailDispatch = std.delay(function() {
var message = std.map(this._emailQueue, joinParts).join('\n')
// TODO send message to error reporting email address
}, 10000) // Send at most one email per 10 seconds
})
| var std = require('std')
// TODO Send email on error
module.exports = std.Class(function() {
var defaults = {
name: 'Logger'
}
this._init = function(opts) {
if (typeof opts == 'string') { opts = { name:opts } }
opts = std.extend(opts, defaults)
this._name = opts.name
this._emailQueue = []
}
this.log = function() {
this._consoleLog(std.slice(arguments))
}
this.error = function(err, message) {
var messageParts = [this._name, new Date().getTime(), message, err.message, err.stack]
this._consoleLog(messageParts)
this._queueEmail(messageParts)
}
this._queueEmail = function(messageParts) {
this._emailQueue.push(messageParts)
this._scheduleEmailDispatch()
}
var joinParts = function(arr) { return arr.join(' | ') }
this._consoleLog = function(messageParts) {
console.log(joinParts(messageParts))
}
this._scheduleEmailDispatch = std.delay(function() {
var message = std.map(this._emailQueue, joinParts).join('\n')
// TODO send message to error reporting email address
}, 10000) // Send at most one email per 10 seconds
})
| Allow for passing in a simple string as the name of a logger | Allow for passing in a simple string as the name of a logger
| JavaScript | mit | ASAPPinc/std.js,marcuswestin/std.js | ---
+++
@@ -8,6 +8,7 @@
}
this._init = function(opts) {
+ if (typeof opts == 'string') { opts = { name:opts } }
opts = std.extend(opts, defaults)
this._name = opts.name
this._emailQueue = [] |
1c6852058bd117545eef7d05fdc9341d79de80e8 | app/assets/javascripts/signature.js | app/assets/javascripts/signature.js | //= require signature_pad
$( document ).ready(function() {
var wrapper = document.getElementById("Signature"),
clearButton = document.getElementById("clear"),
saveButton = wrapper.querySelector("[data-action=save]"),
canvas = wrapper.querySelector("canvas"),
signaturePad;
signaturePad = new SignaturePad(canvas);
clearButton.addEventListener("click", function (event) {
signaturePad.clear();
});
$('#new_check_in_form').submit(function(e) {
if (signaturePad.isEmpty()) {
$('.Signature-pad').addClass('Signature-pad-error');
$('.description').addClass('Signature-error');
return false;
} else {
$('#check_in_form_signature').val(signaturePad.toDataURL());
}
});
})
| //= require signature_pad
$( document ).ready(function() {
$('select').material_select();
var wrapper = document.getElementById("Signature"),
clearButton = document.getElementById("clear"),
saveButton = wrapper.querySelector("[data-action=save]"),
canvas = wrapper.querySelector("canvas"),
signaturePad;
signaturePad = new SignaturePad(canvas);
clearButton.addEventListener("click", function (event) {
signaturePad.clear();
});
$('#new_check_in_form').submit(function(e) {
if (signaturePad.isEmpty()) {
$('.Signature-pad').addClass('Signature-pad-error');
$('.description').addClass('Signature-error');
return false;
} else {
$('#check_in_form_signature').val(signaturePad.toDataURL());
}
});
})
| Allow dropdown to select work site | Allow dropdown to select work site
| JavaScript | mit | bjmllr/habitat_humanity,bjmllr/habitat_humanity,rubyforgood/habitat_humanity,rubyforgood/habitat_humanity,bjmllr/habitat_humanity,rubyforgood/habitat_humanity | ---
+++
@@ -1,5 +1,7 @@
//= require signature_pad
$( document ).ready(function() {
+ $('select').material_select();
+
var wrapper = document.getElementById("Signature"),
clearButton = document.getElementById("clear"),
saveButton = wrapper.querySelector("[data-action=save]"), |
303b3ea00de021788d419b19399057065a5c1f22 | app/javascript/packs/application.js | app/javascript/packs/application.js | /* eslint no-console:0 */
// This file is automatically compiled by Webpack, along with any other files
// present in this directory. You're encouraged to place your actual application logic in
// a relevant structure within app/javascript and only use these pack files to reference
// that code so it'll be compiled.
//
// To reference this file, add <%= javascript_pack_tag 'application' %> to the appropriate
// layout file, like app/views/layouts/application.html.erb
import 'core-js/stable';
import 'regenerator-runtime/runtime';
import * as Sentry from '@sentry/react';
import { Integrations } from '@sentry/tracing';
const isOnline = !process.env.NEMO_OFFLINE_MODE || process.env.NEMO_OFFLINE_MODE === 'false';
if (isOnline && process.env.NODE_ENV !== 'test') {
Sentry.init({
dsn: process.env.NEMO_SENTRY_DSN,
integrations: [new Integrations.BrowserTracing()],
// Percentage between 0.0 - 1.0.
tracesSampleRate: 1.0,
});
}
// Support component names relative to this directory:
const componentRequireContext = require.context('components', true);
const ReactRailsUJS = require('react_ujs');
ReactRailsUJS.useContext(componentRequireContext);
| /* eslint no-console:0 */
// This file is automatically compiled by Webpack, along with any other files
// present in this directory. You're encouraged to place your actual application logic in
// a relevant structure within app/javascript and only use these pack files to reference
// that code so it'll be compiled.
//
// To reference this file, add <%= javascript_pack_tag 'application' %> to the appropriate
// layout file, like app/views/layouts/application.html.erb
import 'core-js/stable';
import 'regenerator-runtime/runtime';
import * as Sentry from '@sentry/react';
import { Integrations } from '@sentry/tracing';
const isOnline = !process.env.NEMO_OFFLINE_MODE || process.env.NEMO_OFFLINE_MODE === 'false';
if (isOnline && process.env.NODE_ENV !== 'test') {
Sentry.init({
dsn: process.env.NEMO_SENTRY_DSN,
integrations: [new Integrations.BrowserTracing()],
// Uncomment to enable Sentry performance monitoring (disabled in favor of Scout).
// Percentage between 0.0 - 1.0.
//tracesSampleRate: 1.0,
});
}
// Support component names relative to this directory:
const componentRequireContext = require.context('components', true);
const ReactRailsUJS = require('react_ujs');
ReactRailsUJS.useContext(componentRequireContext);
| Disable now-unused Sentry performance traces | Disable now-unused Sentry performance traces
| JavaScript | apache-2.0 | thecartercenter/elmo,thecartercenter/elmo,thecartercenter/elmo | ---
+++
@@ -19,8 +19,9 @@
dsn: process.env.NEMO_SENTRY_DSN,
integrations: [new Integrations.BrowserTracing()],
+ // Uncomment to enable Sentry performance monitoring (disabled in favor of Scout).
// Percentage between 0.0 - 1.0.
- tracesSampleRate: 1.0,
+ //tracesSampleRate: 1.0,
});
}
|
8d16059e20af2b1fe1032d8351cd4ab02cad4889 | app/javascript/src/jsonapi/index.js | app/javascript/src/jsonapi/index.js | const Utils = require('utils');
const defaults = require('lodash/defaults');
console.log(Util);
const defaultConfig = {
baseUrl: '/',
};
class JSONAPI {
constructor(apiConfig) {
Utils.const(this, 'config', defaults({}, apiConfig, defaultConfig));
}
/**
*
* @param {*} modelConfig
*/
define(modelConfig) {
}
}
module.exports = JSONAPI; | const Utils = require('utils');
const defaults = require('lodash/defaults');
const defaultConfig = {
baseUrl: '/',
};
class JSONAPI {
constructor(apiConfig) {
Utils.const(this, 'config', defaults({}, apiConfig, defaultConfig));
}
/**
*
* @param {*} modelConfig
*/
define(modelConfig) {
}
}
module.exports = JSONAPI;
| Remove console.log statement causing an error in browser console. | Remove console.log statement causing an error in browser console.
| JavaScript | mit | SplitTime/OpenSplitTime,SplitTime/OpenSplitTime,SplitTime/OpenSplitTime | ---
+++
@@ -1,8 +1,5 @@
const Utils = require('utils');
const defaults = require('lodash/defaults');
-
-console.log(Util);
-
const defaultConfig = {
baseUrl: '/',
}; |
39e53117259c23b3f0f775939702d177b3b4a6b8 | webpack.config.coverage.js | webpack.config.coverage.js | "use strict";
/**
* Webpack frontend test (w/ coverage) configuration.
*/
var _ = require("lodash");
var testCfg = require("./webpack.config.test");
module.exports = _.merge({}, testCfg, {
module: {
preLoaders: [
// Manually instrument client code for code coverage.
// https://github.com/deepsweet/isparta-loader handles ES6 + normal JS.
{
test: /src\/.*\.jsx?$/,
exclude: /(test|node_modules)\//,
loader: "isparta?{ babel: { stage: 1 } }"
}
]
}
});
| "use strict";
/**
* Webpack frontend test (w/ coverage) configuration.
*/
var _ = require("lodash");
var testCfg = require("./webpack.config.test");
module.exports = _.merge({}, testCfg, {
module: {
preLoaders: [
// Manually instrument client code for code coverage.
// https://github.com/deepsweet/isparta-loader handles ES6 + normal JS.
{
test: /src\/.*\.jsx?$/,
exclude: /(test|node_modules)\//,
loader: "isparta?{ babel: { stage: 0 } }"
}
]
}
});
| Use stage 0 when loaded via isparta | Use stage 0 when loaded via isparta
| JavaScript | mit | FormidableLabs/victory-chart,FormidableLabs/victory-chart,GreenGremlin/victory-chart,GreenGremlin/victory-chart | ---
+++
@@ -13,7 +13,7 @@
{
test: /src\/.*\.jsx?$/,
exclude: /(test|node_modules)\//,
- loader: "isparta?{ babel: { stage: 1 } }"
+ loader: "isparta?{ babel: { stage: 0 } }"
}
]
} |
4e43cc07566d5704831741ad008553c205831c99 | Specs/suites/Suite.js | Specs/suites/Suite.js | exports.setup = function(Tests){
var Suite = require('lib/suite').Suite;
Tests.describe('Suites', function(it, setup){
setup('beforeEach', function(){
});
it('should error out if no `it` named argument is declared', function(expect){
var error = null;
try {
new Suite('Fail', function(){});
} catch(e){
error = e;
} finally {
expect(error).toBeAnInstanceOf(Error);
expect(error.message).toBe('Suite function does not explicitly define an `it` argument.');
}
});
it('should pass an `it` and `setup` function', function(expect){
new Suite('Pass', function(it, setup){
expect(it).toBeAnInstanceOf(Function);
expect(setup).toBeAnInstanceOf(Function);
}).run();
});
});
}; | exports.setup = function(Tests){
var Suite = require('lib/suite').Suite;
Tests.describe('Suites', function(it, setup){
setup('beforeEach', function(){
});
it('should error out if no `it` named argument is declared', function(expect){
var error = null;
try {
new Suite('Fail', function(){});
} catch(e){
error = e;
} finally {
expect(error).toBeAnInstanceOf(Error);
expect(error.message).toBe('Suite function does not explicitly define an `it` argument.');
}
});
it('should pass an `it` and `setup` function', function(expect){
expect.perform(2);
new Suite('Pass', function(it, setup){
expect(it).toBeAnInstanceOf(Function);
expect(setup).toBeAnInstanceOf(Function);
}).run();
});
});
}; | Make it work on flusspferd. | Make it work on flusspferd.
| JavaScript | mit | keeto/testigo | ---
+++
@@ -21,6 +21,7 @@
});
it('should pass an `it` and `setup` function', function(expect){
+ expect.perform(2);
new Suite('Pass', function(it, setup){
expect(it).toBeAnInstanceOf(Function);
expect(setup).toBeAnInstanceOf(Function); |
b7a37e2a25d01de2eb64308b26fc91fb41b39f4d | Mac/MainWindow/Detail/main_mac.js | Mac/MainWindow/Detail/main_mac.js | // Add the mouse listeners for the above functions
function linkHover() {
window.onmouseover = function(event) {
if (event.target.matches('a')) {
window.webkit.messageHandlers.mouseDidEnter.postMessage(event.target.href);
}
}
window.onmouseout = function(event) {
if (event.target.matches('a')) {
window.webkit.messageHandlers.mouseDidExit.postMessage(event.target.href);
}
}
}
function postRenderProcessing() {
linkHover()
}
| // Add the mouse listeners for the above functions
function linkHover() {
window.onmouseover = function(event) {
var closestAnchor = event.target.closest('a')
if (closestAnchor) {
window.webkit.messageHandlers.mouseDidEnter.postMessage(closestAnchor.href);
}
}
window.onmouseout = function(event) {
var closestAnchor = event.target.closest('a')
if (closestAnchor) {
window.webkit.messageHandlers.mouseDidExit.postMessage(closestAnchor.href);
}
}
}
function postRenderProcessing() {
linkHover()
}
| Make mouseover/mouseout work with anchors that nest | Make mouseover/mouseout work with anchors that nest
| JavaScript | mit | brentsimmons/Evergreen,brentsimmons/Evergreen,brentsimmons/Evergreen,brentsimmons/Evergreen | ---
+++
@@ -1,13 +1,15 @@
// Add the mouse listeners for the above functions
function linkHover() {
window.onmouseover = function(event) {
- if (event.target.matches('a')) {
- window.webkit.messageHandlers.mouseDidEnter.postMessage(event.target.href);
+ var closestAnchor = event.target.closest('a')
+ if (closestAnchor) {
+ window.webkit.messageHandlers.mouseDidEnter.postMessage(closestAnchor.href);
}
}
window.onmouseout = function(event) {
- if (event.target.matches('a')) {
- window.webkit.messageHandlers.mouseDidExit.postMessage(event.target.href);
+ var closestAnchor = event.target.closest('a')
+ if (closestAnchor) {
+ window.webkit.messageHandlers.mouseDidExit.postMessage(closestAnchor.href);
}
}
} |
4c070ecfe37c645ae41ebea99b9e6af32f0f8fb6 | static/js/custom.js | static/js/custom.js | $(document).ready(function() {
var height = $("#page-header").height()
$("a").click(function(e) {
e.preventDefault();
var href = $(this).attr("href");
$('html, body').animate({
scrollTop: $(href).offset().top - height
}, 0);
});
});
| $(document).ready(function() {
var height = $("#page-header").height()
$("a.internal").click(function(e) {
e.preventDefault();
var href = $(this).attr("href");
$('html, body').animate({
scrollTop: $(href).offset().top - height
}, 0);
});
});
| Make the selector more restrictive | Make the selector more restrictive
| JavaScript | mit | dgraph-io/hugo-dgraph-theme,dgraph-io/hugo-dgraph-theme | ---
+++
@@ -1,6 +1,6 @@
$(document).ready(function() {
var height = $("#page-header").height()
- $("a").click(function(e) {
+ $("a.internal").click(function(e) {
e.preventDefault();
var href = $(this).attr("href");
$('html, body').animate({ |
694f801676ced7e13d2402d29de38c39d3571061 | js/views/window_controls_view.js | js/views/window_controls_view.js | /* vim: ts=4:sw=4:expandtab
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
(function () {
'use strict';
window.Whisper = window.Whisper || {};
Whisper.WindowControlsView = Whisper.View.extend({
tagName: 'span',
className: 'window-controls',
template: $('#window-controls').html(),
initialize: function(options) {
this.appWindow = options.appWindow;
this.render();
},
events: {
'click .close': 'close',
'click .minimize': 'minimize'
},
close: function() {
if (this.appWindow.id === 'inbox') {
this.appWindow.hide();
} else {
this.appWindow.close();
}
},
minimize: function() {
this.appWindow.minimize();
}
});
})();
| /* vim: ts=4:sw=4:expandtab
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
(function () {
'use strict';
window.Whisper = window.Whisper || {};
Whisper.WindowControlsView = Whisper.View.extend({
tagName: 'span',
className: 'window-controls',
template: $('#window-controls').html(),
initialize: function(options) {
this.appWindow = options.appWindow;
this.render();
},
events: {
'click .close': 'close',
'click .minimize': 'minimize'
},
close: function() {
this.appWindow.close();
},
minimize: function() {
this.appWindow.minimize();
}
});
})();
| Stop hiding inbox instead of closing | Stop hiding inbox instead of closing
This behavior was intended to help keep the websocket alive, but keeping
the inbox window around can cause some stale frontend state. Also we now
have a keepalive alarm to check for new messages once a minute.
| JavaScript | agpl-3.0 | nrizzio/Signal-Desktop,nrizzio/Signal-Desktop,nrizzio/Signal-Desktop,nrizzio/Signal-Desktop | ---
+++
@@ -30,11 +30,7 @@
'click .minimize': 'minimize'
},
close: function() {
- if (this.appWindow.id === 'inbox') {
- this.appWindow.hide();
- } else {
- this.appWindow.close();
- }
+ this.appWindow.close();
},
minimize: function() {
this.appWindow.minimize(); |
d299e2577fe3578df508ed9d96887ea49253ff61 | res/middleware/autoreload.js | res/middleware/autoreload.js | <script type="text/javascript">
//
// Reload the app if server detects local change
//
(function() {
function checkForReload() {
var xhr = new XMLHttpRequest;
xhr.open('get', 'http://' + document.location.host + '/autoreload', true);
xhr.setRequestHeader('X-Requested-With','XMLHttpRequest');
xhr.onreadystatechange = function() {
if (this.readyState === 4 && /^[2]/.test(this.status)) {
var response = JSON.parse(this.responseText);
if (response.outdated) {
window.location.reload();
}
}
}
xhr.send();
}
setInterval(checkForReload, 1000*5);
})(window);
</script>
| <script type="text/javascript">
//
// Reload the app if server detects local change
//
(function() {
function checkForReload() {
var xhr = new XMLHttpRequest;
xhr.open('get', 'http://' + document.location.host + '/autoreload', true);
xhr.setRequestHeader('X-Requested-With','XMLHttpRequest');
xhr.onreadystatechange = function() {
if (this.readyState === 4 && /^[2]/.test(this.status)) {
var response = JSON.parse(this.responseText);
if (response.outdated) {
window.location.reload();
}
}
}
xhr.send();
}
setInterval(checkForReload, 1000 * 3);
})(window);
</script>
| Reduce AutoReload ping to 3s. | [lib] Reduce AutoReload ping to 3s.
| JavaScript | apache-2.0 | tohagan/connect-phonegap,sundbry/connect-phonegap,phonegap/connect-phonegap,sundbry/connect-phonegap,phonegap/connect-phonegap | ---
+++
@@ -19,7 +19,7 @@
xhr.send();
}
- setInterval(checkForReload, 1000*5);
+ setInterval(checkForReload, 1000 * 3);
})(window);
</script> |
e1e6681d0cf0589cb05cfe664a4b270ac56bf1c9 | NoteWrangler/public/js/routes.js | NoteWrangler/public/js/routes.js | // js/routes
(function() {
"use strict";
angular.module("NoteWrangler")
.config(config);
function config($routeProvider) {
$routeProvider
.when("/notes", {
templateUrl: "../templates/pages/notes/index.html",
controller: "NotesIndexController",
controllerAs: "notesIndexCtrl"
})
.when("/users", {
templateUrl: "../templates/pages/users/index.html"
})
.when("/notes/new", {
templateUrl: "templates/pages/notes/new.html",
controller: "NotesCreateController",
controllerAs: "notesCreateCtrl"
})
.when("/notes/:id", {
templateUrl: "templates/pages/notes/show.html",
controller: "NotesShowController",
controllerAs: "notesShowCtrl"
})
.otherwise({
redirectTo: "/",
templateUrl: "templates/pages/index/index.html"
});
}
})();
| // js/routes
(function() {
"use strict";
angular.module("NoteWrangler")
.config(config);
function config($routeProvider) {
$routeProvider
.when("/notes", {
templateUrl: "../templates/pages/notes/index.html",
controller: "NotesIndexController",
controllerAs: "notesIndexCtrl"
})
.when("/users", {
templateUrl: "../templates/pages/users/index.html",
controller: "UsersIndexController",
controllerAs: "usersIndexCtrl"
})
.when("/notes/new", {
templateUrl: "templates/pages/notes/new.html",
controller: "NotesCreateController",
controllerAs: "notesCreateCtrl"
})
.when("/notes/:id", {
templateUrl: "templates/pages/notes/show.html",
controller: "NotesShowController",
controllerAs: "notesShowCtrl"
})
.otherwise({
redirectTo: "/",
templateUrl: "templates/pages/index/index.html"
});
}
})();
| Add controller, controllerAs fields for /users route | Add controller, controllerAs fields for /users route
| JavaScript | mit | var-bin/angularjs-training,var-bin/angularjs-training,var-bin/angularjs-training,var-bin/angularjs-training | ---
+++
@@ -14,7 +14,9 @@
controllerAs: "notesIndexCtrl"
})
.when("/users", {
- templateUrl: "../templates/pages/users/index.html"
+ templateUrl: "../templates/pages/users/index.html",
+ controller: "UsersIndexController",
+ controllerAs: "usersIndexCtrl"
})
.when("/notes/new", {
templateUrl: "templates/pages/notes/new.html", |
4bb17bc94de157d6a6cefe1f5bd3114d880d8851 | src/cli.js | src/cli.js | #!/usr/bin/env node
var express = require('express')
var app = express()
var dafuq = require('./')
var argv = require('yargs')
.usage('$0 Leverages command-based api')
.describe('commands', 'the path to commands directory')
.alias('commands', 'c')
.alias('commands', 'path')
.alias('commands', 'directory')
.demand('commands')
.describe('shebang', 'the interpreter to use when running the command files')
.default('shebang', '')
.describe('port', 'the port where to listen for api call')
.alias('port', 'p')
.default('port', 3000)
.help('help')
.alias('help', 'h')
.argv;
app.use(dafuq({
path: argv.commands,
shebang: argv.shebang
}))
app.listen(argv.port)
| #!/usr/bin/env node
var path = require('path')
var express = require('express')
var app = express()
var dafuq = require('./')
var argv = require('yargs')
.usage('$0 Leverages command-based api')
.describe('commands', 'the path to commands directory')
.alias('commands', 'c')
.alias('commands', 'path')
.alias('commands', 'directory')
.demand('commands')
.describe('shebang', 'the interpreter to use when running the command files')
.default('shebang', '')
.describe('port', 'the port where to listen for api call')
.alias('port', 'p')
.default('port', 3000)
.help('help')
.alias('help', 'h')
.argv;
// Resolve full path when executing via CLI
if (require.main === module)
argv.commands = path.resolve(process.pwd(), argv.commands)
app.use(dafuq({
path: argv.commands,
shebang: argv.shebang
}))
app.listen(argv.port)
| Resolve path names relatives to cwd when using via CLI | Resolve path names relatives to cwd when using via CLI
| JavaScript | mit | Upplication/node-dafuq | ---
+++
@@ -1,4 +1,5 @@
#!/usr/bin/env node
+var path = require('path')
var express = require('express')
var app = express()
var dafuq = require('./')
@@ -19,6 +20,10 @@
.alias('help', 'h')
.argv;
+// Resolve full path when executing via CLI
+if (require.main === module)
+ argv.commands = path.resolve(process.pwd(), argv.commands)
+
app.use(dafuq({
path: argv.commands,
shebang: argv.shebang |
18973cb373cd8239af241aa97418257812c7b9e5 | java/jsinterop/base/jsinterop.js | java/jsinterop/base/jsinterop.js | /*
* Copyright 2017 Google Inc.
*
* 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.
*
*/
/**
* This file provides the @defines for jsinterop configuration options.
* See InternalPreconditions.java for details.
*/
goog.provide('jsinterop');
// Note that disabling checking only disables it for production.
/** @define {string} */
goog.define('jsinterop.checks', 'DISABLED');
| /*
* Copyright 2017 Google Inc.
*
* 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.
*
*/
/**
* This file provides the @defines for jsinterop configuration options.
* See InternalPreconditions.java for details.
*/
goog.provide('jsinterop');
// Note that disabling checking only disables it for production.
/** @define {string} */
jsinterop.checks = goog.define('jsinterop.checks', 'DISABLED');
| Replace calls to goog.define with assignments to the result of goog.define. | Replace calls to goog.define with assignments to the result of goog.define.
Background: To support goog.define within modules, it will soon stop exporting the named variable on the global object. In preparation for this, we need to manually export the names instead. This is effectively performing the rewriting that the compiler was already doing in RewriteClosurePrimitives.
Nonqualified names that are never mutated have been made into module locals for production code and globals for test code. This is consistent with production code being most likely to work compiled (where the compiler rewrites them to locals) and test code being most likely to work uncompiled (where Closure Library makes them global).
This change was generated by http://cs/experimental/users/sdh/util/googdef. See go/lsc-goog-define for more details.
Tested:
TAP train for global presubmit queue
http://test/OCL:240239877:BASE:243307276:1555129632846:51176e8e
PiperOrigin-RevId: 243689196
| JavaScript | apache-2.0 | google/jsinterop-base,google/jsinterop-base,google/jsinterop-base | ---
+++
@@ -25,4 +25,4 @@
// Note that disabling checking only disables it for production.
/** @define {string} */
-goog.define('jsinterop.checks', 'DISABLED');
+jsinterop.checks = goog.define('jsinterop.checks', 'DISABLED'); |
b0cfd42f4c031a8d99d9fe79e07a026703a5cc79 | app/controllers/home/settings.js | app/controllers/home/settings.js | import Ember from 'ember';
export default Ember.Controller.extend({
init () {
Ember.run.schedule('afterRender', () => {
componentHandler.upgradeAllRegistered();
});
},
settingsSnackbar (message) {
const _this = this;
const snackbarContainer = document.querySelector('#snackbar-container');
const handler = function () {
_this.transitionToRoute('home');
Ember.run.later(() => {
window.location.reload(true);
}, 500);
};
const data = {
message,
timeout: 4000,
actionHandler: handler,
actionText: 'Reload'
};
snackbarContainer.MaterialSnackbar.showSnackbar(data);
},
currency: function () {
let currency = this.get('model').findBy('id', 'currency');
if (!currency) {
return {
id: false,
setting: 'Currency',
value: '£'
};
}
return currency;
}.property('model.@each.value'),
userName: function () {
let userName = this.get('model').findBy('id', 'user-name');
if (!userName) {
return {
id: false,
setting: 'Name',
value: 'Guest'
};
}
return userName;
}.property('model.@each.value')
});
| import Ember from 'ember';
export default Ember.Controller.extend({
init () {
Ember.run.schedule('afterRender', () => {
componentHandler.upgradeAllRegistered();
});
},
settingsSnackbar (message) {
const _this = this;
const snackbarContainer = document.querySelector('#snackbar-container');
const handler = function () {
_this.transitionToRoute('home');
Ember.run.later(() => {
window.location.reload(true);
}, 500);
};
const data = {
message,
timeout: 4000,
actionHandler: handler,
actionText: 'Reload'
};
snackbarContainer.MaterialSnackbar.showSnackbar(data);
},
currency: function () {
let currency = this.get('model').findBy('id', 'currency');
if (!currency) {
return {
isDefault: true,
id: 'currency',
setting: 'Currency',
value: '$'
};
}
return currency;
}.property('model'),
userName: function () {
let userName = this.get('model').findBy('id', 'user-name');
if (!userName) {
return {
isDefault: true,
id: 'user-name',
setting: 'Name',
value: 'Guest'
};
}
return userName;
}.property('model'),
});
| Add isDefault property for each setting | refactor: Add isDefault property for each setting
| JavaScript | mit | pe1te3son/spendings-tracker,pe1te3son/spendings-tracker | ---
+++
@@ -28,26 +28,30 @@
},
currency: function () {
let currency = this.get('model').findBy('id', 'currency');
+
if (!currency) {
return {
- id: false,
+ isDefault: true,
+ id: 'currency',
setting: 'Currency',
- value: '£'
+ value: '$'
};
}
return currency;
- }.property('model.@each.value'),
+ }.property('model'),
userName: function () {
let userName = this.get('model').findBy('id', 'user-name');
if (!userName) {
return {
- id: false,
+ isDefault: true,
+ id: 'user-name',
setting: 'Name',
value: 'Guest'
};
}
return userName;
- }.property('model.@each.value')
+ }.property('model'),
+
}); |
f66631ee236787de5d93d1e4db7bf7f8a2fbea7a | lib/utils/parameter-validator.js | lib/utils/parameter-validator.js | 'use strict';
var _ = require('lodash');
var util = require('util');
var validateDeprecation = function(value, expectation, options) {
if (!options.deprecated) {
return;
}
var valid = (value instanceof options.deprecated || typeof(value) === typeof(options.deprecated.call()));
if (valid) {
var message = util.format('%s should not be of type "%s"', util.inspect(value), options.deprecated.name);
console.log('DEPRECATION WARNING:', options.deprecationWarning || message);
}
return valid;
};
var validate = function(value, expectation, options) {
// the second part of this check is a workaround to deal with an issue that occurs in node-webkit when
// using object literals. https://github.com/sequelize/sequelize/issues/2685
if (value instanceof expectation || typeof(value) === typeof(expectation.call())) {
return true;
}
throw new Error(util.format('The parameter (value: %s) is no %s.', value, expectation.name));
};
var ParameterValidator = module.exports = {
check: function(value, expectation, options) {
options = _.extend({
deprecated: false,
index: null,
method: null,
optional: false
}, options || {});
if (!value && options.optional) {
return true;
}
if (value === undefined) {
throw new Error('No value has been passed.');
}
if (expectation === undefined) {
throw new Error('No expectation has been passed.');
}
return false
|| validateDeprecation(value, expectation, options)
|| validate(value, expectation, options);
}
};
| 'use strict';
var _ = require('lodash');
var util = require('util');
var validateDeprecation = function(value, expectation, options) {
if (!options.deprecated) {
return;
}
var valid = value instanceof options.deprecated;
if (valid) {
var message = util.format('%s should not be of type "%s"', util.inspect(value), options.deprecated.name);
console.log('DEPRECATION WARNING:', options.deprecationWarning || message);
}
return valid;
};
var validate = function(value, expectation, options) {
if (value instanceof expectation) {
return true;
}
throw new Error(util.format('The parameter (value: %s) is no %s.', value, expectation.name));
};
var ParameterValidator = module.exports = {
check: function(value, expectation, options) {
options = _.extend({
deprecated: false,
index: null,
method: null,
optional: false
}, options || {});
if (!value && options.optional) {
return true;
}
if (value === undefined) {
throw new Error('No value has been passed.');
}
if (expectation === undefined) {
throw new Error('No expectation has been passed.');
}
return false
|| validateDeprecation(value, expectation, options)
|| validate(value, expectation, options);
}
};
| Revert "Workaround to deal with an issue in node-webkit where the validate function fails on object literals" | Revert "Workaround to deal with an issue in node-webkit where the validate function fails on object literals"
| JavaScript | mit | DavidMorton/sequelize,alanhoff/patch-sequelize-3489,mcanthony/sequelize,Americas/sequelize,bomattin/sequelize,kenjitayama/sequelize,PhinCo/sequelize,jingpei/sequelize,dbirchak/sequelize,3032441712/sequelize,pensierinmusica/sequelize,sreucherand/sequelize,Alexsey/sequelize,toddsby/sequelize,MagicIndustries/sequelize,kevinawoo/sequelize,alexbooker/sequelize,gutobortolozzo/sequelize,angelxmoreno/sequelize,felixfbecker/sequelize,lukealbao/sequelize,bulkan/sequelize,pentium100/sequelize,PsiXdev/sequelize,seshness/sequelize,nemisj/sequelize,adeo-proxideco/sequelize-oracle,jungseob86/sequelize,yjwong/sequelize,yotamofek/sequelize,toddbluhm/sequelize,ojolabs/sequelize,pola88/sequelize,sorin/sequelize,keik/sequelize,mendenhallmagic/sequelize,SerkanSipahi/sequelize,arcana261/sequelize,Znarkus/sequelize,sequelize/sequelize,growaspeople/sequelize,codyrigney92/sequelize,JYzor/sequelize,jasonku/sequelize,elijah513/sequelize,konnecteam/sequelize,Aweary/sequelize,scottty881/sequelize,Wsiegenthaler/sequelize,Daimonos/sequelize,mliszewski/sequelize,cbauerme/sequelize,pixel2/sequelize,ReikoR/sequelize,baotingfang/sequelize,grimurd/sequelize,darwinserrano/sequelize,xpepermint/sequelize,czardoz/sequelize,sequelize/sequelize,alitaheri/sequelize,seanjh/sequelize,rodrigoapereira/sequelize,Verdier/sequelize,skv-headless/sequelize,treejames/sequelize,majorleaguesoccer/sequelize,emhagman/sequelize,p0vidl0/sequelize,gintsgints/sequelize,festo/sequelize,venkatesh-tr/sequelize,denim2x/sequelize,bangbang93/sequelize,3ch01c/sequelize,botter-workshop/sequelize,brunocasanova/sequelize,treythomas123/sequelize,Ghost141/sequelize,eventhough/sequelize,globesherpa/sequelize,hariprasadkulkarni/sequelize,tmcleroy/sequelize,Bibernull/sequelize,zillow-oc/sequelize,inDream/sequelize,crzidea/sequelize,pimterry/sequelize,mikeringrose/sequelize,adeo-proxideco/sequelize-oracle,tedjt/sequelize,bassarisse/sequelize,StefanoDalpiaz/sequelize,lebretr/sequelize-oracle,mdarveau/sequelize,overlookmotel/sequelize,savageautomate/sequelize,johngiudici/sequelize,yonjah/sequelize,chriszs/sequelize,sequelize/sequelize,sobotklp/sequelize,camhux/sequelize,janmeier/sequelize,cschwarz/sequelize,tornillo/sequelize,jessicalc/sequelize,rfink/sequelize,smokeelow/sequelize,pedrox-3w/sequelize,konnecteam/sequelize,jayprakash1/sequelize,rpaterson/sequelize,givery-technology/sequelize,mvnnn/sequelize,yelmontaser/sequelize,overlookmotel/sequelize,atorkhov/sequelize,gorangajic/sequelize,ziflex/sequelize,subjectix/sequelize,andywhite37/sequelize,imjerrybao/sequelize,quiddle/sequelize,abossard/sequelize,appleboy/sequelize,oshoemaker/sequelize,oss92/sequelize,dantman/sequelize,meetearnest/sequelize,inDream/sequelize,abegines/sequelize,joe-at-fiziico/sequelize-point-support,lebretr/sequelize-oracle,eddieajau/sequelize,FredKSchott/sequelize,phanect/sequelize,topikachu/sequelize,scboffspring/sequelize,calvintwr/sequelize,sankethkatta/sequelize,briandamaged/sequelize,seegno-forks/sequelize,linalu1/sequelize,johanneswuerbach/sequelize,jchbh-duplicate/sequelize,wKich/sequelize,peachworks/sequelize,alekbarszczewski/sequelize,Kagaherk/sequelize,paolord/sequelize,jayprakash1/sequelize,Americas/sequelize,chauthai/sequelize,braddunbar/sequelize | ---
+++
@@ -8,7 +8,7 @@
return;
}
- var valid = (value instanceof options.deprecated || typeof(value) === typeof(options.deprecated.call()));
+ var valid = value instanceof options.deprecated;
if (valid) {
var message = util.format('%s should not be of type "%s"', util.inspect(value), options.deprecated.name);
@@ -20,10 +20,7 @@
};
var validate = function(value, expectation, options) {
-
- // the second part of this check is a workaround to deal with an issue that occurs in node-webkit when
- // using object literals. https://github.com/sequelize/sequelize/issues/2685
- if (value instanceof expectation || typeof(value) === typeof(expectation.call())) {
+ if (value instanceof expectation) {
return true;
}
@@ -56,4 +53,3 @@
|| validate(value, expectation, options);
}
};
- |
edf641fede9453d22c0d0ba3880aedbacb8fafec | app/scripts-browserify/mobile.js | app/scripts-browserify/mobile.js | 'use strict';
const helpers = require('../../shared/helpers');
function adjustClasses() {
if (helpers.isMobile($) === true) {
$('body').addClass('is-mobile').removeClass('is-desktop');
}
else {
$('body').addClass('is-desktop').removeClass('is-mobile');
}
}
window.addEventListener('resize', adjustClasses, false);
window.addEventListener('load', adjustClasses, false);
document.addEventListener('DOMContentLoaded', adjustClasses, false); | 'use strict';
const helpers = require('../../shared/helpers');
// General function to add 'is-mobile' and 'is-desktop' class to body.
// Used to adjust styling for mobile/desktop and called on multiple events.
function adjustClasses() {
if (helpers.isMobile($) === true) {
$('body').addClass('is-mobile').removeClass('is-desktop');
}
else {
$('body').addClass('is-desktop').removeClass('is-mobile');
}
}
window.addEventListener('resize', adjustClasses, false);
window.addEventListener('load', adjustClasses, false);
document.addEventListener('DOMContentLoaded', adjustClasses, false); | Add comment to adjustClasses function | Add comment to adjustClasses function
KB-419
| JavaScript | mit | CopenhagenCityArchives/kbh-billeder,CopenhagenCityArchives/kbh-billeder,CopenhagenCityArchives/kbh-billeder | ---
+++
@@ -2,6 +2,8 @@
const helpers = require('../../shared/helpers');
+// General function to add 'is-mobile' and 'is-desktop' class to body.
+// Used to adjust styling for mobile/desktop and called on multiple events.
function adjustClasses() {
if (helpers.isMobile($) === true) {
$('body').addClass('is-mobile').removeClass('is-desktop'); |
d0b06caafa83ddf4999981fd1859ad18f201eaba | lib/wed/modes/generic/generic.js | lib/wed/modes/generic/generic.js | define(function (require, exports, module) {
'use strict';
var Mode = require("../../mode").Mode;
var util = require("../../util");
var oop = require("../../oop");
var GenericDecorator = require("./generic_decorator").GenericDecorator;
var tr = require("./generic_tr").tr;
function GenericMode () {
Mode.call(this);
this._resolver = new util.NameResolver();
}
oop.inherit(GenericMode, Mode);
(function () {
// Modes must override this.
this.getAbsoluteResolver = function () {
return this._resolver;
};
this.makeDecorator = function () {
var obj = Object.create(GenericDecorator.prototype);
// Make arg an array and add our extra argument(s).
var args = Array.prototype.slice.call(arguments);
args.unshift(this);
GenericDecorator.apply(obj, args);
return obj;
};
this.getTransformationRegistry = function () {
return tr;
};
this.getContextualMenuItems = function () {
return [];
};
this.nodesAroundEditableContents = function (parent) {
var ret = [null, null];
var start = parent.childNodes[0];
if ($(start).is("._gui._start_button"))
ret[0] = start;
var end = parent.childNodes[parent.childNodes.length - 1];
if ($(end).is("_gui.start_button"))
ret[1] = end;
return ret;
};
}).call(GenericMode.prototype);
exports.Mode = GenericMode;
});
| define(function (require, exports, module) {
'use strict';
var Mode = require("../../mode").Mode;
var util = require("../../util");
var oop = require("../../oop");
var GenericDecorator = require("./generic_decorator").GenericDecorator;
var tr = require("./generic_tr").tr;
function GenericMode () {
Mode.call(this);
this._resolver = new util.NameResolver();
}
oop.inherit(GenericMode, Mode);
(function () {
// Modes must override this.
this.getAbsoluteResolver = function () {
return this._resolver;
};
this.makeDecorator = function () {
var obj = Object.create(GenericDecorator.prototype);
// Make arg an array and add our extra argument(s).
var args = Array.prototype.slice.call(arguments);
args.unshift(this);
GenericDecorator.apply(obj, args);
return obj;
};
this.getTransformationRegistry = function () {
return tr;
};
this.getContextualMenuItems = function () {
return [];
};
this.nodesAroundEditableContents = function (parent) {
var ret = [null, null];
var start = parent.childNodes[0];
if ($(start).is("._gui._start_button"))
ret[0] = start;
var end = parent.childNodes[parent.childNodes.length - 1];
if ($(end).is("._gui._end_button"))
ret[1] = end;
return ret;
};
}).call(GenericMode.prototype);
exports.Mode = GenericMode;
});
| Fix in how the contents is determined. | Fix in how the contents is determined.
| JavaScript | mpl-2.0 | mangalam-research/wed,mangalam-research/wed,lddubeau/wed,slattery/wed,lddubeau/wed,slattery/wed,mangalam-research/wed,lddubeau/wed,lddubeau/wed,mangalam-research/wed,slattery/wed | ---
+++
@@ -43,7 +43,7 @@
if ($(start).is("._gui._start_button"))
ret[0] = start;
var end = parent.childNodes[parent.childNodes.length - 1];
- if ($(end).is("_gui.start_button"))
+ if ($(end).is("._gui._end_button"))
ret[1] = end;
return ret;
}; |
02b12fb5c6c4375bc1aa4970ad351b6bd778e586 | client/views/resident/resident.js | client/views/resident/resident.js | Template.resident.created = function () {
// Get reference to template instance
var instance = this;
// Get Resident ID from router
instance.residentId = Router.current().params.residentId;
// Subscribe to current resident
instance.subscribe('residentComposite', instance.residentId);
instance.autorun(function () {
if (instance.subscriptionsReady()) {
instance.resident = Residents.findOne(instance.residentId);
instance.activities = Activities.find({residentIds: instance.residentId}).fetch();
}
});
};
Template.resident.events({
'click #edit-resident': function () {
// Get reference to template instance
var instance = Template.instance();
// Show the edit home modal
Modal.show('editResident', instance.resident);
}
});
Template.resident.helpers({
'resident': function () {
// Get reference to template instance
var instance = Template.instance();
// Get resident from template instance
var resident = instance.resident;
return resident;
},
'activities': function () {
// Get reference to template instance
const instance = Template.instance();
// Get activities from template instance
var activities = instance.activities;
return activities;
}
})
| Template.resident.created = function () {
// Get reference to template instance
var instance = this;
// Get Resident ID from router
instance.residentId = Router.current().params.residentId;
// Subscribe to current resident
instance.subscribe('residentComposite', instance.residentId);
// Subscribe to all roles except admin
instance.subscribe("allRolesExceptAdmin");
instance.autorun(function () {
if (instance.subscriptionsReady()) {
instance.resident = Residents.findOne(instance.residentId);
instance.activities = Activities.find({residentIds: instance.residentId}).fetch();
}
});
};
Template.resident.events({
'click #edit-resident': function () {
// Get reference to template instance
var instance = Template.instance();
// Show the edit home modal
Modal.show('editResident', instance.resident);
}
});
Template.resident.helpers({
'resident': function () {
// Get reference to template instance
var instance = Template.instance();
// Get resident from template instance
var resident = instance.resident;
return resident;
},
'activities': function () {
// Get reference to template instance
const instance = Template.instance();
// Get activities from template instance
var activities = instance.activities;
return activities;
}
})
| Add subscription to all roles except admin | Add subscription to all roles except admin
| JavaScript | agpl-3.0 | GeriLife/wellbeing,GeriLife/wellbeing,brylie/juhani-wellbeing,brylie/juhani-wellbeing,brylie/juhani-wellbeing,GeriLife/wellbeing,GeriLife/wellbeing,brylie/juhani-wellbeing | ---
+++
@@ -7,6 +7,9 @@
// Subscribe to current resident
instance.subscribe('residentComposite', instance.residentId);
+
+ // Subscribe to all roles except admin
+ instance.subscribe("allRolesExceptAdmin");
instance.autorun(function () {
if (instance.subscriptionsReady()) { |
3ce02018152b99f3a56766af8189ebe4d89e7f6c | js/ClientApp.js | js/ClientApp.js | /* global React ReactDOM */
var div = React.DOM.div
var h1 = React.DOM.h1
var MyTitle = React.createClass({
render () {
return (
div(null,
h1(null, 'A component!')
)
)
}
})
var MyTitleFactory = React.createFactory(MyTitle)
var MyFirstComponent = (
div(null,
MyTitleFactory(null),
MyTitleFactory(null),
MyTitleFactory(null)
)
)
ReactDOM.render(MyFirstComponent, document.getElementById('app')) | /* global React ReactDOM */
var div = React.DOM.div
var h1 = React.DOM.h1
var MyTitle = React.createClass({
render () {
return (
div(null,
h1({ style: { color: this.props.color, size: this.props.fontstyle } }, this.props.title)
)
)
}
})
var MyTitleFactory = React.createFactory(MyTitle)
var MyFirstComponent = React.createClass({
render: function () {
return (
div(null,
MyTitleFactory({title: 'a title prop', color: 'blue'}),
MyTitleFactory({title: 'another title', color: 'peru'}),
MyTitleFactory({title: 'it\'s the final title', color: 'lavender'})
)
)
}
})
ReactDOM.render(React.createElement(MyFirstComponent), document.getElementById('app')) | Add props to the MyTitle class. | Add props to the MyTitle class.
| JavaScript | mit | sheamunion/fem_intro_react_code_along,sheamunion/fem_intro_react_code_along | ---
+++
@@ -6,7 +6,7 @@
render () {
return (
div(null,
- h1(null, 'A component!')
+ h1({ style: { color: this.props.color, size: this.props.fontstyle } }, this.props.title)
)
)
}
@@ -14,12 +14,16 @@
var MyTitleFactory = React.createFactory(MyTitle)
-var MyFirstComponent = (
- div(null,
- MyTitleFactory(null),
- MyTitleFactory(null),
- MyTitleFactory(null)
- )
-)
+var MyFirstComponent = React.createClass({
+ render: function () {
+ return (
+ div(null,
+ MyTitleFactory({title: 'a title prop', color: 'blue'}),
+ MyTitleFactory({title: 'another title', color: 'peru'}),
+ MyTitleFactory({title: 'it\'s the final title', color: 'lavender'})
+ )
+ )
+ }
+})
-ReactDOM.render(MyFirstComponent, document.getElementById('app'))
+ReactDOM.render(React.createElement(MyFirstComponent), document.getElementById('app')) |
5f292e6d92b332fbc23735e3b13e6e3c71b15efa | server/discord/cogs/rate/index.js | server/discord/cogs/rate/index.js | const config = require('config');
const crypto = require('crypto');
module.exports.info = {
name: 'Rate and Rank',
description: 'Interprets and determines the relevant rank for a query',
category: 'Fun',
aliases: [
'rate',
'rank'
],
use: [
{
name: '',
value: 'Rate the empty air of silence after you and your children\'s deaths, past the end of civilisation, past the end of our Sun, past the heat death of the universe, and is at a global temperature of absolute zero.'
}, {
name: '<thing>',
value: 'Rate the thing'
}
]
};
module.exports.command = (message) => {
if (message.input) {
const input = message.input.replace(/[^@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\\]^_`abcdefghijklmno0123456789:;<=>?pqrstuvwxyz{|}~!ツ ]/g, '');
const hash = crypto.createHash('md5').update(input + config.get('secret')).digest('hex').substring(0, 4);
const rank = parseInt(hash, 16) % 11;
const thing = message.input.length < 100 ? input : `${input.substring(0, 100)}...`;
message.channel.createMessage(`I ${message.command} ${thing} a ${rank} out of 10`);
}
};
| const config = require('config');
const crypto = require('crypto');
module.exports.info = {
name: 'Rate and Rank',
description: 'Interprets and determines the relevant rank for a query',
category: 'Fun',
aliases: [
'rate',
'rank'
],
use: [
{
name: '',
value: 'Rate the empty air of silence after you and your children\'s deaths, past the end of civilisation, past the end of our Sun, past the heat death of the universe, and is at a global temperature of absolute zero.'
}, {
name: '<thing>',
value: 'Rate the thing'
}
]
};
module.exports.command = (message) => {
if (message.input) {
const input = message.input.replace(/[^@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\\]^_`abcdefghijklmno0123456789:;<=>?pqrstuvwxyz{|}~!ツ/' ]/g, '');
const hash = crypto.createHash('md5').update(input + config.get('secret')).digest('hex').substring(0, 4);
const rank = parseInt(hash, 16) % 11;
const thing = message.input.length < 100 ? input : `${input.substring(0, 100)}...`;
message.channel.createMessage(`I ${message.command} ${thing} a ${rank} out of 10`);
}
};
| Add some extra characters in | Add some extra characters in
| JavaScript | mit | moustacheminer/MSS-Discord,moustacheminer/MSS-Discord,moustacheminer/MSS-Discord | ---
+++
@@ -22,7 +22,7 @@
module.exports.command = (message) => {
if (message.input) {
- const input = message.input.replace(/[^@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\\]^_`abcdefghijklmno0123456789:;<=>?pqrstuvwxyz{|}~!ツ ]/g, '');
+ const input = message.input.replace(/[^@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\\]^_`abcdefghijklmno0123456789:;<=>?pqrstuvwxyz{|}~!ツ/' ]/g, '');
const hash = crypto.createHash('md5').update(input + config.get('secret')).digest('hex').substring(0, 4);
const rank = parseInt(hash, 16) % 11;
const thing = message.input.length < 100 ? input : `${input.substring(0, 100)}...`; |
6266384a9047bcd1327dbca5d980eac36a666b2a | client.js | client.js | var CodeMirror = require('codemirror')
, bindCodemirror = require('gulf-codemirror')
module.exports = setup
module.exports.consumes = ['editor']
module.exports.provides = []
function setup(plugin, imports, register) {
var editor = imports.editor
var cmCssLink = document.createElement('link')
cmCssLink.setAttribute('rel', "stylesheet")
cmCssLink.setAttribute('href', "/static/hive-editor-text-codemirror/static/codemirror.css")
document.head.appendChild(cmCssLink)
editor.registerEditor('text', function*() {
var editor = document.querySelector('#editor')
var cm = CodeMirror(function(el) {
editor.appendChild(el)
el.style['height'] = '100%'
el.style['width'] = '100%'
})
editor.style['height'] = '100%'
document.body.style['position'] = 'absolute'
document.body.style['bottom'] =
document.body.style['top'] =
document.body.style['left'] =
document.body.style['right'] = '0'
return bindCodemirror(cm)
})
register()
}
| var CodeMirror = require('codemirror')
, bindCodemirror = require('gulf-codemirror')
module.exports = setup
module.exports.consumes = ['editor']
module.exports.provides = []
function setup(plugin, imports, register) {
var editor = imports.editor
var cmCssLink = document.createElement('link')
cmCssLink.setAttribute('rel', "stylesheet")
cmCssLink.setAttribute('href', "/static/hive-editor-text-codemirror/static/codemirror.css")
document.head.appendChild(cmCssLink)
editor.registerEditor('CodeMirror', 'text', 'An extensible and performant code editor'
, function*(editorEl) {
var cm = CodeMirror(function(el) {
editorEl.appendChild(el)
el.style['height'] = '100%'
el.style['width'] = '100%'
})
editorEl.style['height'] = '100%'
document.body.style['position'] = 'absolute'
document.body.style['bottom'] =
document.body.style['top'] =
document.body.style['left'] =
document.body.style['right'] = '0'
return bindCodemirror(cm)
})
register()
}
| Upgrade to ew editor API | Upgrade to ew editor API
| JavaScript | mpl-2.0 | hivejs/hive-editor-text-codemirror | ---
+++
@@ -12,16 +12,16 @@
cmCssLink.setAttribute('href', "/static/hive-editor-text-codemirror/static/codemirror.css")
document.head.appendChild(cmCssLink)
- editor.registerEditor('text', function*() {
- var editor = document.querySelector('#editor')
+ editor.registerEditor('CodeMirror', 'text', 'An extensible and performant code editor'
+ , function*(editorEl) {
var cm = CodeMirror(function(el) {
- editor.appendChild(el)
-
+ editorEl.appendChild(el)
+
el.style['height'] = '100%'
el.style['width'] = '100%'
})
- editor.style['height'] = '100%'
+ editorEl.style['height'] = '100%'
document.body.style['position'] = 'absolute'
document.body.style['bottom'] =
document.body.style['top'] = |
1218a475d509565ffdb17f77229e7e09882c2c50 | packages/stratocacher/src/keys.js | packages/stratocacher/src/keys.js | import {GLOBAL_VERSION} from "./constants";
import events from "./events";
export function makeKey({
name,
version,
}, args){
const pieces = [
GLOBAL_VERSION,
name,
version || 0,
...args,
]
for (let i = 0; i < pieces.length; i++){
if (
typeof pieces[i] !== 'string' &&
typeof pieces[i] !== 'number'
){
const error = new Error(
`Bad key component (${pieces[i]})`
);
events.emit('error', {name, error});
return null;
}
}
return pieces.join('_');
}
| import {GLOBAL_VERSION} from "./constants";
import events from "./events";
export function makeKey({
name,
version,
}, args){
const pieces = [
GLOBAL_VERSION,
name,
version || 0,
...args,
]
for (let i = 0; i < pieces.length; i++){
if (
typeof pieces[i] !== 'string' &&
typeof pieces[i] !== 'number'
){
const error = new Error(
`Bad key component (${pieces[i]})`
);
events.emit('error', {name, error});
return null;
}
}
return JSON.stringify(pieces);
}
| Use JSON.stringify() instead of .join() to avoid key collision | Use JSON.stringify() instead of .join() to avoid key collision
| JavaScript | apache-2.0 | redfin/stratocacher | ---
+++
@@ -23,5 +23,5 @@
return null;
}
}
- return pieces.join('_');
+ return JSON.stringify(pieces);
} |
e96d16536bc827ef96a448c0bbc13cd8e578bb12 | src/Umbraco.Web.UI.Client/src/common/services/overlay.service.js | src/Umbraco.Web.UI.Client/src/common/services/overlay.service.js | /**
@ngdoc service
* @name umbraco.services.overlayService
*
* @description
* <b>Added in Umbraco 8.0</b>. Application-wide service for handling overlays.
*/
(function () {
"use strict";
function overlayService(eventsService, backdropService) {
function open(overlay) {
var backdropOptions = {};
// set the default overlay position to center
if(!overlay.position) {
overlay.position = "center";
}
// option to disable backdrop clicks
if(overlay.disableBackdropClick) {
backdropOptions.disableEventsOnClick = true;
}
overlay.show = true;
backdropService.open(backdropOptions);
eventsService.emit("appState.overlay", overlay);
}
function close() {
backdropService.close();
eventsService.emit("appState.overlay", null);
}
var service = {
open: open,
close: close
};
return service;
}
angular.module("umbraco.services").factory("overlayService", overlayService);
})(); | /**
@ngdoc service
* @name umbraco.services.overlayService
*
* @description
* <b>Added in Umbraco 8.0</b>. Application-wide service for handling overlays.
*/
(function () {
"use strict";
function overlayService(eventsService, backdropService) {
var currentOverlay = null;
function open(newOverlay) {
// prevent two open overlays at the same time
if(currentOverlay) {
return;
}
var backdropOptions = {};
var overlay = newOverlay;
// set the default overlay position to center
if(!overlay.position) {
overlay.position = "center";
}
// option to disable backdrop clicks
if(overlay.disableBackdropClick) {
backdropOptions.disableEventsOnClick = true;
}
overlay.show = true;
backdropService.open(backdropOptions);
currentOverlay = overlay;
eventsService.emit("appState.overlay", overlay);
}
function close() {
backdropService.close();
currentOverlay = null;
eventsService.emit("appState.overlay", null);
}
var service = {
open: open,
close: close
};
return service;
}
angular.module("umbraco.services").factory("overlayService", overlayService);
})(); | Make sure two overlays can't be open at the same time | Make sure two overlays can't be open at the same time
| JavaScript | mit | tcmorris/Umbraco-CMS,hfloyd/Umbraco-CMS,rasmuseeg/Umbraco-CMS,abryukhov/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,mattbrailsford/Umbraco-CMS,arknu/Umbraco-CMS,tompipe/Umbraco-CMS,KevinJump/Umbraco-CMS,dawoe/Umbraco-CMS,bjarnef/Umbraco-CMS,dawoe/Umbraco-CMS,umbraco/Umbraco-CMS,tcmorris/Umbraco-CMS,marcemarc/Umbraco-CMS,tcmorris/Umbraco-CMS,tompipe/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,mattbrailsford/Umbraco-CMS,arknu/Umbraco-CMS,umbraco/Umbraco-CMS,tcmorris/Umbraco-CMS,WebCentrum/Umbraco-CMS,NikRimington/Umbraco-CMS,abjerner/Umbraco-CMS,abryukhov/Umbraco-CMS,bjarnef/Umbraco-CMS,NikRimington/Umbraco-CMS,leekelleher/Umbraco-CMS,WebCentrum/Umbraco-CMS,lars-erik/Umbraco-CMS,KevinJump/Umbraco-CMS,madsoulswe/Umbraco-CMS,hfloyd/Umbraco-CMS,robertjf/Umbraco-CMS,abjerner/Umbraco-CMS,lars-erik/Umbraco-CMS,tcmorris/Umbraco-CMS,rasmuseeg/Umbraco-CMS,marcemarc/Umbraco-CMS,leekelleher/Umbraco-CMS,robertjf/Umbraco-CMS,robertjf/Umbraco-CMS,robertjf/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,bjarnef/Umbraco-CMS,hfloyd/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,umbraco/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,WebCentrum/Umbraco-CMS,leekelleher/Umbraco-CMS,NikRimington/Umbraco-CMS,leekelleher/Umbraco-CMS,KevinJump/Umbraco-CMS,abryukhov/Umbraco-CMS,abryukhov/Umbraco-CMS,mattbrailsford/Umbraco-CMS,marcemarc/Umbraco-CMS,KevinJump/Umbraco-CMS,robertjf/Umbraco-CMS,umbraco/Umbraco-CMS,tompipe/Umbraco-CMS,KevinJump/Umbraco-CMS,dawoe/Umbraco-CMS,arknu/Umbraco-CMS,abjerner/Umbraco-CMS,madsoulswe/Umbraco-CMS,abjerner/Umbraco-CMS,arknu/Umbraco-CMS,dawoe/Umbraco-CMS,mattbrailsford/Umbraco-CMS,lars-erik/Umbraco-CMS,rasmuseeg/Umbraco-CMS,marcemarc/Umbraco-CMS,lars-erik/Umbraco-CMS,marcemarc/Umbraco-CMS,tcmorris/Umbraco-CMS,hfloyd/Umbraco-CMS,lars-erik/Umbraco-CMS,madsoulswe/Umbraco-CMS,leekelleher/Umbraco-CMS,dawoe/Umbraco-CMS,hfloyd/Umbraco-CMS,bjarnef/Umbraco-CMS | ---
+++
@@ -10,9 +10,17 @@
function overlayService(eventsService, backdropService) {
- function open(overlay) {
+ var currentOverlay = null;
+
+ function open(newOverlay) {
+
+ // prevent two open overlays at the same time
+ if(currentOverlay) {
+ return;
+ }
var backdropOptions = {};
+ var overlay = newOverlay;
// set the default overlay position to center
if(!overlay.position) {
@@ -26,11 +34,13 @@
overlay.show = true;
backdropService.open(backdropOptions);
+ currentOverlay = overlay;
eventsService.emit("appState.overlay", overlay);
}
function close() {
backdropService.close();
+ currentOverlay = null;
eventsService.emit("appState.overlay", null);
}
|
cf99e1301e72356229a9613cbc8fe8ec0c59a5a5 | server/routes/profile.route.js | server/routes/profile.route.js | //----------------------------------------------------------------------------//
var express = require('express');
var router = express.Router();
var pg = require('pg');
var connectionString = require('../modules/db-config.module');
//----------------------------------------------------------------------------//
// Gets a user's profile info and FAQ entries
router.get('/:id', function(req, res) {
var userId = req.params.id;
pg.connect(connectionString, function(error, client, done) {
connectionErrorCheck(error);
client.query(
'SELECT * FROM mentors ' +
'JOIN faq ON mentors.id = faq.mentor_id ' +
'WHERE mentors.id = $1', [userId],
function(error, result) {
if(error) {
console.log('Error when searching mentors and FAQ tables: ', error);
res.sendStatus(500);
} else {
res.send(result.rows);
}
}
);
});
});
module.exports = router;
// Checks for errors connecting to the database
function connectionErrorCheck(error) {
if (error) {
console.log('Database connection error: ', error);
res.sendStatus(500);
}
}
| //----------------------------------------------------------------------------//
var express = require('express');
var router = express.Router();
var pg = require('pg');
var connectionString = require('../modules/db-config.module');
//----------------------------------------------------------------------------//
// Gets a user's profile info and FAQ entries
router.get('/:id', function(req, res) {
var userId = req.params.id;
pg.connect(connectionString, function(error, client, done) {
connectionErrorCheck(error);
client.query(
'SELECT * FROM mentors ' +
'FULL OUTER JOIN faq ON mentors.id = faq.mentor_id ' +
'WHERE mentors.id = $1', [userId],
function(error, result) {
done();
if(error) {
console.log('Error when searching mentors and FAQ tables: ', error);
res.sendStatus(500);
} else {
res.send(result.rows);
}
}
);
});
});
module.exports = router;
// Checks for errors connecting to the database
function connectionErrorCheck(error) {
if (error) {
console.log('Database connection error: ', error);
res.sendStatus(500);
}
}
| Fix issue with pulling users with FAQs | Fix issue with pulling users with FAQs
| JavaScript | mit | STEMentor/STEMentor,STEMentor/STEMentor | ---
+++
@@ -14,9 +14,10 @@
client.query(
'SELECT * FROM mentors ' +
- 'JOIN faq ON mentors.id = faq.mentor_id ' +
+ 'FULL OUTER JOIN faq ON mentors.id = faq.mentor_id ' +
'WHERE mentors.id = $1', [userId],
function(error, result) {
+ done();
if(error) {
console.log('Error when searching mentors and FAQ tables: ', error);
res.sendStatus(500); |
d25ffaac295662dc452ccb2fa930c254a202c591 | unify/framework/source/class/unify/ui/layout/queue/Visibility.js | unify/framework/source/class/unify/ui/layout/queue/Visibility.js | /* ***********************************************************************************************
Unify Project
Homepage: unify-project.org
License: MIT + Apache (V2)
Copyright: 2012, Sebastian Fastner, Mainz, Germany, http://unify-training.com
*********************************************************************************************** */
/**
* @break {unify.ui.layout.queue.Manager}
*/
(function() {
var widgetQueue = [];
core.Module("unify.ui.layout.queue.Visibility", {
name : "visibility",
add : function(widget) {
widgetQueue.push(widget);
unify.ui.layout.queue.Manager.run(unify.ui.layout.queue.Visibility.name);
},
flush : function() {
console.log("VISIBILITY: ", widgetQueue.length, widgetQueue);
for (var i=0,ii=widgetQueue.length; i<ii; i++) {
var widget = widgetQueue[i];
widget.checkAppearanceNeeds();
}
}
});
})(); | /* ***********************************************************************************************
Unify Project
Homepage: unify-project.org
License: MIT + Apache (V2)
Copyright: 2012, Sebastian Fastner, Mainz, Germany, http://unify-training.com
*********************************************************************************************** */
/**
* @break {unify.ui.layout.queue.Manager}
*/
(function() {
var widgetQueue = [];
core.Module("unify.ui.layout.queue.Visibility", {
name : "visibility",
add : function(widget) {
widgetQueue.push(widget);
unify.ui.layout.queue.Manager.run(unify.ui.layout.queue.Visibility.name);
},
flush : function() {
for (var i=0,ii=widgetQueue.length; i<ii; i++) {
var children = widgetQueue[i].getLayoutChildren();
widgetQueue = widgetQueue.concat(children);
}
for (i=0,ii=widgetQueue.length; i<ii; i++) {
widgetQueue[i].checkAppearanceNeeds();
}
}
});
})(); | Add children handling to visibility queue | Add children handling to visibility queue
| JavaScript | mit | unify/unify,unify/unify,unify/unify,unify/unify,unify/unify,unify/unify | ---
+++
@@ -25,11 +25,13 @@
},
flush : function() {
- console.log("VISIBILITY: ", widgetQueue.length, widgetQueue);
+ for (var i=0,ii=widgetQueue.length; i<ii; i++) {
+ var children = widgetQueue[i].getLayoutChildren();
+ widgetQueue = widgetQueue.concat(children);
+ }
- for (var i=0,ii=widgetQueue.length; i<ii; i++) {
- var widget = widgetQueue[i];
- widget.checkAppearanceNeeds();
+ for (i=0,ii=widgetQueue.length; i<ii; i++) {
+ widgetQueue[i].checkAppearanceNeeds();
}
}
}); |
e7c7b7ee125c4a514c280403bbf7ac03a9303f2b | video/getting-started/create-video-client/create-video-client.js | video/getting-started/create-video-client/create-video-client.js | // If you are requiring twilio-video from CommonJS,
//
// const Video = require('twilio-video');
//
// If you are including twilio-video.js from a <script> tag,
//
// const Video = Twilio.Video;
//
// 1.0.0-beta4 and earlier
// const client = new Video.Client(accessToken);
// 1.0.0-beta5 onwards the Client class has been removed.
// Instead of constructing a Client using an Access Token and then calling connect
// on it, you can simply call connect and pass it an Access Token directly.
const room = await Twilio.Video.connect('your-token'); | // If you are requiring twilio-video from CommonJS,
//
// const Video = require('twilio-video');
//
// If you are including twilio-video.js from a <script> tag,
//
// const Video = Twilio.Video;
//
// 1.0.0-beta4 and earlier
// const client = new Video.Client(accessToken);
// 1.0.0-beta5 onwards the Client class has been removed.
// Instead of constructing a Client using an Access Token and then calling connect
// on it, you can simply call connect and pass it an Access Token directly.
const Video = Twilio.Video;
Video.connect('your-token', { name: 'room-name' }).then(function(room) {
console.log('Connected to Room "%s"', room.name);
room.participants.forEach(participantConnected);
room.on('participantConnected', participantConnected);
room.on('participantDisconnected', participantDisconnected);
room.once('disconnected', function(error) {
return room.participants.forEach(participantDisconnected);
});
});
| Fix js snippet to not use async/await | Fix js snippet to not use async/await
| JavaScript | mit | teoreteetik/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,teoreteetik/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,teoreteetik/api-snippets,TwilioDevEd/api-snippets,teoreteetik/api-snippets,TwilioDevEd/api-snippets,teoreteetik/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,teoreteetik/api-snippets,TwilioDevEd/api-snippets,teoreteetik/api-snippets,teoreteetik/api-snippets,teoreteetik/api-snippets,TwilioDevEd/api-snippets | ---
+++
@@ -8,9 +8,21 @@
//
// 1.0.0-beta4 and earlier
-// const client = new Video.Client(accessToken);
+// const client = new Video.Client(accessToken);
-// 1.0.0-beta5 onwards the Client class has been removed.
-// Instead of constructing a Client using an Access Token and then calling connect
+// 1.0.0-beta5 onwards the Client class has been removed.
+// Instead of constructing a Client using an Access Token and then calling connect
// on it, you can simply call connect and pass it an Access Token directly.
-const room = await Twilio.Video.connect('your-token');
+const Video = Twilio.Video;
+
+Video.connect('your-token', { name: 'room-name' }).then(function(room) {
+ console.log('Connected to Room "%s"', room.name);
+
+ room.participants.forEach(participantConnected);
+ room.on('participantConnected', participantConnected);
+
+ room.on('participantDisconnected', participantDisconnected);
+ room.once('disconnected', function(error) {
+ return room.participants.forEach(participantDisconnected);
+ });
+}); |
4dc62bc4847c92cc6f5e220fc257d50c4ed67e5c | tasks/config.js | tasks/config.js | const normalize = require('path').normalize;
const root = 'angular/';
module.exports = {
appRoot: require('path').resolve(__dirname, '..'),
assetsPath: 'public/assets/',
src: {
rootPath: root,
typescript: normalize(root + '**/*.ts'),
sass: {
app: normalize(root + 'app/**/*.scss'),
globals: normalize(root + 'globals.scss')
},
views: normalize(root + 'app/**/*.html')
},
dependencies: {
js: [
'node_modules/es6-shim/es6-shim.min.js',
'node_modules/zone.js/dist/zone.js',
'node_modules/reflect-metadata/Reflect.js'
],
css: [
'node_modules/bootstrap/scss/bootstrap-flex.scss'
]
}
}; | const normalize = require('path').normalize;
const root = 'angular/';
module.exports = {
appRoot: require('path').resolve(__dirname, '..'),
assetsPath: 'public/assets/',
src: {
rootPath: root,
typescript: normalize(root + '**/*.ts'),
sass: {
app: normalize(root + 'app/**/*.scss'),
globals: normalize(root + 'globals.scss')
},
views: normalize(root + 'app/**/*.html')
},
dependencies: {
js: [
'node_modules/es6-shim/es6-shim.min.js',
'node_modules/zone.js/dist/zone.js',
'node_modules/reflect-metadata/Reflect.js'
],
css: [
'node_modules/bootstrap/scss/bootstrap-flex.scss',
'node_modules/loaders.css/src/loaders.scss'
]
}
}; | Include loader.css dependency in the build process | Include loader.css dependency in the build process
| JavaScript | mit | jaesung2061/anvel,jaesung2061/anvel,jaesung2061/anvel | ---
+++
@@ -20,7 +20,8 @@
'node_modules/reflect-metadata/Reflect.js'
],
css: [
- 'node_modules/bootstrap/scss/bootstrap-flex.scss'
+ 'node_modules/bootstrap/scss/bootstrap-flex.scss',
+ 'node_modules/loaders.css/src/loaders.scss'
]
}
}; |
cfd78346a75cd41e633407879ac20d7044c79be7 | __tests__/animation.spec.js | __tests__/animation.spec.js | var AnimationModule = require('../src/js/visuals/animation/index');
var PromiseAnimation = AnimationModule.PromiseAnimation;
var Animation = AnimationModule.Animation;
var Q = require('q');
describe('Promise animation', function() {
it('Will execute the closure', function() {
var value = 0;
var closure = function() {
value++;
};
var animation = new PromiseAnimation({
deferred: Q.defer(),
closure: closure
});
animation.play();
expect(value).toBe(1);
});
it('also takes animation packs', function() {
var value = 0;
var animation = new PromiseAnimation({
animation: function() { value++; }
});
animation.play();
expect(value).toBe(1);
});
it('Will resolve a deferred', function() {
var value = 0;
var closure = function() {
value++;
};
var animation = new PromiseAnimation({
closure: closure
});
animation
.then(function() {
value++;
})
.then(function() {
if (value !== 2) {
console.log('second promise failed!!');
} else {
console.log('1 more test passed');
}
// TODO -- make this work (aka the tests keep running until
// this assertion finishes
expect(value).toBe(2);
});
animation.play();
expect(value).toBe(1);
});
it('will make one from a normal animation', function() {
// poor mans spy function
var value = 0;
var anim = new Animation({
closure: function() { value++; }
});
var animPromise = PromiseAnimation.fromAnimation(anim);
animPromise
.then(function() {
value++;
}).then(function() {
// TODO fix
expect(value).toBe(2);
if (value !== 2) {
console.log('a test failed!!');
} else {
console.log('another test passed');
}
});
animPromise.play();
expect(value).toBe(1);
});
});
| var AnimationModule = require('../src/js/visuals/animation/index');
var PromiseAnimation = AnimationModule.PromiseAnimation;
var Animation = AnimationModule.Animation;
var Q = require('q');
describe('Promise animation', function() {
it('Will execute the closure', function() {
var value = 0;
var closure = function() {
value++;
};
var animation = new PromiseAnimation({
deferred: Q.defer(),
closure: closure
});
animation.play();
expect(value).toBe(1);
});
it('also takes animation packs', function() {
var value = 0;
var animation = new PromiseAnimation({
animation: function() { value++; }
});
animation.play();
expect(value).toBe(1);
});
});
| Remove animation tests to fix build | Remove animation tests to fix build
| JavaScript | mit | pcottle/learnGitBranching,pcottle/learnGitBranching,pcottle/learnGitBranching | ---
+++
@@ -26,57 +26,4 @@
animation.play();
expect(value).toBe(1);
});
-
- it('Will resolve a deferred', function() {
- var value = 0;
- var closure = function() {
- value++;
- };
-
- var animation = new PromiseAnimation({
- closure: closure
- });
- animation
- .then(function() {
- value++;
- })
- .then(function() {
- if (value !== 2) {
- console.log('second promise failed!!');
- } else {
- console.log('1 more test passed');
- }
- // TODO -- make this work (aka the tests keep running until
- // this assertion finishes
- expect(value).toBe(2);
- });
-
- animation.play();
- expect(value).toBe(1);
- });
-
- it('will make one from a normal animation', function() {
- // poor mans spy function
- var value = 0;
- var anim = new Animation({
- closure: function() { value++; }
- });
-
- var animPromise = PromiseAnimation.fromAnimation(anim);
- animPromise
- .then(function() {
- value++;
- }).then(function() {
- // TODO fix
- expect(value).toBe(2);
- if (value !== 2) {
- console.log('a test failed!!');
- } else {
- console.log('another test passed');
- }
- });
-
- animPromise.play();
- expect(value).toBe(1);
- });
}); |
588d56393840ef247a923df4d2f6eeabfdbe72b7 | test/integration/client/dev_setup.js | test/integration/client/dev_setup.js |
'use strict';
define(['../../../src/client/config'], function(config) {
config.baseUrl = '/';
config.paths.jquery = 'bower_components/jquery/dist/jquery';
config.paths['thehelp-test'] = 'node_modules/thehelp-test/dist/thehelp-test';
config.paths['thehelp-test-coverage'] =
'node_modules/thehelp-test/dist/thehelp-test-coverage';
config.paths['grunt-mocha-bridge'] =
'node_modules/thehelp-test/dist/grunt-mocha-bridge';
requirejs.config(config);
require(['jquery', window.entrypoint], function() {});
});
|
'use strict';
define(['../../../src/client/config'], function(config) {
config.baseUrl = '/';
config.paths['thehelp-test'] = 'node_modules/thehelp-test/dist/thehelp-test';
config.paths['thehelp-test-coverage'] =
'node_modules/thehelp-test/dist/thehelp-test-coverage';
config.paths['grunt-mocha-bridge'] =
'node_modules/thehelp-test/dist/grunt-mocha-bridge';
requirejs.config(config);
require([window.entrypoint], function() {});
});
| Remove remaining hints of jquery | Remove remaining hints of jquery | JavaScript | mit | thehelp/core,thehelp/core | ---
+++
@@ -5,7 +5,6 @@
config.baseUrl = '/';
- config.paths.jquery = 'bower_components/jquery/dist/jquery';
config.paths['thehelp-test'] = 'node_modules/thehelp-test/dist/thehelp-test';
config.paths['thehelp-test-coverage'] =
'node_modules/thehelp-test/dist/thehelp-test-coverage';
@@ -14,6 +13,6 @@
requirejs.config(config);
- require(['jquery', window.entrypoint], function() {});
+ require([window.entrypoint], function() {});
}); |
8223a053c2153793d0fd56051eee7e039ec393f2 | bit-ring.js | bit-ring.js | var assert = require('assert');
function BitRing(capacity) {
assert.ok(capacity < 32, 'Capacity must be less than 32');
this.capacity = capacity;
this.bits = 0;
this.pos = 0;
this.length = 0;
this._count = 0;
}
// Update the count and set or clear the next bit in the ring
BitRing.prototype.push = function(bool) {
var num = bool === true ? 1 : 0;
this._count += num - ((this.bits >>> this.pos) & 1);
this.bits ^= (-num ^ this.bits) & (1 << this.pos);
this.pos = (this.pos + 1) % this.capacity;
if (this.length < this.capacity) {
this.length++;
}
};
// Return the number of bits set
BitRing.prototype.count = function() {
return this._count;
};
module.exports = BitRing;
| function BitRing(capacity) {
this.capacity = capacity;
this.bits = new Uint8ClampedArray(capacity);
this.pos = 0;
this.length = 0;
this._count = 0;
}
// Update the count and set or clear the next bit in the ring
BitRing.prototype.push = function(bool) {
var num = bool === true ? 1 : 0;
this._count += num - this.bits[this.pos];
this.bits[this.pos] = num;
this.pos = (this.pos + 1) % this.capacity;
if (this.length < this.capacity) {
this.length++;
}
};
// Return the number of bits set
BitRing.prototype.count = function() {
return this._count;
};
module.exports = BitRing;
| Use a TypedArray instead of a number | Use a TypedArray instead of a number
| JavaScript | mit | uber/airlock | ---
+++
@@ -1,9 +1,6 @@
-var assert = require('assert');
-
function BitRing(capacity) {
- assert.ok(capacity < 32, 'Capacity must be less than 32');
this.capacity = capacity;
- this.bits = 0;
+ this.bits = new Uint8ClampedArray(capacity);
this.pos = 0;
this.length = 0;
this._count = 0;
@@ -12,8 +9,8 @@
// Update the count and set or clear the next bit in the ring
BitRing.prototype.push = function(bool) {
var num = bool === true ? 1 : 0;
- this._count += num - ((this.bits >>> this.pos) & 1);
- this.bits ^= (-num ^ this.bits) & (1 << this.pos);
+ this._count += num - this.bits[this.pos];
+ this.bits[this.pos] = num;
this.pos = (this.pos + 1) % this.capacity;
if (this.length < this.capacity) {
this.length++; |
6215b406f12d0b99760a5539e6aa68bbf35a8dca | week-7/group_project_solution.js | week-7/group_project_solution.js | // inputs will be:
var oddList = [1, 2, 3, 4, 5, 5, 7]
var evenList = [4, 4, 5, 5, 6, 6, 6, 7]
//Our functions are:
function Sum(list) {
for (var length = list.length, counter = 0, total = 0; counter < length; counter++) {
total += list[counter];
}
return total
}
function Mean(list) {
var length = list.length;
return Sum(list)/length;
}
function Median(list) {
var length = list.length;
var half = Math.floor(length/2);
if (length % 2 != 0) {
return list[half+1];
}
else {
var result = (list[half]+list[half+1])/2;
return result;
}
}
// Tests
console.log(Sum(oddList));
console.log(Sum(evenList));
console.log(Mean(oddList));
console.log(Mean(evenList));
console.log(Median(oddList)); // Yes, I know these medians aren't coming out right.
console.log(Median(evenList)); // But we aren't allowed to fix it. It's in the psuedocode. Oh well.
// Trevor: Refactor was not really possible since the code was already really clean and concise. Great job on that guys!
// Trevor: User Stories
// As a user, I want to give you two lists of numbers and I want you to run some tests on them. First, I will want to know the sum of each list. Second, I need to know the mean of these same lists. Lastly, I will need the median of the two lists.
//I think that's how we were supposed to do the user stories, it seems pretty simplistic. If there's anything more you all should think I should add to this feel free to let me know and I'll fiddle with it! | Add user stories and refactor to telephone. | Add user stories and refactor to telephone.
| JavaScript | mit | tnewcomb0/Phase-0,tnewcomb0/Phase-0,tnewcomb0/Phase-0 | ---
+++
@@ -0,0 +1,44 @@
+// inputs will be:
+var oddList = [1, 2, 3, 4, 5, 5, 7]
+var evenList = [4, 4, 5, 5, 6, 6, 6, 7]
+
+//Our functions are:
+function Sum(list) {
+ for (var length = list.length, counter = 0, total = 0; counter < length; counter++) {
+ total += list[counter];
+ }
+ return total
+}
+
+function Mean(list) {
+ var length = list.length;
+ return Sum(list)/length;
+}
+
+function Median(list) {
+ var length = list.length;
+ var half = Math.floor(length/2);
+ if (length % 2 != 0) {
+ return list[half+1];
+ }
+ else {
+ var result = (list[half]+list[half+1])/2;
+ return result;
+ }
+}
+
+// Tests
+console.log(Sum(oddList));
+console.log(Sum(evenList));
+console.log(Mean(oddList));
+console.log(Mean(evenList));
+console.log(Median(oddList)); // Yes, I know these medians aren't coming out right.
+console.log(Median(evenList)); // But we aren't allowed to fix it. It's in the psuedocode. Oh well.
+
+// Trevor: Refactor was not really possible since the code was already really clean and concise. Great job on that guys!
+
+// Trevor: User Stories
+
+// As a user, I want to give you two lists of numbers and I want you to run some tests on them. First, I will want to know the sum of each list. Second, I need to know the mean of these same lists. Lastly, I will need the median of the two lists.
+
+//I think that's how we were supposed to do the user stories, it seems pretty simplistic. If there's anything more you all should think I should add to this feel free to let me know and I'll fiddle with it! | |
e19d5958f6d1ed7bdcf2331b53400ccd74908dff | server/middleware/forward-http-request.js | server/middleware/forward-http-request.js | /* globals console */
/* eslint no-console: 0 */
import http from 'http';
import { get } from 'lodash';
import { ENV } from 'config';
import { stringifyObjectValues, setResponse, httpRequest } from 'utils';
/**
* Forwards an HTTP request using parameters either provided directly by an action,
* or matches a provided key to pre-defined parameters in ENV.json.
*/
const forwardHTTPRequest = async (action, next) => {
const { key } = action;
const keyIsInvalid = key && !ENV.httpRequests[key];
if (keyIsInvalid) {
throw new Error(`Property ${key} not declared in httpRequests property of ENV.json`);
}
const body = get(ENV, `httpRequests[${key}].body)`, action.body);
const optionsOverride = get(ENV, `httpRequests[${key}].options`, action.options);
const payload = body ? JSON.stringify(body) : null;
const headers = stringifyObjectValues({
...optionsOverride.headers,
...action.additionalHeaders
});
const options = {
method: action.method || 'POST',
...optionsOverride,
headers: {
'Content-Type': 'application/json',
'Content-Length': payload ? payload.length : 0,
...headers
}
};
try {
const { rawData } = await httpRequest({ options, payload });
const parsedData = rawData ? JSON.parse(rawData) : '';
if (!parsedData.error) {
return parsedData.access_token;
} else {
throw Error(rawData);
}
} catch (e) {
console.error(e);
}
};
export default forwardHTTPRequest;
| /* globals console */
/* eslint no-console: 0 */
import http from 'http';
import { get } from 'lodash';
import { ENV } from 'config';
import { stringifyObjectValues, setResponse, httpRequest } from 'utils';
/**
* Forwards an HTTP request using parameters either provided directly by an action,
* or matches a provided key to pre-defined parameters in ENV.json.
*/
const forwardHTTPRequest = async (action, next) => {
const { key } = action;
const keyIsInvalid = key && !ENV.httpRequests[key];
if (keyIsInvalid) {
throw new Error(`Property ${key} not declared in httpRequests property of ENV.json`);
}
const body = get(ENV, `httpRequests[${key}].body)`, action.body);
const optionsOverride = get(ENV, `httpRequests[${key}].options`, action.options);
const payload = body ? JSON.stringify(body) : null;
const headers = stringifyObjectValues({
...optionsOverride.headers,
...action.additionalHeaders
});
const options = {
method: action.method || 'POST',
...optionsOverride,
headers: {
'Content-Type': 'application/json',
'Content-Length': payload ? payload.length : 0,
...headers
}
};
try {
const response = await httpRequest({ options, payload });
console.log(`Received response: ${response}`);
} catch (e) {
console.error(e);
}
};
export default forwardHTTPRequest;
| Fix http forwarding response logging. | Fix http forwarding response logging.
| JavaScript | mit | Nase00/moirai,Nase00/moirai,Nase00/pantheon,Nase00/moirai,Nase00/pantheon | ---
+++
@@ -39,14 +39,8 @@
};
try {
- const { rawData } = await httpRequest({ options, payload });
- const parsedData = rawData ? JSON.parse(rawData) : '';
-
- if (!parsedData.error) {
- return parsedData.access_token;
- } else {
- throw Error(rawData);
- }
+ const response = await httpRequest({ options, payload });
+ console.log(`Received response: ${response}`);
} catch (e) {
console.error(e);
} |
44cd2fa9597ebe190bbf0c30693241925f34da0f | user-information-ajax/static/main.js | user-information-ajax/static/main.js | // This alert was to test to see if the JavaScript was loaded :)
// alert("Hello World")
$(document).ready(function() {
function myFunction() {
let userinput = $("#searchbarid").val();
$.post('/searchajax',{data: userinput},(data, status) =>{
// This is working, the data is being console.log
// console.log(data)
console.log(typeof data)
console.log ("I work")
// document.write(data);
$('.autocomplete').empty()
$( ".autocomplete" ).append("<p>" + data + "</p>")
})
}
let AjaxCanRun = true
$('#searchbarid').keyup(function(){
if (AjaxCanRun) {
// console.log('Key was pressed') This Works fine :)
// if (300 second have passed) {
myFunction()
// start counter
/// If false, the fuction will not run, if true it will runn
AjaxCanRun = false
}
// This set time out will make sure to see if the fuction can run
setTimeout(function() {
AjaxCanRun = true
}, 3000)
})
})
| // This alert was to test to see if the JavaScript was loaded :)
// alert("Hello World")
$(document).ready(function() {
function myFunction() {
let userinput = $("#searchbarid").val();
$.post('/searchajax',{data: userinput},(data, status) =>{
// This is working, the data is being console.log
// console.log(data)
console.log(typeof data)
console.log ("I work")
// document.write(data);
$('.autocomplete').empty()
$( ".autocomplete" ).append("<p>" + data + "</p>")
})
}
let AjaxCanRun = true
$('#searchbarid').keyup(function(){
if (AjaxCanRun) {
// console.log('Key was pressed') This Works fine :)
// if (300 second have passed) {
myFunction()
// start counter
/// If false, the fuction will not run, if true it will runn
AjaxCanRun = false
}
// This set time out will make sure to see if the fuction can run
setTimeout(function() {
AjaxCanRun = true
}, 300)
})
})
| Set the timeout back to 300 instead of 3000 which was used for debugging | Set the timeout back to 300 instead of 3000 which was used for debugging
| JavaScript | mit | demolia/NYCDA-Assignments,demolia/NYCDA-Assignments | ---
+++
@@ -37,7 +37,7 @@
setTimeout(function() {
AjaxCanRun = true
- }, 3000)
+ }, 300)
})
}) |
fb2bd5aba24cf1144d381403ab82f7da0a78fedf | src/components/WeaveElement.js | src/components/WeaveElement.js | import React, { Component } from 'react';
import '../styles/WeaveElement.css';
import '../styles/Scheme4.css';
class WeaveElement extends Component {
constructor() {
super();
this.handleClick = this.handleClick.bind(this);
}
componentState() {
const {row, col, currentState} = this.props;
if (currentState.weaves[row]) {
if (currentState.weaves[row][col] === undefined
|| currentState.weaves[row][col] === false) {
return false;
} else {
return true;
}
} else {
return false;
}
}
render() {
const style = this.componentState()
? "WeaveElement redWeaveElement"
: "WeaveElement whiteElement";
return (<div onClick={this.handleClick} className={style}></div>);
}
handleClick(e) {
if (this.componentState()) this.props.offClick(this.props.row, this.props.col);
else this.props.onClick(this.props.row, this.props.col);
}
}
export default WeaveElement;
| import React, { Component } from 'react';
import '../styles/WeaveElement.css';
import '../styles/Scheme4.css';
class WeaveElement extends Component {
constructor() {
super();
this.handleClick = this.handleClick.bind(this);
}
getThreadingNumber() {
const {col, currentState} = this.props;
const threadingState = currentState.threadings;
return (typeof threadingState[col] === 'number' )
? threadingState[col]
: -1;
}
getTreadlingNumber() {
const {row, currentState} = this.props;
const treadlingState = currentState.treadlings;
return (typeof treadlingState[row] === 'number' )
? treadlingState[row]
: -1;
}
getTieUpState(threadingNum, treadlingNum) {
if (threadingNum === -1 || treadlingNum === -1) return false;
const tieUpState = this.props.currentState.tieUp;
return (tieUpState[threadingNum] && tieUpState[threadingNum][treadlingNum])
? true
: false;
}
componentState() {
return this.getTieUpState(this.getThreadingNumber(), this.getTreadlingNumber());
}
render() {
const style = this.componentState()
? "WeaveElement redWeaveElement"
: "WeaveElement whiteElement";
return (<div onClick={this.handleClick} className={style}></div>);
}
handleClick(e) {
if (this.componentState()) this.props.offClick(this.props.row, this.props.col);
else this.props.onClick(this.props.row, this.props.col);
}
}
export default WeaveElement;
| Add more methods for weave's intersection | Add more methods for weave's intersection
| JavaScript | mit | nobus/weaver,nobus/weaver | ---
+++
@@ -8,19 +8,35 @@
this.handleClick = this.handleClick.bind(this);
}
+ getThreadingNumber() {
+ const {col, currentState} = this.props;
+ const threadingState = currentState.threadings;
+
+ return (typeof threadingState[col] === 'number' )
+ ? threadingState[col]
+ : -1;
+ }
+
+ getTreadlingNumber() {
+ const {row, currentState} = this.props;
+ const treadlingState = currentState.treadlings;
+
+ return (typeof treadlingState[row] === 'number' )
+ ? treadlingState[row]
+ : -1;
+ }
+
+ getTieUpState(threadingNum, treadlingNum) {
+ if (threadingNum === -1 || treadlingNum === -1) return false;
+ const tieUpState = this.props.currentState.tieUp;
+
+ return (tieUpState[threadingNum] && tieUpState[threadingNum][treadlingNum])
+ ? true
+ : false;
+ }
+
componentState() {
- const {row, col, currentState} = this.props;
-
- if (currentState.weaves[row]) {
- if (currentState.weaves[row][col] === undefined
- || currentState.weaves[row][col] === false) {
- return false;
- } else {
- return true;
- }
- } else {
- return false;
- }
+ return this.getTieUpState(this.getThreadingNumber(), this.getTreadlingNumber());
}
render() { |
456de23c7e56c3f8e1061cca0678735b1ffbdbc1 | webpack.config.dist.js | webpack.config.dist.js | module.exports = {
entry: './angular2-bootstrap-confirm.ts',
output: {
filename: './angular2-bootstrap-confirm.js',
libraryTarget: 'umd',
library: 'ng2BootstrapConfirm'
},
externals: {
'angular2/core': {
root: ['ng', 'core'],
commonjs: 'angular2/core',
commonjs2: 'angular2/core',
amd: 'angular2/core'
}
},
devtool: 'source-map',
module: {
preLoaders: [{
test: /\.ts$/, loader: 'tslint?emitErrors=true&failOnHint=true', exclude: /node_modules/
}],
loaders: [{
test: /\.ts$/, loader: 'ts', exclude: /node_modules/,
query: {
compilerOptions: {
declaration: true
}
}
}]
},
resolve: {
extensions: ['', '.ts', '.js']
}
}; | module.exports = {
entry: './angular2-bootstrap-confirm.ts',
output: {
filename: './angular2-bootstrap-confirm.js',
libraryTarget: 'umd',
library: 'ng2BootstrapConfirm'
},
externals: {
'angular2/core': {
root: ['ng', 'core'],
commonjs: 'angular2/core',
commonjs2: 'angular2/core',
amd: 'angular2/core'
},
'ng2-bootstrap/components/position': 'ng2-bootstrap/components/position'
},
devtool: 'source-map',
module: {
preLoaders: [{
test: /\.ts$/, loader: 'tslint?emitErrors=true&failOnHint=true', exclude: /node_modules/
}],
loaders: [{
test: /\.ts$/, loader: 'ts', exclude: /node_modules/,
query: {
compilerOptions: {
declaration: true
}
}
}]
},
resolve: {
extensions: ['', '.ts', '.js']
}
}; | Revert "Bundle the position service with the lib for now so users dont have to depend on ng2-bootstrap" | Revert "Bundle the position service with the lib for now so users dont have to depend on ng2-bootstrap"
This reverts commit 807a45bfcc7140124271e7e0e47e6fb4a22093b0.
| JavaScript | mit | mattlewis92/angular2-bootstrap-confirm,mattlewis92/angular2-bootstrap-confirm | ---
+++
@@ -11,7 +11,8 @@
commonjs: 'angular2/core',
commonjs2: 'angular2/core',
amd: 'angular2/core'
- }
+ },
+ 'ng2-bootstrap/components/position': 'ng2-bootstrap/components/position'
},
devtool: 'source-map',
module: { |
735598fa34216071b9a1cfc211dfe0a91e7dad16 | InstanceManager.js | InstanceManager.js | "use strict";
const aim = require("arangodb-instance-manager");
exports.create = () => {
let pathOrImage;
let runner;
if (process.env.RESILIENCE_ARANGO_BASEPATH) {
pathOrImage = process.env.RESILIENCE_ARANGO_BASEPATH;
runner = "local";
} else if (process.env.RESILIENCE_DOCKER_IMAGE) {
pathOrImage = process.env.RESILIENCE_DOCKER_IMAGE;
runner = "docker";
}
if (!runner) {
throw new Error(
'Must specify RESILIENCE_ARANGO_BASEPATH (source root dir including a "build" folder containing compiled binaries or RESILIENCE_DOCKER_IMAGE to test a docker container'
);
}
let storageEngine;
if (process.env.ARANGO_STORAGE_ENGINE) {
storageEngine = process.env.ARANGO_STORAGE_ENGINE;
if (storageEngine !== "rocksdb") {
storageEngine = "mmfiles";
}
} else {
storageEngine = "mmfiles";
}
return new aim.InstanceManager(pathOrImage, runner, storageEngine);
};
exports.endpointToUrl = aim.endpointToUrl;
exports.FailoverError = aim.FailoverError;
exports.waitForInstance = aim.InstanceManager.waitForInstance;
exports.rpAgency = aim.InstanceManager.rpAgency;
| "use strict";
const aim = require("arangodb-instance-manager");
exports.create = () => {
let pathOrImage;
let runner;
if (process.env.RESILIENCE_ARANGO_BASEPATH) {
pathOrImage = process.env.RESILIENCE_ARANGO_BASEPATH;
runner = "local";
} else if (process.env.RESILIENCE_DOCKER_IMAGE) {
pathOrImage = process.env.RESILIENCE_DOCKER_IMAGE;
runner = "docker";
}
if (!runner) {
throw new Error(
'Must specify RESILIENCE_ARANGO_BASEPATH (source root dir including a "build" folder containing compiled binaries or RESILIENCE_DOCKER_IMAGE to test a docker container'
);
}
let storageEngine = process.env.ARANGO_STORAGE_ENGINE === "mmfiles" ? "mmfiles" : "rocksdb";
return new aim.InstanceManager(pathOrImage, runner, storageEngine);
};
exports.endpointToUrl = aim.endpointToUrl;
exports.FailoverError = aim.FailoverError;
exports.waitForInstance = aim.InstanceManager.waitForInstance;
exports.rpAgency = aim.InstanceManager.rpAgency;
| Set the Default Storage_Engine to RocksDB | Set the Default Storage_Engine to RocksDB
| JavaScript | apache-2.0 | arangodb/resilience-tests | ---
+++
@@ -17,15 +17,7 @@
);
}
- let storageEngine;
- if (process.env.ARANGO_STORAGE_ENGINE) {
- storageEngine = process.env.ARANGO_STORAGE_ENGINE;
- if (storageEngine !== "rocksdb") {
- storageEngine = "mmfiles";
- }
- } else {
- storageEngine = "mmfiles";
- }
+ let storageEngine = process.env.ARANGO_STORAGE_ENGINE === "mmfiles" ? "mmfiles" : "rocksdb";
return new aim.InstanceManager(pathOrImage, runner, storageEngine);
};
|
a4ab990d520f90b2430653a230d00b0905f14a70 | src/modules/workshop-list/workshop-list.routes.js | src/modules/workshop-list/workshop-list.routes.js | // Imports
import UserRoles from '../../core/auth/constants/userRoles';
import WorkshopListController from './workshop-list.controller';
import WorkshopListHeaderController from './workshop-list-header.controller';
import { workshops } from './workshop-list.resolve';
/**
* @ngInject
* @param RouterHelper
*/
export default function routing(RouterHelper) {
const states = [{
state: 'modules.workshop_list',
config: {
url: '/palvelut/:serviceType/:carBrand/:city',
title: 'Korjaamot',
data: {
access: UserRoles.ROLE_ANON,
},
views: {
'content@': {
template: require('./partials/list.html'),
controller: WorkshopListController,
controllerAs: 'vm',
resolve: {
_workshops: workshops,
},
},
'header@': {
template: require('./partials/header.html'),
controller: WorkshopListHeaderController,
controllerAs: 'vm',
},
},
},
}];
RouterHelper.configureStates(states);
}
| // Imports
import UserRoles from '../../core/auth/constants/userRoles';
import WorkshopListController from './workshop-list.controller';
import WorkshopListHeaderController from './workshop-list-header.controller';
import { workshops } from './workshop-list.resolve';
/**
* @ngInject
* @param RouterHelper
* @param WorkshopListSharedDataService
*/
export default function routing(RouterHelper, WorkshopListSharedDataService) {
const states = [{
state: 'modules.workshop_list',
config: {
url: '/palvelut/:serviceType/:carBrand/:city',
title: 'Korjaamot',
data: {
access: UserRoles.ROLE_ANON,
},
views: {
'content@': {
template: require('./partials/list.html'),
controller: WorkshopListController,
controllerAs: 'vm',
resolve: {
_workshops: workshops,
_sharedData() {
// Set order to distance when coming to page
WorkshopListSharedDataService.order = 'distance';
},
},
},
'header@': {
template: require('./partials/header.html'),
controller: WorkshopListHeaderController,
controllerAs: 'vm',
},
},
},
}];
RouterHelper.configureStates(states);
}
| Set workshop list order to distance when coming to page | Set workshop list order to distance when coming to page
| JavaScript | mit | ProtaconSolutions/Poc24h-January2017-FrontEnd,ProtaconSolutions/Poc24h-January2017-FrontEnd | ---
+++
@@ -7,8 +7,9 @@
/**
* @ngInject
* @param RouterHelper
+ * @param WorkshopListSharedDataService
*/
-export default function routing(RouterHelper) {
+export default function routing(RouterHelper, WorkshopListSharedDataService) {
const states = [{
state: 'modules.workshop_list',
config: {
@@ -24,6 +25,10 @@
controllerAs: 'vm',
resolve: {
_workshops: workshops,
+ _sharedData() {
+ // Set order to distance when coming to page
+ WorkshopListSharedDataService.order = 'distance';
+ },
},
},
'header@': { |
b96161cdb6cb8da90e1a998d7147b80926b203be | src/inspect.js | src/inspect.js | var util = require("util");
var tty = require("tty");
var opts = {
depth: null,
// colors: tty.isatty(process.stdin),
colors: true,
};
function inspect(x) {
return util.inspect(x, opts);
}
module.exports = inspect;
| var util = require("util");
var tty = require("tty");
var opts = {
depth: null,
colors: tty.isatty(process.stdin),
// colors: true,
};
function inspect(x) {
return util.inspect(x, opts);
}
module.exports = inspect;
| Set colors back to auto | Set colors back to auto
| JavaScript | mit | squiggle-lang/squiggle-lang,saikobee/squiggle,wavebeem/squiggle,saikobee/expr-lang,saikobee/squiggle,wavebeem/squiggle,saikobee/expr-lang,wavebeem/squiggle,saikobee/expr-lang,saikobee/squiggle,squiggle-lang/squiggle-lang,squiggle-lang/squiggle-lang | ---
+++
@@ -3,8 +3,8 @@
var opts = {
depth: null,
- // colors: tty.isatty(process.stdin),
- colors: true,
+ colors: tty.isatty(process.stdin),
+ // colors: true,
};
function inspect(x) { |
a3dd2a013496efee8cc3ab0fef3ac8b165c69720 | lib/node_modules/@stdlib/array/float64/lib/index.js | lib/node_modules/@stdlib/array/float64/lib/index.js | 'use strict';
/**
* Typed array constructor which returns a typed array representing an array of double-precision floating-point numbers in the platform byte order.
*
* @module @stdlib/array/float64
*
* @example
* var ctor = require( '@stdlib/array/float64' );
*
* var arr = new ctor( 10 );
* // returns <Float64Array>
*/
// MODULES //
var hasFloat64ArraySupport = require( '@stdlib/utils/detect-float64array-support' );
// MAIN //
var ctor;
if ( hasFloat64ArraySupport() ) {
ctor = require( './float64array.js' );
} else {
ctor = require( './polyfill.js' );
}
// EXPORTS //
module.exports = ctor;
| 'use strict';
/**
* Typed array constructor which returns a typed array representing an array of double-precision floating-point numbers in the platform byte order.
*
* @module @stdlib/array/float64
*
* @example
* var ctor = require( '@stdlib/array/float64' );
*
* var arr = new ctor( 10 );
* // returns <Float64Array>
*/
// MODULES //
var hasFloat64ArraySupport = require( '@stdlib/utils/detect-float64array-support' );
var builtin = require( './float64array.js' );
var polyfill = require( './polyfill.js' );
// MAIN //
var ctor;
if ( hasFloat64ArraySupport() ) {
ctor = builtin;
} else {
ctor = polyfill;
}
// EXPORTS //
module.exports = ctor;
| Refactor to avoid dynamic module resolution | Refactor to avoid dynamic module resolution
| JavaScript | apache-2.0 | stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib | ---
+++
@@ -15,15 +15,17 @@
// MODULES //
var hasFloat64ArraySupport = require( '@stdlib/utils/detect-float64array-support' );
+var builtin = require( './float64array.js' );
+var polyfill = require( './polyfill.js' );
// MAIN //
var ctor;
if ( hasFloat64ArraySupport() ) {
- ctor = require( './float64array.js' );
+ ctor = builtin;
} else {
- ctor = require( './polyfill.js' );
+ ctor = polyfill;
}
|
de18cab53dbd7766db8d0e92da67eea291d1159f | server/boot/01-frontend-server.js | server/boot/01-frontend-server.js | var webpack = require('webpack');
var devConfig = require('../webpack.dev.config.js');
// If the node_env is NOT set to production, run the webpackdev server
// Uses the webpack.dev.config.js file for webpack configuration.
if (process.env.NODE_ENV !== 'production') {
var WebpackDevServer = require('webpack-dev-server');
new WebpackDevServer(webpack(devConfig), {
publicPath: devConfig.output.publicPath,
hot: true,
historyApiFallback: false
}).listen(8080, '0.0.0.0', function (err, result) {
if (err) {
return console.log(err);
}
console.log('Frontend located at http://localhost:8080/client/');
});
} | var webpack = require('webpack');
var devConfig = require('../webpack.dev.config.js');
// If the node_env is NOT set to production, run the webpackdev server
// Uses the webpack.dev.config.js file for webpack configuration.
if (process.env.NODE_ENV !== 'production') {
var WebpackDevServer = require('webpack-dev-server');
new WebpackDevServer(webpack(devConfig), {
publicPath: devConfig.output.publicPath,
hot: true,
historyApiFallback: false,
proxy: {
'/api/*': {
target: 'http://0.0.0.0:3000'
}
}
}).listen(8080, '0.0.0.0', function (err, result) {
if (err) {
return console.log(err);
}
console.log('Frontend located at http://localhost:8080/client/');
});
}
| Add basic proxy for api from webpack dev server | Add basic proxy for api from webpack dev server
| JavaScript | isc | codefordenver/encorelink,codefordenver/encorelink | ---
+++
@@ -10,7 +10,12 @@
new WebpackDevServer(webpack(devConfig), {
publicPath: devConfig.output.publicPath,
hot: true,
- historyApiFallback: false
+ historyApiFallback: false,
+ proxy: {
+ '/api/*': {
+ target: 'http://0.0.0.0:3000'
+ }
+ }
}).listen(8080, '0.0.0.0', function (err, result) {
if (err) {
return console.log(err); |
501fceee14551b946e1161993ac992bc87d84b9d | uri.js | uri.js | // State machine representing URI's
//
// Cleans up the logic of connecting via ports,
// urls or file sockets.
var state = require('state');
module.exports = state({
// Possible states for the URI
Initial: state('initial', {
set: function(value) {
this.input = value;
}
}),
Url: state(),
Port: state(),
File: state(),
// default for all
get: function() {
return this.input;
}
});
| // State machine representing URI's
//
// Cleans up the logic of connecting via ports,
// urls or file sockets.
var state = require('state');
var isUrl = require('is-url');
var _ = require('lodash');
module.exports = state({
// Possible states for the URI
Initial: state('initial', {
set: function(input) {
this.input = input;
},
listen: function(input) {
this.mode = 'listen';
this.set(input);
},
forward: function(input) {
this.mode = 'forward';
this.set(input);
}
}),
Url: state(),
Port: state(),
File: state(),
// default for all
get: function() {
return this.input;
},
// noops in all but initial state.
listen: function() {},
forward: function() {}
});
| Add listen and forward methods. | Add listen and forward methods.
We are adding noops to the root state (ie: not in the child states),
because we only need an implementation in the Initial state.
Future calls to these functions will no longer result in any
change of the object.
| JavaScript | mit | AdrianRossouw/waif | ---
+++
@@ -4,12 +4,22 @@
// urls or file sockets.
var state = require('state');
+var isUrl = require('is-url');
+var _ = require('lodash');
module.exports = state({
// Possible states for the URI
Initial: state('initial', {
- set: function(value) {
- this.input = value;
+ set: function(input) {
+ this.input = input;
+ },
+ listen: function(input) {
+ this.mode = 'listen';
+ this.set(input);
+ },
+ forward: function(input) {
+ this.mode = 'forward';
+ this.set(input);
}
}),
Url: state(),
@@ -19,5 +29,9 @@
// default for all
get: function() {
return this.input;
- }
+ },
+
+ // noops in all but initial state.
+ listen: function() {},
+ forward: function() {}
}); |
db3bcd017d7ea2c0d890c13d8ec7b5945642e0f4 | main.js | main.js | window.addEventListener('load', function() {
var context = document.getElementById('display').getContext('2d');
var display = new Display(context);
//var game = new Snake(display);
var video = new VideoGame(display, 'opencl.webm');
var image = new ImageGame(display, 'Snake.png');
var game = new ComposeGame(video, image);
var controls = new Controls(game);
game.run();
});
| window.addEventListener('load', function() {
var context = document.getElementById('display').getContext('2d');
var display = new Display(context);
var video = new VideoGame(display, 'opencl.webm');
var image = new ImageGame(display, 'Snake.png');
var title = new ComposeGame(video, image);
var controls = new Controls(title);
title.run();
title.press = function() {
title.stop();
controls.remove(title);
display.clear();
var snake = new Snake(display);
controls.add(snake);
snake.run();
};
});
| Make the title screen work. | Make the title screen work.
| JavaScript | unlicense | skeeto/ti-game | ---
+++
@@ -1,10 +1,17 @@
window.addEventListener('load', function() {
var context = document.getElementById('display').getContext('2d');
var display = new Display(context);
- //var game = new Snake(display);
var video = new VideoGame(display, 'opencl.webm');
var image = new ImageGame(display, 'Snake.png');
- var game = new ComposeGame(video, image);
- var controls = new Controls(game);
- game.run();
+ var title = new ComposeGame(video, image);
+ var controls = new Controls(title);
+ title.run();
+ title.press = function() {
+ title.stop();
+ controls.remove(title);
+ display.clear();
+ var snake = new Snake(display);
+ controls.add(snake);
+ snake.run();
+ };
}); |
961735251727e28dcbbe3c4d59152b014469525e | server/genres/genresController.js | server/genres/genresController.js | var Genre = require( './genres' );
module.exports = {
/*insert methods here*/
};
| var Genre = require( './genres' );
module.exports = {
getAllGenres: function() {},
getGenre: function() {}
};
| Add placeholder functions matching endpoint expectations | Add placeholder functions matching endpoint expectations
| JavaScript | mpl-2.0 | CantillatingZygote/rubiginouschanticleer,RubiginousChanticleer/rubiginouschanticleer,CantillatingZygote/rubiginouschanticleer,RubiginousChanticleer/rubiginouschanticleer | ---
+++
@@ -2,6 +2,8 @@
module.exports = {
- /*insert methods here*/
+ getAllGenres: function() {},
+
+ getGenre: function() {}
}; |
d9f65c2e8bed3afa9576b7ae0cf28e7a660f8e2e | index.js | index.js | #!/usr/bin/env node
var fs = require('fs');
var path = require('path');
var chalk = require('chalk');
var rimraf = require('rimraf');
var helpers = require('broccoli-kitchen-sink-helpers');
var Watcher = require('broccoli/lib/watcher');
var broccoli = require('broccoli');
function createWatcher(destDir, interval) {
var tree = broccoli.loadBrocfile();
var builder = new broccoli.Builder(tree);
var watcher = new Watcher(builder, {interval: interval || 100});
var atExit = function() {
builder.cleanup();
process.exit(1);
};
process.on('SIGINT', atExit);
process.on('SIGTERM', atExit);
watcher.on('change', function(results) {
rimraf.sync(destDir);
helpers.copyRecursivelySync(results.directory, destDir);
console.log(chalk.green("Build successful - " + Math.floor(results.totalTime / 1e6) + 'ms'));
});
watcher.on('error', function(err) {
console.log(chalk.red('\n\nBuild failed.\n'));
});
return watcher;
}
createWatcher(process.argv[2], process.argv[3]);
| #!/usr/bin/env node
var fs = require('fs');
var path = require('path');
var chalk = require('chalk');
var rimraf = require('rimraf');
var helpers = require('broccoli-kitchen-sink-helpers');
var Watcher = require('broccoli/lib/watcher');
var broccoli = require('broccoli');
function createWatcher(destDir, interval) {
var tree = broccoli.loadBrocfile();
var builder = new broccoli.Builder(tree);
var watcher = new Watcher(builder, {interval: interval || 100});
var atExit = function() {
builder.cleanup()
.then(function() {
process.exit(1);
});
};
process.on('SIGINT', atExit);
process.on('SIGTERM', atExit);
watcher.on('change', function(results) {
rimraf.sync(destDir);
helpers.copyRecursivelySync(results.directory, destDir);
console.log(chalk.green("Build successful - " + Math.floor(results.totalTime / 1e6) + 'ms'));
});
watcher.on('error', function(err) {
console.log(chalk.red('\n\nBuild failed.\n'));
});
return watcher;
}
createWatcher(process.argv[2], process.argv[3]);
| Allow cleanup to be a promise. | Allow cleanup to be a promise.
| JavaScript | mit | rwjblue/broccoli-timepiece | ---
+++
@@ -14,8 +14,10 @@
var watcher = new Watcher(builder, {interval: interval || 100});
var atExit = function() {
- builder.cleanup();
- process.exit(1);
+ builder.cleanup()
+ .then(function() {
+ process.exit(1);
+ });
};
process.on('SIGINT', atExit); |
edfcf41c59b7a91daf351004f72bbb09916a5158 | index.js | index.js | 'use strict'
module.exports = function (filename, encoding) {
}
| 'use strict'
module.exports = function (filename, encoding) {
var filename = filename || '.env'
var encoding = encoding || 'utf8'
}
| Add the default values to the parameters. | Add the default values to the parameters.
| JavaScript | mit | rhberro/thenv | ---
+++
@@ -1,5 +1,7 @@
'use strict'
+
module.exports = function (filename, encoding) {
-
+ var filename = filename || '.env'
+ var encoding = encoding || 'utf8'
} |
64bb28d5db80a5c6e32da653f963d3a672086a03 | tasks/build.js | tasks/build.js | const gulp = require('gulp')
const runSequence = require('run-sequence')
const harp = require('harp')
const webpackStream = require('webpack-stream')
const del = require('del')
const config = require('./config')
gulp.task('clean', () => {
return del(['./www'])
})
gulp.task('webpack:prod', () => {
return gulp.src('./site/public/_js/script.js')
.pipe(webpackStream(config.webpack.prod))
.pipe(gulp.dest('site/'))
})
gulp.task('harp:compile', done => {
harp.compile('./site', '../www', done)
})
gulp.task('build', done => {
runSequence(
['clean', 'dist'],
'webpack:prod',
'harp:compile',
done
)
})
| const gulp = require('gulp')
const runSequence = require('run-sequence')
const harp = require('harp')
const webpackStream = require('webpack-stream')
const del = require('del')
const config = require('./config')
gulp.task('clean', () => {
return del(['./www'])
})
gulp.task('webpack:prod', () => {
return gulp.src('./site/public/_js/script.js')
.pipe(webpackStream(config.webpack.prod))
.pipe(gulp.dest('site/'))
})
gulp.task('harp:compile', done => {
harp.compile('./site', '../www', done)
})
gulp.task('copy:site', done => {
return gulp.src(['./www/**/*'])
.pipe(gulp.dest('./releases'))
})
gulp.task('build', done => {
runSequence(
['clean', 'dist'],
'webpack:prod',
'harp:compile',
'copy:site',
'clean',
done
)
})
| Copy site into releases folder | site: Copy site into releases folder
| JavaScript | mit | ipfs/distributions,ipfs/distributions,ipfs/distributions | ---
+++
@@ -20,11 +20,18 @@
harp.compile('./site', '../www', done)
})
+gulp.task('copy:site', done => {
+ return gulp.src(['./www/**/*'])
+ .pipe(gulp.dest('./releases'))
+})
+
gulp.task('build', done => {
runSequence(
['clean', 'dist'],
'webpack:prod',
'harp:compile',
+ 'copy:site',
+ 'clean',
done
)
}) |
fa7adb475bf1eafb0cae139b1cd407d6b771bbe8 | analytics/snowplow.js | analytics/snowplow.js | //
// Hooks into Segment's analytics object events and tries to mimic the
// equivalent in snowplow.
//
// Segment automatically includes an analytics.page() call so to mimic that
// we send a page view to snowplow here.
snowplow('trackPageView');
analytics.on('track', function(event, properties, options){
snowplow(event, /*consult Will*/);
})
| //
// Hooks into Segment's analytics object events and tries to mimic the
// equivalent in snowplow.
//
// Segment automatically includes an analytics.page() call so to mimic that
// we send a page view to snowplow here.
snowplow('trackPageView');
analytics.on('track', function(event, properties, options) {
// consult Will
// snowplow(event);
});
| Disable Snowplow call for now | Disable Snowplow call for now
| JavaScript | mit | xtina-starr/force,joeyAghion/force,kanaabe/force,cavvia/force-1,dblock/force,eessex/force,oxaudo/force,joeyAghion/force,TribeMedia/force-public,damassi/force,mzikherman/force,oxaudo/force,dblock/force,erikdstock/force,joeyAghion/force,erikdstock/force,xtina-starr/force,izakp/force,oxaudo/force,kanaabe/force,kanaabe/force,joeyAghion/force,kanaabe/force,xtina-starr/force,izakp/force,dblock/force,yuki24/force,artsy/force,damassi/force,yuki24/force,artsy/force,anandaroop/force,anandaroop/force,mzikherman/force,eessex/force,izakp/force,damassi/force,xtina-starr/force,mzikherman/force,cavvia/force-1,anandaroop/force,artsy/force,cavvia/force-1,artsy/force,mzikherman/force,oxaudo/force,izakp/force,artsy/force-public,damassi/force,erikdstock/force,yuki24/force,kanaabe/force,eessex/force,eessex/force,TribeMedia/force-public,yuki24/force,erikdstock/force,artsy/force-public,anandaroop/force,cavvia/force-1 | ---
+++
@@ -7,7 +7,7 @@
// we send a page view to snowplow here.
snowplow('trackPageView');
-analytics.on('track', function(event, properties, options){
- snowplow(event, /*consult Will*/);
-})
-
+analytics.on('track', function(event, properties, options) {
+ // consult Will
+ // snowplow(event);
+}); |
9d60403b3fe383c72649d6ec5d404de4fd5706b8 | tasks/watch.js | tasks/watch.js | module.exports = {
options: {
atBegin: true,
interrupt: true,
},
develop: {
files: [
'package.json',
'src/**/*.js',
'tasks/**/*.js*',
'tests/**/*.js*',
'webpack.config.js',
'.flowconfig',
],
tasks: [
'build-tests',
'mochaTest',
'lint',
'flowbin:status',
],
},
};
| module.exports = {
options: {
atBegin: true,
interrupt: true,
},
develop: {
files: [
'package.json',
'src/**/*.js',
'tasks/**/*.js*',
'tests/**/*.js*',
'webpack.config.js',
'.flowconfig',
],
tasks: [
'flowbin:status',
'build-tests',
'mochaTest',
'lint',
],
},
};
| Check flow before running tests | Check flow before running tests
| JavaScript | mpl-2.0 | mozilla/web-ext,kumar303/web-ext,mozilla/web-ext,rpl/web-ext,shubheksha/web-ext,kumar303/web-ext,shubheksha/web-ext,rpl/web-ext | ---
+++
@@ -13,10 +13,10 @@
'.flowconfig',
],
tasks: [
+ 'flowbin:status',
'build-tests',
'mochaTest',
'lint',
- 'flowbin:status',
],
},
}; |
11337c044cd68a8a89b20187e78728b09010fa08 | ably.js | ably.js | (function (root, factory) {
'use strict';
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define([], factory);
} else {
// Browser globals (root is window)
root.ably = factory();
}
}(this, function () {
'use strict';
var Ably = {},
tests = [],
addTest = function (params) {
tests.push(params);
},
getTests = function () {
return tests;
},
when = function (test, variant, callback) {
};
// exported functions
Ably.addTest = addTest;
Ably.when = when;
Ably.getTests = getTests;
return Ably;
}));
| (function (root, factory) {
'use strict';
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define([], factory);
} else if (typeof exports === 'object') {
// Node. Does not work with strict CommonJS, but
// only CommonJS-like environments that support module.exports,
// like Node.
module.exports = factory();
} else {
// Browser globals (root is window)
root.ably = factory();
}
}(this, function () {
'use strict';
var Ably = {},
tests = [],
addTest = function (params) {
tests.push(params);
},
getTests = function () {
return tests;
},
when = function (test, variant, callback) {
};
// exported functions
Ably.addTest = addTest;
Ably.when = when;
Ably.getTests = getTests;
return Ably;
}));
| Add an exports-type module definition | Add an exports-type module definition
| JavaScript | mit | vgno/ably | ---
+++
@@ -3,6 +3,11 @@
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define([], factory);
+ } else if (typeof exports === 'object') {
+ // Node. Does not work with strict CommonJS, but
+ // only CommonJS-like environments that support module.exports,
+ // like Node.
+ module.exports = factory();
} else {
// Browser globals (root is window)
root.ably = factory(); |
ef8b6b315e7f58cb845387cbcbaa04bfbedc5d44 | app/js/PauseButton.js | app/js/PauseButton.js | /* @flow */
import React from 'react';
// Unpack TW.
const { settings } = chrome.extension.getBackgroundPage().TW;
export default function PauseButton() {
// $FlowFixMe Upgrade Flow to get latest React types
const [paused, setPaused] = React.useState(settings.get('paused'));
function pause() {
chrome.browserAction.setIcon({ path: 'img/icon-paused.png' });
settings.set('paused', true);
setPaused(true);
}
function play() {
chrome.browserAction.setIcon({ path: 'img/icon.png' });
settings.set('paused', false);
setPaused(false);
}
return (
<button className="btn btn-outline-dark btn-sm" onClick={paused ? play : pause} type="button">
{paused ? (
<>
<i className="fas fa-play" /> {chrome.i18n.getMessage('extension_resume')}
</>
) : (
<>
<i className="fas fa-pause" /> {chrome.i18n.getMessage('extension_pause')}
</>
)}
</button>
);
}
| /* @flow */
import React from 'react';
// Unpack TW.
const { settings } = chrome.extension.getBackgroundPage().TW;
export default function PauseButton() {
const [paused, setPaused] = React.useState(settings.get('paused'));
function pause() {
chrome.browserAction.setIcon({ path: 'img/icon-paused.png' });
settings.set('paused', true);
setPaused(true);
}
function play() {
chrome.browserAction.setIcon({ path: 'img/icon.png' });
settings.set('paused', false);
setPaused(false);
}
return (
<button className="btn btn-outline-dark btn-sm" onClick={paused ? play : pause} type="button">
{paused ? (
<>
<i className="fas fa-play" /> {chrome.i18n.getMessage('extension_resume')}
</>
) : (
<>
<i className="fas fa-pause" /> {chrome.i18n.getMessage('extension_pause')}
</>
)}
</button>
);
}
| Remove unneeded $FlowFixMe, it was fixed | Remove unneeded $FlowFixMe, it was fixed | JavaScript | mit | tabwrangler/tabwrangler,tabwrangler/tabwrangler,tabwrangler/tabwrangler | ---
+++
@@ -6,7 +6,6 @@
const { settings } = chrome.extension.getBackgroundPage().TW;
export default function PauseButton() {
- // $FlowFixMe Upgrade Flow to get latest React types
const [paused, setPaused] = React.useState(settings.get('paused'));
function pause() { |
cdc5b9bac475eed91921343552c71bc8f03adf7c | app/scripts/google.js | app/scripts/google.js |
(function loadGapi() {
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = "https://apis.google.com/js/client.js?onload=initgapi";
head.appendChild(script);
})();
(function() {
window.ga = window.ga || function(...args) {
(ga.q = ga.q || []).push(...args);
};
ga.l = Number(new Date);
ga('create', 'UA-60316581-1', 'auto');
})();
|
(function loadGapi() {
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = "https://apis.google.com/js/client.js?onload=initgapi";
head.appendChild(script);
})();
(function() {
window.ga = window.ga || function(...args) {
(ga.q = ga.q || []).push(...args);
};
ga.l = Number(new Date);
ga('create', 'UA-60316581-1', 'auto');
ga('set', 'DIMVersion', '$DIM_VERSION');
})();
| Add DIM version custom dimension | Add DIM version custom dimension
| JavaScript | mit | bhollis/DIM,DestinyItemManager/DIM,bhollis/DIM,48klocs/DIM,bhollis/DIM,delphiactual/DIM,bhollis/DIM,48klocs/DIM,chrisfried/DIM,chrisfried/DIM,delphiactual/DIM,DestinyItemManager/DIM,chrisfried/DIM,DestinyItemManager/DIM,chrisfried/DIM,48klocs/DIM,DestinyItemManager/DIM,delphiactual/DIM,LouisFettet/DIM,LouisFettet/DIM,delphiactual/DIM | ---
+++
@@ -13,4 +13,5 @@
};
ga.l = Number(new Date);
ga('create', 'UA-60316581-1', 'auto');
+ ga('set', 'DIMVersion', '$DIM_VERSION');
})(); |
1649379e24a98426c0f58e062378afb32da74811 | src/Statistics/Percent/Percent.js | src/Statistics/Percent/Percent.js | import React from 'react'
import Statistics from '../Statistics'
const Percent = ({metrics, label, icon, size, description=""}) => {
const value = metrics.partitions[label] ? metrics.partitions[label].yes : 0
const percent = value ? Math.floor((value / metrics.totalCount) * 100) : 0
const color = () => {
if (percent < 20) {
return 'red'
} else if (percent > 55) {
return 'green'
} else {
return 'yellow'
}
}
return (
<Statistics
value={percent}
label={label}
description={description}
unit="%"
icon={icon}
color={color()}
size={size} />
)
}
export default Percent
| import React from 'react'
import Statistics from '../Statistics'
const Percent = ({metrics, label, icon, size, description=""}) => {
const value = metrics.partitions[label] ? metrics.partitions[label].yes : 0
const percent = value ? Math.floor((value / metrics.totalCount) * 100) : 0
const color = () => {
if (percent < 20) {
return 'red'
} else if (percent > 55) {
return 'green'
} else {
return 'yellow'
}
}
return (
<Statistics
value={percent}
label={label === 'openness' ? 'open data' : label}
description={description}
unit="%"
icon={icon}
color={color()}
size={size} />
)
}
export default Percent
| Rename opennes in open data | Rename opennes in open data
| JavaScript | mit | sgmap/inspire,sgmap/inspire | ---
+++
@@ -17,7 +17,7 @@
return (
<Statistics
value={percent}
- label={label}
+ label={label === 'openness' ? 'open data' : label}
description={description}
unit="%"
icon={icon} |
7f93863a680a3857036441873088663f42e9380d | blueprints/ember-toastr/index.js | blueprints/ember-toastr/index.js | module.exports = {
description: 'Install toastr.js from bower'
// locals: function(options) {
// // Return custom template variables here.
// return {
// foo: options.entity.options.foo
// };
// }
afterInstall: function() {
return this.addBowerPackageToProject('toastr');
}
};
| module.exports = {
description: 'Install toastr.js from bower',
// locals: function(options) {
// // Return custom template variables here.
// return {
// foo: options.entity.options.foo
// };
// }
afterInstall: function() {
return this.addBowerPackageToProject('toastr');
}
};
| Fix syntax error with blueprint | Fix syntax error with blueprint
| JavaScript | mit | coladarci/ember-toastr,knownasilya/ember-toastr,GramozKrasniqi/ember-toastr,GramozKrasniqi/ember-toastr,coladarci/ember-toastr,knownasilya/ember-toastr | ---
+++
@@ -1,5 +1,5 @@
module.exports = {
- description: 'Install toastr.js from bower'
+ description: 'Install toastr.js from bower',
// locals: function(options) {
// // Return custom template variables here. |
f5a67f87778e910e876ed33510cc28e11155f4eb | src/js/components/search-input.js | src/js/components/search-input.js | import React from 'react'
import { sparqlConnect } from '../sparql/configure-sparql'
import { LOADING, LOADED, FAILED } from 'sparql-connect'
import { Link } from 'react-router'
import { uriToLink } from '../router-mapping'
import { connect } from 'react-redux'
import { changeKeyword } from '../actions/app-state'
function SearchInput({ keyword, changeKeyword }) {
return (
<span>
Search everything :
<input type="search" placeholder="Enter a keyword"
name="search_input"
value={keyword}
onChange={e => changeKeyword(e.target.value)} />
<Link to={uriToLink.searchItems(keyword)}>Search</Link>
</span>
)
}
const mapStateToProps = state => ({ keyword: state.appState.keyword })
export default connect(mapStateToProps, { changeKeyword })(SearchInput)
| import React from 'react'
import { sparqlConnect } from '../sparql/configure-sparql'
import { LOADING, LOADED, FAILED } from 'sparql-connect'
import { browserHistory } from 'react-router'
import { uriToLink } from '../router-mapping'
import { connect } from 'react-redux'
import { changeKeyword } from '../actions/app-state'
function SearchInput({ keyword, changeKeyword }) {
return (
<span>
Search everything :
<input type="search" placeholder="Enter a keyword"
name="search_input"
value={keyword}
onChange={e => changeKeyword(e.target.value)} />
<button
onClick={() => browserHistory.push(uriToLink.searchItems(keyword))}>
OK
</button>
</span>
)
}
const mapStateToProps = state => ({ keyword: state.appState.keyword })
export default connect(mapStateToProps, { changeKeyword })(SearchInput)
| Use button instead of link to navigate to search results | Use button instead of link to navigate to search results
| JavaScript | mit | Antoine-Dreyer/Classification-Explorer,Antoine-Dreyer/Classification-Explorer,UNECE/Classification-Explorer,UNECE/Classification-Explorer | ---
+++
@@ -1,7 +1,7 @@
import React from 'react'
import { sparqlConnect } from '../sparql/configure-sparql'
import { LOADING, LOADED, FAILED } from 'sparql-connect'
-import { Link } from 'react-router'
+import { browserHistory } from 'react-router'
import { uriToLink } from '../router-mapping'
import { connect } from 'react-redux'
import { changeKeyword } from '../actions/app-state'
@@ -14,7 +14,10 @@
name="search_input"
value={keyword}
onChange={e => changeKeyword(e.target.value)} />
- <Link to={uriToLink.searchItems(keyword)}>Search</Link>
+ <button
+ onClick={() => browserHistory.push(uriToLink.searchItems(keyword))}>
+ OK
+ </button>
</span>
)
} |
f9d43e6ea41e59c457d2790be1d8711f0a439daa | public/js/application.js | public/js/application.js | $(document).ready(function() {
$('.schema-explanation').hide();
$('.get-started').click(function(e){
e.preventDefault();
$('.home-explanation').hide();
$('.schema-explanation').show();
})
$('.modal-trigger').leanModal();
}); | $(document).ready(function() {
window.onbeforeunload = function() {
return "You are attempting to leave this page.";}
$('.schema-explanation').hide();
$('.get-started').click(function(e){
e.preventDefault();
$('.home-explanation').hide();
$('.schema-explanation').show();
})
$('.modal-trigger').leanModal();
}); | Add popup when back button or refresh hit | Add popup when back button or refresh hit
| JavaScript | mit | Srossmanreich/actvrcrd.ly,Srossmanreich/actvrcrd.ly,Srossmanreich/actvrcrd.ly | ---
+++
@@ -1,4 +1,7 @@
$(document).ready(function() {
+
+ window.onbeforeunload = function() {
+ return "You are attempting to leave this page.";}
$('.schema-explanation').hide();
|
64f7c1b70af2928ff2849bc71379c2a180b3ed24 | app/scripts/events.js | app/scripts/events.js | var events = new Vue({
el: '#events',
data: {
message: 'This is a message'
},
methods: {
foo: function(){
return 'I am a function';
}
}
}) | var events = new Vue({
el: '#events',
data: {
message: 'This is a message'
},
methods: {
foo: function(){
return 'I am a function';
}
}
})
function fetch_from_github() {
return [ { type: 'push',
handle: 'Billy Bob',
image_url: 'http://foo',
repo: 'prodigy',
branch: 'master',
date: '2017-03-22',
description: 'Some cool stuff'
},
{ type: 'create_branch',
handle: 'Billy Bob',
image_url: 'http://foo',
repo: 'prodigy',
branch: 'master2',
date: '2017-04-22',
description: 'Some cool stuff'
},
];
}
| Add initial fetching response format | Add initial fetching response format
| JavaScript | apache-2.0 | thabotitus/tech-hub,thabotitus/tech-hub | ---
+++
@@ -9,3 +9,23 @@
}
}
})
+
+function fetch_from_github() {
+ return [ { type: 'push',
+ handle: 'Billy Bob',
+ image_url: 'http://foo',
+ repo: 'prodigy',
+ branch: 'master',
+ date: '2017-03-22',
+ description: 'Some cool stuff'
+ },
+ { type: 'create_branch',
+ handle: 'Billy Bob',
+ image_url: 'http://foo',
+ repo: 'prodigy',
+ branch: 'master2',
+ date: '2017-04-22',
+ description: 'Some cool stuff'
+ },
+ ];
+} |
adfafdba669b60530f929d5e1cb01c7894880167 | back/SocketHandler.js | back/SocketHandler.js | 'use strict';
var uuid = require('uuid');
/**
* Handle the socket connections.
*
* @class
* @param {Socket.io} io - The listening object
*/
function SocketHandler(io) {
/**
* The states of all the users.
*/
var states = {};
// send the users position on a regular time basis
setInterval(function() {
io.emit('states', states);
}, 50/*ms*/);
/**
* Called on each new user connection.
*/
io.on('connection', function(socket) {
var user = {
id: uuid.v4()
};
// give the user its information
socket.emit('handshake', user);
// inform the other users
socket.broadcast.emit('new_player', user);
/**
* Called when a player sends its position.
*/
socket.on('state', function(data) {
// store the user state
states[user.id] = data;
});
/**
* Called when the user disconnects.
*/
socket.on('disconnect', function() {
// delete the user state
delete states[user.id];
});
});
}
module.exports = SocketHandler;
| 'use strict';
var uuid = require('uuid');
/**
* Handle the socket connections.
*
* @class
* @param {Socket.io} io - The listening object
*/
function SocketHandler(io) {
/**
* The states of all the users.
*/
var states = {
players: {}
};
// send the users position on a regular time basis
setInterval(function() {
io.emit('states', states);
}, 50/*ms*/);
/**
* Called on each new user connection.
*/
io.on('connection', function(socket) {
var user = {
id: uuid.v4()
};
// give the user its information
socket.emit('handshake', user);
// inform the other users
socket.broadcast.emit('new_player', user);
/**
* Called when a player sends its position.
*/
socket.on('state', function(data) {
// store the user state
states.players[user.id] = data;
});
/**
* Called when the user disconnects.
*/
socket.on('disconnect', function() {
// delete the user state
delete states.players[user.id];
});
});
}
module.exports = SocketHandler;
| Adjust event to match the doc | Adjust event to match the doc
| JavaScript | mit | fhacktory/collablock | ---
+++
@@ -16,7 +16,9 @@
* The states of all the users.
*/
- var states = {};
+ var states = {
+ players: {}
+ };
// send the users position on a regular time basis
setInterval(function() {
@@ -46,7 +48,7 @@
socket.on('state', function(data) {
// store the user state
- states[user.id] = data;
+ states.players[user.id] = data;
});
@@ -57,7 +59,7 @@
socket.on('disconnect', function() {
// delete the user state
- delete states[user.id];
+ delete states.players[user.id];
});
|
e443870e103737de294f31ff43c6cc9391420bd4 | test.js | test.js | var assert = require('./');
var execFile = require('child_process').execFile;
assert(assert, 'assert exists');
assert(assert.equal, 'assert.equal exists');
assert.equal(typeof assert.strictEqual, 'function',
'assert.strictEqual is a function');
assert.doesNotThrow(function() {
assert.throws(function() {
throw Error('expected!');
}, /expected/, 'supports assert.throws');
}, 'nested asserts are weird.');
execFile(process.execPath, ['test-bad-tests.js'], {}, assertBad);
execFile(process.execPath, ['.'], {}, assertNoTests);
function assertBad(err, stdout, stderr) {
assert(err, 'bad file exits with an error');
assert(/Premature exit with code \d/.test(stdout), 'exits prematurely');
assert(/No assertions run/.test(stdout),
'notices that no asserions were run');
}
function assertNoTests(err, stdout, stderr) {
assert(err, 'no assertions run is considered a failure');
assert(!/Premature exit with code/.test(stdout),
'does not exit prematurely');
assert(/No assertions run/.test(stdout), 'says no assertions were run');
}
| var assert = require('./');
var execFile = require('child_process').execFile;
assert(assert, 'assert exists');
assert(assert.equal, 'assert.equal exists');
assert.equal(typeof assert.strictEqual, 'function',
'assert.strictEqual is a function');
assert.doesNotThrow(function() {
assert.throws(function() {
throw Error('expected!');
}, /expected/, 'supports assert.throws');
}, 'nested asserts are weird.');
execFile(process.execPath, ['test-bad-tests.js'], {}, assertBad);
execFile(process.execPath, ['.'], {}, assertNoTests);
function assertBad(err, stdout, stderr) {
assertHeader(err, stdout, stderr);
assert(err, 'bad file exits with an error');
assert.notEqual(stderr, '', 'tapsert does not clear stderr');
assert(/Premature exit with code \d/.test(stdout), 'exits prematurely');
assert(/No assertions run/.test(stdout),
'notices that no asserions were run');
}
function assertNoTests(err, stdout, stderr) {
assertHeader(err, stdout, stderr);
assert(err, 'no assertions run is considered a failure');
assert.equal(stderr, '', 'tapsert does not write to stderr');
assert(!/Premature exit with code/.test(stdout),
'does not exit prematurely');
assert(/No assertions run/.test(stdout), 'says no assertions were run');
}
function assertHeader(err, stdout, stderr) {
assert(/^[\s]*TAP version 13/.test(stdout),
'TAP version header is the first non-whitespace output');
}
| Test for headers and stderr changes | Test for headers and stderr changes
| JavaScript | mit | tapjs/tapsert,rmg/tapsert | ---
+++
@@ -15,15 +15,24 @@
execFile(process.execPath, ['.'], {}, assertNoTests);
function assertBad(err, stdout, stderr) {
+ assertHeader(err, stdout, stderr);
assert(err, 'bad file exits with an error');
+ assert.notEqual(stderr, '', 'tapsert does not clear stderr');
assert(/Premature exit with code \d/.test(stdout), 'exits prematurely');
assert(/No assertions run/.test(stdout),
'notices that no asserions were run');
}
function assertNoTests(err, stdout, stderr) {
+ assertHeader(err, stdout, stderr);
assert(err, 'no assertions run is considered a failure');
+ assert.equal(stderr, '', 'tapsert does not write to stderr');
assert(!/Premature exit with code/.test(stdout),
'does not exit prematurely');
assert(/No assertions run/.test(stdout), 'says no assertions were run');
}
+
+function assertHeader(err, stdout, stderr) {
+ assert(/^[\s]*TAP version 13/.test(stdout),
+ 'TAP version header is the first non-whitespace output');
+} |
ca92caa879182d6d07e52388c2d1ad68c1560c3f | app/assets/javascripts/welcome.js | app/assets/javascripts/welcome.js |
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var programsArr = prepareProgramsCount(countPrograms(gon.programs))
var data = google.visualization.arrayToDataTable(programsArr);
var options = {
legend: 'none',
slices: { 4: {offset: 0.2},
11: {offset: 0.3},
14: {offset: 0.4},
15: {offset: 0.5},
}
}
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
}
function countPrograms(data) {
var programsCount = {}
for (i=0; i < data.length; i++) {
var interest_area = data[i].interest_area;
programsCount[interest_area] = 0 ;
}
for (i=0; i < data.length; i++) {
var interest_area = data[i].interest_area;
programsCount[interest_area] += 1 ;
}
return programsCount
}
function prepareProgramsCount(hsh) {
var programsArr = new Array()
programsArr.push(['Task', 'Hours per Day'])
for (var k in hsh) {
programsArr.push([k, hsh[k]]);
}
return programsArr
}
|
// google.load("visualization", "1", {packages:["corechart"]});
// google.setOnLoadCallback(drawChart);
// function drawChart() {
// var programsArr = prepareProgramsCount(countPrograms(gon.programs))
// var data = google.visualization.arrayToDataTable(programsArr);
// var options = {
// legend: 'none',
// slices: { 4: {offset: 0.2},
// 11: {offset: 0.3},
// 14: {offset: 0.4},
// 15: {offset: 0.5},
// }
// }
// var chart = new google.visualization.PieChart(document.getElementById('piechart'));
// chart.draw(data, options);
// }
// function countPrograms(data) {
// var programsCount = {}
// for (i=0; i < data.length; i++) {
// var interest_area = data[i].interest_area;
// programsCount[interest_area] = 0 ;
// }
// for (i=0; i < data.length; i++) {
// var interest_area = data[i].interest_area;
// programsCount[interest_area] += 1 ;
// }
// return programsCount
// }
// function prepareProgramsCount(hsh) {
// var programsArr = new Array()
// programsArr.push(['Task', 'Hours per Day'])
// for (var k in hsh) {
// programsArr.push([k, hsh[k]]);
// }
// return programsArr
// }
| Comment out text for pie chart | Comment out text for pie chart
| JavaScript | mit | fma2/nyc-high-school-programs,fma2/nyc-high-school-programs | ---
+++
@@ -1,45 +1,45 @@
-google.load("visualization", "1", {packages:["corechart"]});
-google.setOnLoadCallback(drawChart);
-function drawChart() {
- var programsArr = prepareProgramsCount(countPrograms(gon.programs))
- var data = google.visualization.arrayToDataTable(programsArr);
+// google.load("visualization", "1", {packages:["corechart"]});
+// google.setOnLoadCallback(drawChart);
+// function drawChart() {
+// var programsArr = prepareProgramsCount(countPrograms(gon.programs))
+// var data = google.visualization.arrayToDataTable(programsArr);
- var options = {
- legend: 'none',
- slices: { 4: {offset: 0.2},
- 11: {offset: 0.3},
- 14: {offset: 0.4},
- 15: {offset: 0.5},
- }
- }
+// var options = {
+// legend: 'none',
+// slices: { 4: {offset: 0.2},
+// 11: {offset: 0.3},
+// 14: {offset: 0.4},
+// 15: {offset: 0.5},
+// }
+// }
- var chart = new google.visualization.PieChart(document.getElementById('piechart'));
+// var chart = new google.visualization.PieChart(document.getElementById('piechart'));
- chart.draw(data, options);
-}
+// chart.draw(data, options);
+// }
-function countPrograms(data) {
- var programsCount = {}
- for (i=0; i < data.length; i++) {
- var interest_area = data[i].interest_area;
- programsCount[interest_area] = 0 ;
- }
- for (i=0; i < data.length; i++) {
- var interest_area = data[i].interest_area;
- programsCount[interest_area] += 1 ;
- }
- return programsCount
-}
+// function countPrograms(data) {
+// var programsCount = {}
+// for (i=0; i < data.length; i++) {
+// var interest_area = data[i].interest_area;
+// programsCount[interest_area] = 0 ;
+// }
+// for (i=0; i < data.length; i++) {
+// var interest_area = data[i].interest_area;
+// programsCount[interest_area] += 1 ;
+// }
+// return programsCount
+// }
-function prepareProgramsCount(hsh) {
- var programsArr = new Array()
- programsArr.push(['Task', 'Hours per Day'])
- for (var k in hsh) {
- programsArr.push([k, hsh[k]]);
- }
- return programsArr
-}
+// function prepareProgramsCount(hsh) {
+// var programsArr = new Array()
+// programsArr.push(['Task', 'Hours per Day'])
+// for (var k in hsh) {
+// programsArr.push([k, hsh[k]]);
+// }
+// return programsArr
+// }
|
9f445584f77d657ef47078f418c810f243e8d3b3 | test/model/lib/property-groups-process.js | test/model/lib/property-groups-process.js | 'use strict';
var Database = require('dbjs')
, defineFormSection = require('../../../model/form-section');
module.exports = function (t, a) {
var db = new Database()
, FormSection = defineFormSection(db)
, PropertyGroupProcess = t(db)
, process = new PropertyGroupProcess();
process.map._descriptorPrototype_.type = FormSection;
process.define('applicable', { type: FormSection });
a(process.progress, 1);
a(process.weight, 0);
process.map.define('test', { nested: true });
a(process.progress, 1);
a(process.weight, 0);
};
| 'use strict';
var Database = require('dbjs')
, defineFormSection = require('../../../model/form-section');
module.exports = function (t, a) {
var db = new Database()
, FormSection = defineFormSection(db)
, PropertyGroupProcess = t(db)
, process = new PropertyGroupProcess();
process.map._descriptorPrototype_.type = FormSection;
process.define('applicable', { type: FormSection });
a(process.progress, 1);
a(process.weight, 0);
process.map.define('test', { nested: true });
a(process.progress, 1);
a(process.weight, 0);
a(process.status, undefined);
a(process.isRejected, false);
process.status = 'invalid';
a(process.status, 'invalid');
a(process.isRejected, false);
process.rejectReason = 'test';
a(process.isRejected, true);
process.status = 'valid';
a(process.isRejected, false);
};
| Add tests to new PropertyGroupsProcess properties | Add tests to new PropertyGroupsProcess properties
| JavaScript | mit | egovernment/eregistrations,egovernment/eregistrations,egovernment/eregistrations | ---
+++
@@ -4,11 +4,11 @@
, defineFormSection = require('../../../model/form-section');
module.exports = function (t, a) {
- var db = new Database()
- , FormSection = defineFormSection(db)
+ var db = new Database()
+ , FormSection = defineFormSection(db)
, PropertyGroupProcess = t(db)
- , process = new PropertyGroupProcess();
+ , process = new PropertyGroupProcess();
process.map._descriptorPrototype_.type = FormSection;
process.define('applicable', { type: FormSection });
@@ -19,4 +19,17 @@
process.map.define('test', { nested: true });
a(process.progress, 1);
a(process.weight, 0);
+
+ a(process.status, undefined);
+ a(process.isRejected, false);
+
+ process.status = 'invalid';
+ a(process.status, 'invalid');
+ a(process.isRejected, false);
+
+ process.rejectReason = 'test';
+ a(process.isRejected, true);
+
+ process.status = 'valid';
+ a(process.isRejected, false);
}; |
6f9082f31142529e3be7d301b92b30ec7c240ecc | components/utils/utils.js | components/utils/utils.js | export const getViewport = () => ({
height: window.innerHeight || document.documentElement.offsetHeight,
width: window.innerWidth || document.documentElement.offsetWidth,
});
export const isElementOverflowing = element =>
element.clientWidth < element.scrollWidth || element.clientHeight < element.scrollHeight;
| export const getViewport = () => ({
height: window.innerHeight || document.documentElement.offsetHeight,
width: window.innerWidth || document.documentElement.offsetWidth,
});
export const isElementOverflowingX = element =>
element.clientWidth < element.scrollWidth;
export const isElementOverflowingY = element =>
element.clientHeight < element.scrollHeight;
| Split up util function to detect horizontal & vertical overflowing separately | Split up util function to detect horizontal & vertical overflowing separately
| JavaScript | mit | teamleadercrm/teamleader-ui | ---
+++
@@ -3,5 +3,8 @@
width: window.innerWidth || document.documentElement.offsetWidth,
});
-export const isElementOverflowing = element =>
- element.clientWidth < element.scrollWidth || element.clientHeight < element.scrollHeight;
+export const isElementOverflowingX = element =>
+ element.clientWidth < element.scrollWidth;
+
+export const isElementOverflowingY = element =>
+ element.clientHeight < element.scrollHeight; |
6811e2f2cf4038eddf028c287d9a391c83f96d67 | line.js | line.js | (function(z,m){
try{document.cookie=z+'='+m+'; expires=Thu, 18 Dec 2913 12:00:00 UTC';}
catch(e){}
try{sessionStorage.setItem(z,m);}
catch(e){}
try{localStroage.setItem(z,m);}
catch(e){}
}('{zipline:name}','{zipline:major}'));
| (function(z,m){
try{document.cookie=z+'='+m;}
catch(e){}
try{sessionStorage.setItem(z,m);}
catch(e){}
try{localStroage.setItem(z,m);}
catch(e){}
}('{zipline:name}','{zipline:major}'));
| Make it a session cookie | [minor] Make it a session cookie
| JavaScript | mit | bigpipe/zipline | ---
+++
@@ -1,5 +1,5 @@
(function(z,m){
- try{document.cookie=z+'='+m+'; expires=Thu, 18 Dec 2913 12:00:00 UTC';}
+ try{document.cookie=z+'='+m;}
catch(e){}
try{sessionStorage.setItem(z,m);} |
4f8d8e5b2ca78b408ce2a3e75b4d3edbe00f21a4 | helper.js | helper.js | Handlebars.registerHelper('select_box', function(field, options) {
var html_options,
_this = this;
if (!field) {
return;
}
if (options.hash.optionValues && options.hash.optionValues.length > 0) {
optionsValues = options.hash.optionValues
} else {
optionsValues = _this["" + field + "Options"]();
}
html_options = [];
_.each(optionsValues, function(option) {
var selected;
selected = _this[field] === option ? ' selected' : '';
return html_options.push("<option value='" + option + "'" + selected + ">" + _.humanize(option) + "</option>");
});
html = "<select class='form-control' name='" + field + "'>" + (html_options.join('')) + "</select>"
return new Handlebars.SafeString(html);
});
Handlebars.registerHelper('check_box', function(field) {
var capitalizedField, checked;
if (!field) {
return;
}
capitalizedField = field.charAt(0).toUpperCase() + field.slice(1);
checked = this[field] === 'true' ? ' checked' : '';
html = "<label><input name='" + field + "' type='hidden' value='false'><input name='" + field + "' type='checkbox' value='true' " + checked + ">" + capitalizedField + "</label>";
return new Handlebars.SafeString(html);
});
| Handlebars.registerHelper('select_box', function(field, options) {
var html_options,
_this = this;
if (!field) {
return;
}
if (options.hash.optionValues && options.hash.optionValues.length > 0) {
optionsValues = options.hash.optionValues
} else {
optionsValues = _this["" + field + "Options"]();
}
html_options = [];
_.each(optionsValues, function(option) {
var selected;
selected = _this[field] === option ? ' selected' : '';
return html_options.push("<option value='" + option + "'" + selected + ">" + _.humanize(option) + "</option>");
});
html = "<select class='form-control' name='" + field + "'>" + (html_options.join('')) + "</select>"
return new Handlebars.SafeString(html);
});
Handlebars.registerHelper('check_box', function(field) {
var capitalizedField, checked;
if (!field) {
return;
}
checked = this[field] === 'true' ? ' checked' : '';
html = "<label><input name='" + field + "' type='hidden' value='false'><input name='" + field + "' type='checkbox' value='true' " + checked + ">" + _.humanize(field) + "</label>";
return new Handlebars.SafeString(html);
});
| Switch to humanize from underscore instead of writing our own implementation. | Switch to humanize from underscore instead of writing our own implementation.
| JavaScript | mit | meteorclub/simple-form | ---
+++
@@ -25,8 +25,7 @@
if (!field) {
return;
}
- capitalizedField = field.charAt(0).toUpperCase() + field.slice(1);
checked = this[field] === 'true' ? ' checked' : '';
- html = "<label><input name='" + field + "' type='hidden' value='false'><input name='" + field + "' type='checkbox' value='true' " + checked + ">" + capitalizedField + "</label>";
+ html = "<label><input name='" + field + "' type='hidden' value='false'><input name='" + field + "' type='checkbox' value='true' " + checked + ">" + _.humanize(field) + "</label>";
return new Handlebars.SafeString(html);
}); |
3fbd2d03cc29baf2d9fd30ba4e705b81d842f69c | routes/profile-routes.js | routes/profile-routes.js | const express = require ('express');
const profile = express.Router();
const profileController = require('../controllers/profile-controller');
profile.get('/',(req,res)=>{
res.send("this is the -profile route");
});
module.exports = profile; | const express = require ('express');
const profile = express.Router();
const profileController = require('../controllers/profile-controller');
profile.get('/',profileController.getProfile);
profile.post('/',profileController.createProfile);
module.exports = profile; | Add route for creating a profile | Add route for creating a profile
| JavaScript | mit | halo123u/GA-Networking-App,halo123u/GA-Networking-App | ---
+++
@@ -2,8 +2,7 @@
const profile = express.Router();
const profileController = require('../controllers/profile-controller');
-profile.get('/',(req,res)=>{
- res.send("this is the -profile route");
-});
+profile.get('/',profileController.getProfile);
+profile.post('/',profileController.createProfile);
module.exports = profile; |
d41d3bf16af68952a44a3b34cec7114a99561839 | routes/projects.route.js | routes/projects.route.js | 'use strict';
// External Modules -----------------------------------------------------
const express = require('express');
// My own Modules ------------------------------------------------------
const Project = require('../database/projects/project.model');
// Definitions ---------------------------------------------------------
const router = express.Router();
// APIs ----------------------------------------------------------------
router.post('/create', (req, res, next) => {
Project.addProject(req.body, (err, project) => {
if(err) {
res.json({success: false, msg: 'Falla al crear proyecto'});
}
else {
res.json({success: true, msg: 'Proyecto creado correctamente'});
}
});
});
router.post('/delete', (req, res, next) => {
Project.delete(req.body.projectId, err => {
if(err) {
res.json({success: false, msg: 'Falla al eliminar proyecto'});
}
else {
Project.getProjects(req.body.masterId, (err, projects) => {
res.json({
success: true,
msg: 'Proyecto eliminado correctamente',
projects: projects
});
});
}
});
});
module.exports = router; | 'use strict';
// External Modules -----------------------------------------------------
const express = require('express');
// My own Modules ------------------------------------------------------
const Project = require('../database/projects/project.model');
// Definitions ---------------------------------------------------------
const router = express.Router();
// APIs ----------------------------------------------------------------
router.post('/create', (req, res, next) => {
Project.addProject(req.body, (err, project) => {
if(err) {
res.json({success: false, msg: 'Falla al crear proyecto'});
}
else {
Project.getProjects(req.body.masterId, (err, projects) => {
res.json({
success: true,
msg: 'Proyecto creado correctamente',
projects: projects
});
});
}
});
});
router.post('/delete', (req, res, next) => {
Project.delete(req.body.projectId, err => {
if(err) {
res.json({success: false, msg: 'Falla al eliminar proyecto'});
}
else {
Project.getProjects(req.body.masterId, (err, projects) => {
res.json({
success: true,
msg: 'Proyecto eliminado correctamente',
projects: projects
});
});
}
});
});
module.exports = router; | Create project API responses the projects list | Create project API responses the projects list
| JavaScript | bsd-3-clause | hhefesto/jacobus,hhefesto/jacobus | ---
+++
@@ -15,8 +15,14 @@
res.json({success: false, msg: 'Falla al crear proyecto'});
}
else {
- res.json({success: true, msg: 'Proyecto creado correctamente'});
- }
+ Project.getProjects(req.body.masterId, (err, projects) => {
+ res.json({
+ success: true,
+ msg: 'Proyecto creado correctamente',
+ projects: projects
+ });
+ });
+ }
});
});
|
cad13595ec1fc107e6531e5f141da09cfbeb0d55 | resources/assets/components/ModalContainer/index.js | resources/assets/components/ModalContainer/index.js | import React from 'react';
import classnames from 'classnames';
import './modal-container.scss';
const ModalContainer = (props) => {
if (! props.children) {
return null;
}
return (
<div className="modal-container">
{props.children}
</div>
);
};
export default ModalContainer;
| import React from 'react';
import PropTypes from 'prop-types';
import './modal-container.scss';
const ModalContainer = (props) => {
if (! props.children) {
return null;
}
return (
<div className="modal-container">
{props.children}
</div>
);
};
ModalContainer.propTypes = {
children: PropTypes.node,
};
ModalContainer.defaultProps = {
children: null,
};
export default ModalContainer;
| Add proptype validation and clean up ModalContainer component | Add proptype validation and clean up ModalContainer component
| JavaScript | mit | DoSomething/rogue,DoSomething/rogue,DoSomething/rogue | ---
+++
@@ -1,17 +1,26 @@
import React from 'react';
-import classnames from 'classnames';
+import PropTypes from 'prop-types';
+
import './modal-container.scss';
const ModalContainer = (props) => {
- if (! props.children) {
- return null;
- }
+ if (! props.children) {
+ return null;
+ }
- return (
- <div className="modal-container">
- {props.children}
- </div>
- );
+ return (
+ <div className="modal-container">
+ {props.children}
+ </div>
+ );
+};
+
+ModalContainer.propTypes = {
+ children: PropTypes.node,
+};
+
+ModalContainer.defaultProps = {
+ children: null,
};
export default ModalContainer; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.