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 |
|---|---|---|---|---|---|---|---|---|---|---|
022df8496a9174d80c83441c22651bcd654b032b | example_keys.js | example_keys.js | module.exports = {
facebook: {
FACEBOOK_APP_ID: 'YOUR_FACEBOOK_APP_ID',
FACEBOOK_APP_SECRET: 'YOUR_FACEBOOK_APP_SECRET'
}
};
| module.exports = {
facebook: {
FACEBOOK_APP_ID: 'YOUR_FACEBOOK_APP_ID',
FACEBOOK_APP_SECRET: 'YOUR_FACEBOOK_APP_SECRET'
},
aws: {
AWS_ACCESS_KEY_ID: "AWS_ACCESS_KEY_ID",
AWS_SECRET_ACCESS_KEY: "AWS_SECRET_ACCESS_KEY",
AWS_REGION: "AWS_REGION"
}
};
| Create example keys for aws | Create example keys for aws
| JavaScript | mit | inspiredtolive/Picky-Notes,folksy-squid/Picky-Notes,inspiredtolive/Picky-Notes,derektliu/Picky-Notes,inspiredtolive/Picky-Notes,derektliu/Picky-Notes,folksy-squid/Picky-Notes,derektliu/Picky-Notes,folksy-squid/Picky-Notes | ---
+++
@@ -2,5 +2,10 @@
facebook: {
FACEBOOK_APP_ID: 'YOUR_FACEBOOK_APP_ID',
FACEBOOK_APP_SECRET: 'YOUR_FACEBOOK_APP_SECRET'
+ },
+ aws: {
+ AWS_ACCESS_KEY_ID: "AWS_ACCESS_KEY_ID",
+ AWS_SECRET_ACCESS_KEY: "AWS_SECRET_ACCESS_KEY",
+ AWS_REGION: "AWS_REGION"
}
}; |
16ea8bea2adcd747a171fcc144576fcfc65f43fc | website/src/app/components2/process-files-table/process-files-table.component.js | website/src/app/components2/process-files-table/process-files-table.component.js | class MCProcessFilesTableComponentController {
/*@ngInject*/
constructor() {
this.state = {
files: [],
};
}
$onChanges(changes) {
if (changes.files) {
this.state.files = angular.copy(changes.files.currentValue);
}
}
showFile(file) {
}
}
angular.module('materialscommons').component('mcProcessFilesTable', {
controller: MCProcessFilesTableComponentController,
template: require('./process-files-table.html'),
bindings: {
files: '<'
}
}); | class MCProcessFilesTableComponentController {
/*@ngInject*/
constructor() {
this.state = {
files: [],
};
}
$onChanges(changes) {
if (changes.files) {
this.state.files = angular.copy(changes.files.currentValue);
}
}
// showFile(file) {
//
// }
}
angular.module('materialscommons').component('mcProcessFilesTable', {
controller: MCProcessFilesTableComponentController,
template: require('./process-files-table.html'),
bindings: {
files: '<'
}
}); | Comment out show file for now | Comment out show file for now
| JavaScript | mit | materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org | ---
+++
@@ -12,9 +12,9 @@
}
}
- showFile(file) {
-
- }
+ // showFile(file) {
+ //
+ // }
}
angular.module('materialscommons').component('mcProcessFilesTable', { |
798536ac5a8119320fec76c2d8a1191b10512242 | commands/config/get.js | commands/config/get.js | 'use strict';
let cli = require('heroku-cli-util');
let shellescape = require('shell-escape');
let co = require('co');
function* run (context, heroku) {
let configVars = yield heroku.request({path: `/apps/${context.app}/config-vars`});
let v = configVars[context.args.key];
if (typeof(v) === 'undefined') {
cli.log(''); // match v2 output for missing
} else {
if (context.flags.shell) {
v = process.stdout.isTTY ? shellescape([v]) : v;
cli.log(`${context.args.key}=${v}`);
} else {
cli.log(v);
}
}
}
module.exports = {
topic: 'config',
command: 'get',
description: 'display a config value for an app',
help: `Example:
$ heroku config:get RAILS_ENV
production
`,
args: [{name: 'key'}],
flags: [{name: 'shell', char: 's', description: 'output config var in shell format'}],
needsApp: true,
needsAuth: true,
run: cli.command(co.wrap(run))
};
| 'use strict';
let cli = require('heroku-cli-util');
let shellescape = require('shell-escape');
let co = require('co');
function* run (context, heroku) {
let configVars = yield heroku.request({path: `/apps/${context.app}/config-vars`});
let v = configVars[context.args.key];
if (v === undefined) {
cli.log(''); // match v3 output for missing
} else {
if (context.flags.shell) {
v = process.stdout.isTTY ? shellescape([v]) : v;
cli.log(`${context.args.key}=${v}`);
} else {
cli.log(v);
}
}
}
module.exports = {
topic: 'config',
command: 'get',
description: 'display a config value for an app',
help: `Example:
$ heroku config:get RAILS_ENV
production
`,
args: [{name: 'key'}],
flags: [{name: 'shell', char: 's', description: 'output config var in shell format'}],
needsApp: true,
needsAuth: true,
run: cli.command(co.wrap(run))
};
| Rework undefined test & fix v2 typo | Rework undefined test & fix v2 typo
| JavaScript | isc | heroku/heroku-apps,heroku/heroku-apps | ---
+++
@@ -7,8 +7,8 @@
function* run (context, heroku) {
let configVars = yield heroku.request({path: `/apps/${context.app}/config-vars`});
let v = configVars[context.args.key];
- if (typeof(v) === 'undefined') {
- cli.log(''); // match v2 output for missing
+ if (v === undefined) {
+ cli.log(''); // match v3 output for missing
} else {
if (context.flags.shell) {
v = process.stdout.isTTY ? shellescape([v]) : v; |
9fd0a284f0a48a1ed09a25d3fe1d1cbd24802587 | packages/machinomy/migrations/20180325060555-add-created-at.js | packages/machinomy/migrations/20180325060555-add-created-at.js | 'use strict';
var dbm;
var type;
var seed;
/**
* We receive the dbmigrate dependency from dbmigrate initially.
* This enables us to not have to rely on NODE_PATH.
*/
exports.setup = function(options, seedLink) {
dbm = options.dbmigrate;
type = dbm.dataType;
seed = seedLink;
};
exports.up = function(db) {
return db.addColumn('payment', '"createdAt"', {
type: 'bigint'
});
};
exports.down = function(db) {
return db.removeColumn('payment', '"createdAt"');
};
exports._meta = {
"version": 1
};
| 'use strict';
var dbm;
var type;
var seed;
/**
* We receive the dbmigrate dependency from dbmigrate initially.
* This enables us to not have to rely on NODE_PATH.
*/
exports.setup = function(options, seedLink) {
dbm = options.dbmigrate;
type = dbm.dataType;
seed = seedLink;
};
exports.up = function(db) {
return db.runSql('SELECT createdAt FROM payment', (err) => {
if (err !== null) {
return db.addColumn('payment', 'createdAt', {
type: 'bigint'
});
}
})
};
exports.down = function(db) {
return db.removeColumn('payment', 'createdAt');
};
exports._meta = {
"version": 1
};
| Fix error when column exists. | Fix error when column exists.
| JavaScript | apache-2.0 | machinomy/machinomy,machinomy/machinomy,machinomy/machinomy | ---
+++
@@ -15,13 +15,17 @@
};
exports.up = function(db) {
- return db.addColumn('payment', '"createdAt"', {
- type: 'bigint'
- });
+ return db.runSql('SELECT createdAt FROM payment', (err) => {
+ if (err !== null) {
+ return db.addColumn('payment', 'createdAt', {
+ type: 'bigint'
+ });
+ }
+ })
};
exports.down = function(db) {
- return db.removeColumn('payment', '"createdAt"');
+ return db.removeColumn('payment', 'createdAt');
};
exports._meta = { |
8b8a0ed595428f6712e241623ac5a0b404b22931 | samples/IntegerScrollPickerSample.js | samples/IntegerScrollPickerSample.js | enyo.kind({
name: "moon.sample.IntegerScrollPickerSample",
classes: "moon enyo-unselectable enyo-fit",
components: [
{kind: "enyo.Spotlight"},
{kind: "moon.IntegerScrollPicker", value: 2013, min: 1900, max: 2100, onChange: "changed"},
{kind: "moon.Divider", content: "Result"},
{name: "value", content: "No change yet"}
],
changed: function(inSender, inEvent) {
if (this.$.value){
this.$.value.setContent(inEvent.name + " changed to " + inEvent.value);
}
}
}); | enyo.kind({
name: "moon.sample.IntegerScrollPickerSample",
kind: "FittableRows",
classes: "moon enyo-unselectable enyo-fit",
components: [
{kind: "enyo.Spotlight"},
{fit:true, components: [
{kind: "moon.Divider", content: "Integer Picker"},
{kind: "moon.IntegerScrollPicker", value: 2013, min: 1900, max: 2100, onChange: "changed"}
]},
{kind: "moon.Divider", content: "Result"},
{name: "value", content: "No change yet"}
],
changed: function(inSender, inEvent) {
if (this.$.value){
this.$.value.setContent(inEvent.name + " changed to " + inEvent.value);
}
}
}); | Use standard "result" layout, and add divider title to sample. | Use standard "result" layout, and add divider title to sample.
Enyo-DCO-1.1-Signed-off-by: Kevin Schaaf kevin.schaaf@lge.com
| JavaScript | apache-2.0 | mcanthony/moonstone,mcanthony/moonstone,mcanthony/moonstone,enyojs/moonstone | ---
+++
@@ -1,9 +1,13 @@
enyo.kind({
name: "moon.sample.IntegerScrollPickerSample",
+ kind: "FittableRows",
classes: "moon enyo-unselectable enyo-fit",
components: [
{kind: "enyo.Spotlight"},
- {kind: "moon.IntegerScrollPicker", value: 2013, min: 1900, max: 2100, onChange: "changed"},
+ {fit:true, components: [
+ {kind: "moon.Divider", content: "Integer Picker"},
+ {kind: "moon.IntegerScrollPicker", value: 2013, min: 1900, max: 2100, onChange: "changed"}
+ ]},
{kind: "moon.Divider", content: "Result"},
{name: "value", content: "No change yet"}
], |
50f24f26524b20b87c59a393ea412224b35cc19f | config.js | config.js | module.exports = {
algorithm : 'aes-256-ctr',
password : 'qmAXae3Ofx9K0NpX4ODB4Dt9l9QhEW',
filename : '.data.db'
}
| module.exports = {
algorithm : 'aes-256-ctr',
password : process.env.NEON_SECURE_PASSWORD,
filename : '.data.db'
}
| Remove RSA password from repo. | Remove RSA password from repo.
| JavaScript | bsd-2-clause | soachishti/NeONStudentAPI,soachishti/NeONStudentAPI | ---
+++
@@ -1,6 +1,6 @@
module.exports = {
algorithm : 'aes-256-ctr',
- password : 'qmAXae3Ofx9K0NpX4ODB4Dt9l9QhEW',
+ password : process.env.NEON_SECURE_PASSWORD,
filename : '.data.db'
}
|
b38f6995f1d51144bd08c98ee75aee090a3e9ab3 | src/react/src/routes/SprkDividerDocs/SprkDividerDocs.js | src/react/src/routes/SprkDividerDocs/SprkDividerDocs.js | import React from 'react';
import CentralColumnLayout from '../../containers/CentralColumnLayout/CentralColumnLayout';
import { SprkDivider } from '@sparkdesignsystem/spark-core-react';
const SprkDividerDocs = () => {
return (
<CentralColumnLayout>
<div className="sprk-u-mbm">
<h2 className="drizzle-b-h2">Divider as span</h2>
<SprkDivider idString="divider-1" element="span"></SprkDivider>
</div>
<div className="sprk-u-mbm">
<h2 className="drizzle-b-h2">Divider as hr</h2>
<SprkDivider idString="divider-1" element="hr"></SprkDivider>
</div>
</CentralColumnLayout>
)
}
export default SprkDividerDocs; | import React from 'react';
import CentralColumnLayout from '../../containers/CentralColumnLayout/CentralColumnLayout';
import { SprkDivider } from '@sparkdesignsystem/spark-core-react';
import ExampleContainer from '../../containers/ExampleContainer/ExampleContainer';
const SprkDividerDocs = () => {
return (
<CentralColumnLayout>
<ExampleContainer>
<h2 className="drizzle-b-h2">Divider as span</h2>
<SprkDivider idString="divider-1" element="span"></SprkDivider>
</ExampleContainer>
<ExampleContainer>
<h2 className="drizzle-b-h2">Divider as hr</h2>
<SprkDivider idString="divider-1" element="hr"></SprkDivider>
</ExampleContainer>
</CentralColumnLayout>
)
}
export default SprkDividerDocs; | Update divs to ExampleContainer component | Update divs to ExampleContainer component
| JavaScript | mit | sparkdesignsystem/spark-design-system,sparkdesignsystem/spark-design-system,sparkdesignsystem/spark-design-system,sparkdesignsystem/spark-design-system | ---
+++
@@ -2,19 +2,20 @@
import CentralColumnLayout from '../../containers/CentralColumnLayout/CentralColumnLayout';
import { SprkDivider } from '@sparkdesignsystem/spark-core-react';
+import ExampleContainer from '../../containers/ExampleContainer/ExampleContainer';
const SprkDividerDocs = () => {
return (
<CentralColumnLayout>
- <div className="sprk-u-mbm">
+ <ExampleContainer>
<h2 className="drizzle-b-h2">Divider as span</h2>
<SprkDivider idString="divider-1" element="span"></SprkDivider>
- </div>
+ </ExampleContainer>
- <div className="sprk-u-mbm">
+ <ExampleContainer>
<h2 className="drizzle-b-h2">Divider as hr</h2>
<SprkDivider idString="divider-1" element="hr"></SprkDivider>
- </div>
+ </ExampleContainer>
</CentralColumnLayout>
)
} |
3e8299eda13c911fcfd00003bf20ffc0db2ebfd9 | src/ScoreScreen.js | src/ScoreScreen.js | import html from "innerself";
import { connect } from "./store";
function ScoreScreen({results, target_snapshot}) {
const score = Math.floor(results[results.length - 1]) * 100;
return html`
<img class="ui"
style="opacity: .5"
src="${target_snapshot}">
<div class="ui action"
onclick="dispatch('PLAY_AGAIN')">
<div>${score}%</div>
</div>
`;
}
export default connect(ScoreScreen);
| import html from "innerself";
import { connect } from "./store";
function ScoreScreen({results, target_snapshot}) {
const score = Math.floor(results[results.length - 1] * 100);
return html`
<img class="ui"
style="opacity: .5"
src="${target_snapshot}">
<div class="ui action"
onclick="dispatch('PLAY_AGAIN')">
<div>${score}%</div>
</div>
`;
}
export default connect(ScoreScreen);
| Fix the score on the Score Screen | Fix the score on the Score Screen
| JavaScript | isc | piesku/moment-lost,piesku/moment-lost | ---
+++
@@ -2,7 +2,7 @@
import { connect } from "./store";
function ScoreScreen({results, target_snapshot}) {
- const score = Math.floor(results[results.length - 1]) * 100;
+ const score = Math.floor(results[results.length - 1] * 100);
return html`
<img class="ui"
style="opacity: .5" |
446b0bcdc5dff8d5260151210e0be761e3eab0c3 | src/routes.js | src/routes.js | // Handlers
var
version = require('./version'),
content = require('./content'),
assets = require('./assets');
exports.loadRoutes = function (server) {
server.get('/version', version.report);
server.get('/content/:id', content.retrieve);
server.put('/content/:id', content.store);
server.del('/content/:id', content.delete);
server.post('/assets', assets.accept);
};
| var restify = require('restify');
// Handlers
var
version = require('./version'),
content = require('./content'),
assets = require('./assets');
exports.loadRoutes = function (server) {
server.get('/version', version.report);
server.get('/content/:id', content.retrieve);
server.put('/content/:id', content.store);
server.del('/content/:id', content.delete);
server.post('/assets', restify.bodyParser(), assets.accept);
};
| Use the bodyParser middleware for `/assets`. | Use the bodyParser middleware for `/assets`.
| JavaScript | mit | deconst/content-service,deconst/content-service | ---
+++
@@ -1,3 +1,5 @@
+var restify = require('restify');
+
// Handlers
var
version = require('./version'),
@@ -11,5 +13,5 @@
server.put('/content/:id', content.store);
server.del('/content/:id', content.delete);
- server.post('/assets', assets.accept);
+ server.post('/assets', restify.bodyParser(), assets.accept);
}; |
a8c86273c3a0c2a5e8523b67d500a10911836873 | lib/utils/page-utils.js | lib/utils/page-utils.js | var session = require('../env/session'),
url = require('url');
module.exports = {
visit: function (query) {
var config = require('moonraker').config;
var path = url.parse(this.url.indexOf('http://') > -1 ? this.url : config.baseUrl + this.url);
if (query) path.query = query;
session.getDriver().get(url.format(path));
if (typeof this.onLoad === 'function') session.execute(this.onLoad);
},
title: function (titleHandler) {
session.getDriver().getTitle().then(function (title) {
titleHandler(title);
});
}
};
| var session = require('../env/session'),
url = require('url');
module.exports = {
visit: function (query) {
var config = require('moonraker').config;
var hasProtocol = !!(this.url || '').match('^https?:\/\/');
var path = url.parse(hasProtocol ? this.url : config.baseUrl + this.url);
if (query) path.query = query;
session.getDriver().get(url.format(path));
if (typeof this.onLoad === 'function') session.execute(this.onLoad);
},
title: function (titleHandler) {
session.getDriver().getTitle().then(function (title) {
titleHandler(title);
});
}
};
| Allow to use HTTPS in url | Allow to use HTTPS in url | JavaScript | mit | testingbot/moonraker,riaan53/moonraker,blackout314/moonraker,tegud/moonraker,LateRoomsGroup/moonraker,LateRoomsGroup/moonraker,blackout314/moonraker,dandv/moonraker,testingbot/moonraker,dandv/moonraker,riaan53/moonraker,tegud/moonraker | ---
+++
@@ -5,7 +5,8 @@
visit: function (query) {
var config = require('moonraker').config;
- var path = url.parse(this.url.indexOf('http://') > -1 ? this.url : config.baseUrl + this.url);
+ var hasProtocol = !!(this.url || '').match('^https?:\/\/');
+ var path = url.parse(hasProtocol ? this.url : config.baseUrl + this.url);
if (query) path.query = query;
session.getDriver().get(url.format(path));
if (typeof this.onLoad === 'function') session.execute(this.onLoad); |
1d369069e7700d9898e3cf8384d405c580396aaa | src/server.js | src/server.js | import express from 'express';
import bodyParser from 'body-parser';
import log from './log';
import database from './database';
import configureHelmet from './middleware/configure-helmet';
import requestLogger from './middleware/request-logger';
import userRoutes from './components/user/user-routes';
import postRoutes from './components/post/post-routes';
import notFoundRoute from './errors/not-found-routes';
function startServer() {
database.sync()
.then(() => {
log.info('Connected to Database Successfully');
const app = express();
configureHelmet(app);
app.use(requestLogger);
app.use(bodyParser.json());
app.use('/v2.0/users', userRoutes);
app.use('/v2.0/posts', postRoutes);
app.use(notFoundRoute);
const port = process.env.PORT;
app.listen(port, () => {
log.info({ port }, 'CSBlogs API now running');
});
})
.catch(error => {
if (error instanceof database.ConnectionError) {
log.info('Connection to Database Failed', {
host: process.env.CSBLOGS_DATABASE_HOST,
port: process.env.CSBLOGS_DATABASE_PORT,
name: process.env.CSBLOGS_DATABASE_NAME,
username: process.env.CSBLOGS_DATABASE_USERNAME
});
setTimeout(startServer, 1000);
}
});
}
startServer();
| import express from 'express';
import bodyParser from 'body-parser';
import log from './log';
import database from './database';
import configureHelmet from './middleware/configure-helmet';
import requestLogger from './middleware/request-logger';
import userRoutes from './components/user/user-routes';
import postRoutes from './components/post/post-routes';
import notFoundRoute from './errors/not-found-routes';
function startServer() {
database.sync()
.then(() => {
log.info('Connected to Database Successfully');
const app = express();
configureHelmet(app);
app.use(requestLogger);
app.use(bodyParser.json());
app.use('/v2.0/user', userRoutes);
app.use('/v2.0/post', postRoutes);
app.use(notFoundRoute);
const port = process.env.PORT;
app.listen(port, () => {
log.info({ port }, 'CSBlogs API now running');
});
})
.catch(error => {
if (error instanceof database.ConnectionError) {
log.info('Connection to Database Failed', {
host: process.env.CSBLOGS_DATABASE_HOST,
port: process.env.CSBLOGS_DATABASE_PORT,
name: process.env.CSBLOGS_DATABASE_NAME,
username: process.env.CSBLOGS_DATABASE_USERNAME
});
setTimeout(startServer, 1000);
}
});
}
startServer();
| Update URLs to match best practice of the resource name not being plural | Update URLs to match best practice of the resource name not being plural
| JavaScript | mit | csblogs/api-server,csblogs/api-server | ---
+++
@@ -20,8 +20,8 @@
app.use(requestLogger);
app.use(bodyParser.json());
- app.use('/v2.0/users', userRoutes);
- app.use('/v2.0/posts', postRoutes);
+ app.use('/v2.0/user', userRoutes);
+ app.use('/v2.0/post', postRoutes);
app.use(notFoundRoute);
const port = process.env.PORT; |
509230715bcdbf096c8ae1ef492f0046decce2bc | end-to-end-tests/specs/studyview.spec.js | end-to-end-tests/specs/studyview.spec.js | var assert = require('assert');
var expect = require('chai').expect;
var waitForOncoprint = require('./specUtils').waitForOncoprint;
var goToUrlAndSetLocalStorage = require('./specUtils').goToUrlAndSetLocalStorage;
var waitForNetworkQuiet = require('./specUtils').waitForNetworkQuiet;
var assertScreenShotMatch = require('../lib/testUtils').assertScreenShotMatch;
const CBIOPORTAL_URL = process.env.CBIOPORTAL_URL.replace(/\/$/, "");
describe('new study view screenshot test', function(){
before(function(){
var url = `${CBIOPORTAL_URL}/study?id=laml_tcga`;
goToUrlAndSetLocalStorage(url);
});
it('new study view laml_tcga', function() {
browser.waitForVisible('#mainColumn',10000);
waitForNetworkQuiet();
var res = browser.checkElement('#mainColumn', {hide:['.qtip', '#footer-span-version'] });
assertScreenShotMatch(res);
});
it('new study view laml_tcga clinical data clicked', function() {
browser.click('.tabAnchor_clinicalData');
browser.waitForVisible('#mainColumn',10000);
waitForNetworkQuiet();
var res = browser.checkElement('#mainColumn', {hide:['.qtip', '#footer-span-version'] });
assertScreenShotMatch(res);
});
}); | var assert = require('assert');
var expect = require('chai').expect;
var waitForOncoprint = require('./specUtils').waitForOncoprint;
var goToUrlAndSetLocalStorage = require('./specUtils').goToUrlAndSetLocalStorage;
var waitForNetworkQuiet = require('./specUtils').waitForNetworkQuiet;
var assertScreenShotMatch = require('../lib/testUtils').assertScreenShotMatch;
const CBIOPORTAL_URL = process.env.CBIOPORTAL_URL.replace(/\/$/, "");
describe('study view screenshot test', function(){
before(function(){
var url = `${CBIOPORTAL_URL}/study?id=laml_tcga`;
goToUrlAndSetLocalStorage(url);
});
it('study view laml_tcga', function() {
browser.waitForVisible('#mainColumn',10000);
waitForNetworkQuiet();
var res = browser.checkElement('#mainColumn', {hide:['.qtip', '#footer-span-version'] });
assertScreenShotMatch(res);
});
it('study view laml_tcga clinical data clicked', function() {
browser.click('.tabAnchor_clinicalData');
browser.waitForVisible('#mainColumn',10000);
waitForNetworkQuiet();
var res = browser.checkElement('#mainColumn', {hide:['.qtip', '#footer-span-version'] });
assertScreenShotMatch(res);
});
}); | Include study view screenshot references | Include study view screenshot references
Former-commit-id: e016cb052abecda7dc1c0cd1391edac077634e2a | JavaScript | agpl-3.0 | cBioPortal/cbioportal-frontend,cBioPortal/cbioportal-frontend,alisman/cbioportal-frontend,alisman/cbioportal-frontend,cBioPortal/cbioportal-frontend,alisman/cbioportal-frontend,alisman/cbioportal-frontend,cBioPortal/cbioportal-frontend,cBioPortal/cbioportal-frontend,alisman/cbioportal-frontend,cBioPortal/cbioportal-frontend,alisman/cbioportal-frontend | ---
+++
@@ -7,18 +7,18 @@
const CBIOPORTAL_URL = process.env.CBIOPORTAL_URL.replace(/\/$/, "");
-describe('new study view screenshot test', function(){
+describe('study view screenshot test', function(){
before(function(){
var url = `${CBIOPORTAL_URL}/study?id=laml_tcga`;
goToUrlAndSetLocalStorage(url);
});
- it('new study view laml_tcga', function() {
+ it('study view laml_tcga', function() {
browser.waitForVisible('#mainColumn',10000);
waitForNetworkQuiet();
var res = browser.checkElement('#mainColumn', {hide:['.qtip', '#footer-span-version'] });
assertScreenShotMatch(res);
});
- it('new study view laml_tcga clinical data clicked', function() {
+ it('study view laml_tcga clinical data clicked', function() {
browser.click('.tabAnchor_clinicalData');
browser.waitForVisible('#mainColumn',10000);
waitForNetworkQuiet(); |
4f2f792add2d08f0f843d484ade13bf8b3ed4365 | app/js/forms.js | app/js/forms.js | import React from 'react';
import resumeStructures from './resume-structures';
import { capitalize } from 'lodash';
const buildForm = ([section, attributes]) => props => {
const handleSubmit = (e) => {
e.preventDefault();
props.handleSubmit(section, e.target);
};
return (
<form onSubmit={handleSubmit}>
{
attributes.map(attr => (
<div className="form-group">
<label for={attr}>{capitalize(attr)}</label>
<input type="text" className="form-control" name={attr} />
</div>
))
}
<button type="submit" className="btn btn-default btn-lg btn-block">Save</button>
</form>
)
};
export default resumeStructures.map(r => ({section: r[0], component: buildForm(r)})); | import React from 'react';
import resumeStructures from './resume-structures';
import { capitalize } from 'lodash';
const buildForm = ([section, attributes]) => props => {
const handleSubmit = (e) => {
e.preventDefault();
props.handleSubmit(section, e.target);
};
return (
<form onSubmit={handleSubmit}>
{
attributes.map(attr => (
<div className="form-group">
<label htmlFor={attr}>{capitalize(attr)}</label>
<input type="text" className="form-control" name={attr} />
</div>
))
}
<button type="submit" className="btn btn-default btn-lg btn-block">Save</button>
</form>
)
};
export default resumeStructures.map(r => ({section: r[0], component: buildForm(r)})); | Swap out 'for' for 'htmlFor' | Swap out 'for' for 'htmlFor'
| JavaScript | mit | maxmechanic/resumaker,maxmechanic/resumaker | ---
+++
@@ -14,7 +14,7 @@
{
attributes.map(attr => (
<div className="form-group">
- <label for={attr}>{capitalize(attr)}</label>
+ <label htmlFor={attr}>{capitalize(attr)}</label>
<input type="text" className="form-control" name={attr} />
</div>
)) |
4243ae7ad3a9b69e3d02b8705d083e8dfae58141 | test/test-spawn-fail.js | test/test-spawn-fail.js | 'use strict';
process.stdin.pipe(require('fs').createWriteStream(__dirname + '/output.txt'));
process.stdout.write('output written');
process.stderr.write('error log exists');
setTimeout(function () {
process.exit(13);
}, 500); | 'use strict';
process.stdin.pipe(require('fs').createWriteStream(__dirname + '/output.txt')).on('close', function () {
setTimeout(function () {
process.exit(13);
}, 500);
});
process.stdout.write('output written');
process.stderr.write('error log exists');
| Remove race condition in tests | Remove race condition in tests
| JavaScript | mit | bcoe/spawn-sync,ForbesLindesay/spawn-sync,terabyte/spawn-sync,tmagiera/spawn-sync | ---
+++
@@ -1,9 +1,9 @@
'use strict';
-process.stdin.pipe(require('fs').createWriteStream(__dirname + '/output.txt'));
+process.stdin.pipe(require('fs').createWriteStream(__dirname + '/output.txt')).on('close', function () {
+ setTimeout(function () {
+ process.exit(13);
+ }, 500);
+});
process.stdout.write('output written');
process.stderr.write('error log exists');
-
-setTimeout(function () {
- process.exit(13);
-}, 500); |
8a8a6a65bef69f50ab3ae47a6895dc2ddb79c70a | _lib/server/start.js | _lib/server/start.js | var forever = require('forever-mac');
var config = require('./config');
function start () {
forever.list('array', function (err, processes) {
// stop all forever
if (config === 'stop') {
if (!processes) {
return console.log('no process to stop');
}
forever.stopAll();
console.log('process stoped');
return;
}
// stop on config errors
if (typeof config === 'string') {
return console.log(config);
}
if (processes) {
return console.log('server already running');
}
// start the server directly
if (config.dev) {
return require(config.paths.PROXY_SERVER);
}
// start proxy as a deamon
forever.startDaemon(config.paths.PROXY_SERVER, {
"max" : config.attempts,
"minUptime" : config.minUptime,
"spinSleepTime" : config.spinSleepTime,
"silent" : config.silent,
"verbose" : config.verbose,
"logFile" : config.log
});
console.log('server is running in the background');
});
}
exports.start = start;
| var forever = require('forever');
var config = require('./config');
function start () {
forever.list('array', function (err, processes) {
// stop all forever
if (config === 'stop') {
if (!processes) {
return console.log('no process to stop');
}
forever.stopAll();
console.log('process stoped');
return;
}
// stop on config errors
if (typeof config === 'string') {
return console.log(config);
}
if (processes) {
return console.log('server already running');
}
// start the server directly
if (config.dev) {
return require(config.paths.PROXY_SERVER);
}
// start proxy as a deamon
forever.startDaemon(config.paths.PROXY_SERVER, {
"max" : config.attempts,
"minUptime" : config.minUptime,
"spinSleepTime" : config.spinSleepTime,
"silent" : config.silent,
"verbose" : config.verbose,
"logFile" : config.log
});
console.log('server is running in the background');
});
}
exports.start = start;
| Use forever instead of forever-mac. | Use forever instead of forever-mac.
| JavaScript | mit | jillix/flow-nodejs | ---
+++
@@ -1,4 +1,4 @@
-var forever = require('forever-mac');
+var forever = require('forever');
var config = require('./config');
function start () { |
ce567c59e7b975961c7e0a1435ee83f56389fa7e | demo/core.green.js | demo/core.green.js | import { coreInit } from 'isolated-core'
const CSS2 = { __html: require('./style2.less') }
coreInit({
scriptURL: 'green.js',
run: core => {
const React = require('react')
const DemoUI = require('./DemoUI').default
// Monkeypatch in some extra render nodes.
const origRender = DemoUI.prototype.render
DemoUI.prototype.render = function render() {
return (
<div>
{origRender.apply(this)}
<style dangerouslySetInnerHTML={CSS2} />
<div id="frame" />
</div>
)
}
DemoUI.prototype.isGreen = true
require('./').init(core)
},
})
| import { coreInit } from 'isolated-core'
const CSS2 = { __html: require('./style2.less') }
coreInit({
scriptURL: 'green.js',
run: core => {
const React = require('react')
const DemoUI = require('./DemoUI').default
// Monkeypatch in some extra render nodes.
const origRender = DemoUI.prototype.render
DemoUI.prototype.render = function render() {
return (
<div>
{origRender.apply(this)}
<style dangerouslySetInnerHTML={CSS2} />
</div>
)
}
DemoUI.prototype.isGreen = true
require('./').init(core)
},
})
| Remove unused element from demo | Remove unused element from demo
| JavaScript | mit | chromakode/isolated-core,chromakode/isolated-core,chromakode/isolated-core | ---
+++
@@ -15,7 +15,6 @@
<div>
{origRender.apply(this)}
<style dangerouslySetInnerHTML={CSS2} />
- <div id="frame" />
</div>
)
} |
588f88f9e530c92f7fd02737ab511f2a22dde80f | src/client/app/layout/pv-top-nav.directive.js | src/client/app/layout/pv-top-nav.directive.js | (function() {
'use strict';
angular
.module('app.layout')
.directive('pvTopNav', pvTopNav);
/* @ngInject */
function pvTopNav () {
var directive = {
bindToController: true,
controller: TopNavController,
controllerAs: 'vm',
restrict: 'EA',
scope: {
'inHeader': '='
},
templateUrl: 'app/layout/pv-top-nav.html'
};
/* @ngInject */
function TopNavController($scope, $document, $state, $rootScope) {
var vm = this;
activate();
function activate() {
checkWithinIntro();
$document.on('scroll', checkWithinIntro);
$rootScope.$on('$viewContentLoaded', checkWithinIntro);
}
function checkWithinIntro() {
var aboutTopPosition = $document.find('#about').offset().top,
navbarHeight = $document.find('#pv-top-nav').height(),
triggerHeight = aboutTopPosition - navbarHeight - 1;
vm.inHeader = $state.current.url === '/' && $document.scrollTop() <= triggerHeight;
$scope.$applyAsync();
}
}
return directive;
}
})();
| (function() {
'use strict';
angular
.module('app.layout')
.directive('pvTopNav', pvTopNav);
/* @ngInject */
function pvTopNav () {
var directive = {
bindToController: true,
controller: TopNavController,
controllerAs: 'vm',
restrict: 'EA',
scope: {
'inHeader': '='
},
templateUrl: 'app/layout/pv-top-nav.html'
};
/* @ngInject */
function TopNavController($scope, $document, $state, $rootScope) {
var vm = this;
activate();
function activate() {
checkWithinIntro();
$document.on('scroll', checkWithinIntro);
$rootScope.$on('$viewContentLoaded', checkWithinIntro);
}
function checkWithinIntro() {
if ($state.current.name !== 'home') {
vm.inHeader = false;
$scope.$applyAsync();
return;
}
var aboutTopPosition = $document.find('#about').offset().top,
navbarHeight = $document.find('#pv-top-nav').height(),
triggerHeight = aboutTopPosition - navbarHeight - 1;
vm.inHeader = $document.scrollTop() <= triggerHeight;
$scope.$applyAsync();
}
}
return directive;
}
})();
| Fix error in top navigation not being able to find about us section | Fix error in top navigation not being able to find about us section
| JavaScript | apache-2.0 | Poniverse/Poniverse.net | ---
+++
@@ -32,11 +32,18 @@
}
function checkWithinIntro() {
+ if ($state.current.name !== 'home') {
+ vm.inHeader = false;
+ $scope.$applyAsync();
+
+ return;
+ }
+
var aboutTopPosition = $document.find('#about').offset().top,
navbarHeight = $document.find('#pv-top-nav').height(),
triggerHeight = aboutTopPosition - navbarHeight - 1;
- vm.inHeader = $state.current.url === '/' && $document.scrollTop() <= triggerHeight;
+ vm.inHeader = $document.scrollTop() <= triggerHeight;
$scope.$applyAsync();
} |
54da4bc5ebbbfaf3ef4cb0485d19c47d58c54a33 | source/views/activeViews.js | source/views/activeViews.js | import Obj from '../foundation/Object';
/**
Property: O.activeViews
Type: O.Object
Maps from id to the view object for all views currently in a document.
Views with a manually specified ID are added using <O.ComputedProps#set>,
and so you can observe them.
For reasons of performance, views with automatically-generated IDs ('v1',
'v372', &c.) bypass <O.ComputedProps#set>, and so they cannot be observed.
(I can’t think of any legitimate reasons for observing them anyway.)
This object is maintained by <O.View#didEnterDocument> and
<O.View#willLeaveDocument>; no code outside of those two methods is
permitted to mutate it.
*/
const activeViews = new Obj();
export default activeViews;
/**
Function: O.getViewFromNode
Returns the view object that the given DOM node is a part of.
Parameters:
node - {Element} a DOM node.
Returns:
{O.View|null} The view which owns the node.
*/
export const getViewFromNode = function ( node ) {
const doc = node.ownerDocument;
let view = null;
while ( !view && node && node !== doc ) {
view = activeViews[ node.id ];
node = node.parentNode;
}
return view;
};
| import Obj from '../foundation/Object';
/**
Property: O.activeViews
Type: O.Object
Maps from id to the view object for all views currently in a document.
Views with a manually specified ID are added using <O.ComputedProps#set>,
and so you can observe them.
For reasons of performance, views with automatically-generated IDs ('v1',
'v372', &c.) bypass <O.ComputedProps#set>, and so they cannot be observed.
(I can’t think of any legitimate reasons for observing them anyway.)
This object is maintained by <O.View#didEnterDocument> and
<O.View#willLeaveDocument>; no code outside of those two methods is
permitted to mutate it.
*/
const activeViews = new Obj();
export default activeViews;
/**
Function: O.getViewFromNode
Returns the view object that the given DOM node is a part of.
Parameters:
node - {Element} a DOM node.
Returns:
{O.View|null} The view which owns the node.
*/
export const getViewFromNode = function ( node ) {
const doc = node.ownerDocument;
let view = null;
while ( !view && node && node !== doc ) {
view = activeViews[ node.id ] || null;
node = node.parentNode;
}
return view;
};
| Return null not undefined from getViewFromNode | Return null not undefined from getViewFromNode
| JavaScript | mit | fastmail/overture | ---
+++
@@ -35,7 +35,7 @@
const doc = node.ownerDocument;
let view = null;
while ( !view && node && node !== doc ) {
- view = activeViews[ node.id ];
+ view = activeViews[ node.id ] || null;
node = node.parentNode;
}
return view; |
1f18956589b16ffc6cc312d104d113139b516e6d | sourcestats/webpack/util.js | sourcestats/webpack/util.js | // Source Server Stats
// File: sourcestats/webpack/util.js
// Desc: utility functions for the frontend
export function timeAgo(dateString) {
const date = new Date(dateString);
const seconds = Math.floor((new Date() - date) / 1000);
let interval = Math.floor(seconds / 31536000);
if (interval > 1) {
return interval + 'y';
}
interval = Math.floor(seconds / 2592000);
if (interval > 1) {
return interval + 'm';
}
interval = Math.floor(seconds / 86400);
if (interval > 1) {
return interval + 'd';
}
interval = Math.floor(seconds / 3600);
if (interval > 1) {
return interval + 'h';
}
interval = Math.floor(seconds / 60);
if (interval > 1) {
return interval + 'm';
}
return Math.floor(seconds) + 's';
}
| // Source Server Stats
// File: sourcestats/webpack/util.js
// Desc: utility functions for the frontend
import _ from 'lodash';
export function parseDates(list, accessor) {
const dates = [];
_.each(list, value => {
dates.push({
date: new Date(value.datetime),
value: value[accessor]
});
});
return dates;
}
export function timeAgo(dateString) {
// In UTC time
const then = new Date(dateString).getTime();
// In user local time
let now = new Date();
// Add the offset (JavaScript date handling is a joke)
now = now.getTime() + (now.getTimezoneOffset() * 60000);
const seconds = Math.floor((now - then) / 1000);
let interval = Math.floor(seconds / 31536000);
if (interval > 1) {
return interval + 'y';
}
interval = Math.floor(seconds / 2592000);
if (interval > 1) {
return interval + 'm';
}
interval = Math.floor(seconds / 86400);
if (interval > 1) {
return interval + 'd';
}
interval = Math.floor(seconds / 3600);
if (interval > 1) {
return interval + 'h';
}
interval = Math.floor(seconds / 60);
if (interval > 1) {
return interval + 'm';
}
return Math.floor(seconds) + 's';
}
| Support user timezones (and discover JS date fails). | Support user timezones (and discover JS date fails).
| JavaScript | mit | Fizzadar/SourceServerStats,Fizzadar/SourceServerStats,Fizzadar/SourceServerStats | ---
+++
@@ -2,10 +2,33 @@
// File: sourcestats/webpack/util.js
// Desc: utility functions for the frontend
+import _ from 'lodash';
+
+
+export function parseDates(list, accessor) {
+ const dates = [];
+
+ _.each(list, value => {
+ dates.push({
+ date: new Date(value.datetime),
+ value: value[accessor]
+ });
+ });
+
+ return dates;
+}
+
export function timeAgo(dateString) {
- const date = new Date(dateString);
- const seconds = Math.floor((new Date() - date) / 1000);
+ // In UTC time
+ const then = new Date(dateString).getTime();
+
+ // In user local time
+ let now = new Date();
+
+ // Add the offset (JavaScript date handling is a joke)
+ now = now.getTime() + (now.getTimezoneOffset() * 60000);
+ const seconds = Math.floor((now - then) / 1000);
let interval = Math.floor(seconds / 31536000);
|
4dbd8db4145fafc6e88b6be1e90145e5b22c9e2d | nfc.js | nfc.js | var nfc = require('nfc').nfc;
var n = new nfc();
var middleware = function (req, res, next) {
res.sseSetup = function() {
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive'
});
};
res.sseSend = function(data) {
res.write('data: ' + JSON.stringify(data) + '\n\n');
};
next();
}
var init = function(app) {
var tagData = { uid: null };
var connections = [];
app.use(middleware);
app.get('/events', function(req, res) {
res.sseSetup();
res.sseSend(tagData);
connections.push(res);
});
n.on('uid', function(uid) {
console.log('UID:', uid);
tagData.uid = uid;
for(var i = 0; i < connections.length; i++) {
connections[i].sseSend(tagData);
}
});
n.start();
};
module.exports = init; | var nfc = require('nfc').nfc;
var n = new nfc();
var middleware = function (req, res, next) {
res.sseSetup = function() {
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive'
});
};
res.sseSend = function(eventName, data) {
res.write( 'event: ' + eventName + '\ndata: ' + JSON.stringify(data) + '\n\n');
};
next();
}
var init = function(app) {
var connections = [];
var lastUid;
app.use(middleware);
app.get('/events', function(req, res) {
res.sseSetup();
res.sseSend( 'ping', new Date() );
connections.push(res);
});
n.on('uid', function(uid) {
console.log('UID:', uid);
if( lastUid === uid ) {
return;
}
for(var i = 0; i < connections.length; i++) {
connections[i].sseSend( 'nfcread', { uid: uid });
}
lastUid = uid;
setTimeout(function() { lastUid = null; }, 5000);
});
n.start();
};
module.exports = init; | Add some hackish server-side throttling and use named events | Add some hackish server-side throttling and use named events
| JavaScript | mit | anderssonjohan/nfc-express | ---
+++
@@ -10,30 +10,34 @@
});
};
- res.sseSend = function(data) {
- res.write('data: ' + JSON.stringify(data) + '\n\n');
+ res.sseSend = function(eventName, data) {
+ res.write( 'event: ' + eventName + '\ndata: ' + JSON.stringify(data) + '\n\n');
};
next();
}
var init = function(app) {
- var tagData = { uid: null };
var connections = [];
+ var lastUid;
app.use(middleware);
app.get('/events', function(req, res) {
res.sseSetup();
- res.sseSend(tagData);
+ res.sseSend( 'ping', new Date() );
connections.push(res);
});
n.on('uid', function(uid) {
console.log('UID:', uid);
- tagData.uid = uid;
+ if( lastUid === uid ) {
+ return;
+ }
for(var i = 0; i < connections.length; i++) {
- connections[i].sseSend(tagData);
+ connections[i].sseSend( 'nfcread', { uid: uid });
}
+ lastUid = uid;
+ setTimeout(function() { lastUid = null; }, 5000);
});
n.start(); |
e74840fcd3b6204f3dd65f5151729a646aeefe3a | src/client/app/components/basket/basket.template.js | src/client/app/components/basket/basket.template.js | export class BasketTemplate {
static update(render, state, events) {
const headerClasses = "fw6 bb b--black-20 tl pb1 pr1 bg-white";
const trClasses = "pv1 pr1 bb b--black-20";
/* eslint-disable indent */
render`
<h2>Basket</h2>
<input id="assetsSearch" size="32" oninput="${events}" placeholder="What assets to be added?">
<table class="f7 mw8 pa2" cellpsacing="0">
<thead>
<th class="${headerClasses}">Symbol</th>
<th class="${headerClasses}">Description</th>
<th class="${headerClasses}">Type</th>
<th class="${headerClasses}">Market</th>
</thead>
<tbody onclick="${events}" >${state.assetsSearch.map(asset =>
`<tr>
<td id="assetSearch-${asset.symbol}"
class="${trClasses} pointer dim"
data-value='${escape(JSON.stringify(asset))}'
title="Click to add the asset">${asset.symbol}</td>
<td class="${trClasses}">${asset.name}</td>
<td class="${trClasses}">${asset.type}</td>
<td class="${trClasses}">${asset.exchDisp}</td>
</tr>`)
}</tbody>
</table>
`;
/* eslint-enable indent */
}
}
| import { Util } from "../../util.js";
export class BasketTemplate {
static update(render, state, events) {
const headerClasses = "fw6 bb b--black-20 tl pb1 pr1 bg-white";
const trClasses = "pv1 pr1 bb b--black-20";
/* eslint-disable indent */
render`
<h2>Basket</h2>
<input id="assetsSearch" size="32" oninput="${events}" placeholder="What assets to be added?">
<table style="${Util.show(state.assetsSearch.length)}" class="f7 mw8 pa2" cellpsacing="0">
<thead>
<th class="${headerClasses}">Symbol</th>
<th class="${headerClasses}">Description</th>
<th class="${headerClasses}">Type</th>
<th class="${headerClasses}">Market</th>
</thead>
<tbody onclick="${events}" >${state.assetsSearch.map(asset =>
`<tr>
<td id="assetSearch-${asset.symbol}"
class="${trClasses} pointer dim"
data-value='${escape(JSON.stringify(asset))}'
title="Click to add the asset">${asset.symbol}</td>
<td class="${trClasses}">${asset.name}</td>
<td class="${trClasses}">${asset.type}</td>
<td class="${trClasses}">${asset.exchDisp}</td>
</tr>`)
}</tbody>
</table>
`;
/* eslint-enable indent */
}
}
| Hide basket table if no search assets. | Hide basket table if no search assets.
| JavaScript | mit | albertosantini/node-conpa,albertosantini/node-conpa | ---
+++
@@ -1,3 +1,5 @@
+import { Util } from "../../util.js";
+
export class BasketTemplate {
static update(render, state, events) {
const headerClasses = "fw6 bb b--black-20 tl pb1 pr1 bg-white";
@@ -8,7 +10,7 @@
<h2>Basket</h2>
<input id="assetsSearch" size="32" oninput="${events}" placeholder="What assets to be added?">
- <table class="f7 mw8 pa2" cellpsacing="0">
+ <table style="${Util.show(state.assetsSearch.length)}" class="f7 mw8 pa2" cellpsacing="0">
<thead>
<th class="${headerClasses}">Symbol</th>
<th class="${headerClasses}">Description</th> |
b95980041727664708554ea9876b73216439506d | src/helpers.js | src/helpers.js | function getDescriptionAndTags(input) {
const pieces = input.split(' ');
const descriptionPieces = [];
const tags = [];
pieces.forEach(piece => {
if (piece[0] === '#') {
tags.push(piece.slice(1)); // tag without the leading '#'
} else {
descriptionPieces.push(piece);
}
})
return {
description: descriptionPieces.join(' '),
tags: tags,
}
}
export {
getDescriptionAndTags
}
| function getDescriptionAndTags(input) {
const pieces = input.split(' ');
const descriptionPieces = [];
const tags = [];
pieces.forEach(piece => {
if (piece[0] === '#') {
tags.push(piece.slice(1)); // tag without the leading '#'
} else {
descriptionPieces.push(piece);
}
})
return {
description: descriptionPieces.join(' '),
tags: tags,
}
}
function buildDescriptionAndTags(description = '', tags = []) {
const tagString = tags.map(tag => `#${tag}`).join(' ');
return `${description} ${tagString}`;
}
export {
getDescriptionAndTags,
buildDescriptionAndTags,
}
| Build string of description plus tags for editing | Build string of description plus tags for editing
| JavaScript | mit | mknudsen01/today,mknudsen01/today | ---
+++
@@ -18,6 +18,12 @@
}
}
+function buildDescriptionAndTags(description = '', tags = []) {
+ const tagString = tags.map(tag => `#${tag}`).join(' ');
+ return `${description} ${tagString}`;
+}
+
export {
- getDescriptionAndTags
+ getDescriptionAndTags,
+ buildDescriptionAndTags,
} |
c94b317ac7f44494e8d9a97f5b2c25ebbcf50d53 | lib/formatter.js | lib/formatter.js | 'use strict';
const config = require('./config');
const gooGl = require('goo.gl');
const moment = require('moment-timezone');
const removeUrlGarbage = require('link-cleaner');
if (config.shortenLinks) {
gooGl.setKey(config.gooGlKey);
}
async function formatDocuments(data) {
data.sort((a, b) => {
const ap = a.published;
const bp = b.published;
if (ap > bp) {
return 1;
}
if (ap < bp) {
return -1;
}
return 0;
});
const docs = [];
for (let doc of data) {
const link = config.shortenLinks ?
await gooGl.shorten(doc.link) :
removeUrlGarbage(doc.link);
const date = moment.tz(doc.published, 'UTC');
const formattedDate = date.tz(config.tz).format('DD.MM.Y HH:mm');
docs.push(`${formattedDate} ${link}\n${doc.title}`);
}
return docs;
}
module.exports = {
formatDocuments,
};
| 'use strict';
const config = require('./config');
const gooGl = require('goo.gl');
const moment = require('moment-timezone');
const removeUrlGarbage = require('link-cleaner');
if (config.shortenLinks) {
gooGl.setKey(config.gooGlKey);
}
async function formatDocuments(data) {
data.sort((a, b) => {
const ap = a.published;
const bp = b.published;
if (ap > bp) {
return 1;
}
if (ap < bp) {
return -1;
}
return 0;
});
const docs = [];
for (let doc of data) {
const link = config.shortenLinks ?
await gooGl.shorten(doc.link) :
removeUrlGarbage(doc.link);
const date = moment.tz(doc.published, 'UTC');
const formattedDate = date.tz(config.tz).format('DD.MM.Y HH:mm');
docs.push(`${formattedDate} ${link}\n${doc.title}: ${doc.source_title}`);
}
return docs;
}
module.exports = {
formatDocuments,
};
| Add source title to messages | Add source title to messages
| JavaScript | mit | andre487/news487,andre487/news487,andre487/news487,andre487/news487 | ---
+++
@@ -30,7 +30,7 @@
const date = moment.tz(doc.published, 'UTC');
const formattedDate = date.tz(config.tz).format('DD.MM.Y HH:mm');
- docs.push(`${formattedDate} ${link}\n${doc.title}`);
+ docs.push(`${formattedDate} ${link}\n${doc.title}: ${doc.source_title}`);
}
return docs; |
3a5ea9fc0b9eec3040a3986be6e47187449de227 | tests/pages/universe/packages/InstallPackageModal-cy.js | tests/pages/universe/packages/InstallPackageModal-cy.js | xdescribe('Install Package Modal', function () {
beforeEach(function () {
cy
.configureCluster({
mesos: '1-task-healthy',
universePackages: true
})
.visitUrl({url: '/universe'})
.get('.page-body-content .button.button-success')
.eq(0)
.click();
});
xit('displays install modal for package', function () {
cy
.get('.modal .modal-content')
.should('contain', 'marathon');
});
});
| describe('Install Package Modal', function () {
beforeEach(function () {
cy
.configureCluster({
mesos: '1-task-healthy',
universePackages: true
})
.visitUrl({url: '/universe'})
.get('.page-body-content .button.button-success')
.eq(0)
.click();
});
it('displays install modal for package', function () {
cy
.get('.modal .modal-body')
.should('contain', 'marathon');
});
});
| Fix integration tests for InstallPackageModal | Fix integration tests for InstallPackageModal
| JavaScript | apache-2.0 | dcos/dcos-ui,dcos/dcos-ui,dcos/dcos-ui,dcos/dcos-ui,dcos/dcos-ui | ---
+++
@@ -1,4 +1,4 @@
-xdescribe('Install Package Modal', function () {
+describe('Install Package Modal', function () {
beforeEach(function () {
cy
@@ -12,9 +12,9 @@
.click();
});
- xit('displays install modal for package', function () {
+ it('displays install modal for package', function () {
cy
- .get('.modal .modal-content')
+ .get('.modal .modal-body')
.should('contain', 'marathon');
});
|
2968f8edf801fdf651539f3662208454831b268a | react/features/filmstrip/components/native/AudioMutedIndicator.js | react/features/filmstrip/components/native/AudioMutedIndicator.js | import React, { Component } from 'react';
import Icon from 'react-native-vector-icons/FontAwesome';
import styles from './styles';
/**
* Thumbnail badge for displaying the audio mute status of a participant.
*/
export class AudioMutedIndicator extends Component {
/**
* Implements React's {@link Component#render()}.
*
* @inheritdoc
*/
render() {
return (
<Icon
name = 'microphone-slash'
style = { styles.thumbnailIndicator } />
);
}
}
| import React, { Component } from 'react';
import { Icon } from '../../../base/font-icons';
import styles from './styles';
/**
* Thumbnail badge for displaying the audio mute status of a participant.
*/
export class AudioMutedIndicator extends Component {
/**
* Implements React's {@link Component#render()}.
*
* @inheritdoc
*/
render() {
return (
<Icon
name = 'mic-disabled'
style = { styles.thumbnailIndicator } />
);
}
}
| Make the audio muted icon consistent with the web | [RN] Make the audio muted icon consistent with the web
| JavaScript | apache-2.0 | jitsi/jitsi-meet,gpolitis/jitsi-meet,jitsi/jitsi-meet,jitsi/jitsi-meet,bgrozev/jitsi-meet,gpolitis/jitsi-meet,gpolitis/jitsi-meet,gpolitis/jitsi-meet,jitsi/jitsi-meet,jitsi/jitsi-meet,jitsi/jitsi-meet,bgrozev/jitsi-meet,jitsi/jitsi-meet,bgrozev/jitsi-meet,gpolitis/jitsi-meet,bgrozev/jitsi-meet,gpolitis/jitsi-meet,gpolitis/jitsi-meet,bgrozev/jitsi-meet,jitsi/jitsi-meet,bgrozev/jitsi-meet,gpolitis/jitsi-meet | ---
+++
@@ -1,5 +1,6 @@
import React, { Component } from 'react';
-import Icon from 'react-native-vector-icons/FontAwesome';
+
+import { Icon } from '../../../base/font-icons';
import styles from './styles';
@@ -15,7 +16,7 @@
render() {
return (
<Icon
- name = 'microphone-slash'
+ name = 'mic-disabled'
style = { styles.thumbnailIndicator } />
);
} |
df19b8ff3c81b2970801f33017e5a8d1888994f1 | src/options.js | src/options.js | //Karyo Options
Karyo.prototype.Options = function(opt)
{
//Check preview regions
if(typeof opt.previewRegions !== 'undefined'){ this.chrpreview.show = opt.previewRegions; }
//Check navbar height
if(typeof opt.navbarHeight !== 'undefined'){ this.navbar.height = opt.navbarHeight; }
//Check navbar show
if(typeof opt.navbarShow !== 'undefined'){ this.navbar.show = opt.navbarShow; }
//Check navbar show karyotype button
if(typeof opt.navbarShowKaryo !== 'undefined'){ this.navbar.btnKaryoShow = opt.navbarShowKaryo; }
//Check navbar show search button
if(typeof opt.navbarShowSearch !== 'undefined'){ this.navbar.btnSearchShow = opt.navbarShowSearch; }
//Check navbar show help button
if(typeof opt.navbarShowHelp !== 'undefined'){ this.navbar.btnHelpShow = opt.navbarShowHelp; }
//For show the tip alert
if(typeof opt.tipShow !== 'undefined'){ this.alert.tip = opt.tipShow; }
//For personalize the tip message
if(typeof opt.tipText !== 'undefined'){ this.alertmsg.tip = opt.tipText; }
//Select max region
if(typeof opt.selectMax !== 'undefined'){ this.select.max = opt.selectMax; }
//Select enabled
if(typeof opt.selectEnabled !== 'undefined'){ this.select.enabled = opt.selectEnabled; }
};
| //Karyo Options
Karyo.prototype.Options = function(opt)
{
//Check preview regions
if(typeof opt.previewRegions !== 'undefined'){ this.chrpreview.show = opt.previewRegions; }
//Check navbar height
if(typeof opt.navbarHeight !== 'undefined'){ this.navbar.height = opt.navbarHeight; }
//Check navbar show
if(typeof opt.navbarShow !== 'undefined'){ this.navbar.show = opt.navbarShow; }
//Check navbar show karyotype button
if(typeof opt.navbarShowKaryo !== 'undefined'){ this.navbar.btnKaryoShow = opt.navbarShowKaryo; }
//Check navbar show search button
if(typeof opt.navbarShowSearch !== 'undefined'){ this.navbar.btnSearchShow = opt.navbarShowSearch; }
//Check navbar show help button
if(typeof opt.navbarShowHelp !== 'undefined'){ this.navbar.btnHelpShow = opt.navbarShowHelp; }
//For show the tip alert
if(typeof opt.tipShow !== 'undefined'){ this.alert.tip = opt.tipShow; }
//For personalize the tip message
if(typeof opt.tipText !== 'undefined'){ this.alertmsg.tip = opt.tipText; }
//Select max region
if(typeof opt.selectMax !== 'undefined'){ this.select.max = opt.selectMax; }
//Select enabled
if(typeof opt.selectEnabled !== 'undefined'){ this.select.enabled = opt.selectEnabled; }
//Show report table
if(typeof opt.showTable !== 'undefined'){ this.table.show = opt.showTable; }
};
| Add show report table option | Add show report table option
| JavaScript | mit | biowt/karyojs,biowt/karyojs | ---
+++
@@ -30,4 +30,7 @@
//Select enabled
if(typeof opt.selectEnabled !== 'undefined'){ this.select.enabled = opt.selectEnabled; }
+
+ //Show report table
+ if(typeof opt.showTable !== 'undefined'){ this.table.show = opt.showTable; }
}; |
011d3f2af278150c57c20e70ce5d0ccf69c070d0 | webpack.config.babel.js | webpack.config.babel.js |
/**
* Module dependencies.
*/
import packageConfig from './package.json';
import webpack from 'webpack';
/**
* Webpack configuration.
*/
export default {
entry: './src/browser/index.js',
module: {
loaders: [
{
exclude: /node_modules/,
loader: 'babel-loader',
query: {
plugins: [
['transform-es2015-for-of', {
loose: true
}]
],
presets: ['es2015']
},
test: /\.js$/
},
{
exclude: /node_modules\/(?!html-tags).+/,
loader: 'json-loader',
test: /\.json$/
}
]
},
output: {
filename: `${packageConfig.name}.js`,
library: packageConfig.name,
libraryTarget: 'commonjs2',
path: `${__dirname}/dist/browser`
},
plugins: [
new webpack.optimize.UglifyJsPlugin()
]
};
|
/**
* Module dependencies.
*/
import webpack from 'webpack';
/**
* Webpack configuration.
*/
export default {
entry: './src/browser/index.js',
module: {
loaders: [{
exclude: /node_modules/,
loader: 'babel-loader',
query: {
plugins: [
['transform-es2015-for-of', {
loose: true
}]
],
presets: ['es2015']
},
test: /\.js$/
}, {
exclude: /node_modules\/(?!html-tags).+/,
loader: 'json-loader',
test: /\.json$/
}]
},
output: {
filename: 'uphold-sdk-javascript.js',
library: 'uphold-sdk-javascript',
libraryTarget: 'commonjs2',
path: `${__dirname}/dist/browser`
},
plugins: [
new webpack.optimize.UglifyJsPlugin()
]
};
| Fix file name on webpack configuration | Fix file name on webpack configuration
| JavaScript | mit | uphold/uphold-sdk-javascript,uphold/uphold-sdk-javascript | ---
+++
@@ -3,7 +3,6 @@
* Module dependencies.
*/
-import packageConfig from './package.json';
import webpack from 'webpack';
/**
@@ -13,30 +12,27 @@
export default {
entry: './src/browser/index.js',
module: {
- loaders: [
- {
- exclude: /node_modules/,
- loader: 'babel-loader',
- query: {
- plugins: [
- ['transform-es2015-for-of', {
- loose: true
- }]
- ],
- presets: ['es2015']
- },
- test: /\.js$/
+ loaders: [{
+ exclude: /node_modules/,
+ loader: 'babel-loader',
+ query: {
+ plugins: [
+ ['transform-es2015-for-of', {
+ loose: true
+ }]
+ ],
+ presets: ['es2015']
},
- {
- exclude: /node_modules\/(?!html-tags).+/,
- loader: 'json-loader',
- test: /\.json$/
- }
- ]
+ test: /\.js$/
+ }, {
+ exclude: /node_modules\/(?!html-tags).+/,
+ loader: 'json-loader',
+ test: /\.json$/
+ }]
},
output: {
- filename: `${packageConfig.name}.js`,
- library: packageConfig.name,
+ filename: 'uphold-sdk-javascript.js',
+ library: 'uphold-sdk-javascript',
libraryTarget: 'commonjs2',
path: `${__dirname}/dist/browser`
}, |
07b21357297e002a70de3b9336594a54b1cf56e1 | src/renderers/shaders/ShaderLib/shadow_frag.glsl.js | src/renderers/shaders/ShaderLib/shadow_frag.glsl.js | export default /* glsl */`
uniform vec3 color;
uniform float opacity;
#include <common>
#include <packing>
#include <fog_pars_fragment>
#include <bsdfs>
#include <lights_pars_begin>
#include <shadowmap_pars_fragment>
#include <shadowmask_pars_fragment>
void main() {
gl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );
#include <fog_fragment>
}
`;
| export default /* glsl */`
uniform vec3 color;
uniform float opacity;
#include <common>
#include <packing>
#include <fog_pars_fragment>
#include <bsdfs>
#include <lights_pars_begin>
#include <shadowmap_pars_fragment>
#include <shadowmask_pars_fragment>
void main() {
gl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );
#include <tonemapping_fragment>
#include <encodings_fragment>
#include <fog_fragment>
}
`;
| Include tonemapping and encoding chunks | Include tonemapping and encoding chunks
| JavaScript | mit | Itee/three.js,Samsy/three.js,Liuer/three.js,TristanVALCKE/three.js,06wj/three.js,TristanVALCKE/three.js,makc/three.js.fork,makc/three.js.fork,WestLangley/three.js,fraguada/three.js,fraguada/three.js,Samsy/three.js,Samsy/three.js,fyoudine/three.js,TristanVALCKE/three.js,Samsy/three.js,TristanVALCKE/three.js,zhoushijie163/three.js,aardgoose/three.js,WestLangley/three.js,zhoushijie163/three.js,Samsy/three.js,gero3/three.js,greggman/three.js,fraguada/three.js,06wj/three.js,jpweeks/three.js,stanford-gfx/three.js,gero3/three.js,kaisalmen/three.js,mrdoob/three.js,fraguada/three.js,stanford-gfx/three.js,jpweeks/three.js,greggman/three.js,looeee/three.js,fyoudine/three.js,fraguada/three.js,looeee/three.js,mrdoob/three.js,kaisalmen/three.js,fraguada/three.js,donmccurdy/three.js,Itee/three.js,TristanVALCKE/three.js,aardgoose/three.js,donmccurdy/three.js,Samsy/three.js,TristanVALCKE/three.js,Liuer/three.js | ---
+++
@@ -14,6 +14,8 @@
gl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );
+ #include <tonemapping_fragment>
+ #include <encodings_fragment>
#include <fog_fragment>
} |
3b6751431a68c5e56df77d4fc72d0cd255708c4c | client/app/views/filesview.js | client/app/views/filesview.js | define(
['backbone', 'views/filenameview', 'collections/files', 'app'],
function(Backbone, FilenameView, Files, app) {
var FilesView = Backbone.View.extend({
tagName: 'ul',
initialize: function(options) {
options = options || {};
this.$parent = options.$parent;
this.$parent.append(this.$el);
this.listenTo(this.model, 'reset', this.addAll);
var xhr = this.model.fetch({ reset: true });
xhr.error(function(xhr) {
alert("Error loading files: " + xhr.responseText);
});
xhr.success(function(what) {
app.trigger('initialLoad');
});
},
addOne: function(file) {
var view = new FilenameView({ model: file });
this.$el.append(view.render().el);
// if (file.isDir() && file.get('name') === 'node_modules/' ) {
// var files2 = new Files({ path: file.get('name') });
// var files2View = new FilesView({ model: files2, $parent: view.$el });
// }
},
addAll: function() {
var that = this;
this.$el.empty();
this.model.each(function(file) {
that.addOne(file);
});
}
});
return FilesView;
});
| define(
['backbone', 'views/filenameview', 'collections/files', 'app'],
function(Backbone, FilenameView, Files, app) {
var FilesView = Backbone.View.extend({
tagName: 'ul',
initialize: function(options) {
options = options || {};
this.$parent = options.$parent;
this.$parent.append(this.$el);
this.listenTo(this.model, 'reset', this.addAll);
var xhr = this.model.fetch({ reset: true });
xhr.error(function(xhr) {
alert("Error loading files: " + xhr.responseText);
});
xhr.success(function(what) {
app.trigger('initialLoad');
});
},
addOne: function(file) {
var view = new FilenameView({ model: file });
this.$el.append(view.render().el);
// if (file.isDir() && file.get('name') === 'node_modules/' ) {
// var files2 = new Files({ path: file.get('name') });
// var files2View = new FilesView({ model: files2, $parent: view.$el });
// }
},
addAll: function() {
var that = this;
this.$el.empty();
this.model.each(function(file) {
that.addOne(file);
});
}
});
return FilesView;
});
| Remove mix of spaces and tabs | Remove mix of spaces and tabs
| JavaScript | mit | anttisykari/angular-fileedit,anttisykari/backbone-fileedit | ---
+++
@@ -23,10 +23,10 @@
var view = new FilenameView({ model: file });
this.$el.append(view.render().el);
-// if (file.isDir() && file.get('name') === 'node_modules/' ) {
-// var files2 = new Files({ path: file.get('name') });
-// var files2View = new FilesView({ model: files2, $parent: view.$el });
-// }
+// if (file.isDir() && file.get('name') === 'node_modules/' ) {
+// var files2 = new Files({ path: file.get('name') });
+// var files2View = new FilesView({ model: files2, $parent: view.$el });
+// }
},
addAll: function() { |
ad21ee818aa0c44317ca472c6d9e027cdde1e946 | lib/scriptrun.js | lib/scriptrun.js | const exec = require('child_process').exec;
const inspect = require('util').inspect;
const fs = require('fs');
const path = require('path');
const del = require('del');
const mkdirp = require('mkdirp');
const command = 'node';
const inspectOpt = { depth: null };
const readOpt = { encoding: 'utf-8' };
var id = 0;
function createTestFunction(templateFile, testDir) {
del.sync(path.join(testDir + './test-**.js'));
mkdirp(testDir);
var templateJs = fs.readFileSync(templateFile, readOpt);
return function(testcase, done) {
var filepath = createTestFile(templateJs, testDir, testcase, id ++);
exec(command + ' ' + filepath, function(err, stdout, stderr) {
if (stderr !== '') {
throw new Error(stderr);
}
if (err != null) {
throw new Error(err);
}
done();
});
};
}
function createTestFile(template, testDir, testcase, id) {
var filePath = path.resolve(testDir, 'test-' + id + '.js');
var regExp = new RegExp('\\${testcase}', 'g');
var jsSrc = template.replace(regExp, inspect(testcase, inspectOpt));
fs.writeFileSync(filePath, jsSrc);
return filePath;
}
module.exports = createTestFunction;
| const exec = require('child_process').exec;
const inspect = require('util').inspect;
const fs = require('fs');
const path = require('path');
const del = require('del');
const mkdirp = require('mkdirp');
const command = 'node';
const inspectOpt = { depth: null };
const readOpt = { encoding: 'utf-8' };
var id = 0;
function createTestFunction(templateFile, testDir) {
del.sync(path.join(testDir, './test-**.js'));
mkdirp(testDir);
var templateJs = fs.readFileSync(templateFile, readOpt);
return function(testcase, done) {
var filepath = createTestFile(templateJs, testDir, testcase, id ++);
exec(command + ' ' + filepath, function(err, stdout, stderr) {
if (stderr !== '') {
throw new Error(stderr);
}
if (err != null) {
throw new Error(err);
}
done();
});
};
}
function createTestFile(template, testDir, testcase, id) {
var filePath = path.resolve(testDir, 'test-' + id + '.js');
var regExp = new RegExp('\\${testcase}', 'g');
var jsSrc = template.replace(regExp, inspect(testcase, inspectOpt));
fs.writeFileSync(filePath, jsSrc);
return filePath;
}
module.exports = createTestFunction;
| Fix bug of cleaning test files. | Fix bug of cleaning test files.
| JavaScript | mit | sttk/testrun | ---
+++
@@ -12,7 +12,7 @@
var id = 0;
function createTestFunction(templateFile, testDir) {
- del.sync(path.join(testDir + './test-**.js'));
+ del.sync(path.join(testDir, './test-**.js'));
mkdirp(testDir);
var templateJs = fs.readFileSync(templateFile, readOpt);
|
394e49f268ff920b307bfee589f6e4afa18cb4b1 | jest.js | jest.js | 'use strict';
module.exports = {
plugins: [
'jest',
],
env: {
'jest/globals': true,
},
extends: [
'./index',
'./rules/plugin-jest',
].map(require.resolve),
};
| 'use strict';
module.exports = {
plugins: [
'jest',
],
env: {
'jest/globals': true,
},
extends: [
'./index',
'./rules/plugin-jest',
].map(require.resolve),
rules: {
'filenames/match-regex': [
'error',
/^[A-Za-z0-9.-]+$/,
],
},
};
| Apply the same filename rules to Jest as we do React | Apply the same filename rules to Jest as we do React
| JavaScript | isc | CoursePark/eslint-config-bluedrop,CoursePark/eslint-config-bluedrop | ---
+++
@@ -11,4 +11,10 @@
'./index',
'./rules/plugin-jest',
].map(require.resolve),
+ rules: {
+ 'filenames/match-regex': [
+ 'error',
+ /^[A-Za-z0-9.-]+$/,
+ ],
+ },
}; |
89dde9dc27f16239de4ccc3add29fcf49cfb0ef8 | src/relList.js | src/relList.js | ;(function () {
'use strict';
if ('relList' in document.createElement('a')) {
return;
}
var i;
var elements = [HTMLAnchorElement, HTMLAreaElement, HTMLLinkElement];
var getter = function () {
return new DOMTokenList2(this, 'rel');
};
for (i = 0; i < elements.length; i++) {
Object.defineProperty(elements[i].prototype, 'relList', {
get: getter
});
}
}());
| ;(function () {
'use strict';
if ('relList' in document.createElement('a')) {
return;
}
var i;
var elements = [HTMLAnchorElement, HTMLAreaElement, HTMLLinkElement];
var getter = function () {
return new DOMTokenList(this, 'rel');
};
for (i = 0; i < elements.length; i++) {
Object.defineProperty(elements[i].prototype, 'relList', {
get: getter
});
}
}());
| Add proper name for DOMTokenList | Add proper name for DOMTokenList | JavaScript | mit | jwilsson/domtokenlist,jwilsson/domtokenlist | ---
+++
@@ -8,7 +8,7 @@
var i;
var elements = [HTMLAnchorElement, HTMLAreaElement, HTMLLinkElement];
var getter = function () {
- return new DOMTokenList2(this, 'rel');
+ return new DOMTokenList(this, 'rel');
};
for (i = 0; i < elements.length; i++) { |
9a1da20065104aa4dae087c1589b413db4f84ec0 | server/app/mongoose-connection.js | server/app/mongoose-connection.js | module.exports = function(config) {
var mongoose = require('mongoose');
var db = mongoose.connection;
var schemas = {};
var eventSchema = new mongoose.Schema({
'category': String,
'coordinates': {
'latitude': Number,
'longitude': Number
},
'name': String,
'originalId': String,
'origin': String,
'url': String
});
var locationSchema = new mongoose.Schema({
'category': String,
'coordinates': {
'latitude': Number,
'longitude': Number
}
});
var userSchema = new mongoose.Schema({
'coordinates': {
'latitude': Number,
'longitude': Number
},
'dateOfBirth': Date,
'email': String,
'familyName': String,
'givenName': String,
'phoneNumber': String,
'tags': [String]
});
schemas.Event = mongoose.model('Event', eventSchema);
schemas.Location = mongoose.model('Location', locationSchema);
schemas.User = mongoose.model('User', userSchema);
mongoose.connect(config.MONGO_URL, {
user: config.MONGO_USERNAME,
password: config.MONGO_PASSWORD
});
return {
db: db,
schemas: schemas
};
};
| module.exports = function(config) {
['MONGO_URL', 'MONGO_USERNAME', 'MONGO_PASSWORD'].forEach(function(envvar) {
if (config[envvar] === undefined) {
throw new Error('Mongo is missing ' + envvar);
}
});
var mongoose = require('mongoose');
var db = mongoose.connection;
var schemas = {};
var eventSchema = new mongoose.Schema({
'category': String,
'coordinates': {
'latitude': Number,
'longitude': Number
},
'name': String,
'originalId': String,
'origin': String,
'url': String
});
var locationSchema = new mongoose.Schema({
'category': String,
'coordinates': {
'latitude': Number,
'longitude': Number
}
});
var userSchema = new mongoose.Schema({
'coordinates': {
'latitude': Number,
'longitude': Number
},
'dateOfBirth': Date,
'email': String,
'familyName': String,
'givenName': String,
'phoneNumber': String,
'tags': [String]
});
schemas.Event = mongoose.model('Event', eventSchema);
schemas.Location = mongoose.model('Location', locationSchema);
schemas.User = mongoose.model('User', userSchema);
mongoose.connect(config.MONGO_URL, {
user: config.MONGO_USERNAME,
password: config.MONGO_PASSWORD
});
return {
db: db,
schemas: schemas
};
};
| Throw an error if Mongo is missing envvars | Throw an error if Mongo is missing envvars
| JavaScript | mit | volontario/volontario-server | ---
+++
@@ -1,4 +1,10 @@
module.exports = function(config) {
+ ['MONGO_URL', 'MONGO_USERNAME', 'MONGO_PASSWORD'].forEach(function(envvar) {
+ if (config[envvar] === undefined) {
+ throw new Error('Mongo is missing ' + envvar);
+ }
+ });
+
var mongoose = require('mongoose');
var db = mongoose.connection; |
d1e537a39deff3fe6d37a80f1d8e3f5f523ced2d | example/app.js | example/app.js | /**
* Module dependencies
*/
var Zeditor = require('zeditor');
var ZeditorPaste = require('zeditor-paste');
/**
* Get DOM nodes
*/
var editorNode = document.getElementById('editor');
/**
* Instantiate editor
*/
Zeditor(editorNode);
ZeditorPaste(editorNode);
/**
* Other functionality
*/
Zeditor(editorNode).on('error', function (err) {
// for now, any "error" event log to the console
console.error('editor "error" event: %o', err);
});
var outputNode = document.getElementById('output');
var showEditorButtonNode = document.getElementById('showEditor');
var showOutputButtonNode = document.getElementById('showOutput');
showEditorButtonNode.addEventListener('click', function (e) {
e.preventDefault();
showEditorButtonNode.style.display = 'none';
editorNode.style.display = 'block';
showOutputButtonNode.style.display = 'inline';
outputNode.style.display = 'none';
}, false);
showOutputButtonNode.addEventListener('click', function (e) {
e.preventDefault();
showEditorButtonNode.style.display = 'inline';
editorNode.style.display = 'none';
showOutputButtonNode.style.display = 'none';
outputNode.style.display = 'block';
outputNode.textContent = editor.serializer.serializeRoot();
}, false); | /**
* Module dependencies
*/
var Zeditor = require('zeditor');
var ZeditorPaste = require('zeditor-paste');
var ZeditorNormalizer = require('zeditor-normalizer');
/**
* Get DOM nodes
*/
var editorNode = document.getElementById('editor');
/**
* Instantiate editor
*/
Zeditor(editorNode);
ZeditorNormalizer(editorNode);
ZeditorPaste(editorNode);
/**
* Other functionality
*/
Zeditor(editorNode).on('error', function (err) {
// for now, any "error" event log to the console
console.error('editor "error" event: %o', err);
});
var outputNode = document.getElementById('output');
var showEditorButtonNode = document.getElementById('showEditor');
var showOutputButtonNode = document.getElementById('showOutput');
showEditorButtonNode.addEventListener('click', function (e) {
e.preventDefault();
showEditorButtonNode.style.display = 'none';
editorNode.style.display = 'block';
showOutputButtonNode.style.display = 'inline';
outputNode.style.display = 'none';
}, false);
showOutputButtonNode.addEventListener('click', function (e) {
e.preventDefault();
showEditorButtonNode.style.display = 'inline';
editorNode.style.display = 'none';
showOutputButtonNode.style.display = 'none';
outputNode.style.display = 'block';
outputNode.textContent = editor.serializer.serializeRoot();
}, false); | Use normalizer as plugin in example. | Use normalizer as plugin in example.
| JavaScript | mit | bmcmahen/zeditor,Automattic/zeditor,Automattic/zeditor,bmcmahen/zeditor,bmcmahen/zeditor,Automattic/zeditor,bmcmahen/zeditor,Automattic/zeditor | ---
+++
@@ -4,6 +4,7 @@
var Zeditor = require('zeditor');
var ZeditorPaste = require('zeditor-paste');
+var ZeditorNormalizer = require('zeditor-normalizer');
/**
* Get DOM nodes
@@ -16,6 +17,7 @@
*/
Zeditor(editorNode);
+ZeditorNormalizer(editorNode);
ZeditorPaste(editorNode);
/** |
803a4a2d5b965bf2d96edba6879104439093d331 | app/assets/javascripts/multi_select.js | app/assets/javascripts/multi_select.js | $(document).on("page:change", function(){
$("select.multi-select").multiselect({
buttonWidth: '200px',
buttonText: function(options) {
if (options.length) {
return "Pick a strategy (" + options.length + " selected)";
} else {
return "Pick a strategy";
}
},
dropRight: true
});
var cappingInput = $("input[type=checkbox][value=capping_solar_pv]")
cappingInput.parents('a').append($(".slider-wrapper.hidden"));
cappingInput.on("change", showSlider);
showSlider.call(cappingInput);
function showSlider(){
var sliderWrapper = $(this).parents('a').find(".slider-wrapper");
if($(this).is(":checked")){
sliderWrapper.removeClass("hidden");
}
else{
sliderWrapper.addClass("hidden");
}
};
$("#solar_pv_capping").slider({
focus: true,
formatter: function(value){
return value + "%";
}
});
});
| $(document).on("page:change", function(){
$("select.multi-select").multiselect({
buttonText: function(options) {
var text = 'Customise technology behaviour';
if (options.length) {
text = text + ' (' + options.length + ' selected)';
}
return text;
},
dropRight: true
});
var cappingInput = $("input[type=checkbox][value=capping_solar_pv]")
cappingInput.parents('a').append($(".slider-wrapper.hidden"));
cappingInput.on("change", showSlider);
showSlider.call(cappingInput);
function showSlider(){
var sliderWrapper = $(this).parents('a').find(".slider-wrapper");
if($(this).is(":checked")){
sliderWrapper.removeClass("hidden");
}
else{
sliderWrapper.addClass("hidden");
}
};
$("#solar_pv_capping").slider({
focus: true,
formatter: function(value){
return value + "%";
}
});
});
| Reword label on strategy picker | Reword label on strategy picker
Closes #349
| JavaScript | mit | quintel/etmoses,quintel/etmoses,quintel/etmoses,quintel/etmoses,quintel/etmoses | ---
+++
@@ -1,12 +1,13 @@
$(document).on("page:change", function(){
$("select.multi-select").multiselect({
- buttonWidth: '200px',
buttonText: function(options) {
+ var text = 'Customise technology behaviour';
+
if (options.length) {
- return "Pick a strategy (" + options.length + " selected)";
- } else {
- return "Pick a strategy";
+ text = text + ' (' + options.length + ' selected)';
}
+
+ return text;
},
dropRight: true
}); |
c88bd7ead48d63ddc18bc232af80ee38a5630470 | ember-cli-build.js | ember-cli-build.js | /*jshint node:true*/
/* global require, module */
var EmberAddon = require('ember-cli/lib/broccoli/ember-addon');
module.exports = function(defaults) {
var app = new EmberAddon(defaults, {
// Add options here
});
/*
This build file specifies the options for the dummy test app of this
addon, located in `/tests/dummy`
This build file does *not* influence how the addon or the app using it
behave. You most likely want to be modifying `./index.js` or app's build file
*/
app.import('bower_components/urijs/src/URI.min.js');
app.import('bower_components/socket.io-client/socket.io.js');
return app.toTree();
};
| /*jshint node:true*/
/* global require, module */
var EmberAddon = require('ember-cli/lib/broccoli/ember-addon');
module.exports = function(defaults) {
var app = new EmberAddon(defaults, {
// Add options here
});
/*
This build file specifies the options for the dummy test app of this
addon, located in `/tests/dummy`
This build file does *not* influence how the addon or the app using it
behave. You most likely want to be modifying `./index.js` or app's build file
*/
app.import('bower_components/urijs/src/URI.min.js');
if (!process.env.EMBER_CLI_FASTBOOT) {
app.import('bower_components/socket.io-client/socket.io.js');
}
return app.toTree();
};
| Exclude socket.io client from fast boot build | Exclude socket.io client from fast boot build
| JavaScript | mit | thoov/ember-websockets,thoov/ember-websockets | ---
+++
@@ -15,7 +15,10 @@
*/
app.import('bower_components/urijs/src/URI.min.js');
- app.import('bower_components/socket.io-client/socket.io.js');
+
+ if (!process.env.EMBER_CLI_FASTBOOT) {
+ app.import('bower_components/socket.io-client/socket.io.js');
+ }
return app.toTree();
}; |
8deb21a9fe7e50a9b20557d485656470188f30d4 | src/components/BooksList.js | src/components/BooksList.js | import React, {Component} from 'react'
import { Link } from 'react-router-dom';
import PropTypes from 'prop-types'
import escapeRegExp from 'escape-string-regexp'
import sortBy from 'sort-by'
import Book from './Book'
class BooksOverview extends Component {
static propTypes = {
books: PropTypes.array.isRequired,
shelf: PropTypes.string.isRequired,
title: PropTypes.string.isRequired,
subtitle: PropTypes.string.isRequired,
moveTo: PropTypes.func.isRequired
}
render() {
const { books, shelf, title, subtitle, moveTo } = this.props;
return (
<section className="section">
<div className="container">
<h1 className="title">
{title}
</h1>
<h2 className="subtitle">
{subtitle}
</h2>
<div className="content">
<div className="columns">
{books.map((book) => (
<div key={book.id} className="column is-4">
<Book book={book} moveTo={moveTo}/>
</div>
))}
</div>
</div>
</div>
</section>
)
}
}
export default BooksOverview | import React, {Component} from 'react'
import { Link } from 'react-router-dom';
import PropTypes from 'prop-types'
import escapeRegExp from 'escape-string-regexp'
import sortBy from 'sort-by'
import Book from './Book'
class BooksOverview extends Component {
static propTypes = {
books: PropTypes.array.isRequired,
shelf: PropTypes.string.isRequired,
title: PropTypes.string.isRequired,
subtitle: PropTypes.string.isRequired,
moveTo: PropTypes.func.isRequired
}
render() {
const { books, shelf, title, subtitle, moveTo } = this.props;
return (
<section className="section">
<div className="container">
<h1 className="title">
{title}
</h1>
<h2 className="subtitle">
{subtitle}
</h2>
<div className="content">
<div className="columns is-multiline">
{books.map((book) => (
<div key={book.id} className="column is-4">
<Book book={book} moveTo={moveTo}/>
</div>
))}
</div>
</div>
</div>
</section>
)
}
}
export default BooksOverview | Fix the shelves, which are not displaying all the books | fix: Fix the shelves, which are not displaying all the books
There was a problem displaying more than three books inside a shelf at the same time.
It has been fixed adding a style from the Bulma library.
| JavaScript | mit | miquelarranz/my-books,miquelarranz/my-books | ---
+++
@@ -27,7 +27,7 @@
{subtitle}
</h2>
<div className="content">
- <div className="columns">
+ <div className="columns is-multiline">
{books.map((book) => (
<div key={book.id} className="column is-4">
<Book book={book} moveTo={moveTo}/> |
598be47bf009eb5152dad93a3e19fd6f75d47415 | app/index.js | app/index.js | const {app, BrowserWindow, globalShortcut} = require('electron')
const { resolve } = require('path')
let win = null
app.on('window-all-closed', function () {
if (process.platform !== 'darwin') {
app.quit()
}
})
app.on('ready', function () {
win = new BrowserWindow({width: 640, height: 800})
win.loadURL('file://' + resolve(__dirname, 'renderer/index.html'))
globalShortcut.register('f12', function () {
win.toggleDevTools()
})
win.on('closed', function () {
win = null
})
})
| const {app, BrowserWindow, globalShortcut} = require('electron')
const { resolve } = require('path')
let win = null
app.on('window-all-closed', function () {
if (process.platform !== 'darwin') {
app.quit()
}
})
app.on('ready', function () {
win = new BrowserWindow({width: 640, height: 800, titleBarStyle: 'hidden-inset'})
win.loadURL('file://' + resolve(__dirname, 'renderer/index.html'))
globalShortcut.register('f12', function () {
win.toggleDevTools()
})
win.on('closed', function () {
win = null
})
})
| Remove title bar, but keep 'traffic light buttons'. | Remove title bar, but keep 'traffic light buttons'.
| JavaScript | isc | niklasi/halland-proxy,niklasi/halland-proxy | ---
+++
@@ -10,7 +10,7 @@
})
app.on('ready', function () {
- win = new BrowserWindow({width: 640, height: 800})
+ win = new BrowserWindow({width: 640, height: 800, titleBarStyle: 'hidden-inset'})
win.loadURL('file://' + resolve(__dirname, 'renderer/index.html'))
globalShortcut.register('f12', function () { |
373343c27c280e2e13e78a083779278c419cb49e | kolibri/core/assets/src/state/mappers.js | kolibri/core/assets/src/state/mappers.js | import mapKeys from 'lodash/mapKeys';
import mapValues from 'lodash/mapValues';
import camelCase from 'lodash/camelCase';
import snakeCase from 'lodash/snakeCase';
function ensureTypeSnakeCase(value) {
if (typeof value === 'string') {
return snakeCase(value);
}
return value;
}
function assessmentMetaDataState(data) {
const blankState = {
assessment: false,
assessmentIds: [],
masteryModel: null,
randomize: false,
};
if (typeof data.assessmentmetadata === 'undefined') {
return blankState
}
// Data is from a serializer for a one to many key, so it will return an array of length 0 or 1
const assessmentMetaData = data.assessmentmetadata[0];
if (!assessmentMetaData) {
return blankState;
}
const assessmentIds = assessmentMetaData.assessment_item_ids;
const masteryModel = mapValues(assessmentMetaData.mastery_model, ensureTypeSnakeCase);
if (!assessmentIds.length || !Object.keys(masteryModel).length) {
return blankState;
}
return {
assessment: true,
assessmentIds,
masteryModel,
randomize: assessmentMetaData.randomize,
};
}
function convertKeysToCamelCase(object) {
return mapKeys(object, (value, key) => camelCase(key));
}
function convertKeysToSnakeCase(object) {
return mapKeys(object, (value, key) => snakeCase(key));
}
export { assessmentMetaDataState, convertKeysToCamelCase, convertKeysToSnakeCase };
| import mapKeys from 'lodash/mapKeys';
import mapValues from 'lodash/mapValues';
import camelCase from 'lodash/camelCase';
import snakeCase from 'lodash/snakeCase';
function ensureTypeSnakeCase(value) {
if (typeof value === 'string') {
return snakeCase(value);
}
return value;
}
function assessmentMetaDataState(data) {
const blankState = {
assessment: false,
assessmentIds: [],
masteryModel: null,
randomize: false,
};
if (typeof data.assessmentmetadata === 'undefined') {
return blankState;
}
// Data is from a serializer for a one to many key, so it will return an array of length 0 or 1
const assessmentMetaData = data.assessmentmetadata[0];
if (!assessmentMetaData) {
return blankState;
}
const assessmentIds = assessmentMetaData.assessment_item_ids;
const masteryModel = mapValues(assessmentMetaData.mastery_model, ensureTypeSnakeCase);
if (!assessmentIds.length || !Object.keys(masteryModel).length) {
return blankState;
}
return {
assessment: true,
assessmentIds,
masteryModel,
randomize: assessmentMetaData.randomize,
};
}
function convertKeysToCamelCase(object) {
return mapKeys(object, (value, key) => camelCase(key));
}
function convertKeysToSnakeCase(object) {
return mapKeys(object, (value, key) => snakeCase(key));
}
export { assessmentMetaDataState, convertKeysToCamelCase, convertKeysToSnakeCase };
| Add semicolon to the return statement | Add semicolon to the return statement
| JavaScript | mit | lyw07/kolibri,learningequality/kolibri,DXCanas/kolibri,mrpau/kolibri,indirectlylit/kolibri,learningequality/kolibri,learningequality/kolibri,DXCanas/kolibri,lyw07/kolibri,DXCanas/kolibri,indirectlylit/kolibri,DXCanas/kolibri,lyw07/kolibri,mrpau/kolibri,indirectlylit/kolibri,lyw07/kolibri,mrpau/kolibri,mrpau/kolibri,learningequality/kolibri,indirectlylit/kolibri | ---
+++
@@ -18,7 +18,7 @@
randomize: false,
};
if (typeof data.assessmentmetadata === 'undefined') {
- return blankState
+ return blankState;
}
// Data is from a serializer for a one to many key, so it will return an array of length 0 or 1
const assessmentMetaData = data.assessmentmetadata[0]; |
a6919e1c6eb39b10b165ce75ad9f63a2b48bb746 | rest/admin/waitingrequests.js | rest/admin/waitingrequests.js | 'use strict';
var ctrlFactory = require('restitute').controller;
function listController() {
ctrlFactory.list.call(this, '/rest/admin/waitingrequests');
this.controllerAction = function() {
this.jsonService(this.service('manager/waitingrequests/list'));
};
}
listController.prototype = new ctrlFactory.list();
function getController() {
ctrlFactory.get.call(this, '/rest/admin/waitingrequests/:id');
this.controllerAction = function() {
this.jsonService(this.service('manager/waitingrequests/get'));
};
}
getController.prototype = new ctrlFactory.get();
/**
* Confirm or reject a waiting request instead of a manager
*/
function updateController() {
ctrlFactory.update.call(this, '/rest/admin/waitingrequests/:id');
var controller = this;
this.controllerAction = function() {
controller.jsonService(
controller.service('manager/waitingrequests/save')
);
};
}
updateController.prototype = new ctrlFactory.update();
exports = module.exports = {
list: listController,
get: getController,
update: updateController
};
| Add the admin waiting requests controller | Add the admin waiting requests controller
| JavaScript | mit | gadael/gadael,gadael/gadael | ---
+++
@@ -0,0 +1,48 @@
+'use strict';
+
+var ctrlFactory = require('restitute').controller;
+
+
+
+function listController() {
+ ctrlFactory.list.call(this, '/rest/admin/waitingrequests');
+
+ this.controllerAction = function() {
+ this.jsonService(this.service('manager/waitingrequests/list'));
+ };
+}
+listController.prototype = new ctrlFactory.list();
+
+
+function getController() {
+ ctrlFactory.get.call(this, '/rest/admin/waitingrequests/:id');
+
+ this.controllerAction = function() {
+ this.jsonService(this.service('manager/waitingrequests/get'));
+ };
+}
+getController.prototype = new ctrlFactory.get();
+
+
+/**
+ * Confirm or reject a waiting request instead of a manager
+ */
+function updateController() {
+ ctrlFactory.update.call(this, '/rest/admin/waitingrequests/:id');
+
+ var controller = this;
+ this.controllerAction = function() {
+ controller.jsonService(
+ controller.service('manager/waitingrequests/save')
+ );
+ };
+}
+updateController.prototype = new ctrlFactory.update();
+
+
+
+exports = module.exports = {
+ list: listController,
+ get: getController,
+ update: updateController
+}; | |
a86f49fb6d0f2dcb7b33aabc18f26205763a2e53 | functions/breaches/__main__.js | functions/breaches/__main__.js | const hibp = require('hibp');
/**
* Fetches all breached sites in the system.
*
* @param {string} domain a domain by which to filter the results (default: all
* domains)
* @returns {array} an array of breach objects (an empty array if no breaches
* were found)
*/
module.exports = async domain => hibp.breaches({ domain });
| const hibp = require('hibp');
/**
* Fetches all breached sites in the system.
*
* @param {string} domain a domain by which to filter the results (default: all
* domains)
* @returns {array} an array of breach objects (an empty array if no breaches
* were found)
*/
module.exports = async (domain = '') => hibp.breaches({ domain });
| Fix breaches() default domain value | Fix breaches() default domain value
| JavaScript | mit | wKovacs64/hibp-stdlib | ---
+++
@@ -8,4 +8,4 @@
* @returns {array} an array of breach objects (an empty array if no breaches
* were found)
*/
-module.exports = async domain => hibp.breaches({ domain });
+module.exports = async (domain = '') => hibp.breaches({ domain }); |
22e0ceeabba815d2cf0ea743e7d0f441f2f68fa0 | src/lib/storage-extensions.js | src/lib/storage-extensions.js | Storage.prototype.setObject = function (key, value) {
this.setItem(key, JSON.stringify(value));
};
Storage.prototype.getObject = function (key) {
var value = this.getItem(key);
if (value) {
return JSON.parse(value);
}
return null;
};
Storage.prototype.setBoolean = function (key, value) {
this.setItem(key, !!value);
};
Storage.prototype.getBoolean = function (key) {
return this.getItem(key) == 'true';
};
| (function () {
Storage.namespace = 'shikaku';
var originalGetItem = Storage.prototype.getItem,
originalSetItem = Storage.prototype.setItem;
Storage.prototype.setItem = function (key, value) {
key = this.namespace(key);
return originalSetItem.apply(this, arguments);
};
Storage.prototype.getItem = function (key) {
key = this.namespace(key);
return originalGetItem.apply(this, arguments);
};
Storage.prototype.namespace = function (key) {
return Storage.namespace + ':' + key;
};
Storage.prototype.setObject = function (key, value) {
this.setItem(key, JSON.stringify(value));
};
Storage.prototype.getObject = function (key) {
var value = this.getItem(key);
if (value) {
return JSON.parse(value);
}
return null;
};
Storage.prototype.setBoolean = function (key, value) {
this.setItem(key, !!value);
};
Storage.prototype.getBoolean = function (key) {
return this.getItem(key) == 'true';
};
})();
| Update localStorage to namespace keys | Update localStorage to namespace keys
Rationale for this is that if I host similar games on the same domain,
they have a chance of overwriting each others' data.
| JavaScript | mit | endemic/shikaku-madness-arcadia,endemic/shikaku-madness-arcadia,endemic/shikaku-madness-arcadia,endemic/shikaku-madness-arcadia,endemic/shikaku-madness-arcadia,endemic/shikaku-madness-arcadia,endemic/shikaku-madness-arcadia,endemic/shikaku-madness-arcadia | ---
+++
@@ -1,19 +1,42 @@
-Storage.prototype.setObject = function (key, value) {
- this.setItem(key, JSON.stringify(value));
-};
+(function () {
+ Storage.namespace = 'shikaku';
-Storage.prototype.getObject = function (key) {
- var value = this.getItem(key);
- if (value) {
- return JSON.parse(value);
- }
- return null;
-};
+ var originalGetItem = Storage.prototype.getItem,
+ originalSetItem = Storage.prototype.setItem;
-Storage.prototype.setBoolean = function (key, value) {
- this.setItem(key, !!value);
-};
+ Storage.prototype.setItem = function (key, value) {
+ key = this.namespace(key);
+ return originalSetItem.apply(this, arguments);
+ };
-Storage.prototype.getBoolean = function (key) {
- return this.getItem(key) == 'true';
-};
+ Storage.prototype.getItem = function (key) {
+ key = this.namespace(key);
+ return originalGetItem.apply(this, arguments);
+ };
+
+ Storage.prototype.namespace = function (key) {
+ return Storage.namespace + ':' + key;
+ };
+
+ Storage.prototype.setObject = function (key, value) {
+ this.setItem(key, JSON.stringify(value));
+ };
+
+ Storage.prototype.getObject = function (key) {
+ var value = this.getItem(key);
+
+ if (value) {
+ return JSON.parse(value);
+ }
+
+ return null;
+ };
+
+ Storage.prototype.setBoolean = function (key, value) {
+ this.setItem(key, !!value);
+ };
+
+ Storage.prototype.getBoolean = function (key) {
+ return this.getItem(key) == 'true';
+ };
+})(); |
acd97647fb17309410a2ef4bd7d05abff2b64d61 | gulp-tasks/link-svg.js | gulp-tasks/link-svg.js | (function () {
'use strict';
module.exports = function (gulp, plugins, config) {
return function () {
return plugins.vinylFs.src(config.patternsPath + '/**/*.icons.svg')
.pipe(plugins.plumber({ errorHandler: plugins.notify.onError('Error: <%= error.message %>') }))
.pipe(plugins.vinylFs.symlink(config.templatesPath, { relative: true }));
};
};
})();
| (function () {
'use strict';
module.exports = function (gulp, plugins, config) {
return function () {
return plugins.vinylFs.src(config.patternsPath + '/**/*.icons*.svg')
.pipe(plugins.plumber({ errorHandler: plugins.notify.onError('Error: <%= error.message %>') }))
.pipe(plugins.vinylFs.symlink(config.templatesPath, { relative: true }));
};
};
})();
| Include enterprise icons in build. | build(Gulpfile): Include enterprise icons in build.
| JavaScript | mit | Pier1/rocketbelt,Pier1/rocketbelt | ---
+++
@@ -3,7 +3,7 @@
module.exports = function (gulp, plugins, config) {
return function () {
- return plugins.vinylFs.src(config.patternsPath + '/**/*.icons.svg')
+ return plugins.vinylFs.src(config.patternsPath + '/**/*.icons*.svg')
.pipe(plugins.plumber({ errorHandler: plugins.notify.onError('Error: <%= error.message %>') }))
.pipe(plugins.vinylFs.symlink(config.templatesPath, { relative: true }));
}; |
eb858442b557900d9b1a50d6ad787e8c0d1240e8 | src/app/places/browse/browse.controller.js | src/app/places/browse/browse.controller.js | class BrowseController {
constructor($scope, $uibModalInstance, ImageFactory, text) {
'ngInject';
var imageCount = 60;
$scope.text = text;
$scope.photos = [];
$scope.canShowPhotos = false;
var getImages = function(query) {
ImageFactory.getList(query, imageCount).then(function(result) {
var row = 0;
var photos = [];
var data = result.data;
while (data.length) {
photos[row] = data.splice(0, 12);
row += 1;
}
$scope.photos = photos;
$scope.canShowPhotos = true;
});
};
$scope.select = function(photo) {
$uibModalInstance.close(photo);
};
$scope.cancel = function() {
$uibModalInstance.dismiss('cancel');
};
$scope.search = function() {
$scope.canShowPhotos = false;
getImages($scope.text);
};
$scope.search();
}
}
export default BrowseController;
| class BrowseController {
constructor($scope, $uibModalInstance, ImageFactory, text) {
'ngInject';
var imageCount = 90;
$scope.text = text;
$scope.photos = [];
$scope.canShowPhotos = false;
var getImages = function(query) {
ImageFactory.getList(query, imageCount).then(function(result) {
var row = 0;
var photos = [];
var data = result.data;
while (data.length) {
photos[row] = data.splice(0, 12);
row += 1;
}
$scope.photos = photos;
$scope.canShowPhotos = true;
});
};
$scope.select = function(photo) {
$uibModalInstance.close(photo);
};
$scope.cancel = function() {
$uibModalInstance.dismiss('cancel');
};
$scope.search = function() {
$scope.canShowPhotos = false;
getImages($scope.text);
};
$scope.search();
}
}
export default BrowseController;
| Add more images in search | Add more images in search
| JavaScript | mit | hendryl/Famous-Places-CMS,hendryl/Famous-Places-CMS | ---
+++
@@ -2,7 +2,7 @@
constructor($scope, $uibModalInstance, ImageFactory, text) {
'ngInject';
- var imageCount = 60;
+ var imageCount = 90;
$scope.text = text;
$scope.photos = []; |
1053e0faf38d8d5ac691655424cf21b39669890f | gulppipelines.babel.js | gulppipelines.babel.js | import gulpLoadPlugins from 'gulp-load-plugins';
import pkg from './package.json';
const $ = gulpLoadPlugins();
export default {
'js': () => [
$.sourcemaps.init(),
// Exclude files in `app/nobabel`
$.if(file => !/^nobabel\//.test(file.relative),
$.babel()
),
$.uglify({
mangle: {
except: ['$', 'require', 'exports']
}
}),
$.sourcemaps.write('.')
],
'{sass,scss}': () => [
$.sourcemaps.init(),
$.sass({
precision: 10
}).on('error', $.sass.logError),
$.autoprefixer({browsers: ['last 2 versions']}),
// $.minifyCss(),
$.sourcemaps.write('.')
],
'css': () => [
$.sourcemaps.init(),
$.autoprefixer({browsers: ['last 2 versions']}),
$.minifyCss(),
$.sourcemaps.write('.')
],
'html': () => [
$.replace('{%_!_version_!_%}', pkg.version),
$.minifyInline(),
$.minifyHtml()
],
'{png,jpeg,jpg}': () => [
$.imagemin({
progressive: true,
interlaced: true
})
],
'{webm,mp4}': () => [
// copy is implicit
]
};
| import gulpLoadPlugins from 'gulp-load-plugins';
import pkg from './package.json';
const $ = gulpLoadPlugins();
export default {
'js': () => [
$.sourcemaps.init(),
// Exclude files in `app/nobabel`
$.if(file => !/^nobabel\//.test(file.relative),
$.babel()
),
$.uglify({
mangle: {
except: ['$', 'require', 'exports']
}
}),
$.sourcemaps.write('.')
],
'{sass,scss}': () => [
$.sourcemaps.init(),
$.sass({
precision: 10
}).on('error', $.sass.logError),
$.autoprefixer({browsers: ['last 2 versions']}),
// $.minifyCss(),
$.sourcemaps.write('.')
],
'css': () => [
$.sourcemaps.init(),
$.autoprefixer({browsers: ['last 2 versions']}),
$.minifyCss(),
$.sourcemaps.write('.')
],
'html': () => [
$.replace('{%_!_version_!_%}', pkg.version),
$.minifyInline({js: false}),
$.minifyHtml()
],
'{png,jpeg,jpg}': () => [
$.imagemin({
progressive: true,
interlaced: true
})
],
'{webm,mp4}': () => [
// copy is implicit
]
};
| Disable inline JS minification because AAAARGH | Disable inline JS minification because AAAARGH
| JavaScript | mit | surma/surma.github.io,surma/surma.github.io | ---
+++
@@ -33,7 +33,7 @@
],
'html': () => [
$.replace('{%_!_version_!_%}', pkg.version),
- $.minifyInline(),
+ $.minifyInline({js: false}),
$.minifyHtml()
],
'{png,jpeg,jpg}': () => [ |
f9a07a6b338329fd9881541ea63bdc77ec15756e | states/load.js | states/load.js | /* eslint-env browser */
'use strict';
module.exports = {
preload() {
},
init() {
this.state.load('main');
},
};
| /* eslint-env browser */
'use strict';
module.exports = {
preload() {
},
init() {
this.state.start('main');
},
};
| Use the correct funciton call... | Use the correct funciton call...
| JavaScript | mit | to-the-end/to-the-end,to-the-end/to-the-end | ---
+++
@@ -8,6 +8,6 @@
},
init() {
- this.state.load('main');
+ this.state.start('main');
},
}; |
034088a889f414b12de32b8cd6cf1c096457a80b | main.js | main.js | // Written in jquery
// Makes the "Refresh" button print a new aphorism
// Prints an aphorism as soon as the page is started
$(function(){
$("#output").text("Testing testing");
// Prints new aphorism when Refresh button is clicked
$("#refresh_button").click(function(){
$("#output").text("Refresh succesful!");
});
});
| // Written in jquery
// Makes the "Refresh" button print a new aphorism
// Prints an aphorism as soon as the page is started
$(function(){
$("#output").text("Testing testing");
// Prints new aphorism when Refresh button is clicked
$("#refresh_button").click(function(){
$("#output").text(print_aphorism());
});
var aphorisms = [
"Sin always comes in the open, and available to the senses. It walks on its roots, and need not be torn from the ground.",
"There can be knowledge of evil without believing in it, because there is no more evil than exists anyway.",
"Only here is suffering suffering. Not because those who suffer in this world are to receive anything in the next, but because what in this world is Suffering in another world (unchanged and only freed from its opposite) is bliss.",
"The joys of this life are not its own, but our fear of rising to a higher life; the suffering of this life is not its own, but our self-affliction because of that fear.",
];
function print_aphorism() {
document.getElementById("output").innerHTML = aphorisms[Math.floor(Math.random() * aphorisms.length)]
};
}); | Refresh button pulls random quote | Refresh button pulls random quote
from list of quotes, but purely random (eventually want pseudorandom,
so that quotes aren't repeated too often, or cycling through the list
in some order or something)
| JavaScript | mit | marbiru/kafka,marbiru/kafka | ---
+++
@@ -10,7 +10,18 @@
// Prints new aphorism when Refresh button is clicked
$("#refresh_button").click(function(){
- $("#output").text("Refresh succesful!");
+ $("#output").text(print_aphorism());
});
+var aphorisms = [
+"Sin always comes in the open, and available to the senses. It walks on its roots, and need not be torn from the ground.",
+"There can be knowledge of evil without believing in it, because there is no more evil than exists anyway.",
+"Only here is suffering suffering. Not because those who suffer in this world are to receive anything in the next, but because what in this world is Suffering in another world (unchanged and only freed from its opposite) is bliss.",
+"The joys of this life are not its own, but our fear of rising to a higher life; the suffering of this life is not its own, but our self-affliction because of that fear.",
+];
+
+function print_aphorism() {
+ document.getElementById("output").innerHTML = aphorisms[Math.floor(Math.random() * aphorisms.length)]
+ };
+
}); |
df2db9ee11f2d197c4329b2c8a6e197da1edffd4 | src/browser/extension/background/inject.js | src/browser/extension/background/inject.js | // dev only: async fetch bundle
const arrowURLs = [ 'https://github.com' ];
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
if (changeInfo.status !== 'loading') return;
const matched = arrowURLs.every(url => !!tab.url.match(url));
if (!matched) return;
chrome.tabs.executeScript(tabId, {
code: 'var injected = window.browserReduxInjected; window.browserReduxInjected = true; injected;',
runAt: 'document_start'
}, (result) => {
if (chrome.runtime.lastError || result[0]) return;
fetch('http://localhost:3000/js/inject.bundle.js').then(response => {
return response.text();
}).then(response => {
chrome.tabs.executeScript(tabId, { code: response, runAt: 'document_end' });
});
});
});
| // dev only: async fetch bundle
const arrowURLs = [ 'https://github.com' ];
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
if (changeInfo.status !== 'loading') return;
const matched = arrowURLs.every(url => !!tab.url.match(url));
if (!matched) return;
chrome.tabs.executeScript(tabId, {
code: 'var injected = window.browserReduxInjected; window.browserReduxInjected = true; injected;',
runAt: 'document_start'
}, (result) => {
if (chrome.runtime.lastError || result[0]) return;
fetch('http://localhost:3000/js/inject.bundle.js').then(response => {
return response.text();
}).then(response => {
// Include Redux DevTools extension
const httpRequest = new XMLHttpRequest();
httpRequest.open('GET', 'chrome-extension://lmhkpmbekcpmknklioeibfkpmmfibljd/js/inject.bundle.js');
httpRequest.send();
httpRequest.onreadystatechange = function() {
if (httpRequest.readyState === XMLHttpRequest.DONE && httpRequest.status === 200) {
chrome.tabs.executeScript(tabId, { code: httpRequest.responseText, runAt: 'document_start' });
}
};
chrome.tabs.executeScript(tabId, { code: response, runAt: 'document_end' });
});
});
});
| Include Redux DevTools extension in the content script | Include Redux DevTools extension in the content script
| JavaScript | mit | zalmoxisus/browser-redux,jordanco/drafter-frontend,zalmoxisus/crossbuilder,zalmoxisus/browser-redux,jordanco/drafter-frontend,zalmoxisus/crossbuilder,zalmoxisus/crossbuilder,jordanco/drafter-frontend,zalmoxisus/browser-redux | ---
+++
@@ -15,6 +15,17 @@
fetch('http://localhost:3000/js/inject.bundle.js').then(response => {
return response.text();
}).then(response => {
+
+ // Include Redux DevTools extension
+ const httpRequest = new XMLHttpRequest();
+ httpRequest.open('GET', 'chrome-extension://lmhkpmbekcpmknklioeibfkpmmfibljd/js/inject.bundle.js');
+ httpRequest.send();
+ httpRequest.onreadystatechange = function() {
+ if (httpRequest.readyState === XMLHttpRequest.DONE && httpRequest.status === 200) {
+ chrome.tabs.executeScript(tabId, { code: httpRequest.responseText, runAt: 'document_start' });
+ }
+ };
+
chrome.tabs.executeScript(tabId, { code: response, runAt: 'document_end' });
});
}); |
7eaddddd6549107cd87f9ac6332c6fb88bf9d8f0 | authServer/context.js | authServer/context.js | module.exports = function (req) {
function getParam(paramName) {
if (req.query && typeof req.query[paramName] !== 'undefined')
return req.query[paramName];
else if (req.body && typeof req.body[paramName] !== 'undefined')
return req.body[paramName];
else
return null;
};
function getAccessToken() {
if (!req || !req.headers || !req.headers.authorization)
return null;
var authHeader = req.headers.authorization,
startIndex = authHeader.toLowerCase().indexOf('bearer ');
if (startIndex === -1)
return null;
var bearer = authHeader.substring(startIndex + 7),
spaceIndex = bearer.indexOf(' ');
if (spaceIndex > 0)
bearer = bearer.substring(0, spaceIndex);
return bearer;
};
return req ? {
responseType: getParam('response_type'),
clientId: getParam('client_id'),
clientSecret: getParam('client_secret'),
code: getParam('code'),
grantType: getParam('grant_type'),
state: getParam('state'),
password: getParam('password'),
scope: getParam('scope') ? getParam('scope').split(',') : null,
redirectUri: getParam('redirect_uri'),
accessToken: getAccessToken(),
userName: getParam('username')
} : null;
}; | module.exports = function (req) {
function getParam(paramName) {
if (req.query && typeof req.query[paramName] !== 'undefined')
return req.query[paramName];
else if (req.body && typeof req.body[paramName] !== 'undefined')
return req.body[paramName];
else
return null;
};
function getAccessToken() {
if (getParam('access_token')) return getParam('access_token')
if (!req || !req.headers || !req.headers.authorization)
return null;
var authHeader = req.headers.authorization,
startIndex = authHeader.toLowerCase().indexOf('bearer ');
if (startIndex === -1)
return null;
var bearer = authHeader.substring(startIndex + 7),
spaceIndex = bearer.indexOf(' ');
if (spaceIndex > 0)
bearer = bearer.substring(0, spaceIndex);
return bearer;
};
return req ? {
responseType: getParam('response_type'),
clientId: getParam('client_id'),
clientSecret: getParam('client_secret'),
code: getParam('code'),
grantType: getParam('grant_type'),
state: getParam('state'),
password: getParam('password'),
scope: getParam('scope') ? getParam('scope').split(',') : null,
redirectUri: getParam('redirect_uri'),
accessToken: getAccessToken(),
userName: getParam('username')
} : null;
}; | Check query string for access_token before checking in headers | Check query string for access_token before checking in headers
| JavaScript | mit | MauriceButler/simple-oauth-server,geek/OAuth | ---
+++
@@ -9,6 +9,8 @@
};
function getAccessToken() {
+ if (getParam('access_token')) return getParam('access_token')
+
if (!req || !req.headers || !req.headers.authorization)
return null;
|
395d4fe3632fbbf17de053b7f8244eb47286b8dd | server/database/config.js | server/database/config.js | const dotenv = require('dotenv')
const path = require('path')
dotenv.config({ path: path.join(__dirname, '..', '..', '.env') })
const url = process.env.DATABASE_URL
const dialect = process.env.DATABASE_DIALECT || 'postgres'
module.exports = {
development: {
url,
dialect,
},
staging: {
url,
dialect,
},
production: {
url,
dialect,
},
}
| const dotenv = require('dotenv')
const path = require('path')
dotenv.config({ path: path.join(__dirname, '..', '..', '.env') })
const url = process.env.DATABASE_URL
const dialect = process.env.DATABASE_DIALECT || 'postgres'
const timezone = '+00:00' // UTC
module.exports = {
development: {
url,
dialect,
timezone,
},
staging: {
url,
dialect,
timezone,
},
production: {
url,
dialect,
timezone,
},
}
| Set timezone explicitly to UTC on server-side | Set timezone explicitly to UTC on server-side
| JavaScript | agpl-3.0 | adzialocha/hoffnung3000,adzialocha/hoffnung3000 | ---
+++
@@ -6,17 +6,22 @@
const url = process.env.DATABASE_URL
const dialect = process.env.DATABASE_DIALECT || 'postgres'
+const timezone = '+00:00' // UTC
+
module.exports = {
development: {
url,
dialect,
+ timezone,
},
staging: {
url,
dialect,
+ timezone,
},
production: {
url,
dialect,
+ timezone,
},
} |
701ecaee76273075296bc1b9a5f46e24320b1f3d | chromatography.js | chromatography.js | (function() {
var Color;
chromato = function(x, y, z, m) {
return new Color(x, y, z, m);
};
chromato.color = function(x, y, z, m) {
return new Color(x, y, z, m);
};
chromato.color = function(x, y, z, m) {
return new Color(x, y, z, m);
};
chromato.rgb = function(r, g, b, a) {
return new Color(r, g, b, a, 'rgb');
};
chromato.hex = function(x) {
return new Color(x);
};
chromato.interpolate = function(a, b, f, m) {
if ((a == null) || (b == null)) {
return '#000';
}
if (type(a) === 'string') {
a = new Color(a);
}
if (type(b) === 'string') {
b = new Color(b);
}
return a.interpolate(f, b, m);
};
}).call(this); chromato.mix = chromato.interpolate;
| (function() {
var Color;
chromato = function(x, y, z, m) {
return new Color(x, y, z, m);
};
chromato.color = function(x, y, z, m) {
return new Color(x, y, z, m);
};
chromato.color = function(x, y, z, m) {
return new Color(x, y, z, m);
};
chromato.rgb = function(r, g, b, a) {
return new Color(r, g, b, a, 'rgb');
};
chromato.hex = function(x) {
return new Color(x);
};
chromato.interpolate = function(a, b, f, m) {
if ((a == null) || (b == null)) {
return '#000';
}
if (type(a) === 'string') {
a = new Color(a);
}
if (type(b) === 'string') {
b = new Color(b);
}
return a.interpolate(f, b, m);
};
chromato.mix = chromato.interpolate;
}).call(this);
| Make corrections to placement of 'chromato.mix' | Make corrections to placement of 'chromato.mix'
| JavaScript | mit | WeAreVisualizers/chromatography | ---
+++
@@ -35,4 +35,7 @@
return a.interpolate(f, b, m);
};
-}).call(this); chromato.mix = chromato.interpolate;
+ chromato.mix = chromato.interpolate;
+
+}).call(this);
+ |
d40ebb1e43ba8338db40dc4f8d4e8a8768bf53df | lib/util/changeRank.js | lib/util/changeRank.js | // Includes
var setRank = require('../setRank.js').func;
var getRoles = require('./getRoles.js').func;
var getRankNameInGroup = require('./getRankNameInGroup.js').func;
// Args
exports.required = ['group', 'target', 'change'];
exports.optional = ['jar'];
// Define
exports.func = function (args) {
var group = args.group;
var target = args.target;
var amount = args.change;
var jar = args.jar;
return getRankNameInGroup({group: group, userId: target})
.then(function (rank) {
return getRoles({group: group})
.then(function (roles) {
for (var i = 0; i < roles.length; i++) {
var role = roles[i];
var thisRank = role.Name;
if (thisRank === rank) {
var change = i + amount;
var found = roles[change];
if (!found) {
throw new Error('Rank change is out of range');
}
return setRank({group: group, target: target, roleset: found.ID, jar: jar})
.then(function () {
return {newRole: found, oldRole: role};
});
}
}
});
});
};
| // Includes
var setRank = require('../setRank.js').func;
var getRoles = require('./getRoles.js').func;
var getRankNameInGroup = require('./getRankNameInGroup.js').func;
// Args
exports.required = ['group', 'target', 'change'];
exports.optional = ['jar'];
// Define
exports.func = function (args) {
var group = args.group;
var target = args.target;
var amount = args.change;
var jar = args.jar;
return getRankNameInGroup({group: group, userId: target})
.then(function (rank) {
if (rank === 'Guest') {
throw new Error('Target user is not in group');
}
return getRoles({group: group})
.then(function (roles) {
for (var i = 0; i < roles.length; i++) {
var role = roles[i];
var thisRank = role.Name;
if (thisRank === rank) {
var change = i + amount;
var found = roles[change];
if (!found) {
throw new Error('Rank change is out of range');
}
return setRank({group: group, target: target, roleset: found.ID, jar: jar})
.then(function () {
return {newRole: found, oldRole: role};
});
}
}
});
});
};
| Make sure user is in group | Make sure user is in group
| JavaScript | mit | OnlyTwentyCharacters/roblox-js,sentanos/roblox-js,FroastJ/roblox-js | ---
+++
@@ -15,6 +15,9 @@
var jar = args.jar;
return getRankNameInGroup({group: group, userId: target})
.then(function (rank) {
+ if (rank === 'Guest') {
+ throw new Error('Target user is not in group');
+ }
return getRoles({group: group})
.then(function (roles) {
for (var i = 0; i < roles.length; i++) { |
9197f795b0f1ba66063d617cced30afdecf3a73d | main.js | main.js | #!/usr/bin/env node
'use strict';
let isRoot = require('is-root');
if(isRoot()) {
console.error("I refuse to run as root.");
process.exit(-1);
}
let path = require('path');
let dirName = path.dirname;
let fm = require('front-matter');
let hbs = require('handlebars');
let glob = require('glob');
let registerHelpers = require('./registerHelpers');
let registerPartials = require('./registerPartials');
let registerAllUpwardsOf = require('./registerAllUpwardsOf');
let readFileSync = require('./readFileSync');
let templPath = process.argv[2];
if(!templPath) {
templPath = '/dev/stdin';
}
registerHelpers(glob.sync(__dirname + '/builtin/*.helper.js'));
registerPartials(glob.sync(__dirname + '/builtin/*.partial.hbs'));
registerAllUpwardsOf(dirName(templPath));
let { attributes: templFm, body: templSrc } = fm(readFileSync(templPath));
let templ = hbs.compile(templSrc);
process.stdout.write(templ(templFm));
| #!/usr/bin/env node
'use strict';
let isRoot = require('is-root');
if(isRoot()) {
console.error("I refuse to run as root.");
process.exit(-1);
}
let path = require('path');
let dirName = path.dirname;
let fm = require('front-matter');
let hbs = require('handlebars');
let glob = require('glob');
let registerHelpers = require('./registerHelpers');
let registerPartials = require('./registerPartials');
let registerAllUpwardsOf = require('./registerAllUpwardsOf');
let readFileSync = require('./readFileSync');
let templPath = process.argv[2];
let workDir;
if(!templPath) {
templPath = '/dev/stdin';
workDir = process.cwd();
}
else {
workDir = dirName(templPath);
}
registerHelpers(glob.sync(__dirname + '/builtin/*.helper.js'));
registerPartials(glob.sync(__dirname + '/builtin/*.partial.hbs'));
registerAllUpwardsOf(workDir);
let { attributes: templFm, body: templSrc } = fm(readFileSync(templPath));
process.chdir(workDir);
let templ = hbs.compile(templSrc);
process.stdout.write(templ(templFm));
| Fix bad working directory bug. | Fix bad working directory bug.
| JavaScript | agpl-3.0 | n2liquid/mohawk,n2liquid/mohawk,n2liquid/mohawk | ---
+++
@@ -20,17 +20,24 @@
let readFileSync = require('./readFileSync');
let templPath = process.argv[2];
+let workDir;
if(!templPath) {
templPath = '/dev/stdin';
+ workDir = process.cwd();
+}
+else {
+ workDir = dirName(templPath);
}
registerHelpers(glob.sync(__dirname + '/builtin/*.helper.js'));
registerPartials(glob.sync(__dirname + '/builtin/*.partial.hbs'));
-registerAllUpwardsOf(dirName(templPath));
+registerAllUpwardsOf(workDir);
let { attributes: templFm, body: templSrc } = fm(readFileSync(templPath));
+
+process.chdir(workDir);
let templ = hbs.compile(templSrc);
|
88c5656f5f542a1b1fa6850f70db5972c1be0b50 | lib/credentials/load.js | lib/credentials/load.js | var fs = require('fs');
var q = require('q');
var sysu = require('util');
var resolve = require('./resolve');
function loadCredentials(credentials) {
// Prepare PKCS#12 data if available
var pfxPromise = resolve(credentials.pfx || credentials.pfxData);
// Prepare Certificate data if available.
var certPromise = resolve(credentials.cert || credentials.certData);
// Prepare Key data if available
var keyPromise = resolve(credentials.key || credentials.keyData);
// Prepare Certificate Authority data if available.
var caPromises = [];
if (credentials.ca != null && !sysu.isArray(credentials.ca)) {
credentials.ca = [ credentials.ca ];
}
for(var i in credentials.ca) {
var ca = credentials.ca[i];
caPromises.push(resolve(ca));
}
if (caPromises.length == 0) {
delete caPromises;
}
else {
caPromises = q.all(caPromises);
}
return q.all([pfxPromise, certPromise, keyPromise, caPromises])
.spread(function(pfx, cert, key, ca) {
return { pfx: pfx, cert: cert, key: key, ca: ca };
});
}
module.exports = loadCredentials; | var fs = require('fs');
var q = require('q');
var sysu = require('util');
var resolve = require('./resolve');
function loadCredentials(credentials) {
// Prepare PKCS#12 data if available
var pfxPromise = resolve(credentials.pfx || credentials.pfxData);
// Prepare Certificate data if available.
var certPromise = resolve(credentials.cert || credentials.certData);
// Prepare Key data if available
var keyPromise = resolve(credentials.key || credentials.keyData);
// Prepare Certificate Authority data if available.
var caPromises = [];
if (credentials.ca != null && !sysu.isArray(credentials.ca)) {
credentials.ca = [ credentials.ca ];
}
for(var i in credentials.ca) {
var ca = credentials.ca[i];
caPromises.push(resolve(ca));
}
if (caPromises.length == 0) {
delete caPromises;
}
else {
caPromises = q.all(caPromises);
}
return q.all([pfxPromise, certPromise, keyPromise, caPromises])
.spread(function(pfx, cert, key, ca) {
return { pfx: pfx, cert: cert, key: key, ca: ca, passphrase: credentials.passphrase };
});
}
module.exports = loadCredentials; | Include passphrase for validation and connection | Include passphrase for validation and connection
| JavaScript | mit | F4-Group/node-apn,telerik/node-apn,madshell/node-apn,guoyu07/node-apn,hilllinux/node-apn,tempbottle/node-apn,argon/node-apn,node-apn/node-apn,guytuboul/node-apn,maximeloizeau/node-apn,lopper/node-apn | ---
+++
@@ -33,7 +33,7 @@
return q.all([pfxPromise, certPromise, keyPromise, caPromises])
.spread(function(pfx, cert, key, ca) {
- return { pfx: pfx, cert: cert, key: key, ca: ca };
+ return { pfx: pfx, cert: cert, key: key, ca: ca, passphrase: credentials.passphrase };
});
}
|
dde35a6843115c89a57988014796a817892004aa | lib/index.js | lib/index.js | (function () {
var express = require('express')
, namespace = require('express-namespace')
, Multiplexer = require('./lib/Multiplexer')
, _ = require('lodash')
, debug = require('debug')('signalk-server:index')
, app = this.app = express()
, server = require('http').createServer(app)
;
// config & options
require('./config/config');
module.exports = this.app;
server.listen(app.config.port, function() {
app.server = server;
app.signalk = new Multiplexer;
app.interfaces = [];
if(_.isArray(app.config.settings.interfaces)) {
_.each(app.config.settings.interfaces, function(name) {
debug("Loading interface '" + name + "'");
try {
app.interfaces.push(require(__dirname + '/interfaces/' + name));
} catch(e) {
debug('Interface "' + name + '" doesn\'t exist');
debug(e);
}
});
}
process.nextTick(function () {
require('./providers');
});
});
}).call(global); | (function () {
var express = require('express')
, namespace = require('express-namespace')
, Multiplexer = require('./lib/Multiplexer')
, _ = require('lodash')
, debug = require('debug')('signalk-server:index')
, app = this.app = express()
, server = require('http').createServer(app)
;
// config & options
require('./config/config');
module.exports = this.app;
app.server = server;
app.signalk = new Multiplexer;
app.interfaces = [];
debug("Interfaces:" + JSON.stringify(app.config.settings.interfaces));
if(_.isArray(app.config.settings.interfaces)) {
_.each(app.config.settings.interfaces, function(name) {
debug("Loading interface '" + name + "'");
try {
app.interfaces.push(require(__dirname + '/interfaces/' + name));
} catch(e) {
debug('Interface "' + name + '" doesn\'t exist');
debug(e);
}
});
}
process.nextTick(function () {
require('./providers');
});
server.listen(app.config.port);
}).call(global); | Fix Primus ws access by first registering interfaces and then starting http server with listen | Fix Primus ws access by first registering interfaces and then starting http server with listen
| JavaScript | apache-2.0 | sbender9/signalk-server-node,sbender9/signalk-server-node,jaittola/signalk-server-node,lsoltero/signalk-server-node,mauroc/signalk-oauth-node,jaittola/signalk-server-node,SignalK/signalk-server-node,lsoltero/signalk-server-node,webmasterkai/signalk-server-node,mauroc/signalk-oauth-node,webmasterkai/signalk-server-node,jaittola/signalk-server-node,sbender9/signalk-server-node,SignalK/signalk-server-node,SignalK/signalk-server-node,mauroc/signalk-oauth-node,SignalK/signalk-server-node,webmasterkai/signalk-server-node | ---
+++
@@ -14,26 +14,26 @@
module.exports = this.app;
- server.listen(app.config.port, function() {
- app.server = server;
- app.signalk = new Multiplexer;
- app.interfaces = [];
+ app.server = server;
+ app.signalk = new Multiplexer;
+ app.interfaces = [];
- if(_.isArray(app.config.settings.interfaces)) {
- _.each(app.config.settings.interfaces, function(name) {
- debug("Loading interface '" + name + "'");
+ debug("Interfaces:" + JSON.stringify(app.config.settings.interfaces));
+ if(_.isArray(app.config.settings.interfaces)) {
+ _.each(app.config.settings.interfaces, function(name) {
+ debug("Loading interface '" + name + "'");
- try {
- app.interfaces.push(require(__dirname + '/interfaces/' + name));
- } catch(e) {
- debug('Interface "' + name + '" doesn\'t exist');
- debug(e);
- }
- });
- }
+ try {
+ app.interfaces.push(require(__dirname + '/interfaces/' + name));
+ } catch(e) {
+ debug('Interface "' + name + '" doesn\'t exist');
+ debug(e);
+ }
+ });
+ }
- process.nextTick(function () {
- require('./providers');
- });
+ process.nextTick(function () {
+ require('./providers');
});
+ server.listen(app.config.port);
}).call(global); |
11212d00fdd99ad178024506e6752b190c5de0a7 | fsjs.js | fsjs.js | var path = require('path')
, http = require('http')
exports = function(port){
http.createServer(require.main.exports.get).listen(port)
}
| var http = require('http')
, path = require('path')
, fs = require('fs')
, modules = {}
, reRequire = function(event,filename){
var ext = path.extname(filename)
, name = path.basename(filename,ext)
modules[name] = require(filename)
}
, watchAll = function(dir,callback){
fs.watch(dir,rerequire)
callback()
}
, router = function(req,res){
require.main.exports.get()
}
exports = function(port){
watchAll(path.dirname(require.main.filename),function(){
http.createServer(router).listen(port)
})
}
| Watch current application's entry point directory | Watch current application's entry point directory | JavaScript | mit | arpith/fsjs | ---
+++
@@ -1,5 +1,21 @@
-var path = require('path')
-, http = require('http')
+var http = require('http')
+, path = require('path')
+, fs = require('fs')
+, modules = {}
+, reRequire = function(event,filename){
+ var ext = path.extname(filename)
+ , name = path.basename(filename,ext)
+ modules[name] = require(filename)
+}
+, watchAll = function(dir,callback){
+ fs.watch(dir,rerequire)
+ callback()
+}
+, router = function(req,res){
+ require.main.exports.get()
+}
exports = function(port){
- http.createServer(require.main.exports.get).listen(port)
+ watchAll(path.dirname(require.main.filename),function(){
+ http.createServer(router).listen(port)
+ })
} |
8080fc0a3db3a7a276a74a59dbf7925d8eb5a9de | init.js | init.js | Hooks.addMenuItem("Actions/Drupal/Coder Review", "", function () {
Alert.show("Drupal!");
}); | // Clear Drupal Caches.
Hooks.addMenuItem("Actions/Drupal/Clear Drupal caches", "opt-cmd-x", function() {
var exec = require('child_process').exec;
var path = require('path');
var dirPath = path.dirname(Document.current().path());
exec('cd ' + dirPath + ' && drush cc all', function (err, stdout, stderr) {
if (err) {
Alert.show('Error: ' + err);
return false;
}
else if (stderr.indexOf("'all' cache was cleared.") == -1) {
Alert.show('Drush failed to clear all caches.');
return false;
}
else {
Alert.notify({
title: "Drupal caches cleared!",
body: dirpath,
});
};
});
});
// Coder Review.
Hooks.addMenuItem("Actions/Drupal/Coder Review", "opt-cmd-r", function () {
var exec = require('child_process').exec;
var path = require('path');
var dirPath = path.dirname(Document.current().path());
exec('cd ' + dirPath + ' && drush coder --no-empty --minor --comment --i18n --security --sql --style --druplart --sniffer --ignorename', function (err, stdout, stderr) {
if (err) {
Alert.show('Error: ' + err);
return false;
}
else {
Alert.notify({
title: "Drupal caches cleared!",
});
};
});
});
| Clear Drupal caches is sort of working, but need to figure out if $PATH is available in the environment | Clear Drupal caches is sort of working, but need to figure out if $PATH is available in the environment
| JavaScript | mit | shrop/drupal.chocmixin | ---
+++
@@ -1,3 +1,43 @@
-Hooks.addMenuItem("Actions/Drupal/Coder Review", "", function () {
- Alert.show("Drupal!");
+// Clear Drupal Caches.
+Hooks.addMenuItem("Actions/Drupal/Clear Drupal caches", "opt-cmd-x", function() {
+ var exec = require('child_process').exec;
+ var path = require('path');
+ var dirPath = path.dirname(Document.current().path());
+
+ exec('cd ' + dirPath + ' && drush cc all', function (err, stdout, stderr) {
+ if (err) {
+ Alert.show('Error: ' + err);
+ return false;
+ }
+ else if (stderr.indexOf("'all' cache was cleared.") == -1) {
+ Alert.show('Drush failed to clear all caches.');
+ return false;
+ }
+ else {
+ Alert.notify({
+ title: "Drupal caches cleared!",
+ body: dirpath,
+ });
+ };
+ });
});
+
+// Coder Review.
+Hooks.addMenuItem("Actions/Drupal/Coder Review", "opt-cmd-r", function () {
+ var exec = require('child_process').exec;
+ var path = require('path');
+ var dirPath = path.dirname(Document.current().path());
+
+ exec('cd ' + dirPath + ' && drush coder --no-empty --minor --comment --i18n --security --sql --style --druplart --sniffer --ignorename', function (err, stdout, stderr) {
+ if (err) {
+ Alert.show('Error: ' + err);
+ return false;
+ }
+ else {
+ Alert.notify({
+ title: "Drupal caches cleared!",
+ });
+ };
+ });
+
+}); |
de3f66469f6cb68bf742f8a1f96d0cc7deb0a0aa | src/js/components/PoemEditor.js | src/js/components/PoemEditor.js | import React from 'react'
import SimpleMDE from 'react-simplemde-editor'
const PoemEditor = (props) => {
const extraKeys = {
// 'Ctrl-Enter': () => { props.handleEditorSubmit() },
'Cmd-Enter': () => { props.handleEditorSubmit() },
}
return (
<div>
<SimpleMDE
onChange={props.handleEditorChange}
value={props.value}
extraKeys={extraKeys}
options={{
autofocus: false,
spellChecker: false,
indentWithTabs: false,
status: false,
toolbar: false,
}}
/>
<button onClick={props.handleEditorSubmit}>post</button>
</div>
)
}
export default PoemEditor
| import React from 'react'
import SimpleMDE from 'react-simplemde-editor'
const PoemEditor = (props) => {
const extraKeys = {
// 'Ctrl-Enter': () => { props.handleEditorSubmit() },
'Cmd-Enter': () => { props.handleEditorSubmit() },
}
return (
<div>
<SimpleMDE
onChange={props.handleEditorChange}
value={props.value}
options={{
autofocus: false,
spellChecker: false,
indentWithTabs: false,
status: false,
toolbar: false,
}}
addKeyMaps={extraKeys}
/>
<button onClick={props.handleEditorSubmit}>post</button>
</div>
)
}
export default PoemEditor
| Change option from extraKeys to addKeyMaps | Change option from extraKeys to addKeyMaps
| JavaScript | mit | tanaka0325/manday_web,tanaka0325/manday_web | ---
+++
@@ -12,7 +12,6 @@
<SimpleMDE
onChange={props.handleEditorChange}
value={props.value}
- extraKeys={extraKeys}
options={{
autofocus: false,
spellChecker: false,
@@ -20,6 +19,7 @@
status: false,
toolbar: false,
}}
+ addKeyMaps={extraKeys}
/>
<button onClick={props.handleEditorSubmit}>post</button>
</div> |
898a49ef9f184ce94f084f1dd060ae65b6685691 | app/assets/scripts/components/bar-chart.js | app/assets/scripts/components/bar-chart.js | import React from 'react';
import PropTypes from 'prop-types';
import { Bar } from 'react-chartjs-2';
import { round } from '../utils/format';
export default function BarChart({ data, yAxisLabel, xAxisLabels }) {
const series = {
labels: xAxisLabels,
datasets: [
{
label: yAxisLabel,
data: data.map(d => round(d)),
backgroundColor: '#198CFF',
},
],
};
const options = {
defaultFontFamily:
"'Roboto', 'Helvetica Neue', Helvetica, Arial, sans-serif",
legend: {
display: false,
},
tooltips: {
intersect: false,
},
scales: {
yAxes: [
{
ticks: {
beginAtZero: true,
maxTicksLimit: 5,
fontSize: 14,
},
scaleLabel: {
display: true,
labelString: yAxisLabel,
fontSize: 14,
},
},
],
xAxes: [
{
ticks: {
fontSize: 14,
},
gridLines: { display: false },
scaleLabel: {
display: true,
labelString: 'Date',
fontSize: 14,
},
},
],
},
};
return <Bar data={series} options={options} />;
}
BarChart.propTypes = {
data: PropTypes.arrayOf(PropTypes.number).isRequired,
yAxisLabel: PropTypes.string.isRequired,
xAxisLabels: PropTypes.arrayOf(PropTypes.string).isRequired,
};
| import React from 'react';
import PropTypes from 'prop-types';
import { Bar } from 'react-chartjs-2';
import { round } from '../utils/format';
export default function BarChart({ data, yAxisLabel, xAxisLabels }) {
const series = {
labels: xAxisLabels,
datasets: [
{
label: yAxisLabel,
data: data.map(d => round(d)),
backgroundColor: '#198CFF',
},
],
};
const options = {
defaultFontFamily:
"'Roboto', 'Helvetica Neue', Helvetica, Arial, sans-serif",
legend: {
display: false,
},
tooltips: {
intersect: false,
},
scales: {
yAxes: [
{
ticks: {
beginAtZero: true,
maxTicksLimit: 5,
fontSize: 14,
},
scaleLabel: {
display: true,
labelString: yAxisLabel,
fontSize: 14,
},
},
],
xAxes: [
{
ticks: {
fontSize: 14,
},
gridLines: { display: false },
scaleLabel: {
display: true,
fontSize: 14,
},
},
],
},
};
return <Bar data={series} options={options} />;
}
BarChart.propTypes = {
data: PropTypes.arrayOf(PropTypes.number).isRequired,
yAxisLabel: PropTypes.string.isRequired,
xAxisLabels: PropTypes.arrayOf(PropTypes.string).isRequired,
};
| Remove additional label from x axis | Remove additional label from x axis
| JavaScript | bsd-3-clause | openaq/openaq.org,openaq/openaq.org,openaq/openaq.org | ---
+++
@@ -48,7 +48,6 @@
gridLines: { display: false },
scaleLabel: {
display: true,
- labelString: 'Date',
fontSize: 14,
},
}, |
3def618a5cf5607a9bbe95cb1d349de83224565c | javascript/editlock.js | javascript/editlock.js | jQuery.entwine("editlock", function($) {
$('.cms-edit-form').entwine({
RecordID: null,
RecordClass: null,
LockURL: null,
onmatch: function() {
if(this.hasClass('edit-locked')){
this.showLockMessage();
}else{
this.setRecordID(this.data('recordid'));
this.setRecordClass(this.data('recordclass'));
this.setLockURL(this.data('lockurl'));
this.lockRecord();
}
},
lockRecord: function() {
if(!this.getRecordID() || !this.getRecordClass() || !this.getLockURL()){
return false;
}
var data = {
RecordID: this.getRecordID(),
RecordClass: this.getRecordClass()
};
$.post(this.getLockURL(), data).done(function(result){
setTimeout(function(){$('.cms-edit-form').lockRecord()},10000);
});
},
showLockMessage: function(){
this.find('p.message').first().after('<p/>')
.addClass('message warning')
.css('overflow', 'hidden')
.html(this.data('lockedmessage'))
.show();
}
});
});
| jQuery.entwine("editlock", function($) {
var lockTimer = 0;
$('.cms-edit-form').entwine({
RecordID: null,
RecordClass: null,
LockURL: null,
onmatch: function() {
// clear any previously bound lock timer
if (lockTimer) {
clearTimeout(lockTimer);
}
if(this.hasClass('edit-locked')){
this.showLockMessage();
}else{
this.setRecordID(this.data('recordid'));
this.setRecordClass(this.data('recordclass'));
this.setLockURL(this.data('lockurl'));
this.lockRecord();
}
},
lockRecord: function() {
if(!this.getRecordID() || !this.getRecordClass() || !this.getLockURL()){
return false;
}
var data = {
RecordID: this.getRecordID(),
RecordClass: this.getRecordClass()
};
$.post(this.getLockURL(), data).done(function(result){
lockTimer = setTimeout(function(){$('.cms-edit-form').lockRecord()},10000);
});
},
showLockMessage: function(){
this.find('p.message').first().after('<p/>')
.addClass('message warning')
.css('overflow', 'hidden')
.html(this.data('lockedmessage'))
.show();
}
});
});
| FIX Removal of existing lock timer on form load | FIX Removal of existing lock timer on form load | JavaScript | bsd-3-clause | sheadawson/silverstripe-editlock,sheadawson/silverstripe-editlock | ---
+++
@@ -1,10 +1,15 @@
jQuery.entwine("editlock", function($) {
-
+ var lockTimer = 0;
$('.cms-edit-form').entwine({
RecordID: null,
RecordClass: null,
LockURL: null,
onmatch: function() {
+ // clear any previously bound lock timer
+ if (lockTimer) {
+ clearTimeout(lockTimer);
+ }
+
if(this.hasClass('edit-locked')){
this.showLockMessage();
}else{
@@ -14,19 +19,19 @@
this.lockRecord();
}
},
-
+
lockRecord: function() {
if(!this.getRecordID() || !this.getRecordClass() || !this.getLockURL()){
return false;
}
-
+
var data = {
RecordID: this.getRecordID(),
RecordClass: this.getRecordClass()
};
$.post(this.getLockURL(), data).done(function(result){
- setTimeout(function(){$('.cms-edit-form').lockRecord()},10000);
+ lockTimer = setTimeout(function(){$('.cms-edit-form').lockRecord()},10000);
});
},
|
2463c4353cd46f12d4caaf44840d009779834dd0 | spec/random-tip-panel-spec.js | spec/random-tip-panel-spec.js | 'use babel'
import RandomTipPanel from '../lib/random-tip-panel'
describe('RandomTipPanel', () => {
let panel = null
beforeEach(() => {
panel = new RandomTipPanel('user-support-helper-test')
panel.add('foo', 'bar')
})
describe('when showForcedly is called', () => {
it('shows the panel.', () => {
panel.showForcedly()
expect(panel.panel.isVisible()).toBe(true)
})
})
describe('when the show-tips configuration is false', () => {
it('does not show the panel.', () => {
const currentValue = atom.config.get('user-support-helper-test.show-tips')
atom.config.set('user-support-helper-test.show-tips', true)
panel.show()
expect(panel.panel.isVisible()).not.toBe(true)
if (currentValue) {
atom.config.set('user-support-helper-test.show-tips', currentValue)
} else {
atom.conig.removeKeyPath('user-support-helper-test.show-tips')
}
})
})
})
| 'use babel'
import RandomTipPanel from '../lib/random-tip-panel'
describe('RandomTipPanel', () => {
let panel = null
beforeEach(() => {
panel = new RandomTipPanel('user-support-helper-test')
panel.add('foo', 'bar')
})
describe('when showForcedly is called', () => {
it('shows the panel.', () => {
panel.showForcedly()
expect(panel.panel.isVisible()).toBe(true)
})
})
describe('when the show-tips configuration is false', () => {
it('does not show the panel.', () => {
const currentValue = atom.config.get('user-support-helper-test.show-tips')
atom.config.set('user-support-helper-test.show-tips', true)
panel.show()
expect(panel.panel.isVisible()).not.toBe(true)
if (currentValue) {
atom.config.set('user-support-helper-test.show-tips', currentValue)
} else {
atom.config.unset('user-support-helper-test.show-tips')
}
})
})
})
| Fix the typo in the test case | Fix the typo in the test case
ref #34
| JavaScript | mit | HiroakiMikami/atom-user-support-helper | ---
+++
@@ -28,7 +28,7 @@
if (currentValue) {
atom.config.set('user-support-helper-test.show-tips', currentValue)
} else {
- atom.conig.removeKeyPath('user-support-helper-test.show-tips')
+ atom.config.unset('user-support-helper-test.show-tips')
}
})
}) |
78a8cdc9ce29c878b40de9937ed1b56010fb2179 | server/adNotifications.js | server/adNotifications.js | module.exports = function init(params) {
const emails = params.emails;
const knex = params.knex;
const util = params.util;
const service = require('./services/adNotifications')({ knex, util });
function testSending(req, res, next) {
service.notificationObjects()
.then(objects => res.json(objects))
}
return {
testSending
};
}
| module.exports = function init(params) {
const emails = params.emails;
const knex = params.knex;
const util = params.util;
const service = require('./services/adNotifications')({ knex, util });
function testSending(req, res, next) {
service.notificationObjects()
.then(notifications => {
const promises = notifications.map(notification => {
const user = notification.user;
const notificationRows = notification.ads.map(ad => ({
ad_id: ad.id,
user_id: user.id
}))
return knex('user_ad_notifications').insert(notificationRows)
.then(() => notifications)
});
return Promise.all(promises);
})
.then(objects => res.json(objects))
}
return {
testSending
};
}
| Save in DB send status | Save in DB send status
| JavaScript | agpl-3.0 | Tradenomiliitto/tradenomiitti,Tradenomiliitto/tradenomiitti,Tradenomiliitto/tradenomiitti | ---
+++
@@ -6,6 +6,18 @@
function testSending(req, res, next) {
service.notificationObjects()
+ .then(notifications => {
+ const promises = notifications.map(notification => {
+ const user = notification.user;
+ const notificationRows = notification.ads.map(ad => ({
+ ad_id: ad.id,
+ user_id: user.id
+ }))
+ return knex('user_ad_notifications').insert(notificationRows)
+ .then(() => notifications)
+ });
+ return Promise.all(promises);
+ })
.then(objects => res.json(objects))
}
|
8556cc0c4efbbaef3bed161e02091fc3b8311ca9 | gulpfile.babel.js | gulpfile.babel.js | import gulp from 'gulp';
import append from 'gulp-add-src';
import babel from 'gulp-babel';
import mocha from 'gulp-mocha';
import del from 'del';
import runSequence from 'run-sequence';
var config = {
paths: {
js: {
src: 'src/**/*.js',
dist: 'dist/'
}
}
};
gulp.task('clean', () => {
del(config.paths.js.dist);
});
gulp.task('babel', () => {
gulp.src(config.paths.js.src)
.pipe(babel())
.pipe(append('src/resources.json'))
.pipe(gulp.dest(config.paths.js.dist));
});
gulp.task('watch', () => {
gulp.watch(config.paths.js.src, ['babel']);
});
gulp.task('default', () => {
runSequence('clean', ['babel']);
});
| import gulp from 'gulp';
import append from 'gulp-add-src';
import babel from 'gulp-babel';
import mocha from 'gulp-mocha';
import del from 'del';
import runSequence from 'run-sequence';
var config = {
paths: {
js: {
src: 'src/**/*.js',
dist: 'dist/'
}
}
};
gulp.task('clean', () => del(config.paths.js.dist));
gulp.task('babel', () => {
gulp.src(config.paths.js.src)
.pipe(babel())
.pipe(append('src/resources.json'))
.pipe(gulp.dest(config.paths.js.dist));
});
gulp.task('watch', () => {
gulp.watch(config.paths.js.src, ['babel']);
});
gulp.task('default', () => {
runSequence('clean', ['babel']);
});
| Make sure clean happens synchronhously | Make sure clean happens synchronhously
| JavaScript | mit | classy-org/classy-node | ---
+++
@@ -14,9 +14,7 @@
}
};
-gulp.task('clean', () => {
- del(config.paths.js.dist);
-});
+gulp.task('clean', () => del(config.paths.js.dist));
gulp.task('babel', () => {
gulp.src(config.paths.js.src) |
6697a07cf628d048203328829b14f8249f3c29c0 | js/Actors.js | js/Actors.js | /*
* This class represents actors in the game
*/
'use strict';
import Ball from 'Ball.js';
const actorsDefinitions = {
ball: {
xVelocity: 0,
yVelocity: 0,
radius: 10
}
};
export default class {
constructor(canvasWidth, canvasHeight) {
this._actorRefs = [];
this._actors = [];
// Initializing ball
let bX = canvasWidth / 2;
let bY = canvasHeight - 25;
let ball = actorsDefinitions.ball
this.addActor(new Ball(bX, bY, ball.xVelocity, ball.yVelocity, ball.radius));
}
getVisibleActors() {
return this._actors.filter((a)=> a.visible) || [];
}
addActor(actor) {
this._actorRefs.push(actor);
this._actors.push(actor.getAnatomy());
}
}
| /*
* This class represents actors in the game
*/
'use strict';
import Ball from 'Ball.js';
const actorsDefinitions = {
ball: {
xVelocity: 0,
yVelocity: 0,
radius: 10
}
};
export default class {
constructor(canvasWidth, canvasHeight) {
this._actorRefs = [];
// Initializing ball
let bX = canvasWidth / 2;
let bY = canvasHeight - 25;
let ball = actorsDefinitions.ball
this.addActor(new Ball(bX, bY, ball.xVelocity, ball.yVelocity, ball.radius));
}
getActors() {
return this._actorRefs.map((e)=> { return e.getAnatomy(); });
}
moveActors() {
this._actorRefs.forEach((e)=> e.move());
}
addActor(actor) {
this._actorRefs.push(actor);
}
}
| Remove _actors variable and stick with _actorRefs | Remove _actors variable and stick with _actorRefs
| JavaScript | mit | BAJ-/robot-breakout,BAJ-/robot-breakout | ---
+++
@@ -15,7 +15,6 @@
export default class {
constructor(canvasWidth, canvasHeight) {
this._actorRefs = [];
- this._actors = [];
// Initializing ball
let bX = canvasWidth / 2;
@@ -24,12 +23,15 @@
this.addActor(new Ball(bX, bY, ball.xVelocity, ball.yVelocity, ball.radius));
}
- getVisibleActors() {
- return this._actors.filter((a)=> a.visible) || [];
+ getActors() {
+ return this._actorRefs.map((e)=> { return e.getAnatomy(); });
+ }
+
+ moveActors() {
+ this._actorRefs.forEach((e)=> e.move());
}
addActor(actor) {
this._actorRefs.push(actor);
- this._actors.push(actor.getAnatomy());
}
} |
e08ebf35824281c6362107bf597acf06c1043421 | babel.js | babel.js | module.exports = {
"extends": "./",
"parser": "babel-eslint",
"env": {
"es6": true
},
"rules": {
// Override to warn about unnecessary Use Strict Directives
"strict": [1, "never"],
/**
* ECMAScript 6
* These rules are only relevant to ES6 environments and are off by default.
*/
// verify super() callings in constructors (off by default)
"constructor-super": 2,
// enforce the spacing around the * in generator functions (off by default)
"generator-star-spacing": [2, { "before": true, "after": false }],
// disallow to use this/super before super() calling in constructors. (off by default)
"no-this-before-super": 2,
// require let or const instead of var (off by default)
"no-var": 1,
// require method and property shorthand syntax for object literals (off by default)
"object-shorthand": [1, "always"],
// suggest using of const declaration for variables that are never modified after declared (off by default)
"prefer-const": 1
}
};
| module.exports = {
"extends": "./",
"parser": "babel-eslint",
"env": {
"es6": true
},
"rules": {
// Override to warn about unnecessary Use Strict Directives
"strict": [1, "never"],
/**
* ECMAScript 6
* These rules are only relevant to ES6 environments and are off by default.
*/
// require parens in arrow function arguments
"arrow-parens": 0,
// verify super() callings in constructors (off by default)
"constructor-super": 2,
// enforce the spacing around the * in generator functions (off by default)
"generator-star-spacing": [2, { "before": true, "after": false }],
// disallow to use this/super before super() calling in constructors. (off by default)
"no-this-before-super": 2,
// require let or const instead of var (off by default)
"no-var": 1,
// require method and property shorthand syntax for object literals (off by default)
"object-shorthand": [1, "always"],
// suggest using of const declaration for variables that are never modified after declared (off by default)
"prefer-const": 1
}
};
| Add the arrow-parens rule as disabled | Add the arrow-parens rule as disabled
| JavaScript | mit | Springworks/eslint-config-springworks | ---
+++
@@ -16,6 +16,9 @@
* ECMAScript 6
* These rules are only relevant to ES6 environments and are off by default.
*/
+
+ // require parens in arrow function arguments
+ "arrow-parens": 0,
// verify super() callings in constructors (off by default)
"constructor-super": 2, |
7df5fc20ce6cb8d7c7b27d8ecb723ef6ce7c02c4 | demo/src/organisms/Items.js | demo/src/organisms/Items.js | import makeOrganism from '../../../src'
import * as loadItemsState from '../state/placeholderAPI'
import Items from '../components/Items'
// export default makeOrganism(Items, loadItemsState)
const baseURL = 'https://jsonplaceholder.typicode.com'
const fetchAPI = (path) => fetch(baseURL + path).then(r => r.json())
export default makeOrganism(Items, {
initial: () => ({ items: null }),
load: async ({ path }, prevProps, { handlers }) => {
if (!prevProps || path !== prevProps.path) {
handlers.initial()
return { items: await fetchAPI(path) }
}
}
})
| import makeOrganism from '../../../src'
import * as loadItemsState from '../state/placeholderAPI'
import Items from '../components/Items'
// export default makeOrganism(Items, loadItemsState)
const baseURL = 'https://jsonplaceholder.typicode.com'
const fetchAPI = (path) => fetch(baseURL + path).then(r => r.json())
export default makeOrganism(Items, {
initial: () => ({ items: null }),
load: async ({ path }, prevProps) => {
if (!prevProps || path !== prevProps.path) {
return { items: await fetchAPI(path) }
}
}
})
| Fix issue with example expecting other handlers to be passed to load handler | Fix issue with example expecting other handlers to be passed to load handler
| JavaScript | mit | RoyalIcing/react-organism | ---
+++
@@ -10,9 +10,8 @@
export default makeOrganism(Items, {
initial: () => ({ items: null }),
- load: async ({ path }, prevProps, { handlers }) => {
+ load: async ({ path }, prevProps) => {
if (!prevProps || path !== prevProps.path) {
- handlers.initial()
return { items: await fetchAPI(path) }
}
} |
5d85c4b3198ecadbdaa5ae1941de34b771463e2a | src/mobile/AwakeInDevApp.js | src/mobile/AwakeInDevApp.js | import Expo from 'expo';
import React from 'react';
import PropTypes from 'prop-types';
import { View } from 'react-native';
// we don't want this to require transformation
class AwakeInDevApp extends React.Component {
static propTypes = {
exp: PropTypes.object
};
state = {
isReady: false
};
async componentWillMount() {
await Expo.Font.loadAsync({
Roboto: require('native-base/Fonts/Roboto.ttf'),
Roboto_medium: require('native-base/Fonts/Roboto_medium.ttf'),
Ionicons: require('@expo/vector-icons/fonts/Ionicons.ttf')
});
this.setState({ isReady: true });
}
render() {
if (!this.state.isReady) {
return <Expo.AppLoading />;
}
const App = require('./App');
return React.createElement(
View,
{
style: {
flex: 1
}
},
React.createElement(App, { expUri: this.props.exp ? this.props.exp.initialUri : null }),
React.createElement(process.env.NODE_ENV === 'development' ? Expo.KeepAwake : View)
);
}
}
Expo.registerRootComponent(AwakeInDevApp);
| import Expo from 'expo';
import React from 'react';
import PropTypes from 'prop-types';
import { View } from 'react-native';
import App from './App';
// we don't want this to require transformation
class AwakeInDevApp extends React.Component {
static propTypes = {
exp: PropTypes.object
};
state = {
isReady: false
};
async componentWillMount() {
await Expo.Font.loadAsync({
Roboto: require('native-base/Fonts/Roboto.ttf'),
Roboto_medium: require('native-base/Fonts/Roboto_medium.ttf'),
Ionicons: require('@expo/vector-icons/fonts/Ionicons.ttf')
});
this.setState({ isReady: true });
}
render() {
if (!this.state.isReady) {
return <Expo.AppLoading />;
}
return React.createElement(
View,
{
style: {
flex: 1
}
},
React.createElement(App, { expUri: this.props.exp ? this.props.exp.initialUri : null }),
React.createElement(process.env.NODE_ENV === 'development' ? Expo.KeepAwake : View)
);
}
}
Expo.registerRootComponent(AwakeInDevApp);
| Fix root component on mobile platform | Fix root component on mobile platform
| JavaScript | mit | sysgears/apollo-universal-starter-kit,sysgears/apollo-universal-starter-kit,sysgears/apollo-fullstack-starter-kit,sysgears/apollo-universal-starter-kit,sysgears/apollo-universal-starter-kit | ---
+++
@@ -2,6 +2,7 @@
import React from 'react';
import PropTypes from 'prop-types';
import { View } from 'react-native';
+import App from './App';
// we don't want this to require transformation
class AwakeInDevApp extends React.Component {
@@ -27,7 +28,6 @@
return <Expo.AppLoading />;
}
- const App = require('./App');
return React.createElement(
View,
{ |
79477e68eff4eff0bf1924ba9a586df58fde935d | config/environment.js | config/environment.js | /* jshint node: true */
module.exports = function(environment) {
var ENV = {
modulePrefix: 'smallprint',
environment: environment,
baseURL: '/',
locationType: 'auto',
EmberENV: {
FEATURES: {
// Here you can enable experimental features on an ember canary build
// e.g. 'with-controller': true
}
},
APP: {
// Here you can pass flags/options to your application instance
// when it is created
}
};
if (environment === 'development') {
// ENV.APP.LOG_RESOLVER = true;
// ENV.APP.LOG_ACTIVE_GENERATION = true;
// ENV.APP.LOG_TRANSITIONS = true;
// ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
// ENV.APP.LOG_VIEW_LOOKUPS = true;
}
if (environment === 'test') {
// Testem prefers this...
ENV.baseURL = '/';
ENV.locationType = 'none';
// keep test console output quieter
ENV.APP.LOG_ACTIVE_GENERATION = false;
ENV.APP.LOG_VIEW_LOOKUPS = false;
ENV.APP.rootElement = '#ember-testing';
}
if (environment === 'production') {
}
return ENV;
};
| /* jshint node: true */
module.exports = function(environment) {
var ENV = {
modulePrefix: 'smallprint',
environment: environment,
baseURL: '/',
locationType: 'auto',
EmberENV: {
FEATURES: {
// Here you can enable experimental features on an ember canary build
// e.g. 'with-controller': true
}
},
contentSecurityPolicy: {
'style-src': "'self' 'unsafe-inline'",
},
APP: {
// Here you can pass flags/options to your application instance
// when it is created
}
};
if (environment === 'development') {
// ENV.APP.LOG_RESOLVER = true;
// ENV.APP.LOG_ACTIVE_GENERATION = true;
// ENV.APP.LOG_TRANSITIONS = true;
// ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
// ENV.APP.LOG_VIEW_LOOKUPS = true;
}
if (environment === 'test') {
// Testem prefers this...
ENV.baseURL = '/';
ENV.locationType = 'none';
// keep test console output quieter
ENV.APP.LOG_ACTIVE_GENERATION = false;
ENV.APP.LOG_VIEW_LOOKUPS = false;
ENV.APP.rootElement = '#ember-testing';
}
if (environment === 'production') {
}
return ENV;
};
| Stop console error about content security policy | Stop console error about content security policy
| JavaScript | mit | OPCNZ/priv-o-matic,Br3nda/priv-o-matic,Br3nda/priv-o-matic,OPCNZ/priv-o-matic | ---
+++
@@ -12,7 +12,9 @@
// e.g. 'with-controller': true
}
},
-
+ contentSecurityPolicy: {
+ 'style-src': "'self' 'unsafe-inline'",
+ },
APP: {
// Here you can pass flags/options to your application instance
// when it is created |
580f65f87d7ae075d325332149185c43cfdb5141 | packages/rev-models/typedoc.js | packages/rev-models/typedoc.js |
// TypeDoc Configuration
module.exports = {
out: '../../docs/dist/api/rev-models',
readme: './DOCINDEX.md',
includes: './src',
theme: '../../docs/typedoc/theme/',
mode: 'file',
excludeExternals: true,
excludeNotExported: true,
excludePrivate: true
};
|
// TypeDoc Configuration
module.exports = {
out: '../../docs/dist/api/rev-models',
readme: './DOCINDEX.md',
includes: './src',
exclude: '**/{__tests__,examples}/**/*',
theme: '../../docs/typedoc/theme/',
mode: 'file',
excludeExternals: true,
excludeNotExported: true,
excludePrivate: true
};
| Exclude tests and examples from API docs | Exclude tests and examples from API docs
| JavaScript | mit | RevFramework/rev-framework,RevFramework/rev-framework | ---
+++
@@ -5,6 +5,7 @@
readme: './DOCINDEX.md',
includes: './src',
+ exclude: '**/{__tests__,examples}/**/*',
theme: '../../docs/typedoc/theme/',
mode: 'file', |
e312227fb99e871b0e6fc5a847e1d57a28ab0b6a | src/angulartics-segmentio.js | src/angulartics-segmentio.js | /**
* @license Angulartics v0.17.0
* (c) 2013 Luis Farzati http://luisfarzati.github.io/angulartics
* License: MIT
*/
(function(angular) {
'use strict';
/**
* @ngdoc overview
* @name angulartics.segment.io
* Enables analytics support for Segment.io (http://segment.io)
*/
angular.module('angulartics.segment.io', ['angulartics'])
.config(['$analyticsProvider', function ($analyticsProvider) {
$analyticsProvider.registerPageTrack(function (path, $location) {
try {
analytics.page({
path: path,
url: $location.absUrl()
});
} catch (e) {
if (!(e instanceof ReferenceError)) {
throw e;
}
}
});
$analyticsProvider.registerEventTrack(function (action, properties) {
try {
analytics.track(action, properties);
} catch (e) {
if (!(e instanceof ReferenceError)) {
throw e;
}
}
});
}]);
})(angular);
| /**
* @license Angulartics v0.17.0
* (c) 2013 Luis Farzati http://luisfarzati.github.io/angulartics
* License: MIT
*/
(function(angular) {
'use strict';
/**
* @ngdoc overview
* @name angulartics.segment.io
* Enables analytics support for Segment.io (http://segment.io)
*/
angular.module('angulartics.segment.io', ['angulartics'])
.config(['$analyticsProvider', function ($analyticsProvider) {
$analyticsProvider.registerPageTrack(function (path, $location) {
try {
analytics.page({
path: path,
url: $location.absUrl()
});
} catch (e) {
if (!(e instanceof ReferenceError)) {
throw e;
}
}
});
$analyticsProvider.registerEventTrack(function (action, properties) {
try {
analytics.track(action, properties);
} catch (e) {
if (!(e instanceof ReferenceError)) {
throw e;
}
}
});
$analyticsProvider.registerSetUserProperties(function (id, properties) {
try {
analytics.identify(id, properties);
} catch (e) {
if (!(e instanceof ReferenceError)) {
throw e;
}
}
});
$analyticsProvider.registerSetUserPropertiesOnce(function (id, properties) {
try {
analytics.identify(id, properties);
} catch (e) {
if (!(e instanceof ReferenceError)) {
throw e;
}
}
});
}]);
})(angular);
| Add user identification to segment | Add user identification to segment | JavaScript | mit | mushkab/angulartics,TallyFox/angulartics,WoodWing/angulartics,dy2288/angulartics,iamakimmer/angulartics,cwill747/angulartics,angulartics/angulartics,jung01080/angulartics,indiegogo/angulartics,geordie--/angulartics,marcin-wosinek/angulartics,martijndejongh/angulartics,aheuermann/angulartics,abhilashsajeev/angulartics,Ignigena/angulartics,cristoferdomingues/angulartics,trolleycrash/angulartics | ---
+++
@@ -35,5 +35,26 @@
}
}
});
+
+ $analyticsProvider.registerSetUserProperties(function (id, properties) {
+ try {
+ analytics.identify(id, properties);
+ } catch (e) {
+ if (!(e instanceof ReferenceError)) {
+ throw e;
+ }
+ }
+ });
+
+ $analyticsProvider.registerSetUserPropertiesOnce(function (id, properties) {
+ try {
+ analytics.identify(id, properties);
+ } catch (e) {
+ if (!(e instanceof ReferenceError)) {
+ throw e;
+ }
+ }
+ });
+
}]);
})(angular); |
f6e8eb2e847df7cac1167ee8c1614ea51a9cd965 | src/actions/Filter.action.js | src/actions/Filter.action.js | 'use strict';
import Reflux from 'reflux';
import Socket from 'socket.io-client';
import {filter} from 'lodash';
import QueryAction from './QueryUpdate.action.js';
const socket = Socket.connect();
let FilterActions = Reflux.createAction(
{children: ["updated", "failed"]
});
function getQueryTextElements (query) {
return filter(query, element => element.type === 'text')
.map(element => element.value);
}
QueryAction.listen((query) => {
socket.emit('getFilterGuidesRequest', getQueryTextElements(query).join(' '));
});
socket.on('getFilterGuidesResponse', (data) => {
FilterActions.updated(data)
});
export default FilterActions;
| 'use strict';
import Reflux from 'reflux';
import Socket from 'socket.io-client';
import {filter} from 'lodash';
import QueryAction from './QueryUpdate.action.js';
const socket = Socket.connect();
let FilterActions = Reflux.createAction({
children: ["updated", "failed"]
});
function getQueryTextElements(query) {
return filter(query, element => element.type === 'text')
.map(element => element.value);
}
QueryAction.listen((query) => {
if (query.length > 0) {
let q = getQueryTextElements(query).join(' ');
socket.emit('getFilterGuidesRequest', q);
} else {
FilterActions.updated([]);
}
});
socket.on('getFilterGuidesResponse', (data) => {
FilterActions.updated(data)
});
export default FilterActions;
| Remove filterelements if no query | Remove filterelements if no query
| JavaScript | agpl-3.0 | DBCDK/serviceprovider,DBCDK/serviceprovider | ---
+++
@@ -6,17 +6,23 @@
const socket = Socket.connect();
-let FilterActions = Reflux.createAction(
- {children: ["updated", "failed"]
+let FilterActions = Reflux.createAction({
+ children: ["updated", "failed"]
});
-function getQueryTextElements (query) {
+function getQueryTextElements(query) {
return filter(query, element => element.type === 'text')
.map(element => element.value);
}
QueryAction.listen((query) => {
- socket.emit('getFilterGuidesRequest', getQueryTextElements(query).join(' '));
+ if (query.length > 0) {
+ let q = getQueryTextElements(query).join(' ');
+ socket.emit('getFilterGuidesRequest', q);
+ } else {
+ FilterActions.updated([]);
+ }
+
});
socket.on('getFilterGuidesResponse', (data) => { |
4adfb1a39013feb66bf6d1d8fca75caac7241c37 | src/components/Link/index.js | src/components/Link/index.js | import { Link as GatsbyLink } from "gatsby"
import React from "react"
const styles = {
borderRadius: "0.3em",
code: {
textShadow: "none",
},
}
const Link = props => {
if (props.hasOwnProperty("to")) {
return <GatsbyLink css={styles} {...props} />
}
return <a css={styles} {...props} />
}
export default Link
| import { Link as GatsbyLink } from "gatsby"
import React from "react"
const styles = {
borderRadius: "0.3em",
code: {
textShadow: "none",
},
}
const Link = ({ to, href, ...props }) => {
if (to) {
return <GatsbyLink css={styles} to={to} {...props} />
}
if (/^https?:\/\/(?!jbhannah\.net)/.test(href)) {
props.rel = "noopener"
props.target = "_blank"
}
return <a css={styles} href={href} {...props} />
}
export default Link
| Add rel="noopener" target="_blank" to external links | Add rel="noopener" target="_blank" to external links
| JavaScript | mit | jbhannah/jbhannah.net,jbhannah/jbhannah.net | ---
+++
@@ -8,12 +8,17 @@
},
}
-const Link = props => {
- if (props.hasOwnProperty("to")) {
- return <GatsbyLink css={styles} {...props} />
+const Link = ({ to, href, ...props }) => {
+ if (to) {
+ return <GatsbyLink css={styles} to={to} {...props} />
}
- return <a css={styles} {...props} />
+ if (/^https?:\/\/(?!jbhannah\.net)/.test(href)) {
+ props.rel = "noopener"
+ props.target = "_blank"
+ }
+
+ return <a css={styles} href={href} {...props} />
}
export default Link |
49456960a85dfb9f380abe1f1a429564ac2130fd | src/components/search_bar.js | src/components/search_bar.js | import React, { Component } from 'react';
class SearchBar extends Component {
render() {
return <input />;
}
};
export default SearchBar;
| import React, { Component } from 'react';
class SearchBar extends Component {
constructor(props) {
super(props);
this.state = { term: '' };
}
render() {
return (
<div>
<input
value={this.state.term}
onChange={event => this.setState({ term: event.target.value })}/>
</div>
);
}
}
export default SearchBar;
| Add constructormethod and set state on input value change | Add constructormethod and set state on input value change
| JavaScript | mit | izabelka/redux-simple-starter,izabelka/redux-simple-starter | ---
+++
@@ -1,9 +1,21 @@
import React, { Component } from 'react';
class SearchBar extends Component {
+ constructor(props) {
+ super(props);
+
+ this.state = { term: '' };
+ }
+
render() {
- return <input />;
+ return (
+ <div>
+ <input
+ value={this.state.term}
+ onChange={event => this.setState({ term: event.target.value })}/>
+ </div>
+ );
}
-};
+}
export default SearchBar; |
ecf8ce910360d232f1c729ad488d8047d23a9f53 | src/get-last-timestamp.js | src/get-last-timestamp.js | import Promise from 'bluebird';
//
// getLastTimetamp will get the last indexing timestamp from Firebase
//
const getLastTimestamp = ({ CONFIG, dataset, fb }) => {
if (!CONFIG.timestampField || !CONFIG.firebase.uid || !dataset.index) {
return Promise.resolve(null);
}
return fb
.child(`${CONFIG.firebase.uid}/${dataset.index}/ts`)
.once('value')
.then(fbRef => {
return fbRef && fbRef.val() || null;
});
};
export default getLastTimestamp;
| import Promise from 'bluebird';
import Debug from './debug';
const info = Debug('info:get-last-timestamp');
//
// getLastTimetamp will get the last indexing timestamp from Firebase
//
const getLastTimestamp = ({ CONFIG, dataset, fb }) => {
if (!CONFIG.timestampField || !CONFIG.firebase.uid || !dataset.index) {
info(`Unable to fetch timestamp for index ${dataset.index}`);
return Promise.resolve(null);
}
return fb
.child(`${CONFIG.firebase.uid}/${dataset.index}/ts`)
.once('value')
.then(fbRef => {
const ts = fbRef.val();
info(
fbRef.val() ?
`Timestamp for index ${dataset.index}: ${ts}` :
`Timestamp not found for index ${dataset.index}`
)
return ts;
});
};
export default getLastTimestamp;
| Add some output info, remove unused branching | Add some output info, remove unused branching
| JavaScript | mit | webstylestory/figolia,webstylestory/algolia-firebase-indexer | ---
+++
@@ -1,4 +1,8 @@
import Promise from 'bluebird';
+
+import Debug from './debug';
+
+const info = Debug('info:get-last-timestamp');
//
// getLastTimetamp will get the last indexing timestamp from Firebase
@@ -6,6 +10,7 @@
const getLastTimestamp = ({ CONFIG, dataset, fb }) => {
if (!CONFIG.timestampField || !CONFIG.firebase.uid || !dataset.index) {
+ info(`Unable to fetch timestamp for index ${dataset.index}`);
return Promise.resolve(null);
}
@@ -13,7 +18,13 @@
.child(`${CONFIG.firebase.uid}/${dataset.index}/ts`)
.once('value')
.then(fbRef => {
- return fbRef && fbRef.val() || null;
+ const ts = fbRef.val();
+ info(
+ fbRef.val() ?
+ `Timestamp for index ${dataset.index}: ${ts}` :
+ `Timestamp not found for index ${dataset.index}`
+ )
+ return ts;
});
}; |
b7196b5b93ccb19a23aa3e21c3c8cd3708941e8e | src/store/calendar/actions.js | src/store/calendar/actions.js | import * as types from './actionTypes'
export function changeDate (date) {
return {
type: types.CHANGE_DATE,
date,
}
}
| import * as types from './actionTypes'
import store from '../../store'
import { getCurrentDate } from './reducer'
import { getCurrentBuffer } from '../editor/reducer'
import notesService from '../../services/notes'
import { changeBuffer } from '../editor/actions'
export function changeDate (date) {
// Save the current note
const state = store.getState()
const currentDate = getCurrentDate(state)
const currentBuffer = getCurrentBuffer(state)
notesService.setNoteByDateToLocalStorage(currentDate, currentBuffer)
// Load the new date's note
const newBuffer = notesService.getNoteByDateFromLocalStorage(date)
store.dispatch(changeBuffer(newBuffer))
// Proceed to the action creation
return {
type: types.CHANGE_DATE,
date,
}
}
| Save buffer when changing date, and load the new date's buffer | Save buffer when changing date, and load the new date's buffer
Straightforwardly do this in the changeDate action creator
| JavaScript | mit | yurivyatkin/zhurnik-webapp,yurivyatkin/zhurnik-webapp | ---
+++
@@ -1,6 +1,20 @@
import * as types from './actionTypes'
+import store from '../../store'
+import { getCurrentDate } from './reducer'
+import { getCurrentBuffer } from '../editor/reducer'
+import notesService from '../../services/notes'
+import { changeBuffer } from '../editor/actions'
export function changeDate (date) {
+ // Save the current note
+ const state = store.getState()
+ const currentDate = getCurrentDate(state)
+ const currentBuffer = getCurrentBuffer(state)
+ notesService.setNoteByDateToLocalStorage(currentDate, currentBuffer)
+ // Load the new date's note
+ const newBuffer = notesService.getNoteByDateFromLocalStorage(date)
+ store.dispatch(changeBuffer(newBuffer))
+ // Proceed to the action creation
return {
type: types.CHANGE_DATE,
date, |
6540487fb903f03282885b6263ddfa46fc7640d8 | src/tasks/load-model-files.js | src/tasks/load-model-files.js | var path = require('path'),
vow = require('vow'),
inherit = require('inherit'),
fsExtra = require('fs-extra'),
Base = require('./base');
module.exports = inherit(Base, {
logger: undefined,
__constructor: function (baseConfig, taskConfig) {
this.__base(baseConfig, taskConfig);
this.logger = this.createLogger(module);
this.logger.info('Initialize "%s" task successfully', this.getName());
},
/**
* Returns name of current task
* @returns {string} - name of task
*/
getName: function () {
return 'load model files';
},
/**
* Performs task
* @returns {Promise}
*/
run: function () {
var newModelFilePath = path.resolve(this.getBaseConfig().getModelFilePath()),
oldModelFilePath = path.resolve(this.getBaseConfig().getDestinationDirPath(), 'model.json'),
newModel,
oldModel;
try {
newModel = fsExtra.readJSONSync(newModelFilePath);
} catch (error) {
this.logger.error('Can\'t read or parse model file "%s"', newModelFilePath);
throw error;
}
try {
oldModel = fsExtra.readJSONSync(oldModelFilePath);
} catch (error) {
this.logger.warn('Can\'t read or parse model file "%s". New model will be created', newModelFilePath);
oldModel = [];
}
return vow.resolve({ newModel: newModel, oldModel: oldModel });
}
});
| var path = require('path'),
vow = require('vow'),
inherit = require('inherit'),
fsExtra = require('fs-extra'),
Base = require('./base');
module.exports = inherit(Base, {
logger: undefined,
__constructor: function (baseConfig, taskConfig) {
this.__base(baseConfig, taskConfig);
this.logger = this.createLogger(module);
this.logger.info('Initialize "%s" task successfully', this.getName());
},
/**
* Returns name of current task
* @returns {string} - name of task
*/
getName: function () {
return 'load model files';
},
/**
* Performs task
* @returns {Promise}
*/
run: function () {
var newModelFilePath = path.resolve(this.getBaseConfig().getModelFilePath()),
oldModelFilePath = path.resolve(this.getBaseConfig().getCacheDirPath, 'model.json'),
newModel,
oldModel;
try {
newModel = fsExtra.readJSONSync(newModelFilePath);
} catch (error) {
this.logger.error('Can\'t read or parse model file "%s"', newModelFilePath);
throw error;
}
try {
oldModel = fsExtra.readJSONSync(oldModelFilePath);
} catch (error) {
this.logger.warn('Can\'t read or parse model file "%s". New model will be created', newModelFilePath);
oldModel = [];
}
return vow.resolve({ newModel: newModel, oldModel: oldModel });
}
});
| Change source path of old model file from data to cache folder | Change source path of old model file from data to cache folder
| JavaScript | mpl-2.0 | bem-site/builder-core,bem-site/gorshochek | ---
+++
@@ -28,7 +28,7 @@
*/
run: function () {
var newModelFilePath = path.resolve(this.getBaseConfig().getModelFilePath()),
- oldModelFilePath = path.resolve(this.getBaseConfig().getDestinationDirPath(), 'model.json'),
+ oldModelFilePath = path.resolve(this.getBaseConfig().getCacheDirPath, 'model.json'),
newModel,
oldModel;
|
abc5eda09a114faca128a18ecb045dcc1e1522ae | src/components/HeaderMenu.js | src/components/HeaderMenu.js | const PropTypes = require('prop-types');
const React = require('react');
const Button = require('./Button');
const SimpleSelect = require('./SimpleSelect');
class HeaderMenu extends React.Component {
static propTypes = {
buttonIcon: PropTypes.string,
buttonText: PropTypes.string.isRequired,
items: PropTypes.array.isRequired,
theme: themeShape
}
state = {
showSimpleSelectMenu: false
}
toggle = () => {
this.setState({
showSimpleSelectMenu: !this.state.showSimpleSelectMenu
});
}
render () {
const theme = StyleUtils.mergeTheme(this.props.theme);
const items = this.props.items.map(item =>
Object.assign({}, item, {
onClick: (event, itemClicked) => {
this.toggle();
item.onClick(event, itemClicked);
}
})
);
return (
<div style={{ width: 150 }}>
<Button
icon={this.props.buttonIcon}
onClick={this.toggle}
theme={theme}
type='neutral'
>
{this.props.buttonText}
</Button>
{this.state.showSimpleSelectMenu ? (
<SimpleSelect
items={items}
onScrimClick={this.toggle}
styles={{ menu: { left: 65 } }}
/>
) : null}
</div>
);
}
}
module.exports = HeaderMenu;
| const PropTypes = require('prop-types');
const React = require('react');
const Button = require('./Button');
const SimpleSelect = require('./SimpleSelect');
class HeaderMenu extends React.Component {
static propTypes = {
buttonIcon: PropTypes.string,
buttonText: PropTypes.string.isRequired,
items: PropTypes.array.isRequired,
theme: themeShape
}
state = {
showSimpleSelectMenu: false
}
toggle = () => {
this.setState({
showSimpleSelectMenu: !this.state.showSimpleSelectMenu
});
}
render () {
const theme = StyleUtils.mergeTheme(this.props.theme);
const items = this.props.items.map(item =>
Object.assign({}, item, {
onClick: (event, itemClicked) => {
this.toggle();
item.onClick(event, itemClicked);
}
})
);
return (
<div style={{ width: 150 }}>
<Button
icon={this.props.buttonIcon}
onClick={this.toggle}
theme={theme}
type='neutral'
>
{this.props.buttonText}
</Button>
{this.state.showSimpleSelectMenu ? (
<SimpleSelect
items={items}
onScrimClick={this.toggle}
styles={{ menu: { left: 65 } }}
theme={theme}
/>
) : null}
</div>
);
}
}
module.exports = HeaderMenu;
| Add theme prop to SimpleSelect instance | Add theme prop to SimpleSelect instance
| JavaScript | mit | mxenabled/mx-react-components | ---
+++
@@ -47,6 +47,7 @@
items={items}
onScrimClick={this.toggle}
styles={{ menu: { left: 65 } }}
+ theme={theme}
/>
) : null}
</div> |
18b22a8cc0c8de565a9b14b2eb24a4109fc511a1 | yyid.js | yyid.js | function yyid() {
/* eslint-disable arrow-body-style, no-plusplus */
if (!window.crypto) {
return 'xx-x-x-x-xxx'.replace(/x/g, () => {
return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1)
})
}
let i = 0
const randomTwoBytes = new Uint16Array(8)
window.crypto.getRandomValues(randomTwoBytes)
return 'xx-x-x-x-xxx'.replace(/x/g, () => {
return `000${randomTwoBytes[i++].toString(16)}`.substr(-4)
})
/* eslint-enable arrow-body-style, no-plusplus */
}
export default yyid | function yyid() {
/* eslint-disable arrow-body-style, no-plusplus */
if (!window.crypto) {
return 'xx-x-x-x-xxx'.replace(/x/g, () => {
return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1)
})
}
let i = 0
const randomTwoBytes = new Uint16Array(8)
window.crypto.getRandomValues(randomTwoBytes)
return 'xx-x-x-x-xxx'.replace(/x/g, () => {
return randomTwoBytes[i++].toString(16).padStart(4, 0);
})
/* eslint-enable arrow-body-style, no-plusplus */
}
export default yyid
| Use `padStart` to complete random bytes with zeros | Use `padStart` to complete random bytes with zeros
The use of `String.padStart()` is in my opinion more idiomatic than manually add zeros at the beginning, then removing them. | JavaScript | mit | janlelis/yyid.js | ---
+++
@@ -11,7 +11,7 @@
window.crypto.getRandomValues(randomTwoBytes)
return 'xx-x-x-x-xxx'.replace(/x/g, () => {
- return `000${randomTwoBytes[i++].toString(16)}`.substr(-4)
+ return randomTwoBytes[i++].toString(16).padStart(4, 0);
})
/* eslint-enable arrow-body-style, no-plusplus */
} |
9710aeb0ef670c41f5ac18709c199f12dda94139 | spec.js | spec.js | const test = require('blue-tape')
const Dexie = require('dexie')
const DexieBatch = require('./dexie-batch')
const batchSize = 10
const testEntries = Array(42).fill().map((_, i) => i)
testWithTable('basic operation', (t, table) => {
let maxIdx = -1
const readEntries = []
return table.count()
.then(n => {
t.is(n, testEntries.length, 'written right number of entries')
return new DexieBatch({ batchSize, limit: n })
})
.then(db => db.each(table.toCollection(), (entry, i) => {
readEntries.push(entry)
maxIdx = Math.max(maxIdx, i)
}))
.then(_ => {
readEntries.sort((a, b) => a - b)
t.ok(maxIdx > 0, 'indices valid')
t.ok(maxIdx < batchSize, 'batches sized correctly')
t.deepEqual(readEntries, testEntries, 'entries read correctly')
})
})
function testWithTable(name, f) {
const db = new Dexie('test-db')
db.version(1).stores({ test: '++' })
db.test.bulkAdd(testEntries)
.then(_ => test(name, t => {
return f(t, db.test)
.then(_ => db.delete())
.catch(err => {
db.delete()
throw err
})
}))
}
| const test = require('blue-tape')
const Dexie = require('dexie')
const DexieBatch = require('./dexie-batch')
const batchSize = 10
const testEntries = Array(42).fill().map((_, i) => i)
testWithTable('basic serial operation', (t, table) => {
return testBasicOperation(t, table, new DexieBatch({ batchSize }))
})
testWithTable('basic parallel operation', (t, table) => {
return table.count()
.then(n => new DexieBatch({ batchSize, limit: n }))
.then(db => testBasicOperation(t, table, db))
})
function testBasicOperation(t, table, db) {
let maxIdx = -1
const readEntries = []
return Promise.resolve(db)
.then(db => db.each(table.toCollection(), (entry, i) => {
readEntries.push(entry)
maxIdx = Math.max(maxIdx, i)
}))
.then(_ => {
readEntries.sort((a, b) => a - b)
t.equal(maxIdx + 1, batchSize, 'batches sized correctly')
t.deepEqual(readEntries, testEntries, 'entries read correctly')
})
}
function testWithTable(name, f) {
const db = new Dexie(name)
db.version(1).stores({ test: '++' })
db.test.bulkAdd(testEntries)
.then(_ => test(name, t => {
return f(t, db.test)
.then(_ => db.delete())
.catch(err => {
db.delete()
throw err
})
}))
}
| Add tests for serial operation | Add tests for serial operation
| JavaScript | mit | raphinesse/dexie-batch | ---
+++
@@ -5,29 +5,34 @@
const batchSize = 10
const testEntries = Array(42).fill().map((_, i) => i)
-testWithTable('basic operation', (t, table) => {
+testWithTable('basic serial operation', (t, table) => {
+ return testBasicOperation(t, table, new DexieBatch({ batchSize }))
+})
+
+testWithTable('basic parallel operation', (t, table) => {
+ return table.count()
+ .then(n => new DexieBatch({ batchSize, limit: n }))
+ .then(db => testBasicOperation(t, table, db))
+})
+
+function testBasicOperation(t, table, db) {
let maxIdx = -1
const readEntries = []
- return table.count()
- .then(n => {
- t.is(n, testEntries.length, 'written right number of entries')
- return new DexieBatch({ batchSize, limit: n })
- })
+ return Promise.resolve(db)
.then(db => db.each(table.toCollection(), (entry, i) => {
readEntries.push(entry)
maxIdx = Math.max(maxIdx, i)
}))
.then(_ => {
readEntries.sort((a, b) => a - b)
- t.ok(maxIdx > 0, 'indices valid')
- t.ok(maxIdx < batchSize, 'batches sized correctly')
+ t.equal(maxIdx + 1, batchSize, 'batches sized correctly')
t.deepEqual(readEntries, testEntries, 'entries read correctly')
})
-})
+}
function testWithTable(name, f) {
- const db = new Dexie('test-db')
+ const db = new Dexie(name)
db.version(1).stores({ test: '++' })
db.test.bulkAdd(testEntries)
.then(_ => test(name, t => { |
a0b1d9966a30859d004ee6feb2b9623a05fa5965 | task.js | task.js | #! /usr/local/bin/node
const fs = require('fs')
const add = require('./commands/add')
const list = require('./commands/list')
const done = require('./commands/done')
const command = process.argv[2]
const argument = process.argv.slice(3).join(' ')
switch(command) {
case "add":
add(argument)
break;
case "list":
list()
break;
case "done":
done(argument)
}
| #! /usr/local/bin/node
const fs = require('fs')
const add = require('./commands/add')
const list = require('./commands/list')
const done = require('./commands/done')
const command = process.argv[2]
const argument = process.argv.slice(3).join(' ')
switch(command) {
case "add":
add(argument)
break;
case "list":
list()
break;
case "done":
done(argument)
break;
default:
console.log("Invalid command, use \"add\", \"list\", or \"done\"")
}
| Add default case to switch statement | Add default case to switch statement
| JavaScript | mit | breyana/Command-Line-Todo-List | ---
+++
@@ -19,4 +19,8 @@
case "done":
done(argument)
+ break;
+
+ default:
+ console.log("Invalid command, use \"add\", \"list\", or \"done\"")
} |
ecc99fcf52d07c8eb89060e3544b9f3f97b62656 | lib/express.js | lib/express.js | exports.name = 'adapter-base-express';
exports.attach = function(/* options */){
var self = this;
/**
* This plugin requires that a template engine plugin has already
* been loaded:
*/
if (!self.engine){
throw new Error('A template engine is required.');
}
/**
* If the engine supports the __express(path, options, callback) method
* then use it as our renderFile method:
*/
if (self.engine.__express){
self.renderFile = self.engine.__express;
}
};
| exports.name = 'adapter-base-express';
exports.attach = function(/* options */){
var self = this;
/**
* This plugin requires that a template engine plugin has already
* been loaded:
*/
if (!self.engine){
throw new Error('A template engine is required.');
}
/**
* If the engine supports the __express(path, options, callback) method
* then use it as our renderFile method:
*/
if (self.engine.__express){
self.renderFile = self.engine.__express;
}
/**
* Alternatively, if the engine supports a renderFile method then use that:
*/
else if (self.engine.renderFile){
self.renderFile = self.engine.renderFile;
}
};
| Use renderFile directly if an engine supports it. | Use renderFile directly if an engine supports it.
| JavaScript | mit | markbirbeck/adapter-template | ---
+++
@@ -20,4 +20,12 @@
if (self.engine.__express){
self.renderFile = self.engine.__express;
}
+
+ /**
+ * Alternatively, if the engine supports a renderFile method then use that:
+ */
+
+ else if (self.engine.renderFile){
+ self.renderFile = self.engine.renderFile;
+ }
}; |
3fdd8e937840660ab52be3e73e655c9af2d31009 | src/main/webapp/dashboard.js | src/main/webapp/dashboard.js | google.charts.load('current', {'packages':['corechart']});
function drawChart() {
// Instead of the following, get the visits and days array from localStorage
var visits = [5, 10, 7,20,10];
var data=[];
var Header= ['Day', 'Visits', { role: 'style' }];
data.push(Header);
for (var i = 0; i < visits.length; i++) {
var temp=[];
temp.push(i.toString());
temp.push(visits[i]);
temp.push("blue"); // Line graph will change based on number of visits
data.push(temp);
}
var chartdata = new google.visualization.arrayToDataTable(data);
var options = {
title: 'Site Visitors',
legend: { position: 'right' },
hAxis: {title: 'Day' },
vAxis: {title: 'Number of Visits' },
};
var chart = new google.visualization.LineChart(document.getElementById('line-chart'));
chart.draw(chartdata, options);
}
google.charts.setOnLoadCallback(drawChart); | google.charts.load('current', {'packages':['corechart']});
function drawChart() {
// Instead of the following, get the visits and days array from localStorage
var visits = [5, 10, 7,20,10];
var data=[];
var Header= ['Day', 'Visits', { role: 'style' }];
data.push(Header);
for (var i = 0; i < visits.length; i++) {
var temp=[];
temp.push(i.toString());
temp.push(visits[i]);
temp.push("blue"); // Line graph will change based on number of visits
data.push(temp);
}
var chartdata = new google.visualization.arrayToDataTable(data);
var options = {
title: 'Site Visitors',
legend: { position: 'right' },
hAxis: {title: 'Day' },
vAxis: {title: 'Number of Visits' },
backgroundColor: {
gradient: {
// Start color for gradient
color1: '#fcf7b6',
// Finish color for gradient
color2: '#4ccd88',
// Start and end point of gradient, start
// on upper left corner
x1: '0%', y1: '0%',
x2: '100%', y2: '100%',
// If true, the boundary for x1,
// y1, x2, and y2 is the box. If
// false, it's the entire chart.
useObjectBoundingBoxUnits: true
},
},
};
var chart = new google.visualization.LineChart(document.getElementById('line-chart'));
chart.draw(chartdata, options);
}
google.charts.setOnLoadCallback(drawChart); | Change chart background to gradient. | Change chart background to gradient.
| JavaScript | apache-2.0 | googleinterns/step87-2020,googleinterns/step87-2020,googleinterns/step87-2020,googleinterns/step87-2020 | ---
+++
@@ -24,6 +24,22 @@
legend: { position: 'right' },
hAxis: {title: 'Day' },
vAxis: {title: 'Number of Visits' },
+ backgroundColor: {
+ gradient: {
+ // Start color for gradient
+ color1: '#fcf7b6',
+ // Finish color for gradient
+ color2: '#4ccd88',
+ // Start and end point of gradient, start
+ // on upper left corner
+ x1: '0%', y1: '0%',
+ x2: '100%', y2: '100%',
+ // If true, the boundary for x1,
+ // y1, x2, and y2 is the box. If
+ // false, it's the entire chart.
+ useObjectBoundingBoxUnits: true
+ },
+ },
};
var chart = new google.visualization.LineChart(document.getElementById('line-chart')); |
1bc7f6a7b12e4050277bb375b393731032008077 | lib/persist.js | lib/persist.js | class persist {
static get SESSION_TOKEN_KEY () { return 'sessionToken' }
static willGetSessionToken() {
return new Promise(resolve => {
try {
resolve(localStorage && localStorage.getItem(persist.SESSION_TOKEN_KEY))
} catch (err) {
resolve(null)
}
})
}
static willSetSessionToken(sessionToken) {
return !sessionToken ? persist.willRemoveSessionToken : new Promise(resolve => {
try {
localStorage && localStorage.setItem(persist.SESSION_TOKEN_KEY, sessionToken)
} catch (err) {
// Ignore
}
resolve(sessionToken)
})
}
static willRemoveSessionToken() {
return new Promise(resolve => {
try {
localStorage && localStorage.removeItem(persist.SESSION_TOKEN_KEY)
} catch (err) {
// Ignore
}
resolve(null)
})
}
}
module.exports = persist
| const localForage = require('localforage')
class persist {
static get SESSION_TOKEN_KEY() { return 'sessionToken' }
static get ACCESS_TOKEN_KEY() { return 'accessToken' }
static async willGetSessionToken() {
return localForage.getItem(persist.SESSION_TOKEN_KEY).catch(err => err)
}
static async willSetSessionToken(value) {
return localForage.setItem(persist.SESSION_TOKEN_KEY, value).catch(err => err)
}
static async willRemoveSessionToken() {
return localForage.removeItem(persist.SESSION_TOKEN_KEY).catch(err => err)
}
static async willGetAccessToken() {
return localForage.getItem(persist.ACCESS_TOKEN_KEY).catch(err => err)
}
static async willSetAccessToken(value) {
return localForage.setItem(persist.ACCESS_TOKEN_KEY, value).catch(err => err)
}
static async willRemoveAccessToken() {
return localForage.removeItem(persist.ACCESS_TOKEN_KEY).catch(err => err)
}
}
module.exports = persist
| Use localForage instead of localStorage | feat(client): Use localForage instead of localStorage
| JavaScript | mit | digithun/jamplay-nap,digithun/jamplay-nap,digithun/nap,digithun/jamplay-nap,rabbotio/nap,digithun/nap,rabbotio/nap,digithun/nap | ---
+++
@@ -1,35 +1,31 @@
+const localForage = require('localforage')
+
class persist {
- static get SESSION_TOKEN_KEY () { return 'sessionToken' }
- static willGetSessionToken() {
- return new Promise(resolve => {
- try {
- resolve(localStorage && localStorage.getItem(persist.SESSION_TOKEN_KEY))
- } catch (err) {
- resolve(null)
- }
- })
+ static get SESSION_TOKEN_KEY() { return 'sessionToken' }
+ static get ACCESS_TOKEN_KEY() { return 'accessToken' }
+
+ static async willGetSessionToken() {
+ return localForage.getItem(persist.SESSION_TOKEN_KEY).catch(err => err)
}
- static willSetSessionToken(sessionToken) {
- return !sessionToken ? persist.willRemoveSessionToken : new Promise(resolve => {
- try {
- localStorage && localStorage.setItem(persist.SESSION_TOKEN_KEY, sessionToken)
- } catch (err) {
- // Ignore
- }
- resolve(sessionToken)
- })
+ static async willSetSessionToken(value) {
+ return localForage.setItem(persist.SESSION_TOKEN_KEY, value).catch(err => err)
}
- static willRemoveSessionToken() {
- return new Promise(resolve => {
- try {
- localStorage && localStorage.removeItem(persist.SESSION_TOKEN_KEY)
- } catch (err) {
- // Ignore
- }
- resolve(null)
- })
+ static async willRemoveSessionToken() {
+ return localForage.removeItem(persist.SESSION_TOKEN_KEY).catch(err => err)
+ }
+
+ static async willGetAccessToken() {
+ return localForage.getItem(persist.ACCESS_TOKEN_KEY).catch(err => err)
+ }
+
+ static async willSetAccessToken(value) {
+ return localForage.setItem(persist.ACCESS_TOKEN_KEY, value).catch(err => err)
+ }
+
+ static async willRemoveAccessToken() {
+ return localForage.removeItem(persist.ACCESS_TOKEN_KEY).catch(err => err)
}
}
|
61dbd38378d85260e7af27608ada77a2eca52105 | db/models/note.js | db/models/note.js | const mongoose = require('mongoose');
| const mongoose = require('mongoose');
const noteSchema = mongoose.Schema({
user_id: String,
// not sure what notes should be
notes: Array,
// this should probably be unique for a user
title: String
});
module.exports = mongoose.model('Note', noteSchema);
| Set up models for DB | Set up models for DB
| JavaScript | mit | enchanted-spotlight/Plato,enchanted-spotlight/Plato | ---
+++
@@ -1 +1,11 @@
const mongoose = require('mongoose');
+
+const noteSchema = mongoose.Schema({
+ user_id: String,
+ // not sure what notes should be
+ notes: Array,
+ // this should probably be unique for a user
+ title: String
+});
+
+module.exports = mongoose.model('Note', noteSchema); |
bda2cf353e87d132bc946a8af69c586e74c5068f | src/js/model/refugee-constants.js | src/js/model/refugee-constants.js |
var moment = require('moment');
// note that month indices are zero-based
module.exports.DATA_START_YEAR = 2012;
module.exports.DATA_START_MONTH = 0;
module.exports.DATA_END_YEAR = 2015;
module.exports.DATA_END_MONTH = 9;
module.exports.DATA_END_MOMENT = moment([
module.exports.DATA_END_YEAR,
module.exports.DATA_END_MONTH, 30]);
module.exports.ASYLUM_APPLICANTS_DATA_UPDATED_MOMENT = moment([2015, 11, 1]);
module.exports.SYRIA_REFUGEES_DATA_UPDATED_MOMENT = moment([2015, 11, 2]);
module.exports.disableLabels = ['BIH', 'MKD', 'ALB', 'LUX', 'MNE', 'ARM', 'AZE', 'LBN'];
module.exports.labelShowBreakPoint = 992;
|
var moment = require('moment');
// note that month indices are zero-based
module.exports.DATA_START_YEAR = 2012;
module.exports.DATA_START_MONTH = 0;
module.exports.DATA_END_YEAR = 2015;
module.exports.DATA_END_MONTH = 9;
module.exports.DATA_END_MOMENT = moment([
module.exports.DATA_END_YEAR,
module.exports.DATA_END_MONTH, 30]);
module.exports.ASYLUM_APPLICANTS_DATA_UPDATED_MOMENT = moment([2015, 11, 1]);
module.exports.SYRIA_REFUGEES_DATA_UPDATED_MOMENT = moment([2015, 11, 8]);
module.exports.disableLabels = ['BIH', 'MKD', 'ALB', 'LUX', 'MNE', 'ARM', 'AZE', 'LBN'];
module.exports.labelShowBreakPoint = 992;
| Correct update date in constants | Correct update date in constants
| JavaScript | mit | lucified/lucify-refugees,lucified/lucify-refugees,lucified/lucify-refugees,lucified/lucify-refugees | ---
+++
@@ -14,7 +14,7 @@
module.exports.DATA_END_MONTH, 30]);
module.exports.ASYLUM_APPLICANTS_DATA_UPDATED_MOMENT = moment([2015, 11, 1]);
-module.exports.SYRIA_REFUGEES_DATA_UPDATED_MOMENT = moment([2015, 11, 2]);
+module.exports.SYRIA_REFUGEES_DATA_UPDATED_MOMENT = moment([2015, 11, 8]);
module.exports.disableLabels = ['BIH', 'MKD', 'ALB', 'LUX', 'MNE', 'ARM', 'AZE', 'LBN'];
|
e7d7ecfd5e7c24ac59a5fb12ba077c1f3ea4f222 | lib/server/handshake.js | lib/server/handshake.js | 'use strict';
module.exports = function(client, data){
client.shaking = true;
let socket = client.socket;
socket.write('Nice');
};
| 'use strict';
const crypto = require('crypto');
module.exports = function(client, bufdata){
client.shaking = true;
let data = bufdata.toString(),
header = data.split(/\r\n\r\n/)[0],
wskey = header.match(/(?:^|\r\n|\r|\n)Sec-WebSocket-Key: (.+)(?:$|\r\n|\r|\n)/i);
if (wskey) wskey = wskey[1];
else {
client.end('No no!');
return;
}
let hash = crypto.createHash('sha1');
hash.update(wskey + '258EAFA5-E914-47DA-95CA-C5AB0DC85B11');
let reskey = hash.digest('base64');
};
| Add key reading and response key hashing and encoding | Add key reading and response key hashing and encoding
| JavaScript | mit | jamen/rela | ---
+++
@@ -1,7 +1,20 @@
'use strict';
-module.exports = function(client, data){
+const crypto = require('crypto');
+
+module.exports = function(client, bufdata){
client.shaking = true;
- let socket = client.socket;
- socket.write('Nice');
+ let data = bufdata.toString(),
+ header = data.split(/\r\n\r\n/)[0],
+ wskey = header.match(/(?:^|\r\n|\r|\n)Sec-WebSocket-Key: (.+)(?:$|\r\n|\r|\n)/i);
+
+ if (wskey) wskey = wskey[1];
+ else {
+ client.end('No no!');
+ return;
+ }
+
+ let hash = crypto.createHash('sha1');
+ hash.update(wskey + '258EAFA5-E914-47DA-95CA-C5AB0DC85B11');
+ let reskey = hash.digest('base64');
}; |
677114100cbb3dc4547c3223ec6a58bcceeb4db0 | test/actions/TalkAction_spec.js | test/actions/TalkAction_spec.js | 'use strict';
const chai = require('chai');
const {expect} = chai;
const {sandbox} = require('sinon');
chai.use(require('sinon-chai'));
describe('TalkAction', () => {
let TalkAction, TalkStore;
before(() => {
sandbox.create();
TalkAction = require('../../app/actions/TalkAction');
});
beforeEach(() => {
delete require.cache[require.resolve('../../app/stores/TalkStore')];
TalkStore = require('../../app/stores/TalkStore');
});
after(() => {
sandbox.restore();
});
it('should be set nowtalking in store if called talk action', () => {
TalkAction.talk('sample');
setTimeout(() => {
expect(TalkStore.isTalkingNow()).to.be.equal(true);
}, 100);
});
});
| 'use strict';
const chai = require('chai');
const {expect} = chai;
const {sandbox} = require('sinon');
chai.use(require('sinon-chai'));
describe('TalkAction', () => {
let TalkAction, TalkStore;
before(() => {
sandbox.create();
TalkAction = require('../../app/actions/TalkAction');
});
beforeEach(() => {
delete require.cache[require.resolve('../../app/stores/TalkStore')];
TalkStore = require('../../app/stores/TalkStore');
});
after(() => {
sandbox.restore();
});
it('should be set nowtalking in store if called talk action', () => {
TalkAction.talk('samplesamplesamplesample');
setTimeout(() => {
expect(TalkStore.isTalkingNow()).to.be.equal(true);
}, 400);
});
it('should dont to set nowtalking in store if called talk action', () => {
TalkAction.talk('/disconnect');
setTimeout(() => {
expect(TalkStore.isTalkingNow()).to.be.equal(false);
}, 400);
});
});
| Add test case of TalkAction | Add test case of TalkAction
- should dont to set nowtalking if call talk method
| JavaScript | mit | MaxMEllon/comelon,MaxMEllon/comelon | ---
+++
@@ -23,10 +23,17 @@
});
it('should be set nowtalking in store if called talk action', () => {
- TalkAction.talk('sample');
+ TalkAction.talk('samplesamplesamplesample');
setTimeout(() => {
expect(TalkStore.isTalkingNow()).to.be.equal(true);
- }, 100);
+ }, 400);
+ });
+
+ it('should dont to set nowtalking in store if called talk action', () => {
+ TalkAction.talk('/disconnect');
+ setTimeout(() => {
+ expect(TalkStore.isTalkingNow()).to.be.equal(false);
+ }, 400);
});
}); |
2f7516bfc7024d25ff424e4619ad7e3ca6eee5b0 | web/src/scripts/controller/CartBlogListCtrl.js | web/src/scripts/controller/CartBlogListCtrl.js | 'use strict';
/* global CartUtility */
module.exports = function ($scope, $location, $window) {
CartUtility.log('CartBlogListCtrl');
}; | 'use strict';
/* global uuid, CartUtility */
module.exports = function ($scope, $location, $window) {
CartUtility.log('CartBlogListCtrl');
$scope.createNew = function() {
// redirect to create post page
$window.location.href = CartUtility.getPureRootUrlFromLocation($location) + 'new/' + uuid.v4();
};
}; | Add new blog post redirect function button. | Add new blog post redirect function button.
| JavaScript | mit | agreatfool/Cart,agreatfool/Cart,agreatfool/Cart,agreatfool/Cart,agreatfool/Cart,agreatfool/Cart,agreatfool/Cart,agreatfool/Cart,agreatfool/Cart,agreatfool/Cart,agreatfool/Cart,agreatfool/Cart,agreatfool/Cart,agreatfool/Cart,agreatfool/Cart,agreatfool/Cart,agreatfool/Cart,agreatfool/Cart | ---
+++
@@ -1,6 +1,11 @@
'use strict';
-/* global CartUtility */
+/* global uuid, CartUtility */
module.exports = function ($scope, $location, $window) {
CartUtility.log('CartBlogListCtrl');
+
+ $scope.createNew = function() {
+ // redirect to create post page
+ $window.location.href = CartUtility.getPureRootUrlFromLocation($location) + 'new/' + uuid.v4();
+ };
}; |
f47e265c5bffc2871bd1f4cb90c73531de292280 | src/store/actions/actions.js | src/store/actions/actions.js | const {bindActionCreators} = require('redux')
const store = require('../store')
const globals = require('./globals')
const captures = require('./captures')
const unboundActions = Object.assign({}, globals, captures)
const actions = bindActionCreators(unboundActions, store.dispatch)
module.exports = {
unboundActions,
actions
}
| const {bindActionCreators} = require('redux')
const objectAssign = require('object-assign')
const store = require('../store')
const globals = require('./globals')
const captures = require('./captures')
const unboundActions = objectAssign({}, globals, captures)
const actions = bindActionCreators(unboundActions, store.dispatch)
module.exports = {
unboundActions,
actions
}
| Use object-assign polyfill for object creation | Use object-assign polyfill for object creation
| JavaScript | mit | onfido/onfido-sdk-core | ---
+++
@@ -1,9 +1,10 @@
const {bindActionCreators} = require('redux')
+const objectAssign = require('object-assign')
const store = require('../store')
const globals = require('./globals')
const captures = require('./captures')
-const unboundActions = Object.assign({}, globals, captures)
+const unboundActions = objectAssign({}, globals, captures)
const actions = bindActionCreators(unboundActions, store.dispatch)
module.exports = { |
3202c19fd0531b19da283f236eb9ccb2e3be654e | src/extendables/get_usableCommands.js | src/extendables/get_usableCommands.js | exports.conf = {
type: "get",
method: "usableCommands",
appliesTo: ["Message"],
};
// eslint-disable-next-line func-names
exports.extend = function () {
this.client.commands.filter(command => !this.client.commandInhibitors.some((inhibitor) => {
if (inhibitor.conf.enabled && !inhibitor.conf.spamProtection) return inhibitor.run(this.client, this, command);
return false;
}));
};
| exports.conf = {
type: "get",
method: "usableCommands",
appliesTo: ["Message"],
};
// eslint-disable-next-line func-names
exports.extend = function () {
return this.client.commands.filter(command => !this.client.commandInhibitors.some((inhibitor) => {
if (inhibitor.conf.enabled && !inhibitor.conf.spamProtection) return inhibitor.run(this.client, this, command);
return false;
}));
};
| Fix usableCommand bug from Kyra | Fix usableCommand bug from Kyra
| JavaScript | mit | dirigeants/komada,dirigeants/komada,eslachance/komada | ---
+++
@@ -6,9 +6,8 @@
// eslint-disable-next-line func-names
exports.extend = function () {
- this.client.commands.filter(command => !this.client.commandInhibitors.some((inhibitor) => {
+ return this.client.commands.filter(command => !this.client.commandInhibitors.some((inhibitor) => {
if (inhibitor.conf.enabled && !inhibitor.conf.spamProtection) return inhibitor.run(this.client, this, command);
return false;
}));
};
- |
080d0b9e175b42d7596f917885050f59fef119c7 | lib/font-family.js | lib/font-family.js | var _ = require('lodash')
var fs = require('fs')
var gzip = require('gzip-size')
var filesize = require('filesize')
var cssstats = require('cssstats')
var module = require('tachyons-font-family/package.json')
var moduleCss = fs.readFileSync('node_modules/tachyons-font-family/tachyons-font-family.min.css', 'utf8')
var moduleObj = cssstats(moduleCss)
var moduleSize = filesize(moduleObj.gzipSize)
var srcCSS = fs.readFileSync('./src/_font-family.css', 'utf8')
var navDocs = fs.readFileSync('./templates/nav_docs.html', 'utf8')
var template = fs.readFileSync('./templates/docs/font-family/index.html', 'utf8')
var tpl = _.template(template)
var html = tpl({
moduleVersion: module.version,
moduleSize: moduleSize,
moduleObj: moduleObj,
srcCSS: srcCSS,
navDocs: navDocs
})
fs.writeFileSync('./docs/typography/font-family/index.html', html)
| var _ = require('lodash')
var fs = require('fs')
var gzip = require('gzip-size')
var filesize = require('filesize')
var cssstats = require('cssstats')
var module = require('tachyons-font-family/package.json')
var moduleCss = fs.readFileSync('node_modules/tachyons-font-family/tachyons-font-family.min.css', 'utf8')
var moduleObj = cssstats(moduleCss)
var moduleSize = filesize(moduleObj.gzipSize)
var srcCSS = fs.readFileSync('./src/_font-family.css', 'utf8')
var navDocs = fs.readFileSync('./templates/nav_docs.html', 'utf8')
var siteFooter = fs.readFileSync('./templates/footer.html', 'utf8')
var template = fs.readFileSync('./templates/docs/font-family/index.html', 'utf8')
var tpl = _.template(template)
var html = tpl({
moduleVersion: module.version,
moduleSize: moduleSize,
moduleObj: moduleObj,
srcCSS: srcCSS,
navDocs: navDocs,
siteFooter: siteFooter
})
fs.writeFileSync('./docs/typography/font-family/index.html', html)
| Add site footer to each documentation generator | Add site footer to each documentation generator
| JavaScript | mit | fenderdigital/css-utilities,matyikriszta/moonlit-landing-page,tachyons-css/tachyons,fenderdigital/css-utilities,topherauyeung/portfolio,topherauyeung/portfolio,pietgeursen/pietgeursen.github.io,cwonrails/tachyons,getfrank/tachyons,topherauyeung/portfolio | ---
+++
@@ -11,6 +11,7 @@
var srcCSS = fs.readFileSync('./src/_font-family.css', 'utf8')
var navDocs = fs.readFileSync('./templates/nav_docs.html', 'utf8')
+var siteFooter = fs.readFileSync('./templates/footer.html', 'utf8')
var template = fs.readFileSync('./templates/docs/font-family/index.html', 'utf8')
@@ -20,7 +21,8 @@
moduleSize: moduleSize,
moduleObj: moduleObj,
srcCSS: srcCSS,
- navDocs: navDocs
+ navDocs: navDocs,
+ siteFooter: siteFooter
})
fs.writeFileSync('./docs/typography/font-family/index.html', html) |
ce97c63a930708391e0637bdac00f4a27064dd20 | main.js | main.js | 'use strict'
const electron = require('electron')
const app = electron.app // Module to control application life.
const BrowserWindow = electron.BrowserWindow // Module to create native browser window.
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow
// Quit when all windows are closed.
app.on('window-all-closed', () => {
// On OS X it is common for applications and their menu bar
// to stay active until the user quits explicitly with Cmd + Q
if (process.platform != 'darwin') {
app.quit()
}
})
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
app.on('ready', () => {
// Create the browser window.
mainWindow = new BrowserWindow({width: 1200, height: 900})
// and load the index.html of the app.
mainWindow.loadURL(`file://${__dirname}/index.html`)
// Open the DevTools.
// mainWindow.webContents.openDevTools()
// Emitted when the window is closed.
mainWindow.on('closed', function() {
// Dereference the window object, usually you would store windows
// in an array if your app supports multi windows, this is the time
// when you should delete the corresponding element.
mainWindow = null
})
}) | 'use strict'
const electron = require('electron')
const app = electron.app // Module to control application life.
const BrowserWindow = electron.BrowserWindow // Module to create native browser window.
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow
// Quit when all windows are closed.
app.on('window-all-closed', () => {
// On OS X it is common for applications and their menu bar
// to stay active until the user quits explicitly with Cmd + Q
if (process.platform != 'darwin') {
app.quit()
}
})
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
app.on('ready', () => {
// Create the browser window.
mainWindow = new BrowserWindow({width: 800, height: 600})
// and load the index.html of the app.
mainWindow.loadURL(`file://${__dirname}/index.html`)
// Open the DevTools.
// mainWindow.webContents.openDevTools()
// Emitted when the window is closed.
mainWindow.on('closed', function() {
// Dereference the window object, usually you would store windows
// in an array if your app supports multi windows, this is the time
// when you should delete the corresponding element.
mainWindow = null
})
}) | Make default window size smaller | Make default window size smaller
| JavaScript | mit | romaklimenko/core,romaklimenko/core | ---
+++
@@ -21,7 +21,7 @@
// initialization and is ready to create browser windows.
app.on('ready', () => {
// Create the browser window.
- mainWindow = new BrowserWindow({width: 1200, height: 900})
+ mainWindow = new BrowserWindow({width: 800, height: 600})
// and load the index.html of the app.
mainWindow.loadURL(`file://${__dirname}/index.html`) |
df372c1835f1282b3d3543ffa7a53f549d771ab9 | tests/test-scope-bootstrap.js | tests/test-scope-bootstrap.js | test("scope() must be defined",function(){
ok(false, "missing tests");
});
| (function(){
var
// global object
global = this;
test("scope() must be defined",function(){
strictEqual(typeof scope, "function", "scope() must be a function");
});
test("scope(code) must run code in global context",function(){
var
hasRun = false;
scope(function(context){
hasRun = true;
strictEqual(context, global, "code must run in global context");
});
ok(hasRun,"code must run synchronously");
});
test("scope(code,needs) must run code ignoring needs",function(){
var
hasRun = false;
scope(function(context){
hasRun = true;
strictEqual(context, global, "code must run in global context");
},["a","ab","abc"]);
ok(
hasRun,
"code must run synchronously, ignoring needs"
);
});
test("scope(code,needs,name) must set result in global context",function(){
var
PROPERTY_NAME = "property-name/for/unit.test",
RESULT_VALUE = {result:"value"};
hasRun = false;
scope(function(context){
hasRun = true;
strictEqual(context, global, "code must run in global context");
return RESULT_VALUE;
},["a","ab","abc"],PROPERTY_NAME);
ok(
hasRun,
"code must run synchronously, ignoring needs"
);
strictEqual(
global[PROPERTY_NAME],
RESULT_VALUE,
"result value must be set with given name in global context"
);
});
}());
| Add unit tests for scope-bootstrap.js in the browser | Add unit tests for scope-bootstrap.js in the browser
| JavaScript | mit | eric-brechemier/scope-in-browser,eric-brechemier/scopeornot,eric-brechemier/scopeornot | ---
+++
@@ -1,3 +1,58 @@
-test("scope() must be defined",function(){
- ok(false, "missing tests");
-});
+(function(){
+
+ var
+ // global object
+ global = this;
+
+ test("scope() must be defined",function(){
+ strictEqual(typeof scope, "function", "scope() must be a function");
+ });
+
+ test("scope(code) must run code in global context",function(){
+ var
+ hasRun = false;
+
+ scope(function(context){
+ hasRun = true;
+ strictEqual(context, global, "code must run in global context");
+ });
+ ok(hasRun,"code must run synchronously");
+ });
+
+ test("scope(code,needs) must run code ignoring needs",function(){
+ var
+ hasRun = false;
+
+ scope(function(context){
+ hasRun = true;
+ strictEqual(context, global, "code must run in global context");
+ },["a","ab","abc"]);
+ ok(
+ hasRun,
+ "code must run synchronously, ignoring needs"
+ );
+ });
+
+ test("scope(code,needs,name) must set result in global context",function(){
+ var
+ PROPERTY_NAME = "property-name/for/unit.test",
+ RESULT_VALUE = {result:"value"};
+ hasRun = false;
+
+ scope(function(context){
+ hasRun = true;
+ strictEqual(context, global, "code must run in global context");
+ return RESULT_VALUE;
+ },["a","ab","abc"],PROPERTY_NAME);
+ ok(
+ hasRun,
+ "code must run synchronously, ignoring needs"
+ );
+ strictEqual(
+ global[PROPERTY_NAME],
+ RESULT_VALUE,
+ "result value must be set with given name in global context"
+ );
+ });
+
+}()); |
efc216e5524c192f5e5ba382fd82a3658a53fb93 | dev/grunt/sass.js | dev/grunt/sass.js | module.exports = {
// Production settings
prod: {
options: {
sourceMap: true,
loadPath: require('node-refills').includePaths,
style: 'expanded',
update: true,
},
files: [{
expand: true,
cwd: '<%= sourceCSSDir %>',
src: ['*.scss'],
dest: '<%= destCSSDir %>',
ext: '.css'
}]
}
};
| module.exports = {
// Production settings
prod: {
options: {
trace: true,
sourcemap: true,
loadPath: require('node-refills').includePaths,
style: 'expanded',
update: true,
},
files: [{
expand: true,
cwd: '<%= sourceCSSDir %>',
src: ['*.scss'],
dest: '<%= destCSSDir %>',
ext: '.css'
}]
}
};
| Fix OptionParser::InvalidOption: invalid option: --source-map | Fix OptionParser::InvalidOption: invalid option: --source-map
| JavaScript | mit | ideus-team/html-framework,ideus-team/html-framework | ---
+++
@@ -3,7 +3,8 @@
// Production settings
prod: {
options: {
- sourceMap: true,
+ trace: true,
+ sourcemap: true,
loadPath: require('node-refills').includePaths,
style: 'expanded',
update: true, |
74231e7082066c60de8eafa1a8183a5e50e811d5 | lib/age_groups.js | lib/age_groups.js | calculateAgeGroup = function (age) {
/*
* Calculate the age group
* based on an age input
* return the age group string
* 0-5: child
* 6-10: youth
* 11-17: teen
* 18-25: yaf
* 26+: adult
*/
// Make sure age is an integer
try {
parseInt(age);
}
catch (error) {
console.log(error.message);
return;
}
// determine the age group as described above
if (age >= 0 && age <= 5) {
return 'child';
} else if (age >= 6 && age <= 10) {
return 'youth';
} else if (age >= 11 && age <= 17) {
return 'teen';
} else if (age >= 18 && age <= 25) {
return 'youngAdult';
} else if (age >= 26 ) {
return 'adult';
} else {
return undefined;
}
};
| calculateAgeGroup = function (age) {
/*
* Calculate the age group
* based on an age input
* return the age group string
* 0-5: child
* 6-12: youth
* 13-17: teen
* 18-25: yaf
* 26+: adult
*/
// Make sure age is an integer
try {
parseInt(age);
}
catch (error) {
console.log(error.message);
return;
}
// determine the age group as described above
if (age >= 0 && age <= 5) {
return 'child';
} else if (age >= 6 && age <= 12) {
return 'youth';
} else if (age >= 13 && age <= 17) {
return 'teen';
} else if (age >= 18 && age <= 25) {
return 'youngAdult';
} else if (age >= 26 ) {
return 'adult';
} else {
return undefined;
}
};
| Set age groups to match paper registration. | Set age groups to match paper registration.
| JavaScript | agpl-3.0 | quaker-io/pym-2015,quaker-io/pym-2015,quaker-io/pym-online-registration,quaker-io/pym-online-registration | ---
+++
@@ -4,8 +4,8 @@
* based on an age input
* return the age group string
* 0-5: child
- * 6-10: youth
- * 11-17: teen
+ * 6-12: youth
+ * 13-17: teen
* 18-25: yaf
* 26+: adult
*/
@@ -22,9 +22,9 @@
// determine the age group as described above
if (age >= 0 && age <= 5) {
return 'child';
- } else if (age >= 6 && age <= 10) {
+ } else if (age >= 6 && age <= 12) {
return 'youth';
- } else if (age >= 11 && age <= 17) {
+ } else if (age >= 13 && age <= 17) {
return 'teen';
} else if (age >= 18 && age <= 25) {
return 'youngAdult'; |
7e30fb3eacaf0ac4d467c2b4d3788cd3a9319000 | src/uiSelectMatchDirective.js | src/uiSelectMatchDirective.js | uis.directive('uiSelectMatch', ['uiSelectConfig', function(uiSelectConfig) {
return {
restrict: 'EA',
require: '^uiSelect',
replace: true,
transclude: true,
templateUrl: function(tElement) {
// Gets theme attribute from parent (ui-select)
var theme = tElement.parent().attr('theme') || uiSelectConfig.theme;
var multi = tElement.parent().attr('multiple');
return theme + (multi ? '/match-multiple.tpl.html' : '/match.tpl.html');
},
link: function(scope, element, attrs, $select) {
$select.lockChoiceExpression = attrs.uiLockChoice;
attrs.$observe('placeholder', function(placeholder) {
$select.placeholder = placeholder !== undefined ? placeholder : uiSelectConfig.placeholder;
});
function setAllowClear(allow)
{
$select.allowClear = (angular.isDefined(allow)) ? (allow === '') ? true : (allow.toLowerCase() === 'true') : false;
}
attrs.$observe('allowClear', setAllowClear);
setAllowClear(attrs.allowClear);
if($select.multiple){
$select.sizeSearchInput();
}
}
};
}]);
| uis.directive('uiSelectMatch', ['uiSelectConfig', function(uiSelectConfig) {
return {
restrict: 'EA',
require: '^uiSelect',
replace: true,
transclude: true,
templateUrl: function(tElement) {
// Gets theme attribute from parent (ui-select)
var theme = tElement.parent().attr('theme') || uiSelectConfig.theme;
var multi = tElement.parent().attr('multiple');
return theme + (multi ? '/match-multiple.tpl.html' : '/match.tpl.html');
},
link: function(scope, element, attrs, $select) {
$select.lockChoiceExpression = attrs.uiLockChoice;
attrs.$observe('placeholder', function(placeholder) {
$select.placeholder = placeholder !== undefined ? placeholder : uiSelectConfig.placeholder;
});
function setAllowClear(allow) {
$select.allowClear = (angular.isDefined(allow)) ? (allow === '') ? true : (allow.toLowerCase() === 'true') : false;
}
attrs.$observe('allowClear', setAllowClear);
setAllowClear(attrs.allowClear);
if($select.multiple){
$select.sizeSearchInput();
}
}
};
}]);
| Put bracket in wrong place | Put bracket in wrong place
| JavaScript | mit | exwar/ui-select,dimpu/ui-select,zamabraga/ui-select,arachnys/ui-select,sunshinemu/ui-select,viniciusdacal/ui-select,driver-by/ui-select,oncompass/ui-select,billypon/ui-select,WorktileTech/ui-select,colvir/ui-select,krotovic/ui-select,tommyp1ckles/ui-select,cbryer/ui-select,artemijan/ui-select,Vitaliy-Yarovuy/ui-select,Jobularity/ui-select,jlebit/ui-select,prakashn27/ui-select,panda-network/ui-select,hdngr/ui-select,mbajur/ui-select,romario333/ui-select,seegno-forks/ui-select,fcaballero/ui-select,tb/ui-select,leornado/ui-select-wnd,Servoy/ui-select,ralphite/ui-select,Crunch-io/ui-select,ivanvoznyakovsky/ui-select,ftferes/ui-select,ivanvoznyakovsky/ui-select,cbryer/ui-select,ChiDragon/ui-select,pra85/ui-select,varsitynewsnetwork/ui-select,nakedcreativity/ui-select,mattlucas121/ui-select,mattlucas121/ui-select,bunnyinc/ui-select,Vitaliy-Yarovuy/ui-select,leornado/ui-select-wnd,homerjam/ui-select,Vreasy/ui-select,cdjackson/ui-select,hobbesmedia/ui-select,exwar/ui-select,shabith/ui-select,vettery/ui-select-mirror,tommyp1ckles/ui-select,se3000/ui-select,piebe/ui-select,ConfidentCannabis/ui-select,Phalynx/ui-select,Jefiozie/ui-select,viniciusdacal/angular-select,seegno-forks/ui-select,viniciusdacal/ui-select,HourlyNerd/ui-select,zhaokunfay/ui-select,mattmcardle/ui-select,lukaw3d/ui-select,billypon/ui-select,angular-ui/ui-select,dmitry-polubentsev-cp/ui-select,videonote/ui-select,greus/ui-select,billypon/ui-select,iamsowmyan/ui-select,aszmyd/ui-select,zyncro/ui-select,dynamicaction/ui-select,panda-network/ui-select,dbmggithub/ui-select,Sjors/ui-select,MartinDeHaan/ui-select-submitform,ConfidentCannabis/ui-select,MartinDeHaan/ui-select-submitform,bobricca/ui-select,falcon1kr/ui-select,ChiDragon/ui-select,tomersimis/ui-select,littlebigbot/ui-select,falcon1kr/ui-select,gshireesh/ui-select,varsitynewsnetwork/ui-select,seedinvest/ui-select,m0ppers/ui-select,piebe/ui-select,Qmerce/ui-select,ivanvoznyakovsky/ui-select,MartinNuc/ui-select,WorktileTech/ui-select,Phalynx/ui-select,colvir/ui-select,ebergama/ui-select,xilix/ui-select,aszmyd/ui-select,allwebsites/ui-select,romario333/ui-select,looker/ui-select,Jobularity/ui-select,ConfidentCannabis/ui-select,homerjam/ui-select,allwebsites/ui-select,zyncro/ui-select,mattmcardle/ui-select,evillemez/ui-select,kentcooper/ui-select,arachnys/ui-select,noblecraft/ui-select,jlebit/ui-select,Polyconseil/ui-select,ralphite/ui-select,MNBuyskih/ui-select,Qmerce/ui-select,hobbesmedia/ui-select,gshireesh/ui-select,vettery/ui-select-mirror,MartinDeHaan/ui-select-submitform,90TechSAS/ui-select,mkoryak/ui-select,iOffice/ui-select,brianmcd/ui-select,mobiquity-networks/ui-select,Sjors/ui-select,kshutkin/ui-select,piebe/ui-select,dynamicaction/ui-select,D4H/ui-select,seedinvest/ui-select,ebergama/ui-select,prakashn27/ui-select,thesocialstation/ui-select,hightower/ui-select,dmitry-polubentsev-cp/ui-select,ravishivt/ui-select,Avien/multi-checkbox-select,dimpu/ui-select,Jobularity/ui-select,shabith/ui-select,dbmggithub/ui-select,WorktileTech/ui-select,angular-ui/ui-select,videonote/ui-select,hubba/ui-select,Polyconseil/ui-select,se3000/ui-select,fcaballero/ui-select,driver-by/ui-select,artemijan/ui-select,mbajur/ui-select,bigpandaio/ui-select,oncompass/ui-select,granteagon/ui-select-temp,prakashn27/ui-select,outbrain/ui-select,Jefiozie/ui-select,bigpandaio/ui-select,HourlyNerd/ui-select,slawekkolodziej/ui-select,zamabraga/ui-select,tomersimis/ui-select,ftferes/ui-select,Servoy/ui-select,codedogfish/angular-ui-select,90TechSAS/ui-select,Servoy/ui-select,kshutkin/ui-select,eugenehp/ui-select,xilix/ui-select,D4H/ui-select,iOffice/ui-select,littlebigbot/ui-select,hightower/ui-select,bobricca/ui-select,ravishivt/ui-select,thesocialstation/ui-select,mobiquity-networks/ui-select,oncompass/ui-select,MNBuyskih/ui-select,looker/ui-select,Crunch-io/ui-select,m0ppers/ui-select,lukaw3d/ui-select,evillemez/ui-select,karptonite/ui-select,greus/ui-select,karptonite/ui-select,eugenehp/ui-select,oslo10e/ui-select,zhaokunfay/ui-select,dynamicaction/ui-select,viniciusdacal/angular-select,outbrain/ui-select,pra85/ui-select,tb/ui-select,Jefiozie/ui-select,MartinNuc/ui-select,fcaballero/ui-select,UseFedora/ui-select,UseFedora/ui-select,codedogfish/angular-ui-select,Vreasy/ui-select,kentcooper/ui-select,Vreasy/ui-select,hdngr/ui-select,looker/ui-select,angular-ui/ui-select,granteagon/ui-select-temp,brianmcd/ui-select,noblecraft/ui-select,krotovic/ui-select,mkoryak/ui-select,hubba/ui-select,sunshinemu/ui-select,bunnyinc/ui-select,oslo10e/ui-select,iamsowmyan/ui-select,granteagon/ui-select-temp,slawekkolodziej/ui-select,Crunch-io/ui-select,cdjackson/ui-select,nakedcreativity/ui-select | ---
+++
@@ -16,8 +16,7 @@
$select.placeholder = placeholder !== undefined ? placeholder : uiSelectConfig.placeholder;
});
- function setAllowClear(allow)
- {
+ function setAllowClear(allow) {
$select.allowClear = (angular.isDefined(allow)) ? (allow === '') ? true : (allow.toLowerCase() === 'true') : false;
}
|
8700b2759f43ce9af9bcffcdc166f09e36cc51a1 | challengers.js | challengers.js | // Welcome!
// Add your github user if you accepted the challenge!
var players = [
'raphamorim',
'israelst',
'afonsopacifer',
'rafaelfragosom',
'brunokinoshita',
'paulinhoerry',
'enieber',
'alanrsoares'
];
module.exports = players;
| // Welcome!
// Add your github user if you accepted the challenge!
var players = [
'raphamorim',
'israelst',
'afonsopacifer',
'rafaelfragosom',
'brunokinoshita',
'paulinhoerry',
'enieber',
'alanrsoares',
'danilorb'
];
module.exports = players;
| Add user 'danilorb' as new challenger. | Add user 'danilorb' as new challenger.
| JavaScript | mit | arthurvasconcelos/write-code-every-day,rafael-neri/write-code-every-day,pablobfonseca/write-code-every-day,chocsx/write-code-every-day,ppamorim/write-code-every-day,letanloc/write-code-every-day,viniciusdacal/write-code-every-day,letanloc/write-code-every-day,arthurvasconcelos/write-code-every-day,gpedro/write-code-every-day,marabesi/write-code-every-day,jhonmike/write-code-every-day,guilouro/write-code-every-day,Rodrigo54/write-code-every-day,vitorleal/write-code-every-day,ppamorim/write-code-every-day,mauriciojunior/write-code-every-day,ogilvieira/write-code-every-day,gpedro/write-code-every-day,michelwilhelm/write-code-every-day,welksonramos/write-code-every-day,willianjusten/write-code-every-day,jackmakiyama/write-code-every-day,jhonmike/write-code-every-day,marabesi/write-code-every-day,viniciusdacal/write-code-every-day,rafaelfragosom/write-code-every-day,rafaelfragosom/write-code-every-day,raphamorim/write-code-every-day,jozadaquebatista/write-code-every-day,AgtLucas/write-code-every-day,joselitojunior/write-code-every-day,jackmakiyama/write-code-every-day,rafaelstz/write-code-every-day,rafael-neri/write-code-every-day,vitorleal/write-code-every-day,Pompeu/write-code-every-day,AbraaoAlves/write-code-every-day,raphamorim/write-code-every-day,edueo/write-code-every-day,vinimdocarmo/write-code-every-day,hocraveiro/write-code-every-day,AbraaoAlves/write-code-every-day,beni55/write-code-every-day,raphamorim/write-code-every-day,guidiego/write-code-every-day,pablobfonseca/write-code-every-day,fdaciuk/write-code-every-day,fredericksilva/write-code-every-day,ogilvieira/write-code-every-day,chocsx/write-code-every-day,fdaciuk/write-code-every-day,beni55/write-code-every-day,AgtLucas/write-code-every-day,Gcampes/write-code-every-day,andersonweb/write-code-every-day,hocraveiro/write-code-every-day,rtancman/write-code-every-day,Gcampes/write-code-every-day,guilouro/write-code-every-day,michelwilhelm/write-code-every-day,diegosaraujo/write-code-every-day,mabrasil/write-code-every-day,diegosaraujo/write-code-every-day,edueo/write-code-every-day,guidiego/write-code-every-day,arthurvasconcelos/write-code-every-day,Rodrigo54/write-code-every-day,mauriciojunior/write-code-every-day,vinimdocarmo/write-code-every-day,rtancman/write-code-every-day,fredericksilva/write-code-every-day,rafaelstz/write-code-every-day,andersonweb/write-code-every-day,jozadaquebatista/write-code-every-day,joselitojunior/write-code-every-day,welksonramos/write-code-every-day,Pompeu/write-code-every-day,cesardeazevedo/write-code-every-day,pablobfonseca/write-code-every-day,willianjusten/write-code-every-day,mabrasil/write-code-every-day,cesardeazevedo/write-code-every-day | ---
+++
@@ -9,7 +9,8 @@
'brunokinoshita',
'paulinhoerry',
'enieber',
- 'alanrsoares'
+ 'alanrsoares',
+ 'danilorb'
];
module.exports = players; |
d311883f3607cc560355d673e706af73e3033198 | lib/cfs/images.js | lib/cfs/images.js | // Read AWS config from orion. Orion ensures these are only available on the server.
var awsConfig = {
accessKeyId: orion.config.get('AWS_API_KEY'),
secretAccessKey: orion.config.get('AWS_API_SECRET'),
bucket: orion.config.get('AWS_S3_BUCKET')
};
var imagesOriginalsStore = new FS.Store.S3("originals",
_.extend({
folder: 'images/originals'
}, awsConfig)
);
var imagesThumbnailsStore = new FS.Store.S3("thumbnails",
_.extend({
folder: 'images/thumbnails',
transformWrite: function(fileObj, readStream, writeStream) {
gm(readStream, fileObj.name()).resize(null, 100).stream().pipe(writeStream);
}
}, awsConfig)
);
Images = new FS.Collection("images", {
stores: [imagesOriginalsStore, imagesThumbnailsStore],
filter: {
allow: {
contentTypes: ['image/*']
}
}
});
Images.allow({
download: function() {
return true; // All images are public
},
insert: function() {
return true; // All users can upload new images
},
update: function(userId, doc) {
// TODO Only the owner of the image should be allowed to update. Unfortunately, meteor-autoform-file does not currently let us add the owner metadata easily when uploading the file
return true;
}
});
| // Read AWS config from orion. Orion ensures these are only available on the server.
var awsConfig = {
accessKeyId: orion.config.get('AWS_API_KEY'),
secretAccessKey: orion.config.get('AWS_API_SECRET'),
bucket: orion.config.get('AWS_S3_BUCKET') || 'geomakers.org-user-files'
};
var imagesOriginalsStore = new FS.Store.S3("originals",
_.extend({
folder: 'images/originals'
}, awsConfig)
);
var imagesThumbnailsStore = new FS.Store.S3("thumbnails",
_.extend({
folder: 'images/thumbnails',
transformWrite: function(fileObj, readStream, writeStream) {
gm(readStream, fileObj.name()).resize(null, 100).stream().pipe(writeStream);
}
}, awsConfig)
);
Images = new FS.Collection("images", {
stores: [imagesOriginalsStore, imagesThumbnailsStore],
filter: {
allow: {
contentTypes: ['image/*']
}
}
});
Images.allow({
download: function() {
return true; // All images are public
},
insert: function() {
return true; // All users can upload new images
},
update: function(userId, doc) {
// TODO Only the owner of the image should be allowed to update. Unfortunately, meteor-autoform-file does not currently let us add the owner metadata easily when uploading the file
return true;
}
});
| Add fallback value for bucket | Add fallback value for bucket
Otherwise, we cannot get to the orion configuration page in a newly
deployed app (because FS.Store will crash without the bucket specified).
| JavaScript | apache-2.0 | GeoMakers/geomakers.org,GeoMakers/geomakers.org | ---
+++
@@ -2,7 +2,7 @@
var awsConfig = {
accessKeyId: orion.config.get('AWS_API_KEY'),
secretAccessKey: orion.config.get('AWS_API_SECRET'),
- bucket: orion.config.get('AWS_S3_BUCKET')
+ bucket: orion.config.get('AWS_S3_BUCKET') || 'geomakers.org-user-files'
};
var imagesOriginalsStore = new FS.Store.S3("originals", |
5a6be2217aeede1ab994f477090d1a54c0d12be4 | logglyMeteorMethods.js | logglyMeteorMethods.js | /***
* loggerSet - checks to see if the Logger object has been created on server
* @returns {boolean} - return true if the Logger object has been created on server
*/
var loggerSet = function () {
if (typeof Logger !== 'undefined' && Logger !== null) {
return true;
}
console.log('Logger object was not created on the Meteor Server');
return false;
};
Meteor.methods({
logglyLog: function(param, tag) {
if (loggerSet()){
Logger.log(param, tag);
}
},
logglyTrace: function(param, tag) {
if (loggerSet()){
Logger.trace(param, tag);
}
},
logglyInfo: function(param, tag) {
if (loggerSet()){
Logger.info(param, tag);
}
},
logglyWarn: function(param, tag) {
if (loggerSet()){
Logger.warn(param, tag);
}
},
logglyError: function(param, tag) {
if (loggerSet()) {
Logger.error(param, tag);
}
}
});
| /***
* loggerSet - checks to see if the Logger object has been created on server
* @returns {boolean} - return true if the Logger object has been created on server
*/
var loggerSet = function () {
if (typeof Logger !== 'undefined' && Logger !== null) {
return true;
}
console.log('Logger object was not created on the Meteor Server');
return false;
};
Meteor.methods({
logglyLog: function(param, tag) {
check(param,Object);
check(tag,Match.Optional([String]));
if (loggerSet()){
Logger.log(param, tag);
}
},
logglyTrace: function(param, tag) {
check(param,Object);
check(tag,Match.Optional([String]));
if (loggerSet()){
Logger.trace(param, tag);
}
},
logglyInfo: function(param, tag) {
check(param,Object);
check(tag,Match.Optional([String]));
if (loggerSet()){
Logger.info(param, tag);
}
},
logglyWarn: function(param, tag) {
check(param,Object);
check(tag,Match.Optional([String]));
if (loggerSet()){
Logger.warn(param, tag);
}
},
logglyError: function(param, tag) {
check(param,Object);
check(tag,Match.Optional([String]));
if (loggerSet()) {
Logger.error(param, tag);
}
}
});
| Use match() in meteor methods to be able to use the "audit-argument-checks" MDG package | Use match() in meteor methods to be able to use the "audit-argument-checks" MDG package
| JavaScript | mit | miktam/loggly,avrora/loggly | ---
+++
@@ -12,26 +12,41 @@
Meteor.methods({
logglyLog: function(param, tag) {
+ check(param,Object);
+ check(tag,Match.Optional([String]));
+
if (loggerSet()){
Logger.log(param, tag);
}
},
logglyTrace: function(param, tag) {
+ check(param,Object);
+ check(tag,Match.Optional([String]));
+
if (loggerSet()){
Logger.trace(param, tag);
}
},
logglyInfo: function(param, tag) {
+ check(param,Object);
+ check(tag,Match.Optional([String]));
+
if (loggerSet()){
Logger.info(param, tag);
}
},
logglyWarn: function(param, tag) {
+ check(param,Object);
+ check(tag,Match.Optional([String]));
+
if (loggerSet()){
Logger.warn(param, tag);
}
},
logglyError: function(param, tag) {
+ check(param,Object);
+ check(tag,Match.Optional([String]));
+
if (loggerSet()) {
Logger.error(param, tag);
} |
7a23fa571854fa6c1e7e7dc7fdfddeafa9759d58 | client/main.js | client/main.js | var Karma = require('./karma');
var StatusUpdater = require('./updater');
var util = require('./util');
var KARMA_URL_ROOT = require('./constants').KARMA_URL_ROOT;
// Connect to the server using socket.io http://socket.io
var socket = io(location.protocol + location.host, {
reconnectionDelay: 500,
reconnectionDelayMax: Infinity,
timeout: 2000,
path: '/' + KARMA_URL_ROOT.substr(1) + 'socket.io',
'sync disconnect on unload': true
});
// instantiate the updater of the view
new StatusUpdater(socket, util.elm('title'), util.elm('banner'), util.elm('browsers'));
window.karma = new Karma(socket, util.elm('context'), window.open,
window.navigator, window.location);
| var Karma = require('./karma');
var StatusUpdater = require('./updater');
var util = require('./util');
var KARMA_URL_ROOT = require('./constants').KARMA_URL_ROOT;
// Connect to the server using socket.io http://socket.io
var socket = io(location.host, {
reconnectionDelay: 500,
reconnectionDelayMax: Infinity,
timeout: 2000,
path: '/' + KARMA_URL_ROOT.substr(1) + 'socket.io',
'sync disconnect on unload': true
});
// instantiate the updater of the view
new StatusUpdater(socket, util.elm('title'), util.elm('banner'), util.elm('browsers'));
window.karma = new Karma(socket, util.elm('context'), window.open,
window.navigator, window.location);
| Update location detection for socket.io | fix(client): Update location detection for socket.io
| JavaScript | mit | gayancliyanage/karma,tomkuk/karma,johnjbarton/karma,simudream/karma,mprobst/karma,jjoos/karma,mprobst/karma,skycocker/karma,harme199497/karma,karma-runner/karma,marthinus-engelbrecht/karma,jjoos/karma,clbond/karma,powerkid/karma,Dignifiedquire/karma,brianmhunt/karma,brianmhunt/karma,wesleycho/karma,aiboy/karma,rhlass/karma,SamuelMarks/karma,kahwee/karma,brianmhunt/karma,codedogfish/karma,tomkuk/karma,maksimr/karma,simudream/karma,oyiptong/karma,pedrotcaraujo/karma,karma-runner/karma,vtsvang/karma,rhlass/karma,SamuelMarks/karma,harme199497/karma,vtsvang/karma,patrickporto/karma,IsaacChapman/karma,codedogfish/karma,pedrotcaraujo/karma,pmq20/karma,timebackzhou/karma,shirish87/karma,tomkuk/karma,jjoos/karma,SamuelMarks/karma,codedogfish/karma,vtsvang/karma,Klaudit/karma,youprofit/karma,powerkid/karma,shirish87/karma,shirish87/karma,kahwee/karma,youprofit/karma,codedogfish/karma,kahwee/karma,ernsheong/karma,buley/karma,xiaoking/karma,clbond/karma,IveWong/karma,brianmhunt/karma,astorije/karma,marthinus-engelbrecht/karma,aiboy/karma,IveWong/karma,gayancliyanage/karma,david-garcia-nete/karma,skycocker/karma,IsaacChapman/karma,david-garcia-nete/karma,panrafal/karma,clbond/karma,harme199497/karma,unional/karma,ernsheong/karma,youprofit/karma,powerkid/karma,mprobst/karma,patrickporto/karma,aiboy/karma,unional/karma,maksimr/karma,johnjbarton/karma,KrekkieD/karma,panrafal/karma,stevemao/karma,johnjbarton/karma,skycocker/karma,pedrotcaraujo/karma,KrekkieD/karma,marthinus-engelbrecht/karma,KrekkieD/karma,panrafal/karma,hitesh97/karma,aiboy/karma,karma-runner/karma,chrisirhc/karma,simudream/karma,stevemao/karma,stevemao/karma,patrickporto/karma,Sanjo/karma,rhlass/karma,karma-runner/karma,timebackzhou/karma,buley/karma,oyiptong/karma,tomkuk/karma,buley/karma,unional/karma,skycocker/karma,powerkid/karma,pmq20/karma,harme199497/karma,hitesh97/karma,kahwee/karma,hitesh97/karma,oyiptong/karma,chrisirhc/karma,pedrotcaraujo/karma,gayancliyanage/karma,Dignifiedquire/karma,simudream/karma,johnjbarton/karma,wesleycho/karma,timebackzhou/karma,gayancliyanage/karma,astorije/karma,ernsheong/karma,IsaacChapman/karma,Klaudit/karma,pmq20/karma,jamestalmage/karma,xiaoking/karma,marthinus-engelbrecht/karma,KrekkieD/karma,IsaacChapman/karma,vtsvang/karma,david-garcia-nete/karma,chrisirhc/karma,youprofit/karma,wesleycho/karma,Dignifiedquire/karma,IveWong/karma,Sanjo/karma,clbond/karma,patrickporto/karma,hitesh97/karma,jamestalmage/karma,timebackzhou/karma,Sanjo/karma,IveWong/karma,oyiptong/karma,buley/karma,Klaudit/karma,Dignifiedquire/karma,maksimr/karma,stevemao/karma,xiaoking/karma,wesleycho/karma,pmq20/karma,Sanjo/karma,Klaudit/karma,unional/karma,chrisirhc/karma,jjoos/karma,jamestalmage/karma,jamestalmage/karma,xiaoking/karma,rhlass/karma,astorije/karma,astorije/karma | ---
+++
@@ -6,7 +6,7 @@
// Connect to the server using socket.io http://socket.io
-var socket = io(location.protocol + location.host, {
+var socket = io(location.host, {
reconnectionDelay: 500,
reconnectionDelayMax: Infinity,
timeout: 2000, |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.