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 |
|---|---|---|---|---|---|---|---|---|---|---|
e8decae34ae5d07fdeecfd55f60f3d010c97cc10 | index.js | index.js | 'use strict'
module.exports = trimTrailingLines
var line = '\n'
// Remove final newline characters from `value`.
function trimTrailingLines(value) {
var string = String(value)
var index = string.length
while (string.charAt(--index) === line) {
// Empty
}
return string.slice(0, index + 1)
}
| 'use strict'
module.exports = trimTrailingLines
// Remove final newline characters from `value`.
function trimTrailingLines(value) {
return String(value).replace(/\n+$/, '')
}
| Refactor code to improve bundle size | Refactor code to improve bundle size
| JavaScript | mit | wooorm/trim-trailing-lines | ---
+++
@@ -2,16 +2,7 @@
module.exports = trimTrailingLines
-var line = '\n'
-
// Remove final newline characters from `value`.
function trimTrailingLines(value) {
- var string = String(value)
- var index = string.length
-
- while (string.charAt(--index) === line) {
- // Empty
- }
-
- return string.slice(0, index + 1)
+ return String(value).replace(/\n+$/, '')
} |
a6edc68779d82e7193360d321ebdc97307e5c59f | index.js | index.js | 'use strict'
const _ = require('lodash')
const Promise = require('bluebird')
const arr = []
module.exports = function loadAllPages (callFx, opts) {
opts['page'] = opts.page || 1
return Promise
.resolve(callFx(opts))
.then((result) => {
arr.push(result)
if (_.isFunction(result.nextPage)) {
opts.page = opts.page + 1
return loadAllPages(callFx, opts)
} else {
return Promise.resolve(_.flatten(arr))
}
}).catch((err) => {
if (err) {
console.log('Failed to depaginate\n', err)
}
})
}
| 'use strict'
const _ = require('lodash')
const Promise = require('bluebird')
var arr = []
module.exports = function loadAllPages (callFx, opts) {
opts['page'] = opts.page || 1
return Promise
.resolve(callFx(opts))
.then((result) => {
arr.push(result)
if (_.isFunction(result.nextPage)) {
opts.page = opts.page + 1
return loadAllPages(callFx, opts)
} else {
var newArr = arr
arr = []
return _.flatten(newArr)
}
}).catch((err) => {
if (err) {
console.log('Failed to depaginate\n', err)
}
})
}
| Reset array after each use | Reset array after each use
| JavaScript | mit | RichardLitt/depaginate | ---
+++
@@ -1,7 +1,7 @@
'use strict'
const _ = require('lodash')
const Promise = require('bluebird')
-const arr = []
+var arr = []
module.exports = function loadAllPages (callFx, opts) {
opts['page'] = opts.page || 1
@@ -14,11 +14,13 @@
opts.page = opts.page + 1
return loadAllPages(callFx, opts)
} else {
- return Promise.resolve(_.flatten(arr))
+ var newArr = arr
+ arr = []
+ return _.flatten(newArr)
}
}).catch((err) => {
if (err) {
console.log('Failed to depaginate\n', err)
}
- })
+ })
} |
a76d316430fd9f95d9eaee90915a25a7b2ec582a | index.js | index.js | 'use strict';
var yargs = require('yargs');
var uploader = require('./lib/uploader');
var version = require('./package.json').version;
var argv = yargs
.usage('$0 [options] <directory>')
.demand(1, 1)
.option('api-key', {
demand: true,
describe: 'Cloudinary API key',
type: 'string',
nargs: 1
})
.option('api-secret', {
demand: true,
describe: 'Cloudinary API secret',
type: 'string',
nargs: 1
})
.option('cloud-name', {
demand: true,
describe: 'Cloudinary cloud name',
type: 'string',
nargs: 1
})
.help('h')
.alias('h', 'help')
.example('$0 --api-key 12345 --api-secret somesecret --cloud-name name ~/pics',
'Upload all images under ~/pics directory to Cloudinary')
.argv;
uploader.config({
apiKey: argv.apiKey,
apiSecret: argv.apiSecret,
cloudName: argv.cloudName
});
function logError(e) {
if (e instanceof Error) {
return e.stack;
}
return JSON.stringify(e);
}
var imagesDir = argv._[0];
uploader.uploadImages(imagesDir, function (err, result) {
if (err) {
console.error(logError(err));
} else {
console.log(result);
}
});
| 'use strict';
var yargs = require('yargs');
var uploader = require('./lib/uploader');
var version = require('./package.json').version;
var argv = yargs
.usage('$0 [options] <directory>')
.demand(1, 1)
.option('api-key', {
demand: true,
describe: 'Cloudinary API key',
type: 'string',
nargs: 1
})
.option('api-secret', {
demand: true,
describe: 'Cloudinary API secret',
type: 'string',
nargs: 1
})
.option('cloud-name', {
demand: true,
describe: 'Cloudinary cloud name',
type: 'string',
nargs: 1
})
.help('h')
.alias('h', 'help')
.example('$0 --api-key 12345 --api-secret somesecret --cloud-name name ~/pics',
'Upload all images under ~/pics directory to Cloudinary')
.version(version)
.argv;
uploader.config({
apiKey: argv.apiKey,
apiSecret: argv.apiSecret,
cloudName: argv.cloudName
});
function logError(e) {
if (e instanceof Error) {
return e.stack;
}
return JSON.stringify(e);
}
var imagesDir = argv._[0];
uploader.uploadImages(imagesDir, function (err, result) {
if (err) {
console.error(logError(err));
} else {
console.log(result);
}
});
| Add option to print version | Add option to print version
| JavaScript | mit | kemskems/cloudinary-cli-upload | ---
+++
@@ -31,6 +31,7 @@
.alias('h', 'help')
.example('$0 --api-key 12345 --api-secret somesecret --cloud-name name ~/pics',
'Upload all images under ~/pics directory to Cloudinary')
+ .version(version)
.argv;
uploader.config({ |
43364f8b042a3bc6b1b03f55a65fc670ae7efd2e | index.js | index.js | var postcss = require('postcss');
module.exports = postcss.plugin('postcss-property-lookup', propertyLookup);
function propertyLookup() {
return function(css, result) {
css.eachRule(function(rule) {
rule.replaceValues(/@([a-z-]+)(\s?)/g, { fast: '@' }, function(orig, prop, space) {
var replacementVal;
rule.eachDecl(prop, function(decl) {
replacementVal = decl.value;
});
if (replacementVal) {
return replacementVal + space;
} else {
result.warn('Unable to find property ' + orig, { node: rule });
return '';
}
});
});
};
}
| var postcss = require('postcss');
module.exports = postcss.plugin('postcss-property-lookup', propertyLookup);
function propertyLookup() {
return function(css, result) {
css.eachRule(function(rule) {
rule.replaceValues(/@([a-z-]+)(\s?)/g, { fast: '@' }, function(orig, prop, space) {
var replacementVal;
rule.eachDecl(prop, function(decl) {
replacementVal = decl.value;
});
if (replacementVal) {
return replacementVal + space;
} else {
result.warn('Unable to find property ' + orig + ' in ' + rule.selector, { node: rule });
return '';
}
});
});
};
}
| Add rule selector to console warning | Add rule selector to console warning
| JavaScript | mit | jedmao/postcss-property-lookup,simonsmith/postcss-property-lookup | ---
+++
@@ -14,7 +14,7 @@
if (replacementVal) {
return replacementVal + space;
} else {
- result.warn('Unable to find property ' + orig, { node: rule });
+ result.warn('Unable to find property ' + orig + ' in ' + rule.selector, { node: rule });
return '';
}
}); |
40e92a2240c7d764dd430ccd64cb6eaff3b5879b | lib/define.js | lib/define.js |
/*jslint browser:true, node:true*/
'use strict';
/**
* Module Dependencies
*/
var View = require('./view');
var store = require('./store');
/**
* Creates and registers a
* FruitMachine view constructor.
*
* @param {Object|View}
* @return {View}
*/
module.exports = function(props) {
var module = props.module || 'undefined';
var view;
// Remove the module key
delete props.module;
props._module = module;
// If an existing FruitMachine.View
// has been passed in, use that.
// If just an object literal has
// been passed in then we extend the
// default FruitMachine.View prototype
// with the properties passed in.
view = (props.__super__)
? props
: View.extend(props);
// Store the module by module type
// so that module can be referred to
// by just a string in layout definitions
return store.modules[module] = view;
};
/**
* Removes a module
* from the module store.
*
* If no module key is passed
* the entire store is cleared.
*
* @param {String|undefined} module
* @api public
*/
module.exports.clear = function(module) {
if (module) delete store.modules[module];
else store.modules = {};
}; |
/*jslint browser:true, node:true*/
'use strict';
/**
* Module Dependencies
*/
var View = require('./view');
var store = require('./store');
/**
* Creates and registers a
* FruitMachine view constructor.
*
* @param {Object|View}
* @return {View}
*/
module.exports = function(props) {
var module = props.module || 'undefined';
var view;
// Move the module key
delete props.module;
props._module = module;
// If an existing FruitMachine.View
// has been passed in, use that.
// If just an object literal has
// been passed in then we extend the
// default FruitMachine.View prototype
// with the properties passed in.
view = (props.__super__)
? props
: View.extend(props);
// Store the module by module type
// so that module can be referred to
// by just a string in layout definitions
return store.modules[module] = view;
}; | Remove API to clear stored modules | Remove API to clear stored modules
| JavaScript | mit | quarterto/fruitmachine,quarterto/fruitmachine,ftlabs/fruitmachine | ---
+++
@@ -6,7 +6,6 @@
/**
* Module Dependencies
*/
-
var View = require('./view');
var store = require('./store');
@@ -22,7 +21,7 @@
var module = props.module || 'undefined';
var view;
- // Remove the module key
+ // Move the module key
delete props.module;
props._module = module;
@@ -41,18 +40,3 @@
// by just a string in layout definitions
return store.modules[module] = view;
};
-
-/**
- * Removes a module
- * from the module store.
- *
- * If no module key is passed
- * the entire store is cleared.
- *
- * @param {String|undefined} module
- * @api public
- */
-module.exports.clear = function(module) {
- if (module) delete store.modules[module];
- else store.modules = {};
-}; |
9a7ce192e5e13c34c6bdf97b5ac4123071978fdb | desktop/src/Settings/SettingsContainer.js | desktop/src/Settings/SettingsContainer.js | import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import * as actionCreators from './actionCreators';
import Settings from './Settings';
const mapStateToProps = state => ({
fullscreen: state.appProperties.fullscreen,
showNotYetTasks: state.appProperties.showNotYetTasks,
calendarSystem: state.appProperties.calendarSystem,
});
const mapDispatchToProps = dispatch => bindActionCreators(actionCreators, dispatch);
const SettingsContainer = connect(mapStateToProps, mapDispatchToProps)(Settings);
export default SettingsContainer;
| import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import * as actionCreators from './actionCreators';
import Settings from './Settings';
const mapStateToProps = state => ({
fullscreen: state.appProperties.fullscreen,
showNotYetTasks: state.appProperties.showNotYetTasks,
calendarSystem: state.appProperties.calendarSystem,
firstDayOfWeek: state.appProperties.firstDayOfWeek,
});
const mapDispatchToProps = dispatch => bindActionCreators(actionCreators, dispatch);
const SettingsContainer = connect(mapStateToProps, mapDispatchToProps)(Settings);
export default SettingsContainer;
| Add firstDayOfWeek to Settings mapped props | Add firstDayOfWeek to Settings mapped props
| JavaScript | mit | mkermani144/wanna,mkermani144/wanna | ---
+++
@@ -8,6 +8,7 @@
fullscreen: state.appProperties.fullscreen,
showNotYetTasks: state.appProperties.showNotYetTasks,
calendarSystem: state.appProperties.calendarSystem,
+ firstDayOfWeek: state.appProperties.firstDayOfWeek,
});
const mapDispatchToProps = dispatch => bindActionCreators(actionCreators, dispatch); |
164bcc02f7ebf73fe99e7ecb1d6d0b158cd5965c | test/logger.js | test/logger.js | 'use strict';
// logger.js tests
const chai = require('chai');
const expect = chai.expect;
const chalk = require('chalk');
const Logger = require('../lib/logger');
// Init logger
const logger = new Logger();
// Tests
describe('logger.js tests', () => {
it('should check if logger._getdate() works', (done) => {
// Date to help with checking
const date = new Date();
// Test
expect(logger._getdate()).to.equal(chalk.grey(`${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`));
done();
});
it('should check if logger.info() works', (done) => {
// Date to help with checking
const date = new Date();
// Pipe console.log
old = console.log;
console.log = (txt) => {
const str = chalk.green.bold('INFO');
expect(txt).to.equal(`[ ${logger._getdate()} ${str} ] test`);
};
// Test
logger.info('test');
// Reset
console.log = old;
done();
});
});
| 'use strict';
// logger.js tests
const chai = require('chai');
const expect = chai.expect;
const chalk = require('chalk');
const Logger = require('../lib/logger');
// Init logger
const logger = new Logger();
// Tests
describe('logger.js tests', () => {
it('should check if logger._getdate() works', (done) => {
// Date to help with checking
const date = new Date();
// Test
expect(logger._getdate()).to.equal(chalk.grey(`${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`));
done();
});
it('should check if logger.info() works', (done) => {
// Date to help with checking
const date = new Date();
// Patch console.log
const old = console.log;
console.log = (txt) => {
const str = chalk.green.bold('INFO');
expect(txt).to.equal(`[ ${logger._getdate()} ${str} ] test`);
};
// Test
logger.info('test');
// Reset
console.log = old;
done();
});
});
| Fix issue in tests where old was not defined | :bug: Fix issue in tests where old was not defined
| JavaScript | mit | Gum-Joe/bedel,Gum-Joe/bedel,Gum-Joe/bedel,Gum-Joe/bedel | ---
+++
@@ -21,8 +21,8 @@
it('should check if logger.info() works', (done) => {
// Date to help with checking
const date = new Date();
- // Pipe console.log
- old = console.log;
+ // Patch console.log
+ const old = console.log;
console.log = (txt) => {
const str = chalk.green.bold('INFO');
expect(txt).to.equal(`[ ${logger._getdate()} ${str} ] test`); |
f3dc47b0a0e7f606aceeceb263c3c15872cb7ab5 | lib/gitlab.js | lib/gitlab.js | import _ from 'underscore'
import sendMessage from './sendMessage'
import sendResultBy from './sendResultBy'
import sendIgnore from './sendIgnore'
import debug from 'debug'
export default function(req, res, next) {
let result = sendResultBy(res)
debug('request')(req.body)
if (_.isString(req.objectKind)) {
sendMessage(req.objectKind, result, req.params, req.body)
} else {
sendIgnore(req.objectKind, result)
}
}
| import _ from 'underscore'
import sendMessage from './sendMessage'
import sendResultBy from './sendResultBy'
import sendIgnore from './sendIgnore'
import debug from 'debug'
export default function(req, res, next) {
let result = sendResultBy(res)
debug('request')(JSON.stringify(req.body, null, 2))
if (_.isString(req.objectKind)) {
sendMessage(req.objectKind, result, req.params, req.body)
} else {
sendIgnore(req.objectKind, result)
}
}
| Format son in the debug print. | Format son in the debug print.
| JavaScript | mit | luxiar/syamo,luxiar/syamo,ledsun/syamo,ledsun/syamo | ---
+++
@@ -7,7 +7,7 @@
export default function(req, res, next) {
let result = sendResultBy(res)
- debug('request')(req.body)
+ debug('request')(JSON.stringify(req.body, null, 2))
if (_.isString(req.objectKind)) {
sendMessage(req.objectKind, result, req.params, req.body) |
59a6fcf57baedffd5d88042f4f3b0caa7b54ee82 | static/scripts/views/event/creation.js | static/scripts/views/event/creation.js | define(['backbone', 'marionette'], function(Backbone, Marionette) {
return Backbone.View.extend({
template: '#event-creation',
events: {
'click button.create-event': 'create_event'
},
initialize: function() {},
render: function() {
var rendered_template = _.template($(this.template).html())();
this.$el.empty();
this.$el.append(rendered_template);
return this;
},
create_event: function(e) {
e.preventDefault();
var title = this.$el.find('.event-title').val();
var description = this.$el.find('.event-description').val();
this.$el.html($('#loading').html());
this.collection.create({
title: title,
description: description
}, {
wait: true,
success: function (model, response, options) {
this.render();
}.bind(this),
error: function (model, xhr, options) {
}
});
}
});
});
| define(['backbone', 'marionette'], function(Backbone, Marionette) {
return Backbone.View.extend({
template: '#event-creation',
events: {
'click button.create-event': 'create_event'
},
initialize: function() {},
render: function() {
var rendered_template = _.template($(this.template).html())();
this.$el.empty();
this.$el.append(rendered_template);
return this;
},
create_event: function(e) {
e.preventDefault();
var title = this.$el.find('.event-title').val();
var description = this.$el.find('.event-description').val();
this.$el.html($('#loading').html());
this.collection.create({
title: title,
description: description,
date: Date.now()
}, {
wait: true,
success: function (model, response, options) {
this.render();
console.log(this.collection.models);
}.bind(this),
error: function (model, xhr, options) {
console.log('ERROR!');
this.render();
}
});
}
});
});
| Set date when creating event, not when it's require'd | Set date when creating event, not when it's require'd
| JavaScript | mit | amackera/stratus | ---
+++
@@ -22,14 +22,17 @@
this.$el.html($('#loading').html());
this.collection.create({
title: title,
- description: description
+ description: description,
+ date: Date.now()
}, {
wait: true,
success: function (model, response, options) {
this.render();
+ console.log(this.collection.models);
}.bind(this),
error: function (model, xhr, options) {
-
+ console.log('ERROR!');
+ this.render();
}
});
} |
7a5a493bb83d3f6c75ec870e29f79e94a09dd479 | src/js/SimpleTourItem.js | src/js/SimpleTourItem.js | import React from 'react';
class SimpleTourItem extends React.Component {
render() {
const containerStyle = {
background: 'white',
padding: '20px',
color: 'black',
maxWidth: '300px'
};
const buttonStyle = {
cursor: 'pointer',
textDecoration: 'none',
color: '#3498db',
margin: '12px'
};
return (
<div style={containerStyle}>
<p>{this.props.message}</p>
<span
className='simple-tour-item-button'
style={buttonStyle}
onClick={this.props.onSkip}>
Skip
</span>
<span
className='simple-tour-item-button'
style={buttonStyle}
onClick={this.props.onDone}>
Close
</span>
</div>
);
}
}
SimpleTourItem.propTypes = {
message: React.PropTypes.string,
onSkip: React.PropTypes.func,
onDone: React.PropTypes.func
};
export default SimpleTourItem;
| import React from 'react';
class SimpleTourItem extends React.Component {
render() {
const containerStyle = {
background: 'white',
padding: '20px',
color: 'black',
maxWidth: '300px'
};
const buttonStyle = {
cursor: 'pointer',
textDecoration: 'none',
color: '#3498db',
margin: '12px'
};
return (
<div style={containerStyle}>
<p>{this.props.message}</p>
<span
className='simple-tour-item-button'
style={buttonStyle}
onClick={this.props.onSkip}>
Skip
</span>
<span
className='simple-tour-item-button'
style={buttonStyle}
onClick={this.props.onDone}>
Next
</span>
</div>
);
}
}
SimpleTourItem.propTypes = {
message: React.PropTypes.string,
onSkip: React.PropTypes.func,
onDone: React.PropTypes.func
};
export default SimpleTourItem;
| Change word from Done to Next | Change word from Done to Next
| JavaScript | mit | khankuan/react-tourist,khankuan/react-tourist | ---
+++
@@ -33,7 +33,7 @@
className='simple-tour-item-button'
style={buttonStyle}
onClick={this.props.onDone}>
- Close
+ Next
</span>
</div> |
d1ca08ada6e949b9fb0c052b8f9a3056da8065a0 | source/loosely-matches.js | source/loosely-matches.js | "use strict";
const flow = require("lodash.flow");
const deburr = require("lodash.deburr");
const toLower = require("lodash.tolower");
const looseMatchTransform = flow(deburr, toLower);
/**
* Function that returns true when `needle` is found in `haystack`.
* The main advantages of this function are that it removes accented characters and that
* it is case-insensitive.
*
* Powered by lodash's {@link https://lodash.com/docs/#deburr deburr}
*
* @function looselyMatches
*
* @param haystack {String} The string to inspect.
* @param needle {String} The substring to look for.
*
* @return {Boolean} True when variations of `needle` can be found inside `haystack`.
*/
module.exports = (haystack, needle) => {
return looseMatchTransform(haystack).indexOf(looseMatchTransform(needle)) !== -1;
};
| "use strict";
const flow = require("lodash.flow");
const deburr = require("lodash.deburr");
const toLower = require("lodash.tolower");
const looseMatchTransform = flow(deburr, toLower);
/**
* Function that returns true when `needle` is found in `haystack`.
* The main advantages of this function are that it removes accented characters and that
* it is case-insensitive.
*
* Powered by lodash's {@link https://lodash.com/docs/#deburr deburr}.
*
* @function looselyMatches
*
* @param haystack {String} The string to inspect.
* @param needle {String} The substring to look for.
*
* @return {Boolean} True when variations of `needle` can be found inside `haystack`.
*/
module.exports = (haystack, needle) => {
return looseMatchTransform(haystack).indexOf(looseMatchTransform(needle)) !== -1;
};
| Add terminal . at end of sentence in looselyMatches documentation string | Add terminal . at end of sentence in looselyMatches documentation string
| JavaScript | mit | tentwentyfour/helpbox | ---
+++
@@ -11,7 +11,7 @@
* The main advantages of this function are that it removes accented characters and that
* it is case-insensitive.
*
- * Powered by lodash's {@link https://lodash.com/docs/#deburr deburr}
+ * Powered by lodash's {@link https://lodash.com/docs/#deburr deburr}.
*
* @function looselyMatches
* |
52b58f48625f7a54f4e342e263b865747137dcfa | src/Middleware/MiddlewareStack.js | src/Middleware/MiddlewareStack.js | export default class MiddlewareStack {
constructor(handler, stack = []) {
this._handler = handler;
this._stack = stack.map(element => (typeof element === 'function' ? new element() : element));
this._regenerateMiddlewareProcess();
}
push(middleware) {
this._stack.push(middleware);
this._regenerateMiddlewareProcess();
}
pop() {
return this._stack.pop();
}
process(...data) {
return this._middlewareProcess(...data);
}
_generateMiddlewareProcess(action) {
return this._stack.reduceRight(
(previous, current) => (...data) => current.handle(previous, ...data),
...data => action(...data)
);
}
_regenerateMiddlewareProcess() {
this._middlewareProcess = this._generateMiddlewareProcess(this._handler.action);
}
}
| export default class MiddlewareStack {
constructor(handler, stack = []) {
this._handler = handler;
this._stack = stack.map(element => (typeof element === 'function' ? new element() : element));
this._regenerateMiddlewareProcess();
}
push(middleware) {
this._stack.push(middleware);
this._regenerateMiddlewareProcess();
}
pop() {
const popped = this._stack.pop();
this._regenerateMiddlewareProcess();
return popped;
}
process(...data) {
return this._middlewareProcess(...data);
}
_generateMiddlewareProcess(action) {
return this._stack.reduceRight(
(previous, current) => (...data) => current.handle(previous, ...data),
...data => action(...data)
);
}
_regenerateMiddlewareProcess() {
this._middlewareProcess = this._generateMiddlewareProcess(this._handler.action);
}
}
| Make the middleware regen after pops. | Make the middleware regen after pops.
| JavaScript | mit | hkwu/ghastly | ---
+++
@@ -11,7 +11,10 @@
}
pop() {
- return this._stack.pop();
+ const popped = this._stack.pop();
+ this._regenerateMiddlewareProcess();
+
+ return popped;
}
process(...data) { |
20542df46f1a5274c2292c9c05cf8024ab4679ad | test/react/router.spec.js | test/react/router.spec.js | var makeSignatureFromRoutes = require('../../src/react/router').makeSignatureFromRoutes
describe("react: makeSignatureFromRoutes", function() {
it("should correctly join paths", function() {
var routes = [
{path: "/"}, {path: "/something"},
]
expect(makeSignatureFromRoutes(routes)).toBe("/something")
routes = [
{path: "/"}, {path: "something"},
]
expect(makeSignatureFromRoutes(routes)).toBe("/something")
})
it("should handle zero routes", function() {
expect(makeSignatureFromRoutes([])).toBe("unknown")
})
}) | var makeSignatureFromRoutes = require('../../src/react/router').makeSignatureFromRoutes
var pushLocation = {action: 'PUSH'}, replaceLocation = {action: 'REPLACE'}
describe("react: makeSignatureFromRoutes", function() {
it("should correctly join paths", function() {
var routes = [
{path: "/"}, {path: "/something"},
]
var pushLocation = {
action: 'PUSH'
}
expect(makeSignatureFromRoutes(routes, pushLocation)).toBe("/something")
routes = [
{path: "/"}, {path: "something"},
]
expect(makeSignatureFromRoutes(routes, pushLocation)).toBe("/something")
})
it("should handle zero routes", function() {
expect(makeSignatureFromRoutes([], pushLocation)).toBe("unknown")
})
it("should handle REPLACE routes", function() {
var routes = [
{path: "/"}, {path: "something"},
]
expect(makeSignatureFromRoutes(routes, replaceLocation)).toBe("/something (REPLACE)")
})
})
| Add test for REPLACE route | Add test for REPLACE route
| JavaScript | mit | opbeat/opbeat-react,opbeat/opbeat-react,opbeat/opbeat-react | ---
+++
@@ -1,4 +1,5 @@
var makeSignatureFromRoutes = require('../../src/react/router').makeSignatureFromRoutes
+var pushLocation = {action: 'PUSH'}, replaceLocation = {action: 'REPLACE'}
describe("react: makeSignatureFromRoutes", function() {
it("should correctly join paths", function() {
@@ -7,16 +8,28 @@
{path: "/"}, {path: "/something"},
]
- expect(makeSignatureFromRoutes(routes)).toBe("/something")
+ var pushLocation = {
+ action: 'PUSH'
+ }
+
+ expect(makeSignatureFromRoutes(routes, pushLocation)).toBe("/something")
routes = [
{path: "/"}, {path: "something"},
]
- expect(makeSignatureFromRoutes(routes)).toBe("/something")
+ expect(makeSignatureFromRoutes(routes, pushLocation)).toBe("/something")
})
it("should handle zero routes", function() {
- expect(makeSignatureFromRoutes([])).toBe("unknown")
+ expect(makeSignatureFromRoutes([], pushLocation)).toBe("unknown")
+ })
+
+
+ it("should handle REPLACE routes", function() {
+ var routes = [
+ {path: "/"}, {path: "something"},
+ ]
+ expect(makeSignatureFromRoutes(routes, replaceLocation)).toBe("/something (REPLACE)")
})
}) |
76d385139e36b3b685d73ba209e2f52ad89ebd01 | client/apps/user_tool/actions/application.js | client/apps/user_tool/actions/application.js | import wrapper from 'atomic-fuel/libs/constants/wrapper';
import Network from 'atomic-fuel/libs/constants/network';
// Local actions
const actions = [];
// Actions that make an api request
const requests = ['SEARCH_FOR_ACCOUNT_USERS', 'GET_ACCOUNT_USER', 'UPDATE_ACCOUNT_USER'];
export const Constants = wrapper(actions, requests);
export const searchForAccountUsers = (searchTerm, page) => ({
type: Constants.SEARCH_FOR_ACCOUNT_USERS,
method: Network.GET,
url: 'api/canvas_account_users',
params: {
search_term: searchTerm,
page,
},
});
export const getAccountUser = userId => ({
type: Constants.GET_ACCOUNT_USER,
method: Network.GET,
url: `api/canvas_account_users/${userId}`,
});
export const updateAccountUser = (userId, userAttributes) => ({
type: Constants.UPDATE_ACCOUNT_USER,
method: Network.PUT,
url: `api/canvas_account_users/${userId}`,
body: {
user: {
name: userAttributes.name,
login_id: userAttributes.loginId,
sis_user_id: userAttributes.sisUserId,
email: userAttributes.email,
},
},
});
| import wrapper from 'atomic-fuel/libs/constants/wrapper';
import Network from 'atomic-fuel/libs/constants/network';
// Increasing timeout to accomodate slow environments. Default is 20_000.
Network.TIMEOUT = 60_000;
// Local actions
const actions = [];
// Actions that make an api request
const requests = ['SEARCH_FOR_ACCOUNT_USERS', 'GET_ACCOUNT_USER', 'UPDATE_ACCOUNT_USER'];
export const Constants = wrapper(actions, requests);
export const searchForAccountUsers = (searchTerm, page) => ({
type: Constants.SEARCH_FOR_ACCOUNT_USERS,
method: Network.GET,
url: 'api/canvas_account_users',
params: {
search_term: searchTerm,
page,
},
});
export const getAccountUser = userId => ({
type: Constants.GET_ACCOUNT_USER,
method: Network.GET,
url: `api/canvas_account_users/${userId}`,
});
export const updateAccountUser = (userId, userAttributes) => ({
type: Constants.UPDATE_ACCOUNT_USER,
method: Network.PUT,
url: `api/canvas_account_users/${userId}`,
body: {
user: {
name: userAttributes.name,
login_id: userAttributes.loginId,
sis_user_id: userAttributes.sisUserId,
email: userAttributes.email,
},
},
});
| Increase client-side network timeout from 20 seconds to 60 | fix: Increase client-side network timeout from 20 seconds to 60
We're having problems in the staging environment where requests
are taking longer than 20 seconds and are timing out so the user can't
perform certain actions. Increasing the timeout to 60 seconds won't
improve the slow performance obviously, but it will at least prevent
requests from timing out and will allow the user to use the application
normally (albeit slowly).
| JavaScript | mit | atomicjolt/adhesion,atomicjolt/adhesion,atomicjolt/adhesion,atomicjolt/adhesion | ---
+++
@@ -1,5 +1,8 @@
import wrapper from 'atomic-fuel/libs/constants/wrapper';
import Network from 'atomic-fuel/libs/constants/network';
+
+// Increasing timeout to accomodate slow environments. Default is 20_000.
+Network.TIMEOUT = 60_000;
// Local actions
const actions = []; |
fcda3bb2aa828f7f34a0fa667b43089b10786bd5 | public/app/service-api.js | public/app/service-api.js | var svcMod = angular.module( "linksWeb.service-api", [] );
svcMod.factory( 'API', [ "$http", "$window", function ( $http, $window ) {
var apiRequest = function ( method, path, requestData, callback ) {
var headers = {
"Content-Type": "application/json",
"Authorization": "Token " + $window.sessionStorage.token
};
var options = {
method: method,
url: path,
headers: headers,
data: requestData
};
$http( options )
.success( function ( data, status, headers, config ) {
callback( null, data );
} )
.error( function ( data, status, headers, config ) {
var error = {
data: data,
status: status
};
callback( error, null );
} );
};
return {
$get: function ( path, callback ) {
return apiRequest( 'GET', path, {}, callback );
},
$post: function ( path, requestData, callback ) {
return apiRequest( 'POST', path, requestData, callback );
},
$put: function ( path, requestData, callback ) {
return apiRequest( 'PUT', path, requestData, callback );
},
$patch: function ( path, requestData, callback ) {
return apiRequest( 'PATCH', path, requestData, callback );
},
$delete: function ( path, callback ) {
return apiRequest( 'DELETE', path, {}, callback );
}
};
} ] );
| var svcMod = angular.module( "linksWeb.service-api", [] );
svcMod.factory( 'API', [ "$http", "$window", function ( $http, $window ) {
var apiRequest = function ( method, path, requestData, callback ) {
var headers = {
"Content-Type": "application/json"
};
if ( $window.sessionStorage.token ) {
headers.Authorization = "Token " + $window.sessionStorage.token;
}
var options = {
method: method,
url: path,
headers: headers,
data: requestData
};
$http( options )
.success( function ( data, status, headers, config ) {
callback( null, data );
} )
.error( function ( data, status, headers, config ) {
var error = {
data: data,
status: status
};
callback( error, null );
} );
};
return {
$get: function ( path, callback ) {
return apiRequest( 'GET', path, {}, callback );
},
$post: function ( path, requestData, callback ) {
return apiRequest( 'POST', path, requestData, callback );
},
$put: function ( path, requestData, callback ) {
return apiRequest( 'PUT', path, requestData, callback );
},
$patch: function ( path, requestData, callback ) {
return apiRequest( 'PATCH', path, requestData, callback );
},
$delete: function ( path, callback ) {
return apiRequest( 'DELETE', path, {}, callback );
}
};
} ] );
| Set the Authorization header if a token exists | Set the Authorization header if a token exists
| JavaScript | mit | projectweekend/Links-Web,projectweekend/Links-Web | ---
+++
@@ -6,9 +6,12 @@
var apiRequest = function ( method, path, requestData, callback ) {
var headers = {
- "Content-Type": "application/json",
- "Authorization": "Token " + $window.sessionStorage.token
+ "Content-Type": "application/json"
};
+
+ if ( $window.sessionStorage.token ) {
+ headers.Authorization = "Token " + $window.sessionStorage.token;
+ }
var options = {
method: method, |
4a31e8979533dfccd99157832def834f134f340a | test/fixtures/index.js | test/fixtures/index.js | var sample_xform = require('./sample_xform');
module.exports = function() {
return [
{
request: {
method: "GET",
url: "http://www.example.org/xform00",
params: {},
},
response: {
code: "200",
data: sample_xform,
},
},
];
};
| module.exports = function() {
return [];
};
| Revert "Add fixture for getting an xform from an external server" | Revert "Add fixture for getting an xform from an external server"
This reverts commit 8ef11ed11f09b9f4ce7d53234fdb6100c7fe8451.
| JavaScript | bsd-3-clause | praekelt/go-jsbox-xform,praekelt/go-jsbox-xform | ---
+++
@@ -1,17 +1,3 @@
-var sample_xform = require('./sample_xform');
-
module.exports = function() {
- return [
- {
- request: {
- method: "GET",
- url: "http://www.example.org/xform00",
- params: {},
- },
- response: {
- code: "200",
- data: sample_xform,
- },
- },
- ];
+ return [];
}; |
28929cc0260ea14c2de5ec19874c6dbba00f9100 | matchMedia.js | matchMedia.js | /*! matchMedia() polyfill - Test a CSS media type/query in JS. Authors & copyright (c) 2012: Scott Jehl, Paul Irish, Nicholas Zakas. Dual MIT/BSD license */
window.matchMedia = window.matchMedia || (function( doc, undefined ) {
"use strict";
var bool,
docElem = doc.documentElement,
refNode = docElem.firstElementChild || docElem.firstChild,
// fakeBody required for <FF4 when executed in <head>
fakeBody = doc.createElement( "body" ),
div = doc.createElement( "div" );
div.id = "mq-test-1";
div.style.cssText = "position:absolute;top:-100em";
fakeBody.style.background = "none";
fakeBody.appendChild(div);
return function(q){
div.innerHTML = "­<style media=\"" + q + "\"> #mq-test-1 { width: 42px; }</style>";
docElem.insertBefore( fakeBody, refNode );
bool = div.offsetWidth === 42;
docElem.removeChild( fakeBody );
return {
matches: bool,
media: q
};
};
}( document ));
| /*! matchMedia() polyfill - Test a CSS media type/query in JS. Authors & copyright (c) 2012: Scott Jehl, Paul Irish, Nicholas Zakas. Dual MIT/BSD license */
window.matchMedia || (window.matchMedia = function() {
"use strict";
var styleMedia = (window.styleMedia || window.media);
// For those that doen't support matchMedium
if (!styleMedia) {
var style = document.createElement('style'),
info = null,
setStyle = function(text) {
if (style.styleSheet) {
style.styleSheet.cssText = text;
} else {
style.textContent = text;
}
};
style.type = 'text/css';
style.id = 'matchmediajs-test';
document.getElementsByTagName('head')[0].appendChild(style);
info = ('getComputedStyle' in window) && window.getComputedStyle(style) || style.currentStyle;
styleMedia = {
matchMedium: function(media) {
var text = '@media ' + media + '{ #matchmediajs-test { width: 1px; } }',
match;
// Add css text
setStyle(text);
match = info.width === '1px';
// remove css text
setStyle('');
return match;
}
};
}
return function(media) {
return {
matches: styleMedia.matchMedium(media || 'all'),
media: media || 'all'
};
};
}());
| Complete rewrite in an effort to gain performance | Complete rewrite in an effort to gain performance | JavaScript | mit | therealedsheenan/matchMedia.js,amitabhaghosh197/matchMedia.js,AndBicScadMedia/matchMedia.js,ababic/matchMedia.js,therealedsheenan/matchMedia.js,paulirish/matchMedia.js,zxfjessica/match-media-polyfill,CondeNast/matchMedia.js,CondeNast/matchMedia.js,ababic/matchMedia.js,dirajkumar/matchMedia.js,zxfjessica/match-media-polyfill,alejonext/matchMedia.js,dirajkumar/matchMedia.js,paulirish/matchMedia.js,alejonext/matchMedia.js,amitabhaghosh197/matchMedia.js,AndBicScadMedia/matchMedia.js | ---
+++
@@ -1,36 +1,51 @@
/*! matchMedia() polyfill - Test a CSS media type/query in JS. Authors & copyright (c) 2012: Scott Jehl, Paul Irish, Nicholas Zakas. Dual MIT/BSD license */
-window.matchMedia = window.matchMedia || (function( doc, undefined ) {
+window.matchMedia || (window.matchMedia = function() {
+ "use strict";
- "use strict";
+ var styleMedia = (window.styleMedia || window.media);
- var bool,
- docElem = doc.documentElement,
- refNode = docElem.firstElementChild || docElem.firstChild,
- // fakeBody required for <FF4 when executed in <head>
- fakeBody = doc.createElement( "body" ),
- div = doc.createElement( "div" );
+ // For those that doen't support matchMedium
+ if (!styleMedia) {
+ var style = document.createElement('style'),
+ info = null,
+ setStyle = function(text) {
+ if (style.styleSheet) {
+ style.styleSheet.cssText = text;
+ } else {
+ style.textContent = text;
+ }
+ };
- div.id = "mq-test-1";
- div.style.cssText = "position:absolute;top:-100em";
- fakeBody.style.background = "none";
- fakeBody.appendChild(div);
+ style.type = 'text/css';
+ style.id = 'matchmediajs-test';
- return function(q){
+ document.getElementsByTagName('head')[0].appendChild(style);
+ info = ('getComputedStyle' in window) && window.getComputedStyle(style) || style.currentStyle;
- div.innerHTML = "­<style media=\"" + q + "\"> #mq-test-1 { width: 42px; }</style>";
+ styleMedia = {
+ matchMedium: function(media) {
+ var text = '@media ' + media + '{ #matchmediajs-test { width: 1px; } }',
+ match;
- docElem.insertBefore( fakeBody, refNode );
- bool = div.offsetWidth === 42;
- docElem.removeChild( fakeBody );
+ // Add css text
+ setStyle(text);
- return {
- matches: bool,
- media: q
+ match = info.width === '1px';
+
+ // remove css text
+ setStyle('');
+
+ return match;
+ }
+ };
+
+ }
+
+ return function(media) {
+ return {
+ matches: styleMedia.matchMedium(media || 'all'),
+ media: media || 'all'
+ };
};
-
- };
-
-}( document ));
-
-
+}()); |
6e648cc1f0abfd8df74f11a48682c8c177ad309d | pa11y.js | pa11y.js | // This is our options configuration for Pa11y
// https://github.com/pa11y/pa11y#configuration
const options = {
timeout: 60000,
hideElements: '.skip-to, .is-visuallyhidden'
};
module.exports = options;
| // This is our options configuration for Pa11y
// https://github.com/pa11y/pa11y#configuration
const options = {
timeout: 60000,
hideElements: '.skip-to, .is-visuallyhidden, .visuallyhidden'
};
module.exports = options;
| Add .visuallyhidden class to Pa11y test excludes | Add .visuallyhidden class to Pa11y test excludes
| JavaScript | mit | AusDTO/gov-au-ui-kit,AusDTO/gov-au-ui-kit,AusDTO/gov-au-ui-kit | ---
+++
@@ -3,7 +3,7 @@
const options = {
timeout: 60000,
- hideElements: '.skip-to, .is-visuallyhidden'
+ hideElements: '.skip-to, .is-visuallyhidden, .visuallyhidden'
};
module.exports = options; |
ad11af7002bfb7e6c0737bae5f48270010e1a42e | modules/wikipedia/index.js | modules/wikipedia/index.js | const wiki = require('wikijs').default;
module.exports.commands = ['wiki', 'wikipedia'];
function prettyPage(page) {
return page.summary()
// Get the first "sentence" (hopefully)
.then(str => str.substr(0, str.indexOf('.') + 1))
// Truncate with an ellipsis if length exceeds 250 chars
.then(str => (str.length > 250 ? `${str.substr(0, 250)}...` : str))
// Append Wikipedia URL
.then(str => `${str} <${page.raw.canonicalurl}>`);
}
module.exports.run = function run(remainder, parts, reply) {
wiki().search(remainder, 1)
.then(data => data.results[0])
.then(wiki().page)
.then(prettyPage)
.then(reply)
.catch(() => reply(`No Wikipedia page found for "${remainder}"`));
};
| const wiki = require('wikijs').default;
module.exports.commands = ['wiki', 'wikipedia'];
const urlRegex = /^(?:https?:\/\/)?(?:en\.)?wikipedia\.org\/wiki\/(.+)/;
const errorMessage = term => `No Wikipedia page found for "${term}"`;
function shortSummary(page, withUrl) {
return page.summary()
// Get the first "sentence" (hopefully)
.then(str => str.substr(0, str.indexOf('.') + 1))
// Truncate with an ellipsis if length exceeds 250 chars
.then(str => (str.length > 250 ? `${str.substr(0, 250)}...` : str))
// Append URL if requested
.then(str => (withUrl ? `${str} <${page.raw.canonicalurl}>` : str));
}
module.exports.run = (remainder, parts, reply) => {
wiki().search(remainder, 1)
.then(data => data.results[0])
.then(wiki().page)
.then(page => shortSummary(page, true))
.then(reply)
.catch(() => reply(errorMessage(remainder)));
};
module.exports.url = (url, reply) => {
if (urlRegex.test(url)) {
const [, match] = urlRegex.exec(url);
const title = decodeURIComponent(match);
wiki().page(title)
.then(shortSummary)
.then(reply)
.catch(() => reply(errorMessage(title)));
}
};
| Add URL matching to Wikipedia module | Add URL matching to Wikipedia module
| JavaScript | mit | LinuxMercedes/EuIrcBot,gmackie/EuIrcBot,euank/EuIrcBot,euank/EuIrcBot,gmackie/EuIrcBot,LinuxMercedes/EuIrcBot | ---
+++
@@ -2,21 +2,37 @@
module.exports.commands = ['wiki', 'wikipedia'];
-function prettyPage(page) {
+const urlRegex = /^(?:https?:\/\/)?(?:en\.)?wikipedia\.org\/wiki\/(.+)/;
+
+const errorMessage = term => `No Wikipedia page found for "${term}"`;
+
+function shortSummary(page, withUrl) {
return page.summary()
// Get the first "sentence" (hopefully)
.then(str => str.substr(0, str.indexOf('.') + 1))
// Truncate with an ellipsis if length exceeds 250 chars
.then(str => (str.length > 250 ? `${str.substr(0, 250)}...` : str))
- // Append Wikipedia URL
- .then(str => `${str} <${page.raw.canonicalurl}>`);
+ // Append URL if requested
+ .then(str => (withUrl ? `${str} <${page.raw.canonicalurl}>` : str));
}
-module.exports.run = function run(remainder, parts, reply) {
+module.exports.run = (remainder, parts, reply) => {
wiki().search(remainder, 1)
.then(data => data.results[0])
.then(wiki().page)
- .then(prettyPage)
+ .then(page => shortSummary(page, true))
.then(reply)
- .catch(() => reply(`No Wikipedia page found for "${remainder}"`));
+ .catch(() => reply(errorMessage(remainder)));
};
+
+module.exports.url = (url, reply) => {
+ if (urlRegex.test(url)) {
+ const [, match] = urlRegex.exec(url);
+ const title = decodeURIComponent(match);
+
+ wiki().page(title)
+ .then(shortSummary)
+ .then(reply)
+ .catch(() => reply(errorMessage(title)));
+ }
+}; |
334c168af32f349fa8dbd1ee319611647fa44004 | components/org.wso2.carbon.siddhi.editor.core/src/main/resources/web/commons/js/menu-bar/deploy-menu.js | components/org.wso2.carbon.siddhi.editor.core/src/main/resources/web/commons/js/menu-bar/deploy-menu.js | /**
* Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
define(([], function () {
var DeployMenu = {
id: "deploy",
label: "Deploy",
items: [
{
id: "deploy-to-server",
label: "Deploy To Server",
command: {
id: "deploy-to-server",
shortcuts: {
mac: {
key: "shift+d",
label: "\u21E7D"
},
other: {
key: "shift+d",
label: "Shift+D"
}
}
},
disabled: false
}
]
};
return DeployMenu;
}));
| /**
* Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
define(([], function () {
var DeployMenu = {
id: "deploy",
label: "Deploy",
items: [
{
id: "deploy-to-server",
label: "Deploy To Server",
command: {
id: "deploy-to-server",
shortcuts: {
mac: {
key: "command+shift+d",
label: "\u2318\u21E7D"
},
other: {
key: "ctrl+shift+d",
label: "Ctrl+Shift+D"
}
}
},
disabled: false
}
]
};
return DeployMenu;
}));
| Change shortcut key for deploy to server | Change shortcut key for deploy to server
| JavaScript | apache-2.0 | tishan89/carbon-analytics,minudika/carbon-analytics,Niveathika92/carbon-analytics,erangatl/carbon-analytics,Niveathika92/carbon-analytics,minudika/carbon-analytics,minudika/carbon-analytics,tishan89/carbon-analytics,tishan89/carbon-analytics,wso2/carbon-analytics,wso2/carbon-analytics,tishan89/carbon-analytics,wso2/carbon-analytics,tishan89/carbon-analytics,erangatl/carbon-analytics,erangatl/carbon-analytics,erangatl/carbon-analytics,erangatl/carbon-analytics,wso2/carbon-analytics,minudika/carbon-analytics,Niveathika92/carbon-analytics,minudika/carbon-analytics,Niveathika92/carbon-analytics,wso2/carbon-analytics,Niveathika92/carbon-analytics | ---
+++
@@ -28,12 +28,12 @@
id: "deploy-to-server",
shortcuts: {
mac: {
- key: "shift+d",
- label: "\u21E7D"
+ key: "command+shift+d",
+ label: "\u2318\u21E7D"
},
other: {
- key: "shift+d",
- label: "Shift+D"
+ key: "ctrl+shift+d",
+ label: "Ctrl+Shift+D"
}
}
}, |
da490e3f5353be00b9deb384813b48952a8db3cc | erpnext/stock/doctype/serial_no/serial_no.js | erpnext/stock/doctype/serial_no/serial_no.js | // Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors
// License: GNU General Public License v3. See license.txt
cur_frm.add_fetch("customer", "customer_name", "customer_name")
cur_frm.add_fetch("supplier", "supplier_name", "supplier_name")
cur_frm.add_fetch("item_code", "item_name", "item_name")
cur_frm.add_fetch("item_code", "description", "description")
cur_frm.add_fetch("item_code", "item_group", "item_group")
cur_frm.add_fetch("item_code", "brand", "brand")
cur_frm.cscript.onload = function() {
cur_frm.set_query("item_code", function() {
return erpnext.queries.item({"is_stock_item": "Yes", "has_serial_no": "Yes"})
});
};
frappe.ui.form.on("Serial No", "refresh", function(frm) {
frm.toggle_enable("item_code", frm.doc.__islocal);
if(frm.doc.status == "Sales Returned" && frm.doc.warehouse)
cur_frm.add_custom_button(__('Set Status as Available'), cur_frm.cscript.set_status_as_available);
});
cur_frm.cscript.set_status_as_available = function() {
cur_frm.set_value("status", "Available");
cur_frm.save()
}
| // Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors
// License: GNU General Public License v3. See license.txt
cur_frm.add_fetch("customer", "customer_name", "customer_name")
cur_frm.add_fetch("supplier", "supplier_name", "supplier_name")
cur_frm.add_fetch("item_code", "item_name", "item_name")
cur_frm.add_fetch("item_code", "description", "description")
cur_frm.add_fetch("item_code", "item_group", "item_group")
cur_frm.add_fetch("item_code", "brand", "brand")
cur_frm.cscript.onload = function() {
cur_frm.set_query("item_code", function() {
return erpnext.queries.item({"is_stock_item": "Yes", "has_serial_no": "Yes"})
});
};
frappe.ui.form.on("Serial No", "refresh", function(frm) {
frm.toggle_enable("item_code", frm.doc.__islocal);
if(frm.doc.status == "Sales Returned" && frm.doc.warehouse)
cur_frm.add_custom_button(__('Set Status as Available'), function() {
cur_frm.set_value("status", "Available");
cur_frm.save();
});
});
| Set status button in serial no | Set status button in serial no
| JavaScript | agpl-3.0 | Tejal011089/fbd_erpnext,indictranstech/erpnext,suyashphadtare/sajil-final-erp,rohitwaghchaure/erpnext-receipher,mbauskar/Das_Erpnext,rohitwaghchaure/New_Theme_Erp,gangadharkadam/office_erp,Tejal011089/huntercamp_erpnext,suyashphadtare/gd-erp,mbauskar/helpdesk-erpnext,gangadharkadam/v5_erp,rohitwaghchaure/New_Theme_Erp,mbauskar/alec_frappe5_erpnext,indictranstech/fbd_erpnext,indictranstech/trufil-erpnext,suyashphadtare/vestasi-erp-final,indictranstech/phrerp,rohitwaghchaure/erpnext_smart,BhupeshGupta/erpnext,suyashphadtare/gd-erp,rohitwaghchaure/erpnext-receipher,sagar30051991/ozsmart-erp,Tejal011089/fbd_erpnext,gangadharkadam/tailorerp,netfirms/erpnext,ThiagoGarciaAlves/erpnext,shft117/SteckerApp,netfirms/erpnext,hanselke/erpnext-1,suyashphadtare/vestasi-update-erp,gangadharkadam/v4_erp,suyashphadtare/sajil-final-erp,Tejal011089/osmosis_erpnext,indictranstech/internal-erpnext,indictranstech/focal-erpnext,mahabuber/erpnext,treejames/erpnext,suyashphadtare/vestasi-erp-1,gangadhar-kadam/helpdesk-erpnext,dieface/erpnext,aruizramon/alec_erpnext,mbauskar/phrerp,indictranstech/Das_Erpnext,gangadhar-kadam/verve_erp,sagar30051991/ozsmart-erp,Drooids/erpnext,rohitwaghchaure/GenieManager-erpnext,gangadhar-kadam/verve-erp,gangadhar-kadam/latestchurcherp,gangadharkadam/sher,gmarke/erpnext,fuhongliang/erpnext,shitolepriya/test-erp,gsnbng/erpnext,gangadhar-kadam/verve_live_erp,SPKian/Testing,mbauskar/omnitech-erpnext,meisterkleister/erpnext,ThiagoGarciaAlves/erpnext,shitolepriya/test-erp,sagar30051991/ozsmart-erp,tmimori/erpnext,suyashphadtare/vestasi-erp-final,meisterkleister/erpnext,geekroot/erpnext,mbauskar/omnitech-erpnext,sheafferusa/erpnext,dieface/erpnext,Tejal011089/paypal_erpnext,MartinEnder/erpnext-de,indictranstech/osmosis-erpnext,gangadhar-kadam/verve_live_erp,indictranstech/tele-erpnext,sheafferusa/erpnext,rohitwaghchaure/GenieManager-erpnext,gangadharkadam/johnerp,shitolepriya/test-erp,indictranstech/reciphergroup-erpnext,Suninus/erpnext,indictranstech/fbd_erpnext,SPKian/Testing2,treejames/erpnext,rohitwaghchaure/digitales_erpnext,Tejal011089/trufil-erpnext,netfirms/erpnext,indictranstech/tele-erpnext,dieface/erpnext,tmimori/erpnext,gangadharkadam/letzerp,gangadhar-kadam/verve_test_erp,hatwar/buyback-erpnext,gmarke/erpnext,anandpdoshi/erpnext,Tejal011089/digitales_erpnext,hatwar/focal-erpnext,njmube/erpnext,rohitwaghchaure/erpnext-receipher,ShashaQin/erpnext,MartinEnder/erpnext-de,suyashphadtare/test,gangadharkadam/v6_erp,Tejal011089/paypal_erpnext,gangadharkadam/saloon_erp,gangadharkadam/sterp,indictranstech/tele-erpnext,indictranstech/osmosis-erpnext,indictranstech/focal-erpnext,pombredanne/erpnext,hernad/erpnext,Drooids/erpnext,rohitwaghchaure/New_Theme_Erp,Tejal011089/paypal_erpnext,indictranstech/focal-erpnext,gangadharkadam/v4_erp,suyashphadtare/sajil-erp,gangadhar-kadam/verve_live_erp,gangadhar-kadam/laganerp,suyashphadtare/vestasi-update-erp,Aptitudetech/ERPNext,gangadharkadam/tailorerp,gangadhar-kadam/laganerp,rohitwaghchaure/digitales_erpnext,indictranstech/trufil-erpnext,anandpdoshi/erpnext,Suninus/erpnext,indictranstech/osmosis-erpnext,gangadharkadam/saloon_erp_install,4commerce-technologies-AG/erpnext,fuhongliang/erpnext,gangadharkadam/saloon_erp,gangadharkadam/v6_erp,mbauskar/alec_frappe5_erpnext,gangadharkadam/v5_erp,SPKian/Testing2,gangadharkadam/office_erp,susuchina/ERPNEXT,Tejal011089/trufil-erpnext,gangadharkadam/letzerp,indictranstech/reciphergroup-erpnext,Suninus/erpnext,gangadharkadam/saloon_erp_install,hernad/erpnext,mbauskar/omnitech-erpnext,gangadharkadam/vlinkerp,sheafferusa/erpnext,indictranstech/reciphergroup-erpnext,gangadhar-kadam/latestchurcherp,dieface/erpnext,gangadharkadam/smrterp,indictranstech/biggift-erpnext,gangadharkadam/verveerp,suyashphadtare/vestasi-erp-jan-end,netfirms/erpnext,ShashaQin/erpnext,gangadharkadam/v6_erp,indictranstech/erpnext,mbauskar/Das_Erpnext,indictranstech/biggift-erpnext,mbauskar/omnitech-demo-erpnext,indictranstech/erpnext,sagar30051991/ozsmart-erp,hatwar/focal-erpnext,indictranstech/erpnext,gmarke/erpnext,indictranstech/Das_Erpnext,gangadharkadam/saloon_erp,treejames/erpnext,indictranstech/osmosis-erpnext,pombredanne/erpnext,suyashphadtare/vestasi-erp-jan-end,suyashphadtare/gd-erp,hatwar/focal-erpnext,shft117/SteckerApp,mbauskar/sapphire-erpnext,Tejal011089/huntercamp_erpnext,suyashphadtare/vestasi-update-erp,mbauskar/phrerp,mbauskar/Das_Erpnext,tmimori/erpnext,mbauskar/alec_frappe5_erpnext,gangadharkadam/v5_erp,hatwar/buyback-erpnext,mbauskar/sapphire-erpnext,njmube/erpnext,saurabh6790/test-erp,gangadharkadam/smrterp,BhupeshGupta/erpnext,indictranstech/fbd_erpnext,mbauskar/phrerp,suyashphadtare/vestasi-erp-jan-end,ShashaQin/erpnext,indictranstech/vestasi-erpnext,suyashphadtare/vestasi-erp-final,mbauskar/Das_Erpnext,BhupeshGupta/erpnext,gangadharkadam/letzerp,indictranstech/vestasi-erpnext,hatwar/Das_erpnext,rohitwaghchaure/digitales_erpnext,4commerce-technologies-AG/erpnext,gangadhar-kadam/verve_erp,indictranstech/phrerp,Tejal011089/fbd_erpnext,gangadhar-kadam/latestchurcherp,gangadharkadam/contributionerp,indictranstech/trufil-erpnext,gangadhar-kadam/verve_test_erp,indictranstech/phrerp,pawaranand/phrerp,anandpdoshi/erpnext,hatwar/Das_erpnext,gangadharkadam/saloon_erp_install,indictranstech/trufil-erpnext,mbauskar/omnitech-demo-erpnext,indictranstech/biggift-erpnext,mbauskar/sapphire-erpnext,pawaranand/phrerp,gangadhar-kadam/verve_erp,suyashphadtare/test,saurabh6790/test-erp,hanselke/erpnext-1,gangadharkadam/saloon_erp_install,saurabh6790/test-erp,susuchina/ERPNEXT,indictranstech/reciphergroup-erpnext,indictranstech/buyback-erp,SPKian/Testing2,Tejal011089/fbd_erpnext,mahabuber/erpnext,gangadharkadam/letzerp,indictranstech/vestasi-erpnext,rohitwaghchaure/GenieManager-erpnext,gangadharkadam/saloon_erp,Tejal011089/huntercamp_erpnext,gangadharkadam/vlinkerp,Tejal011089/osmosis_erpnext,hatwar/Das_erpnext,gangadhar-kadam/helpdesk-erpnext,geekroot/erpnext,mbauskar/phrerp,indictranstech/focal-erpnext,hatwar/focal-erpnext,suyashphadtare/sajil-erp,gangadharkadam/verveerp,geekroot/erpnext,gsnbng/erpnext,pawaranand/phrerp,Tejal011089/digitales_erpnext,Tejal011089/digitales_erpnext,gangadharkadam/sher,ThiagoGarciaAlves/erpnext,geekroot/erpnext,mbauskar/omnitech-demo-erpnext,SPKian/Testing,indictranstech/internal-erpnext,gangadharkadam/contributionerp,gangadharkadam/vlinkerp,shft117/SteckerApp,sheafferusa/erpnext,meisterkleister/erpnext,indictranstech/tele-erpnext,Suninus/erpnext,hatwar/Das_erpnext,indictranstech/Das_Erpnext,gangadharkadam/contributionerp,gsnbng/erpnext,suyashphadtare/sajil-final-erp,gangadhar-kadam/laganerp,aruizramon/alec_erpnext,Tejal011089/paypal_erpnext,suyashphadtare/vestasi-erp-1,pawaranand/phrerp,rohitwaghchaure/erpnext-receipher,SPKian/Testing2,gangadharkadam/sterp,fuhongliang/erpnext,rohitwaghchaure/GenieManager-erpnext,rohitwaghchaure/erpnext_smart,hanselke/erpnext-1,ThiagoGarciaAlves/erpnext,gmarke/erpnext,gangadhar-kadam/helpdesk-erpnext,Tejal011089/trufil-erpnext,ShashaQin/erpnext,anandpdoshi/erpnext,njmube/erpnext,fuhongliang/erpnext,meisterkleister/erpnext,susuchina/ERPNEXT,indictranstech/Das_Erpnext,indictranstech/internal-erpnext,SPKian/Testing,suyashphadtare/gd-erp,Drooids/erpnext,njmube/erpnext,hatwar/buyback-erpnext,MartinEnder/erpnext-de,indictranstech/phrerp,Tejal011089/digitales_erpnext,gangadharkadam/v6_erp,gangadharkadam/v4_erp,suyashphadtare/vestasi-erp-1,pombredanne/erpnext,mbauskar/helpdesk-erpnext,mbauskar/sapphire-erpnext,hernad/erpnext,BhupeshGupta/erpnext,gangadharkadam/office_erp,mahabuber/erpnext,gangadhar-kadam/verve_erp,gangadhar-kadam/verve_live_erp,rohitwaghchaure/erpnext_smart,indictranstech/buyback-erp,mbauskar/alec_frappe5_erpnext,aruizramon/alec_erpnext,4commerce-technologies-AG/erpnext,suyashphadtare/test,gangadhar-kadam/verve-erp,hanselke/erpnext-1,indictranstech/internal-erpnext,indictranstech/buyback-erp,gangadhar-kadam/smrterp,gangadhar-kadam/verve_test_erp,mbauskar/omnitech-demo-erpnext,gangadharkadam/johnerp,gangadhar-kadam/latestchurcherp,mbauskar/helpdesk-erpnext,Tejal011089/osmosis_erpnext,gangadharkadam/v4_erp,suyashphadtare/vestasi-erp-jan-end,suyashphadtare/sajil-erp,shft117/SteckerApp,Tejal011089/huntercamp_erpnext,aruizramon/alec_erpnext,indictranstech/buyback-erp,gangadhar-kadam/verve-erp,gangadharkadam/contributionerp,susuchina/ERPNEXT,mbauskar/helpdesk-erpnext,rohitwaghchaure/New_Theme_Erp,gangadharkadam/verveerp,treejames/erpnext,gsnbng/erpnext,gangadharkadam/verveerp,Tejal011089/trufil-erpnext,MartinEnder/erpnext-de,indictranstech/fbd_erpnext,indictranstech/vestasi-erpnext,hernad/erpnext,mahabuber/erpnext,Tejal011089/osmosis_erpnext,SPKian/Testing,indictranstech/biggift-erpnext,gangadharkadam/vlinkerp,shitolepriya/test-erp,hatwar/buyback-erpnext,mbauskar/omnitech-erpnext,gangadhar-kadam/smrterp,pombredanne/erpnext,gangadhar-kadam/helpdesk-erpnext,gangadharkadam/v5_erp,rohitwaghchaure/digitales_erpnext,saurabh6790/test-erp,Drooids/erpnext,tmimori/erpnext,gangadhar-kadam/verve_test_erp | ---
+++
@@ -19,10 +19,8 @@
frm.toggle_enable("item_code", frm.doc.__islocal);
if(frm.doc.status == "Sales Returned" && frm.doc.warehouse)
- cur_frm.add_custom_button(__('Set Status as Available'), cur_frm.cscript.set_status_as_available);
+ cur_frm.add_custom_button(__('Set Status as Available'), function() {
+ cur_frm.set_value("status", "Available");
+ cur_frm.save();
+ });
});
-
-cur_frm.cscript.set_status_as_available = function() {
- cur_frm.set_value("status", "Available");
- cur_frm.save()
-} |
44f3adfdbf85467272d71cf10c9ecd4fe75b57b7 | src/KeyboardObserver.js | src/KeyboardObserver.js | import {DeviceEventEmitter} from 'react-native';
class KeyboardObserver {
constructor() {
this.keyboardHeight = 0;
this.animationWillEndAt = 0;
this.listeners = {};
this.listenerId = 0;
DeviceEventEmitter.addListener('keyboardWillShow', this.handleKeyboardWillShow.bind(this));
DeviceEventEmitter.addListener('keyboardWillHide', this.handleKeyboardWillHide.bind(this));
}
addListener(callback) {
const id = this.listenerId++;
this.listeners[id] = callback;
return {remove: () => delete this.listeners[id]};
}
notifyListeners() {
const info = this.getKeyboardInfo();
Object.keys(this.listeners).forEach(key => this.listeners[key](info));
}
handleKeyboardWillShow(frames) {
this.keyboardHeight = frames.endCoordinates.height;
this.animationWillEndAt = new Date().getTime() + frames.duration;
this.notifyListeners()
}
handleKeyboardWillHide(frames) {
this.animationWillEndAt = new Date().getTime() + frames.duration;
this.keyboardHeight = 0;
this.notifyListeners()
}
getKeyboardInfo() {
return {
keyboardHeight: this.keyboardHeight,
animationWillEndAt: this.animationWillEndAt,
};
}
}
export default new KeyboardObserver();
| import {Keyboard} from 'react-native';
class KeyboardObserver {
constructor() {
this.keyboardHeight = 0;
this.animationWillEndAt = 0;
this.listeners = {};
this.listenerId = 0;
Keyboard.addListener('keyboardWillShow', this.handleKeyboardWillShow.bind(this));
Keyboard.addListener('keyboardWillHide', this.handleKeyboardWillHide.bind(this));
}
addListener(callback) {
const id = this.listenerId++;
this.listeners[id] = callback;
return {remove: () => delete this.listeners[id]};
}
notifyListeners() {
const info = this.getKeyboardInfo();
Object.keys(this.listeners).forEach(key => this.listeners[key](info));
}
handleKeyboardWillShow(frames) {
this.keyboardHeight = frames.endCoordinates.height;
this.animationWillEndAt = new Date().getTime() + frames.duration;
this.notifyListeners()
}
handleKeyboardWillHide(frames) {
this.animationWillEndAt = new Date().getTime() + frames.duration;
this.keyboardHeight = 0;
this.notifyListeners()
}
getKeyboardInfo() {
return {
keyboardHeight: this.keyboardHeight,
animationWillEndAt: this.animationWillEndAt,
};
}
}
export default new KeyboardObserver();
| Fix React Native Keyboard warnings | Fix React Native Keyboard warnings
| JavaScript | mit | azendoo/react-native-keyboard-responsive-view | ---
+++
@@ -1,4 +1,4 @@
-import {DeviceEventEmitter} from 'react-native';
+import {Keyboard} from 'react-native';
class KeyboardObserver {
@@ -7,8 +7,8 @@
this.animationWillEndAt = 0;
this.listeners = {};
this.listenerId = 0;
- DeviceEventEmitter.addListener('keyboardWillShow', this.handleKeyboardWillShow.bind(this));
- DeviceEventEmitter.addListener('keyboardWillHide', this.handleKeyboardWillHide.bind(this));
+ Keyboard.addListener('keyboardWillShow', this.handleKeyboardWillShow.bind(this));
+ Keyboard.addListener('keyboardWillHide', this.handleKeyboardWillHide.bind(this));
}
addListener(callback) { |
166231a4e9c666d017f6823b46f238fd50537e5a | lib/node_modules/@stdlib/math/base/special/gammaincinv/lib/index.js | lib/node_modules/@stdlib/math/base/special/gammaincinv/lib/index.js | 'use strict';
/**
* Computes the inverse of the lower incomplete gamma function.
*
* @module @stdlib/math/base/special/gammaincinv
*
* @example
* var gammaincinv = require( '@stdlib/math/base/special/gammaincinv' );
*
* var val = gammaincinv( 0.5, 2.0 );
* // returns ~1.678
*
* val = gammaincinv( 0.1, 10.0 );
* // returns ~6.221
*
* val = gammaincinv( 0.75, 3.0 );
* // returns ~3.92
*
* val = gammaincinv( 0.75, 3.0, true );
* // returns ~1.727
*
* val = gammaincinv( 0.75, NaN );
* // returns NaN
*
* val = gammaincinv( NaN, 3.0 );
* // returns NaN
*/
// MODULES //
var gammaincinv = require( './gammaincinv.js' );
// EXPORTS //
module.exports = gammaincinv;
| 'use strict';
/**
* Compute the inverse of the lower incomplete gamma function.
*
* @module @stdlib/math/base/special/gammaincinv
*
* @example
* var gammaincinv = require( '@stdlib/math/base/special/gammaincinv' );
*
* var val = gammaincinv( 0.5, 2.0 );
* // returns ~1.678
*
* val = gammaincinv( 0.1, 10.0 );
* // returns ~6.221
*
* val = gammaincinv( 0.75, 3.0 );
* // returns ~3.92
*
* val = gammaincinv( 0.75, 3.0, true );
* // returns ~1.727
*
* val = gammaincinv( 0.75, NaN );
* // returns NaN
*
* val = gammaincinv( NaN, 3.0 );
* // returns NaN
*/
// MODULES //
var gammaincinv = require( './gammaincinv.js' );
// EXPORTS //
module.exports = gammaincinv;
| Update description to imperative mood | Update description to imperative mood
| JavaScript | apache-2.0 | stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib | ---
+++
@@ -1,7 +1,7 @@
'use strict';
/**
-* Computes the inverse of the lower incomplete gamma function.
+* Compute the inverse of the lower incomplete gamma function.
*
* @module @stdlib/math/base/special/gammaincinv
* |
c8639e7b8e380cbe1f68c7597de438ccdebdda77 | server/instaFeed.es6.js | server/instaFeed.es6.js | Meteor.methods({
fetchInstaApi: function(){
var instaDebounce = _.debounce(Meteor.bindEnvironment(function(){
var ig = Meteor.npmRequire('instagram-node').instagram();
ig.use({ access_token: Meteor.settings.instagram.access_token });
ig.user_self_media_recent(Meteor.bindEnvironment(function(err, medias, pagination, remaining, limit) {
if(!err){
medias.forEach(function(entry){
if(entry.tags.indexOf("webonaut") > -1 || entry.tags.indexOf("Webonaut") > -1){
Meteor.call('addInsta', entry) ;
}
})
}
}, 60 * 1000));
}));
instaDebounce();
}
});
| Meteor.methods({
fetchInstaApi: function(){
/*var instaDebounce = _.debounce(Meteor.bindEnvironment(function(){
var ig = Meteor.npmRequire('instagram-node').instagram();
ig.use({ access_token: Meteor.settings.instagram.access_token });
ig.user_self_media_recent(Meteor.bindEnvironment(function(err, medias, pagination, remaining, limit) {
if(!err){
medias.forEach(function(entry){
if(entry.tags.indexOf("webonaut") > -1 || entry.tags.indexOf("Webonaut") > -1){
Meteor.call('addInsta', entry) ;
}
})
}
}, 60 * 1000));
}));
instaDebounce();*/
}
});
| Revert "Scaling crash testing twitFeed" | Revert "Scaling crash testing twitFeed"
This reverts commit 3216af3058e496f249781cf97e94359e01d7fa82.
| JavaScript | mit | Rhjulskov/webonaut,Rhjulskov/webonaut,Rhjulskov/webonaut | ---
+++
@@ -1,6 +1,6 @@
Meteor.methods({
fetchInstaApi: function(){
- var instaDebounce = _.debounce(Meteor.bindEnvironment(function(){
+ /*var instaDebounce = _.debounce(Meteor.bindEnvironment(function(){
var ig = Meteor.npmRequire('instagram-node').instagram();
ig.use({ access_token: Meteor.settings.instagram.access_token });
@@ -14,6 +14,6 @@
}
}, 60 * 1000));
}));
- instaDebounce();
+ instaDebounce();*/
}
}); |
8c4b151b36ac5ff4d83206e19675c45932248809 | src/BBM.fn.toBBM.js | src/BBM.fn.toBBM.js | (function (){
"use strict";
var BBM = require("./BBM.js");
var ENUM = BBM.ENUM;
var REGSTR =
[
"\"{3,}"
, "--"
, "\\*{2}"
, "\\^{2}"
, ",,"
, "__"
, "''"
, "\\?<"
, "!<"
, "#<"
, "#\\["
, "-\\["
, "\\]"
];
var REGEX = new RegExp(REGSTR.join("|"), "g");
//Serializes this subtree into BBM.
function toBBM()
{
}
BBM.prototype.toBBM = toBBM;
}()); | (function (){
"use strict";
var BBM = require("./BBM.js");
var ENUM = BBM.ENUM;
var REGSTR =
[
"\\\\[\\s\\S]"
, "\"{3,}"
, "--"
, "\\*{2}"
, "\\^{2}"
, ",,"
, "__"
, "''"
, "\\?<"
, "!<"
, "#<"
, "#\\["
, "-\\["
, "\\]"
];
var REGEX = new RegExp(REGSTR.join("|"), "g");
//Serializes this subtree into BBM.
function toBBM()
{
}
BBM.prototype.toBBM = toBBM;
}()); | Add backslash tokens to the escape list. | Add backslash tokens to the escape list.
| JavaScript | mit | Preole/bbm,Preole/bbm | ---
+++
@@ -5,7 +5,8 @@
var ENUM = BBM.ENUM;
var REGSTR =
[
- "\"{3,}"
+ "\\\\[\\s\\S]"
+, "\"{3,}"
, "--"
, "\\*{2}"
, "\\^{2}" |
a8bde2cb21c53fbdcf6a4aae9124a310f9e0111f | lib/client/error_reporters/window_error.js | lib/client/error_reporters/window_error.js | var prevWindowOnError = window.onerror;
window.onerror = function(message, url, line, stack) {
var now = Date.now();
stack = stack || 'window@'+url+':'+line+':0';
Kadira.sendErrors([{
appId : Kadira.options.appId,
name : message,
source : 'client',
startTime : now,
type : 'window.onerror',
info : getBrowserInfo(),
stack : [{at: now, events: [], stack: stack}],
}]);
if(prevWindowOnError && typeof prevWindowOnError === 'function') {
prevWindowOnError(message, url, line);
}
}
| var prevWindowOnError = window.onerror;
window.onerror = function(message, url, line, stack) {
var now = Date.now();
stack = stack || 'window@'+url+':'+line+':0';
Kadira.sendErrors([{
appId : Kadira.options.appId,
name : 'Error: ' + message,
source : 'client',
startTime : now,
type : 'window.onerror',
info : getBrowserInfo(),
stack : [{at: now, events: [], stack: stack}],
}]);
if(prevWindowOnError && typeof prevWindowOnError === 'function') {
prevWindowOnError(message, url, line);
}
}
| Use 'ErrorName: message' format for name | Use 'ErrorName: message' format for name
| JavaScript | mit | chatr/kadira,meteorhacks/kadira | ---
+++
@@ -4,7 +4,7 @@
stack = stack || 'window@'+url+':'+line+':0';
Kadira.sendErrors([{
appId : Kadira.options.appId,
- name : message,
+ name : 'Error: ' + message,
source : 'client',
startTime : now,
type : 'window.onerror', |
7035a1f61994961884bc8c584b793b2f657ad242 | web/frontend/pages/rich_text_editor.js | web/frontend/pages/rich_text_editor.js | import tinymce from 'tinymce/tinymce';
window.tinymce = tinymce;
import 'tinymce/themes/silver';
import 'tinymce/plugins/link';
import 'tinymce/plugins/lists';
import 'tinymce/plugins/image';
import 'tinymce/plugins/table';
import 'tinymce/plugins/code';
import 'tinymce/plugins/paste';
import 'tinymce/plugins/media';
import 'tinymce/plugins/noneditable';
import {getInitConfig} from '../libs/tinymce_extensions';
const ENHANCED = window.VERIFIED || window.SUP;
function initRichTextEditor(element, code=false) {
// Vue rebuilds the whole dom in between the call to init and tinymce actually doing the init
// so we use a selector here until we use vue to init tinymce
const selector=`${element.type}#${element.id}`;
let config = getInitConfig(selector, ENHANCED, code);
return tinymce.init(config);
}
for (const textArea of document.querySelectorAll('.richtext-editor'))
initRichTextEditor(textArea);
for (const textArea of document.querySelectorAll('.richtext-editor-src'))
initRichTextEditor(textArea, true);
global.initRichTextEditor = initRichTextEditor;
| import tinymce from 'tinymce/tinymce';
window.tinymce = tinymce;
import 'tinymce/themes/silver';
import 'tinymce/icons/default';
import 'tinymce/plugins/link';
import 'tinymce/plugins/lists';
import 'tinymce/plugins/image';
import 'tinymce/plugins/table';
import 'tinymce/plugins/code';
import 'tinymce/plugins/paste';
import 'tinymce/plugins/media';
import 'tinymce/plugins/noneditable';
import {getInitConfig} from '../libs/tinymce_extensions';
const ENHANCED = window.VERIFIED || window.SUP;
function initRichTextEditor(element, code=false) {
// Vue rebuilds the whole dom in between the call to init and tinymce actually doing the init
// so we use a selector here until we use vue to init tinymce
const selector=`${element.type}#${element.id}`;
let config = getInitConfig(selector, ENHANCED, code);
return tinymce.init(config);
}
for (const textArea of document.querySelectorAll('.richtext-editor'))
initRichTextEditor(textArea);
for (const textArea of document.querySelectorAll('.richtext-editor-src'))
initRichTextEditor(textArea, true);
global.initRichTextEditor = initRichTextEditor;
| Include TinyMCE icons after update | Include TinyMCE icons after update
| JavaScript | agpl-3.0 | harvard-lil/h2o,harvard-lil/h2o,harvard-lil/h2o,harvard-lil/h2o | ---
+++
@@ -1,6 +1,7 @@
import tinymce from 'tinymce/tinymce';
window.tinymce = tinymce;
import 'tinymce/themes/silver';
+import 'tinymce/icons/default';
import 'tinymce/plugins/link';
import 'tinymce/plugins/lists';
import 'tinymce/plugins/image'; |
a06d8d4a10b0cfb5905a0dc183bf25b26dd51e69 | assets/js/googlesitekit/modules/datastore/__fixtures__/index.js | assets/js/googlesitekit/modules/datastore/__fixtures__/index.js | /**
* Modules datastore fixtures.
*
* Site Kit by Google, Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Internal dependencies
*/
import modules from '../fixtures.json'; // TODO: move into this directory.
// Only Search Console and Site Verification are always active.
const alwaysActive = [ 'search-console', 'site-verification' ];
/**
* Makes a copy of the modules with the given module activation set.
*
* @param {...string} slugs Active module slugs.
* @return {Object[]} Array of module objects.
*/
export const withActive = ( ...slugs ) => {
const activeSlugs = alwaysActive.concat( slugs );
return modules.map( ( module ) => {
return { ...module, active: activeSlugs.includes( module.slug ) };
} );
};
export default withActive();
| /**
* Modules datastore fixtures.
*
* Site Kit by Google, Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Internal dependencies
*/
import modules from '../fixtures.json'; // TODO: move into this directory.
// Only Search Console and Site Verification are always active.
const alwaysActive = [ 'search-console', 'site-verification' ];
/**
* Makes a copy of the modules with the given module activation set.
*
* @since n.e.x.t
*
* @param {...string} slugs Active module slugs.
* @return {Object[]} Array of module objects.
*/
export const withActive = ( ...slugs ) => {
const activeSlugs = alwaysActive.concat( slugs );
return modules.map( ( module ) => {
return { ...module, active: activeSlugs.includes( module.slug ) };
} );
};
export default withActive();
| Fix new docs ESLint rule violation. | Fix new docs ESLint rule violation.
| JavaScript | apache-2.0 | google/site-kit-wp,google/site-kit-wp,google/site-kit-wp,google/site-kit-wp | ---
+++
@@ -27,6 +27,8 @@
/**
* Makes a copy of the modules with the given module activation set.
*
+ * @since n.e.x.t
+ *
* @param {...string} slugs Active module slugs.
* @return {Object[]} Array of module objects.
*/ |
3825954db3a1f20411329f6efde9fc7b09c62f22 | ifrau-client.js | ifrau-client.js | module.exports = import('ifrau').then(function(ifrau) {
return ifrau.Client;
});
| module.exports = import('ifrau').then(function(ifrau) {
return ifrau.SlimClient;
});
| Return slim client instead of full client | Return slim client instead of full client
Co-authored-by: Owen Smith <9069d0e8b554bca3df1592c83c498c5cd0661c2e@omsmith.ca> | JavaScript | apache-2.0 | Brightspace/frau-jwt | ---
+++
@@ -1,3 +1,3 @@
module.exports = import('ifrau').then(function(ifrau) {
- return ifrau.Client;
+ return ifrau.SlimClient;
}); |
61ef41e923fe2d05f36f47ed26139fcf6e4685ae | app/components/language-picker/component.js | app/components/language-picker/component.js | import Ember from 'ember';
import countries from './countries';
export default Ember.Component.extend({
i18n: Ember.inject.service(),
countries: countries,
languages: Ember.computed('countries', function() {
var langs = [];
this.get('countries').forEach((country) => {
country.languages.forEach((lang) => {
langs.push({
countryCode: country.code,
name: lang.name,
code: lang.code
});
});
});
langs.sort(function(a, b) {
if (a.name > b.name) {
return 1;
}
if (a.name < b.name) {
return -1;
}
return 0;
});
return langs;
}),
onPick: null,
country: null,
actions: {
pickLanguage(language, code) {
this.get('onPick')(language, code);
this.set('i18n.locale', code);
}
}
});
| import Ember from 'ember';
import countries from './countries';
export default Ember.Component.extend({
i18n: Ember.inject.service(),
countries: countries,
languages: Ember.computed('countries', function() {
var langs = [];
this.get('countries').forEach((country) => {
country.languages.forEach((lang) => {
langs.push({
countryCode: country.code,
name: lang.name,
code: lang.code
});
});
});
langs.sort(function(a, b) {
if (a.countryCode > b.countryCode) {
return 1;
}
if (a.countryCode < b.countryCode) {
return -1;
}
return 0;
});
return langs;
}),
onPick: null,
country: null,
actions: {
pickLanguage(language, code) {
this.get('onPick')(language, code);
this.set('i18n.locale', code);
}
}
});
| Sort flags by country code | Sort flags by country code
| JavaScript | apache-2.0 | CenterForOpenScience/isp,CenterForOpenScience/isp,samanehsan/isp,samanehsan/isp,CenterForOpenScience/isp,samanehsan/isp | ---
+++
@@ -18,10 +18,10 @@
});
});
langs.sort(function(a, b) {
- if (a.name > b.name) {
+ if (a.countryCode > b.countryCode) {
return 1;
}
- if (a.name < b.name) {
+ if (a.countryCode < b.countryCode) {
return -1;
}
return 0; |
4f0b898c968cca08ac87638d4250c6140f354a7f | src/components/HomepagePetitions/index.js | src/components/HomepagePetitions/index.js | import React from 'react';
import TeaserGrid from 'components/TeaserGrid';
import Container from 'components/Container';
import BlockContainer from 'components/BlockContainer';
import Section from 'components/Section';
import Heading2 from 'components/Heading2';
import styles from './homepage-petitions.scss';
import Link from 'components/Link';
const HomepagePetitions = ({ groupedPetitions, title, text, linkText }) => (
<section>
<Section>
<Container>
<BlockContainer>
<div className={styles.head}>
<div className={styles.left}>
<Heading2 text={title} />
<span className={styles.text}>{text}</span>
</div>
<Link href='/petitions'>{linkText}</Link>
</div>
</BlockContainer>
<TeaserGrid
petitions={groupedPetitions.trending.data}
isLoading={groupedPetitions.trending.isLoading}
/>
</Container>
</Section>
</section>
);
export default HomepagePetitions;
| import React from 'react';
import TeaserGrid from 'components/TeaserGrid';
import Container from 'components/Container';
import BlockContainer from 'components/BlockContainer';
import Section from 'components/Section';
import Heading2 from 'components/Heading2';
import styles from './homepage-petitions.scss';
import Link from 'components/Link';
const HomepagePetitions = ({ groupedPetitions, title, text, linkText }) => (
<section>
<Section>
<Container>
<BlockContainer>
<div className={styles.head}>
<div className={styles.left}>
<Heading2 text={title} />
<span className={styles.text}>{text}</span>
</div>
<Link href='/petitions'>{linkText}</Link>
</div>
</BlockContainer>
<TeaserGrid
petitions={groupedPetitions.latest.data}
isLoading={groupedPetitions.latest.isLoading}
/>
</Container>
</Section>
</section>
);
export default HomepagePetitions;
| Use latest petitions on HP instead... | Use latest petitions on HP instead...
| JavaScript | apache-2.0 | iris-dni/iris-frontend,iris-dni/iris-frontend,iris-dni/iris-frontend | ---
+++
@@ -21,8 +21,8 @@
</div>
</BlockContainer>
<TeaserGrid
- petitions={groupedPetitions.trending.data}
- isLoading={groupedPetitions.trending.isLoading}
+ petitions={groupedPetitions.latest.data}
+ isLoading={groupedPetitions.latest.isLoading}
/>
</Container>
</Section> |
8ea1ff2f989480a77181a384d64cfdcd68a88c18 | blueprints/ember-flexberry-designer/index.js | blueprints/ember-flexberry-designer/index.js | /* globals module */
module.exports = {
afterInstall: function() {
var _this = this;
return _this.addAddonsToProject({
packages: [
{ name: 'ember-flexberry', target: '0.12.3' }
]
}).then(function () {
return _this.addPackagesToProject([
{ name: 'npm:jointjs', target: '^2.1.2' },
]);
});
},
normalizeEntityName: function() {}
};
| /* globals module */
module.exports = {
afterInstall: function() {
var _this = this;
return _this.addAddonsToProject({
packages: [
{ name: 'ember-cli-jstree', target: '1.0.9' },
{ name: 'ember-flexberry', target: '0.12.3' },
{ name: 'ember-promise-helpers', target: '1.0.3' }
]
}).then(function () {
return _this.addPackagesToProject([
{ name: 'jointjs', target: '^2.1.2' }
]);
});
},
normalizeEntityName: function() {}
};
| Fix default blueprint add missing dependencies | Fix default blueprint add missing dependencies
| JavaScript | mit | Flexberry/ember-flexberry-designer,Flexberry/ember-flexberry-designer,Flexberry/ember-flexberry-designer | ---
+++
@@ -4,11 +4,13 @@
var _this = this;
return _this.addAddonsToProject({
packages: [
- { name: 'ember-flexberry', target: '0.12.3' }
+ { name: 'ember-cli-jstree', target: '1.0.9' },
+ { name: 'ember-flexberry', target: '0.12.3' },
+ { name: 'ember-promise-helpers', target: '1.0.3' }
]
}).then(function () {
return _this.addPackagesToProject([
- { name: 'npm:jointjs', target: '^2.1.2' },
+ { name: 'jointjs', target: '^2.1.2' }
]);
});
}, |
3322f2a9c5627719c552d737543a3f7f88888122 | webpack.config.dist.js | webpack.config.dist.js | var config = require('./webpack.config.js');
var webpack = require('webpack');
config.devtool = 'source-map';
config.output.publicPath = './';
config.plugins.push(
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify('production')
}
})
);
config.plugins.push(
new webpack.optimize.UglifyJsPlugin({
compressor: {
warnings: false
}
})
);
config.eslint.emitError = true;
module.exports = config; | var config = require('./webpack.config.js');
var webpack = require('webpack');
var pkg = require('./package.json');
var banner = '@license minigrid ';
banner = banner + pkg.version;
banner = banner + ' – minimal cascading grid layout http://alves.im/minigrid';
config.devtool = 'source-map';
config.output.publicPath = './';
config.plugins.push(
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify('production')
}
})
);
config.plugins.push(
new webpack.optimize.UglifyJsPlugin({
compressor: {
warnings: false
}
}),
new webpack.BannerPlugin(banner)
);
config.eslint.emitError = true;
module.exports = config; | Add banner comment to dis version | Add banner comment to dis version
| JavaScript | mit | messinmotion/minigrid,henriquea/minigrid,henriquea/minigrid | ---
+++
@@ -1,5 +1,10 @@
var config = require('./webpack.config.js');
var webpack = require('webpack');
+var pkg = require('./package.json');
+
+var banner = '@license minigrid ';
+banner = banner + pkg.version;
+banner = banner + ' – minimal cascading grid layout http://alves.im/minigrid';
config.devtool = 'source-map';
@@ -18,7 +23,8 @@
compressor: {
warnings: false
}
- })
+ }),
+ new webpack.BannerPlugin(banner)
);
config.eslint.emitError = true; |
9dd210893d6e961f89836281df4a16c056917d8f | src/TileMap.js | src/TileMap.js | function TileMap(w, h) {
this.width = w;
this.height = h;
this.reset();
}
TileMap.prototype.reset = function() {
this.map = [];
for(var y = 0; y < this.height; y++) {
this.map[y] = [];
for(var x = 0; x < this.width; x++) {
this.map[y][x] = new Tile();
}
}
}
function Tile() {
}
TileMap.Tile = Tile;
if(typeof module != 'undefined') {
module.exports = TileMap;
}
| function TileMap(w, h) {
this.width = w;
this.height = h;
this.reset();
}
TileMap.prototype.reset = function() {
this.map = [];
for(var y = 0; y < this.height; y++) {
this.map[y] = [];
for(var x = 0; x < this.width; x++) {
this.map[y][x] = new Tile(x, y);
}
}
}
function Tile(x, y) {
this.x = x;
this.y = y;
}
TileMap.Tile = Tile;
if(typeof module != 'undefined') {
module.exports = TileMap;
}
| Change Tile to store its own coordinates | Change Tile to store its own coordinates
| JavaScript | mit | yoo2001818/TableFlip | ---
+++
@@ -9,13 +9,14 @@
for(var y = 0; y < this.height; y++) {
this.map[y] = [];
for(var x = 0; x < this.width; x++) {
- this.map[y][x] = new Tile();
+ this.map[y][x] = new Tile(x, y);
}
}
}
-function Tile() {
-
+function Tile(x, y) {
+ this.x = x;
+ this.y = y;
}
TileMap.Tile = Tile; |
cd072a2e2de2213eb9450445c5a48ca5c6452335 | lib/generators/half_pipe/templates/tasks/options/sass.js | lib/generators/half_pipe/templates/tasks/options/sass.js | module.exports = {
options: {
require: ['sass-css-importer'],
loadPath: ['<%%= bowerOpts.directory || "bower_components" %>'],
bundleExec: true,
},
debug: {
src: '<%%= dirs.tmp %>/prepare/assets/styles/main.scss',
dest: '<%%= dirs.tmp %>/public/assets/styles/main.css',
options: {
style: 'expanded'
}
},
"public": {
src: '<%%= dirs.tmp %>/prepare/assets/styles/main.scss',
dest: '<%%= dirs.tmp %>/public/assets/styles/main.css',
options: {
style: 'compressed'
}
}
};
| module.exports = {
options: {
require: ['sass-css-importer'],
loadPath: ['<%%= bowerOpts.directory || "bower_components" %>'],
bundleExec: true
},
debug: {
src: '<%%= dirs.tmp %>/prepare/assets/styles/main.scss',
dest: '<%%= dirs.tmp %>/public/assets/styles/main.css',
options: {
style: 'expanded',
sourcemaps: 'true'
}
},
"public": {
src: '<%%= dirs.tmp %>/prepare/assets/styles/main.scss',
dest: '<%%= dirs.tmp %>/public/assets/styles/main.css',
options: {
style: 'compressed'
}
}
};
| Add sourcemaps option to Sass task | Add sourcemaps option to Sass task | JavaScript | mit | half-pipe/half-pipe,half-pipe/half-pipe | ---
+++
@@ -2,13 +2,14 @@
options: {
require: ['sass-css-importer'],
loadPath: ['<%%= bowerOpts.directory || "bower_components" %>'],
- bundleExec: true,
+ bundleExec: true
},
debug: {
src: '<%%= dirs.tmp %>/prepare/assets/styles/main.scss',
dest: '<%%= dirs.tmp %>/public/assets/styles/main.css',
options: {
- style: 'expanded'
+ style: 'expanded',
+ sourcemaps: 'true'
}
},
"public": { |
5068d340bf68c03d79d3c6b9325f5557d4daa3c9 | lib/libra2/app/assets/javascripts/file_upload_options.js | lib/libra2/app/assets/javascripts/file_upload_options.js | (function() {
"use strict";
function initPage() {
var fileTypes = [
"csv",
"gif",
"jpeg",
"jpg",
"mp3",
"mp4",
"pdf",
"png",
"tif",
"tiff",
"txt",
"xml"
];
var list = fileTypes.join(", ").toUpperCase();
var filter = fileTypes.join("|");
// Match any file that doesn't contain the above extensions.
var regex = new RegExp("(\.|\/)(" + filter + ")$", "i");
var acceptableFileTypeList = $(".acceptable-file-type-list");
acceptableFileTypeList.text(list);
var fileUploadButton = $('#fileupload');
if (fileUploadButton.length > 0) { // If we are on a page with file upload.
// Override curation_concern's file filter. We wait until we are sure that the curation_concern has initialized to make sure this gets called last.
setTimeout(function() {
fileUploadButton.fileupload(
'option',
'acceptFileTypes',
regex
);
}, 1000);
}
}
$(window).bind('page:change', function() {
initPage();
});
})();
| (function() {
"use strict";
function initPage() {
var fileTypes = [
"csv",
"gif",
"htm",
"html",
"jpeg",
"jpg",
"mp3",
"mp4",
"pdf",
"png",
"tif",
"tiff",
"txt",
"xml"
];
var list = fileTypes.join(", ").toUpperCase();
var filter = fileTypes.join("|");
// Match any file that doesn't contain the above extensions.
var regex = new RegExp("(\.|\/)(" + filter + ")$", "i");
var acceptableFileTypeList = $(".acceptable-file-type-list");
acceptableFileTypeList.text(list);
var fileUploadButton = $('#fileupload');
if (fileUploadButton.length > 0) { // If we are on a page with file upload.
// Override curation_concern's file filter. We wait until we are sure that the curation_concern has initialized to make sure this gets called last.
setTimeout(function() {
fileUploadButton.fileupload(
'option',
'acceptFileTypes',
regex
);
}, 1000);
}
}
$(window).bind('page:change', function() {
initPage();
});
})();
| Add html and htm to list of acceptable files | LIBRA-235: Add html and htm to list of acceptable files
| JavaScript | apache-2.0 | uvalib/Libra2,uvalib/Libra2,uvalib/Libra2,uvalib/Libra2,uvalib/Libra2 | ---
+++
@@ -5,6 +5,8 @@
var fileTypes = [
"csv",
"gif",
+ "htm",
+ "html",
"jpeg",
"jpg",
"mp3", |
253529d42c1ef9b7aed7b2754c77bc8a246d892e | repeat.js | repeat.js | /*! http://mths.be/repeat v0.1.0 by @mathias */
if (!String.prototype.repeat) {
(function() {
'use strict'; // needed to support `apply`/`call` with `undefined`/`null`
var repeat = function(count) {
if (this == null) {
throw TypeError();
}
var string = String(this);
// `ToInteger`
var n = count ? Number(count) : 0;
if (n != n) { // better `isNaN`
n = 0;
}
// Account for out-of-bounds indices
if (n < 0 || n == Infinity) {
throw RangeError();
}
if (n == 0) {
return '';
}
var result = '';
while (n--) {
result += string;
}
return result;
};
if (Object.defineProperty) {
Object.defineProperty(String.prototype, 'repeat', {
'value': repeat,
'configurable': true,
'writable': true
});
} else {
String.prototype.repeat = repeat;
}
}());
}
| /*! http://mths.be/repeat v0.1.0 by @mathias */
if (!String.prototype.repeat) {
(function() {
'use strict'; // needed to support `apply`/`call` with `undefined`/`null`
var repeat = function(count) {
if (this == null) {
throw TypeError();
}
var string = String(this);
// `ToInteger`
var n = count ? Number(count) : 0;
if (n != n) { // better `isNaN`
n = 0;
}
// Account for out-of-bounds indices
if (n < 0 || n == Infinity) {
throw RangeError();
}
var result = '';
while (n--) {
result += string;
}
return result;
};
if (Object.defineProperty) {
Object.defineProperty(String.prototype, 'repeat', {
'value': repeat,
'configurable': true,
'writable': true
});
} else {
String.prototype.repeat = repeat;
}
}());
}
| Remove unnecessary check for `n == 0` | Remove unnecessary check for `n == 0`
The `while` loop below handles this case anyway. The only ‘overhead’ the check avoided was a single `n--` and a `ToBoolean(0)` — so this was definitely a micro-optimization.
Closes #3.
| JavaScript | mit | mathiasbynens/String.prototype.repeat | ---
+++
@@ -16,9 +16,6 @@
if (n < 0 || n == Infinity) {
throw RangeError();
}
- if (n == 0) {
- return '';
- }
var result = '';
while (n--) {
result += string; |
c7dd9a0b4aacce1e04e9cbe4400b085cd0eb9119 | src/build.js | src/build.js | var requirejs = require('requirejs');
var applicationConfig = {
baseUrl: './public/js',
name: 'app',
out: './public/app.js',
mainConfigFile: './public/js/app.js',
paths: {
'socket.io': 'empty:',
'requireLib': 'require'
},
include: [
'requireLib'
]
};
var mainConfig = {
baseUrl: './public/js',
name: 'main',
out: './public/main.js',
mainConfigFile: './public/js/main.js',
paths: {
'socket.io': 'empty:',
'requireLib': 'require'
},
include: [
'requireLib'
]
};
requirejs.optimize(applicationConfig, function (log) {
console.log("Application javascript optimisation complete".green);
console.log((log).cyan);
}, function(error) {
console.log(("Error optimizing javascript: " + error).red);
});
requirejs.optimize(mainConfig, function (log) {
console.log("Main javascript optimisation complete".green);
console.log((log).cyan);
}, function(err) {
console.log(("Error optimizing javascript: " + err).red);
}); | var requirejs = require('requirejs');
var applicationConfig = {
baseUrl: './public/js',
name: 'app',
out: './public/app.js',
mainConfigFile: './public/js/app.js',
paths: {
'socket.io': 'empty:',
'requireLib': 'require'
},
include: [
'requireLib'
]
};
var mainConfig = {
baseUrl: './public/js',
name: 'main',
out: './public/main.js',
mainConfigFile: './public/js/main.js',
paths: {
'socket.io': 'empty:',
'requireLib': 'require'
},
include: [
'requireLib'
]
};
requirejs.optimize(applicationConfig, function (log) {
console.log("Application javascript optimisation complete".green);
console.log((log).cyan);
}, function(error) {
console.log(("Error optimizing javascript: " + error).red);
});
requirejs.optimize(mainConfig, function (log) {
console.log("Main javascript optimisation complete".green);
console.log((log).cyan);
}, function(error) {
console.log(("Error optimizing javascript: " + error).red);
});
var cssConfig = {
cssIn: './public/css/main.css',
out: './public/app.css',
optimizeCss: 'standard'
};
requirejs.optimize(cssConfig, function(log) {
console.log(("Application CSS optimisation complete").green);
console.log((log).cyan);
}, function(error) {
console.log(("Error optimizing CSS: " + error).red);
}); | Compress CSS into a single file | Compress CSS into a single file
| JavaScript | apache-2.0 | pinittome/pinitto.me,pinittome/pinitto.me,pinittome/pinitto.me | ---
+++
@@ -37,7 +37,19 @@
requirejs.optimize(mainConfig, function (log) {
console.log("Main javascript optimisation complete".green);
+ console.log((log).cyan);
+}, function(error) {
+ console.log(("Error optimizing javascript: " + error).red);
+});
+
+var cssConfig = {
+ cssIn: './public/css/main.css',
+ out: './public/app.css',
+ optimizeCss: 'standard'
+};
+requirejs.optimize(cssConfig, function(log) {
+ console.log(("Application CSS optimisation complete").green);
console.log((log).cyan);
-}, function(err) {
- console.log(("Error optimizing javascript: " + err).red);
+}, function(error) {
+ console.log(("Error optimizing CSS: " + error).red);
}); |
a9ed364ba26e9952a05934ac5369dce8db23c4da | public/nav_control/nav_control.js | public/nav_control/nav_control.js | import { constant, includes } from 'lodash';
import { element } from 'angular';
import uiModules from 'ui/modules';
import registry from 'ui/registry/chrome_nav_controls';
import '../components/notification_center';
import template from './nav_control.html';
import 'ui/angular-bootstrap';
registry.register(constant({
name: 'notification_center',
order: 1000,
template
}));
const module = uiModules.get('notification_center', []);
module.controller('notificationCenterNavController', ($scope, $compile, $document, NotificationCenter) => {
function initNotificationCenter() {
const $elem = $scope.$notificationCenter = $compile('<notification-center></notification-center>')($scope).appendTo('.app-wrapper');
$document.on('click', ({ target }) => {
if (target !== $elem[0] && !$elem[0].contains(target)) {
$elem.hide();
}
});
};
$scope.openNotificationCenter = event => {
event.preventDefault();
if (!$scope.$notificationCenter) {
initNotificationCenter();
} else {
$scope.$notificationCenter.toggle();
}
event.stopPropagation();
};
$scope.formatTooltip = () =>{
return `${NotificationCenter.notifications.length} new notifications`;
};
});
| import { constant, includes } from 'lodash';
import { element } from 'angular';
import uiModules from 'ui/modules';
import registry from 'ui/registry/chrome_nav_controls';
import '../components/notification_center';
import template from './nav_control.html';
import 'ui/angular-bootstrap';
registry.register(constant({
name: 'notification_center',
order: 1000,
template
}));
const module = uiModules.get('notification_center', []);
module.controller('notificationCenterNavController', ($scope, $compile, $document, NotificationCenter) => {
function initNotificationCenter() {
const $elem = $scope.$notificationCenter = $compile('<notification-center/>')($scope).appendTo('.app-wrapper');
$document.on('click', () => $elem.hide());
$elem.on('click', e => e.stopPropagation());
};
$scope.openNotificationCenter = event => {
event.preventDefault();
if (!$scope.$notificationCenter) {
initNotificationCenter();
} else {
$scope.$notificationCenter.toggle();
}
event.stopPropagation();
};
$scope.formatTooltip = () =>{
return `${NotificationCenter.notifications.length} new notifications`;
};
});
| Fix notification-center not to close when button clicked. | Fix notification-center not to close when button clicked.
| JavaScript | mit | sw-jung/kibana_notification_center,sw-jung/kibana_notification_center | ---
+++
@@ -15,12 +15,9 @@
const module = uiModules.get('notification_center', []);
module.controller('notificationCenterNavController', ($scope, $compile, $document, NotificationCenter) => {
function initNotificationCenter() {
- const $elem = $scope.$notificationCenter = $compile('<notification-center></notification-center>')($scope).appendTo('.app-wrapper');
- $document.on('click', ({ target }) => {
- if (target !== $elem[0] && !$elem[0].contains(target)) {
- $elem.hide();
- }
- });
+ const $elem = $scope.$notificationCenter = $compile('<notification-center/>')($scope).appendTo('.app-wrapper');
+ $document.on('click', () => $elem.hide());
+ $elem.on('click', e => e.stopPropagation());
};
$scope.openNotificationCenter = event => { |
225df4bb8f5e6561161dab095c49a8b78286dbb2 | src/components/Heading.js | src/components/Heading.js | /*
* A reusable component to display a styled heading.
*/
import PropTypes from 'prop-types';
import React, {Component} from 'react';
import {StyleSheet, css} from 'aphrodite/no-important';
export default class Heading extends Component {
static propTypes = {
level: PropTypes.oneOf([1, 2]).isRequired,
}
render() {
const Tag = `h${this.props.level}`;
return <Tag className={css(styles[Tag])}>
{this.props.children}
</Tag>;
}
}
const styles = StyleSheet.create({
h1: {
marginTop: 18,
fontSize: 32,
fontWeight: 'normal',
},
h2: {
marginTop: 14,
fontSize: 24,
fontWeight: 'normal',
},
});
| /*
* A reusable component to display a styled heading.
*/
import PropTypes from 'prop-types';
import React, {Component} from 'react';
import {StyleSheet, css} from 'aphrodite/no-important';
export default class Heading extends Component {
static propTypes = {
level: PropTypes.oneOf([1, 2, 3]).isRequired,
}
render() {
const Tag = `h${this.props.level}`;
return <Tag className={css(styles[Tag])}>
{this.props.children}
</Tag>;
}
}
const styles = StyleSheet.create({
h1: {
marginTop: 18,
fontSize: 32,
fontWeight: 'normal',
},
h2: {
marginTop: 14,
fontSize: 24,
fontWeight: 'normal',
},
h3: {
marginTop: 12,
fontSize: 20,
fontWeight: 'normal',
},
});
| Add support for level-3 headings | Add support for level-3 headings
| JavaScript | mit | wchargin/wchargin.github.io,wchargin/wchargin.github.io | ---
+++
@@ -9,7 +9,7 @@
export default class Heading extends Component {
static propTypes = {
- level: PropTypes.oneOf([1, 2]).isRequired,
+ level: PropTypes.oneOf([1, 2, 3]).isRequired,
}
render() {
@@ -32,4 +32,9 @@
fontSize: 24,
fontWeight: 'normal',
},
+ h3: {
+ marginTop: 12,
+ fontSize: 20,
+ fontWeight: 'normal',
+ },
}); |
641b6937f8b8b54bd654c4ca6ca5345be5ff3f0e | router.js | router.js | var httpProxy = require('http-proxy');
var http = require('http');
var proxy = httpProxy.createProxy();
var routes = {
// Router
'hook.labeli.org' : 'http://localhost:9000',
// Api
'api.labeli.org' : 'http://localhost:9010',
'hook.api.labeli.org' : 'http://localhost:9011',
// Website
'next.labeli.org' : 'http://localhost:9020',
'hook.next.labeli.org' : 'http://localhost:9021',
};
var router = http.createServer(function(req, res)
{
proxy.web(req, res, {target : routes[req.headers.host]});
});
router.listen(80); | var httpProxy = require('http-proxy');
var http = require('http');
var proxy = httpProxy.createProxyServer({});
var routes = {
// Router
'hook.labeli.org' : 'http://localhost:9000',
// Api
'api.labeli.org' : 'http://localhost:9010',
'hook.api.labeli.org' : 'http://localhost:9011',
// Website
'next.labeli.org' : 'http://localhost:9020',
'hook.next.labeli.org' : 'http://localhost:9021',
};
function getRouteFor(host){
if (routes[host] == undefined)
return "http://localhost:9020";
return routes[host];
}
var router = http.createServer(function(req, res)
{
proxy.web(req, res, {target : getRouteFor(req.headers.host)});
});
router.listen(80);
| Add method getRouteFor() to create default route | Add method getRouteFor() to create default route
| JavaScript | mit | asso-labeli/labeli-router,asso-labeli/labeli-router | ---
+++
@@ -1,22 +1,29 @@
var httpProxy = require('http-proxy');
var http = require('http');
-var proxy = httpProxy.createProxy();
+var proxy = httpProxy.createProxyServer({});
var routes = {
- // Router
- 'hook.labeli.org' : 'http://localhost:9000',
- // Api
- 'api.labeli.org' : 'http://localhost:9010',
- 'hook.api.labeli.org' : 'http://localhost:9011',
- // Website
- 'next.labeli.org' : 'http://localhost:9020',
- 'hook.next.labeli.org' : 'http://localhost:9021',
+ // Router
+ 'hook.labeli.org' : 'http://localhost:9000',
+ // Api
+ 'api.labeli.org' : 'http://localhost:9010',
+ 'hook.api.labeli.org' : 'http://localhost:9011',
+ // Website
+ 'next.labeli.org' : 'http://localhost:9020',
+ 'hook.next.labeli.org' : 'http://localhost:9021',
};
+
+function getRouteFor(host){
+ if (routes[host] == undefined)
+ return "http://localhost:9020";
+
+ return routes[host];
+}
var router = http.createServer(function(req, res)
{
- proxy.web(req, res, {target : routes[req.headers.host]});
+ proxy.web(req, res, {target : getRouteFor(req.headers.host)});
});
router.listen(80); |
3c54b4d5f8351898be26699ad9cece43318a32e3 | frontend/config/dev.env.js | frontend/config/dev.env.js | var merge = require('webpack-merge')
var prodEnv = require('./prod.env')
module.exports = merge(prodEnv, {
NODE_ENV: '"development"',
API_HOST: '"http://localhost:3000"'
})
| var merge = require('webpack-merge')
var prodEnv = require('./prod.env')
module.exports = merge(prodEnv, {
NODE_ENV: '"development"',
API_HOST: '"http://localhost:5100"'
})
| Fix local api server path because of Foreman | Fix local api server path because of Foreman
| JavaScript | mit | riseshia/Bonghwa,riseshia/Bonghwa,riseshia/Bonghwa,riseshia/Bonghwa | ---
+++
@@ -3,5 +3,5 @@
module.exports = merge(prodEnv, {
NODE_ENV: '"development"',
- API_HOST: '"http://localhost:3000"'
+ API_HOST: '"http://localhost:5100"'
}) |
c956e63c62f17c3c671ea991f978e42218a94691 | app/assets/javascripts/application.js | app/assets/javascripts/application.js | // This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD
// GO AFTER THE REQUIRES BELOW.
//
//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require leaflet
//= require mapbox
//= require bootstrap
//= require ./typeahead.min
//= require_tree .
| // This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD
// GO AFTER THE REQUIRES BELOW.
//
//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require leaflet
//= require ./leaflet.markercluster
//= require mapbox
//= require bootstrap
//= require ./typeahead.min
//= require_tree .
| Add explicit include (early in order) for the leaflet.markercluster js file | Add explicit include (early in order) for the leaflet.markercluster js file
| JavaScript | mit | codeforgso/cityvoice,ajb/cityvoice,daguar/cityvoice,ajb/cityvoice,codeforgso/cityvoice,daguar/cityvoice,codeforgso/cityvoice,codeforamerica/cityvoice,codeforamerica/cityvoice,ajb/cityvoice,codeforamerica/cityvoice,daguar/cityvoice,daguar/cityvoice,codeforamerica/cityvoice,ajb/cityvoice,codeforgso/cityvoice | ---
+++
@@ -14,6 +14,7 @@
//= require jquery_ujs
//= require turbolinks
//= require leaflet
+//= require ./leaflet.markercluster
//= require mapbox
//= require bootstrap
//= require ./typeahead.min |
d703dad4967b92c85a470b5d445a7a1fd5765352 | app/assets/javascripts/osem-switch.js | app/assets/javascripts/osem-switch.js | $(function () {
$("[class='switch-checkbox']").bootstrapSwitch();
$('input[class="switch-checkbox"]').on('switchChange.bootstrapSwitch', function(event, state) {
var url = $(this).attr('url') + state;
var method = $(this).attr('method');
$.ajax({
url: url,
type: method,
dataType: 'script'
});
});
$("[class='switch-checkbox-schedule']").bootstrapSwitch();
$('input[class="switch-checkbox-schedule"]').on('switchChange.bootstrapSwitch', function(event, state) {
var url = $(this).attr('url');
var method = $(this).attr('method');
if(state){
url += $(this).attr('value');
}
var callback = function(data) {
showError($.parseJSON(data.responseText).errors);
}
$.ajax({
url: url,
type: method,
error: callback,
dataType: 'json'
});
});
});
| function checkboxSwitch(selector){
$(selector).bootstrapSwitch(
);
$(selector).on('switchChange.bootstrapSwitch', function(event, state) {
var url = $(this).attr('url') + state;
var method = $(this).attr('method');
$.ajax({
url: url,
type: method,
dataType: 'script'
});
});
}
$(function () {
checkboxSwitch("[class='switch-checkbox']");
$("[class='switch-checkbox-schedule']").bootstrapSwitch();
$('input[class="switch-checkbox-schedule"]').on('switchChange.bootstrapSwitch', function(event, state) {
var url = $(this).attr('url');
var method = $(this).attr('method');
if(state){
url += $(this).attr('value');
}
var callback = function(data) {
showError($.parseJSON(data.responseText).errors);
}
$.ajax({
url: url,
type: method,
error: callback,
dataType: 'json'
});
});
});
| Add a function for initing boostrapSwitch outside of $() | Add a function for initing boostrapSwitch outside of $()
| JavaScript | mit | bear454/osem,hennevogel/osem,AndrewKvalheim/osem,differentreality/osem,differentreality/osem,rishabhptr/osem,openSUSE/osem,rishabhptr/osem,bear454/osem,SeaGL/osem,openSUSE/osem,rishabhptr/osem,differentreality/osem,hennevogel/osem,hennevogel/osem,SeaGL/osem,hennevogel/osem,openSUSE/osem,bear454/osem,rishabhptr/osem,AndrewKvalheim/osem,differentreality/osem,AndrewKvalheim/osem,bear454/osem,SeaGL/osem | ---
+++
@@ -1,7 +1,9 @@
-$(function () {
- $("[class='switch-checkbox']").bootstrapSwitch();
+function checkboxSwitch(selector){
+ $(selector).bootstrapSwitch(
- $('input[class="switch-checkbox"]').on('switchChange.bootstrapSwitch', function(event, state) {
+ );
+
+ $(selector).on('switchChange.bootstrapSwitch', function(event, state) {
var url = $(this).attr('url') + state;
var method = $(this).attr('method');
@@ -11,6 +13,10 @@
dataType: 'script'
});
});
+}
+
+$(function () {
+ checkboxSwitch("[class='switch-checkbox']");
$("[class='switch-checkbox-schedule']").bootstrapSwitch();
|
23a7aefe2d78f46523bd71a25c3ceb90db254f5e | src/index.js | src/index.js | const fs = require('fs');
const path = require('path');
const { infer } = require('bayesjs');
const { json, send } = require('micro');
const htmlContent = fs
.readFileSync(path.join(__dirname, 'index.html'))
.toString();
module.exports = async (req, res) => {
if (req.url !== '/') {
return send(res, 404);
}
switch (req.method.toUpperCase()) {
case 'GET': {
return htmlContent;
}
case 'POST': {
const payload = await json(req);
return infer(payload.network, payload.nodes, payload.given);
}
}
return send(res, 404);
};
| const fs = require('fs');
const path = require('path');
const { infer } = require('bayesjs');
const { json, send } = require('micro');
const htmlContent = fs
.readFileSync(path.join(__dirname, 'index.html'))
.toString();
module.exports = async (req, res) => {
if (req.url !== '/') {
return send(res, 404);
}
switch (req.method.toUpperCase()) {
case 'GET': {
return htmlContent;
}
case 'POST': {
const payload = await json(req);
return infer(payload.network, payload.nodes, payload.given);
}
default: {
return send(res, 405);
}
}
};
| Change 'not found' to 'method not allowed' | Change 'not found' to 'method not allowed'
| JavaScript | mit | fhelwanger/bayesjs-ws,fhelwanger/bayesjs-ws | ---
+++
@@ -20,7 +20,8 @@
const payload = await json(req);
return infer(payload.network, payload.nodes, payload.given);
}
+ default: {
+ return send(res, 405);
+ }
}
-
- return send(res, 404);
}; |
73f420d634399f26a329fd66f1afc6221e1aeb8b | src/index.js | src/index.js | const Discord = require('discord.js');
const config = require('./config.json');
const manager = new Discord.ShardingManager('./bot.js');
//Spawn with a relevant number of shards automatically
manager.spawn();
| const Discord = require('discord.js');
const config = require('./config.json');
const API = require("./api.json");
const manager = new Discord.ShardingManager('./bot.js', {
token: API.discord
});
//Spawn with a relevant number of shards automatically
manager.spawn();
| Add token in sharding manager | Add token in sharding manager
| JavaScript | mit | moustacheminer/MSS-Discord,moustacheminer/MSS-Discord,moustacheminer/MSS-Discord | ---
+++
@@ -1,6 +1,9 @@
const Discord = require('discord.js');
const config = require('./config.json');
-const manager = new Discord.ShardingManager('./bot.js');
+const API = require("./api.json");
+const manager = new Discord.ShardingManager('./bot.js', {
+ token: API.discord
+});
//Spawn with a relevant number of shards automatically
manager.spawn(); |
5955b691f3e44cbf8224e070c1c67fdd070f5454 | src/content.js | src/content.js | /* Listen for messages and get modResource meta tag*/
chrome.runtime.onMessage.addListener(function(msg, sender, sendResponse) {
if (msg.command && (msg.command == "getResource")) {
function getMetaContentByName(name,content){
var content = (content==null)?'content':content;
var meta = document.querySelector("meta[name='" + name + "']");
if (meta) {
return meta.getAttribute(content);
}
}
sendResponse(getMetaContentByName("modResource"));
}
}); | /* Listen for messages and get modResource meta tag*/
chrome.runtime.onMessage.addListener(function(msg, sender, sendResponse) {
if (msg.command && (msg.command == "getResource")) {
function getMetaContentByName(name,content){
var content = (content==null)?'content':content;
var meta = document.querySelector("meta[name='" + name + "']");
if (meta) {
return meta.getAttribute(content);
}
}
sendResponse(getMetaContentByName('application-name','data-id'));
}
}); | Change meta name for valid html output | Change meta name for valid html output
| JavaScript | mit | bartholomej/modx-manager-switch,bartholomej/modx-manager-switch | ---
+++
@@ -9,6 +9,6 @@
return meta.getAttribute(content);
}
}
- sendResponse(getMetaContentByName("modResource"));
+ sendResponse(getMetaContentByName('application-name','data-id'));
}
}); |
490f0af6992eab28938273d91341073138082b35 | test/unit/tadaboard-node-sdk.js | test/unit/tadaboard-node-sdk.js | import TB from '../../src/tadaboard-node-sdk';
describe('TB', () => {
});
| import TB from '../../src/tadaboard-node-sdk';
describe('TB', () => {
describe('response', () => {
it('is a function', () => {
expect(TB.response).to.be.a('function');
});
});
});
| Add simple test for TB.response | Add simple test for TB.response
| JavaScript | mit | tadaboard/node-sdk,tadaboard/node-sdk | ---
+++
@@ -1,4 +1,9 @@
import TB from '../../src/tadaboard-node-sdk';
describe('TB', () => {
+ describe('response', () => {
+ it('is a function', () => {
+ expect(TB.response).to.be.a('function');
+ });
+ });
}); |
c716b8f23392e2d26c7675f193be4c54f72205cd | app/renderer/js/notification/index.js | app/renderer/js/notification/index.js | 'use strict';
const {
remote: { app }
} = require('electron');
const DefaultNotification = require('./default-notification');
const { appId, loadBots } = require('./helpers');
// From https://github.com/felixrieseberg/electron-windows-notifications#appusermodelid
// On windows 8 we have to explicitly set the appUserModelId otherwise notification won't work.
app.setAppUserModelId(appId);
window.Notification = DefaultNotification;
if (process.platform === 'darwin') {
const DarwinNotification = require('./darwin-notifications');
window.Notification = DarwinNotification;
}
window.addEventListener('load', () => {
loadBots();
});
| 'use strict';
const {
remote: { app }
} = require('electron');
const DefaultNotification = require('./default-notification');
const { appId, loadBots } = require('./helpers');
// From https://github.com/felixrieseberg/electron-windows-notifications#appusermodelid
// On windows 8 we have to explicitly set the appUserModelId otherwise notification won't work.
app.setAppUserModelId(appId);
window.Notification = DefaultNotification;
if (process.platform === 'darwin') {
const DarwinNotification = require('./darwin-notifications');
window.Notification = DarwinNotification;
}
window.addEventListener('load', () => {
// Call this function only when user is logged in
// eslint-disable-next-line no-undef, camelcase
if (page_params.realm_uri) {
loadBots();
}
});
| Refactor code for bot mention in reply. | notification: Refactor code for bot mention in reply.
| JavaScript | apache-2.0 | zulip/zulip-desktop,zulip/zulip-desktop,zulip/zulip-desktop,zulip/zulip-electron,zulip/zulip-electron,zulip/zulip-desktop,zulip/zulip-electron | ---
+++
@@ -12,11 +12,16 @@
app.setAppUserModelId(appId);
window.Notification = DefaultNotification;
+
if (process.platform === 'darwin') {
const DarwinNotification = require('./darwin-notifications');
window.Notification = DarwinNotification;
}
window.addEventListener('load', () => {
- loadBots();
+ // Call this function only when user is logged in
+ // eslint-disable-next-line no-undef, camelcase
+ if (page_params.realm_uri) {
+ loadBots();
+ }
}); |
39525514e4849eb514bb563e51f5cb7e5900f0ea | blueprints/flexberry-edit-form/snippets/getCellComponent-function.js | blueprints/flexberry-edit-form/snippets/getCellComponent-function.js | (attr, bindingPath, model) {
let cellComponent = this._super(...arguments);
if (attr.kind === 'belongsTo') {
switch (<% '`${model.modelName}+${bindingPath}`' %>) {
<%= bodySwitchBindingPath %>
}
}
return cellComponent;
}
| (attr, bindingPath, model) {
let cellComponent = this._super(...arguments);
if (attr.kind === 'belongsTo') {
switch (<%= '`${model.modelName}+${bindingPath}`' %>) {
<%= bodySwitchBindingPath %>
}
}
return cellComponent;
}
| Fix flexberry-edit-form blueprint getCellComponent template | Fix flexberry-edit-form blueprint getCellComponent template
| JavaScript | mit | Flexberry/ember-flexberry,Flexberry/ember-flexberry,Flexberry/ember-flexberry,Flexberry/ember-flexberry | ---
+++
@@ -1,7 +1,7 @@
(attr, bindingPath, model) {
let cellComponent = this._super(...arguments);
if (attr.kind === 'belongsTo') {
- switch (<% '`${model.modelName}+${bindingPath}`' %>) {
+ switch (<%= '`${model.modelName}+${bindingPath}`' %>) {
<%= bodySwitchBindingPath %>
}
} |
2237d762db94f82264d5784412720fcfe69226a0 | Assets/js/init-dropzone.js | Assets/js/init-dropzone.js | $( document ).ready(function() {
Dropzone.autoDiscover = false;
var myDropzone = new Dropzone(".dropzone", {
url: '/api/file',
autoProcessQueue: true,
maxFilesize: maxFilesize,
acceptedFiles : acceptedFiles
});
myDropzone.on("success", function(file, http) {
window.setTimeout(function(){
location.reload();
}, 1000);
});
myDropzone.on("sending", function(file, fromData) {
if ($('.alert-danger').length > 0) {
$('.alert-danger').remove();
}
});
myDropzone.on("error", function(file, errorMessage) {
var html = '<div class="alert alert-danger" role="alert">' + errorMessage.file[0] + '</div>';
$('.col-md-12').first().prepend(html);
setTimeout(function() {
myDropzone.removeFile(file);
}, 2000);
});
});
| $( document ).ready(function() {
Dropzone.autoDiscover = false;
var myDropzone = new Dropzone(".dropzone", {
url: '/api/file',
autoProcessQueue: true,
maxFilesize: maxFilesize,
acceptedFiles : acceptedFiles
});
myDropzone.on("queuecomplete", function(file, http) {
window.setTimeout(function(){
location.reload();
}, 1000);
});
myDropzone.on("sending", function(file, fromData) {
if ($('.alert-danger').length > 0) {
$('.alert-danger').remove();
}
});
myDropzone.on("error", function(file, errorMessage) {
var html = '<div class="alert alert-danger" role="alert">' + errorMessage.file[0] + '</div>';
$('.col-md-12').first().prepend(html);
setTimeout(function() {
myDropzone.removeFile(file);
}, 2000);
});
});
| Fix early redirect when uploading multiple files | Fix early redirect when uploading multiple files
I had the case where I needed to upload 20+ files. Some files were uploaded others not.
The others failed due to the location.reload() function triggered on the first success emit from a first successful upload.
It seems by using the queuecomplete event it works in both cases:
- uploading 1 file
- uploading 20 files | JavaScript | mit | zedee/Media,zedee/Media,AsgardCms/Media,oimken/Media,MentallyFriendly/Media,mikemand/Media,gabva/Media,mikemand/Media,AsgardCms/Media,mikemand/Media,AsgardCms/Media,MentallyFriendly/Media,gabva/Media,ruscon/Media,oimken/Media,zedee/Media,oimken/Media,ruscon/Media | ---
+++
@@ -6,7 +6,7 @@
maxFilesize: maxFilesize,
acceptedFiles : acceptedFiles
});
- myDropzone.on("success", function(file, http) {
+ myDropzone.on("queuecomplete", function(file, http) {
window.setTimeout(function(){
location.reload();
}, 1000); |
16eadc7fd084c4d4471655aa5239b77c933529db | tasks/options/concat_sourcemap.js | tasks/options/concat_sourcemap.js | module.exports = {
app: {
src: ['tmp/transpiled/app/**/*.js'],
dest: 'tmp/public/assets/app.js'
},
test: {
src: 'tmp/transpiled/tests/**/*.js',
dest: 'tmp/public/tests/tests.js'
}
};
| module.exports = {
app: {
src: ['tmp/transpiled/app/**/*.js'],
dest: 'tmp/public/assets/app.js',
options: {
sourcesContent: true
},
},
test: {
src: 'tmp/transpiled/tests/**/*.js',
dest: 'tmp/public/tests/tests.js',
options: {
sourcesContent: true
}
}
};
| Revert "sourceMappingURL instead of sourceContent for now" | Revert "sourceMappingURL instead of sourceContent for now"
This reverts commit cd758092a64445d48c5e4ab61407a5c5b51ea8f1.
| JavaScript | mit | sajt/ember-weather,mixonic/ember-app-kit,duvillierA/try_ember,grese/miner-app-OLD,cevn/tasky-web,ClockworkNet/ember-boilerplate,stefanpenner/ember-app-kit,kiwiupover/seattle-auckland-weather,kiwiupover/ember-weather,shin1ohno/want-js,tomclose/minimal_eak_test_stub_problem,ClockworkNet/ember-boilerplate,Anshdesire/ember-app-kit,eriktrom/ember-weather-traininig,grese/btcArbitrage,joliss/broccoli-todo,digitalplaywright/eak-simple-auth,arjand/weddingapp,lucaspottersky/ember-lab-eak,tobobo/vice-frontend,stefanpenner/ember-app-kit,lucaspottersky/ember-lab-eak,ebryn/ember-github-issues,mharris717/eak_base_app,daevid/broccoli-todo,tobobo/thyme-frontend,digitalplaywright/eak-simple-auth-blog-client,tucsonlabs/ember-weather-legacy,shin1ohno/EmberAppKit,tomclose/test_loading_problem,sajt/ember-weather,grese/miner-app-OLD,tobobo/thyme-frontend,jwlms/ember-weather-legacy,teddyzeenny/assistant,michaelorionmcmanus/eak-bootstrap,aboveproperty/ember-app-kit-karma,Anshdesire/ember-app-kit,thaume/emberjs-es6-modules,ghempton/ember-libs-example,tobobo/shibe_io_frontend,trombom/ember-weather-traininig,achambers/appkit-hanging-test-example,mtian/ember-app-kit-azure,kiwiupover/ember-weather,mtian/ember-app-kit-azure | ---
+++
@@ -1,11 +1,17 @@
module.exports = {
app: {
src: ['tmp/transpiled/app/**/*.js'],
- dest: 'tmp/public/assets/app.js'
+ dest: 'tmp/public/assets/app.js',
+ options: {
+ sourcesContent: true
+ },
},
test: {
src: 'tmp/transpiled/tests/**/*.js',
- dest: 'tmp/public/tests/tests.js'
+ dest: 'tmp/public/tests/tests.js',
+ options: {
+ sourcesContent: true
+ }
}
}; |
c518210b525a55e01f8ec1551ec40a2d08133bac | public/js/routes/Routes.js | public/js/routes/Routes.js | define(['app', 'controllers/Today', 'controllers/History', 'services/History'], function (app) {
"use strict";
return app.config(['$routeProvider', function (routes) {
routes
.when('/', {
controller: 'TodayController',
templateUrl: '/partials/today.html'
})
.when('/history', {
controller: 'HistoryController',
templateUrl: '/partials/history.html'
})
.when('/signedin', {
controller: function (location, historyService) {
historyService.sync();
location.url('/');
},
resolve: {
location: '$location',
historyService: 'historyService'
},
// A view is required in order for the Controller to
// get called.
template: 'Hello!'
})
.otherwise({ redirectTo: '/' });
}]);
});
| define(['app', 'controllers/Today', 'controllers/History', 'services/History'], function (app) {
"use strict";
return app.config(['$routeProvider', function (routes) {
routes
.when('/', {
controller: 'TodayController',
templateUrl: '/partials/today.html'
})
.when('/history', {
controller: 'HistoryController',
templateUrl: '/partials/history.html'
})
.when('/signedin', {
controller: ['$location', 'historyService', function (location, historyService) {
historyService.sync();
location.url('/');
}],
// A view is required in order for the Controller to
// get called.
template: '<span class="text-center">Hello!</span>'
})
.otherwise({ redirectTo: '/' });
}]);
});
| Fix resolve for minified route controller | Fix resolve for minified route controller
| JavaScript | mit | BrettBukowski/tomatar | ---
+++
@@ -12,17 +12,13 @@
templateUrl: '/partials/history.html'
})
.when('/signedin', {
- controller: function (location, historyService) {
+ controller: ['$location', 'historyService', function (location, historyService) {
historyService.sync();
location.url('/');
- },
- resolve: {
- location: '$location',
- historyService: 'historyService'
- },
+ }],
// A view is required in order for the Controller to
// get called.
- template: 'Hello!'
+ template: '<span class="text-center">Hello!</span>'
})
.otherwise({ redirectTo: '/' });
}]); |
11764092ee043286fd017da940c28df51a4eba00 | client/js/directives/fancy-box-directive.js | client/js/directives/fancy-box-directive.js | "use strict";
angular.module("hikeio").
directive("fancybox", ["$rootScope", function($rootScope) {
return {
link: function (scope, element, attrs) {
scope.$on("$routeChangeStart", function () {
$.fancybox.close();
});
scope.$on("fancyboxClose", function () {
$.fancybox.close();
});
$(element).find(attrs.fancybox).fancybox({
afterLoad: function(current, previous) {
$rootScope.$broadcast("fancyboxLoaded");
},
afterClose: function(current, previous) {
$rootScope.$broadcast("fancyboxClosed");
},
padding : 2,
nextEffect : "none",
prevEffect : "none",
closeEffect : "none",
closeBtn : true,
arrows : false,
keys : true,
nextClick : true
});
}
};
}]); | "use strict";
angular.module("hikeio").
directive("fancybox", ["$rootScope", function($rootScope) {
return {
link: function (scope, element, attrs) {
var context = {
afterLoad: function(current, previous) {
$rootScope.$broadcast("fancyboxLoaded");
},
afterClose: function(current, previous) {
$rootScope.$broadcast("fancyboxClosed");
},
padding : 2,
nextEffect : "none",
prevEffect : "none",
closeEffect : "none",
closeBtn : true,
arrows : false,
keys : true,
nextClick : true
};
scope.$on("$routeChangeStart", function () {
$.fancybox.close();
});
scope.$on("fancyboxClose", function () {
$.fancybox.close();
});
scope.$on("$destroy", function () {
context.afterLoad = null;
context.afterClose = null;
});
$(element).find(attrs.fancybox).fancybox(context);
}
};
}]); | Remove fancybox afterLoad / afterClose event on destroy. | Remove fancybox afterLoad / afterClose event on destroy.
| JavaScript | mit | zaknelson/hike.io,zaknelson/hike.io,zaknelson/hike.io,zaknelson/hike.io | ---
+++
@@ -4,13 +4,7 @@
directive("fancybox", ["$rootScope", function($rootScope) {
return {
link: function (scope, element, attrs) {
- scope.$on("$routeChangeStart", function () {
- $.fancybox.close();
- });
- scope.$on("fancyboxClose", function () {
- $.fancybox.close();
- });
- $(element).find(attrs.fancybox).fancybox({
+ var context = {
afterLoad: function(current, previous) {
$rootScope.$broadcast("fancyboxLoaded");
},
@@ -25,7 +19,20 @@
arrows : false,
keys : true,
nextClick : true
+ };
+
+ scope.$on("$routeChangeStart", function () {
+ $.fancybox.close();
});
+ scope.$on("fancyboxClose", function () {
+ $.fancybox.close();
+ });
+ scope.$on("$destroy", function () {
+ context.afterLoad = null;
+ context.afterClose = null;
+ });
+
+ $(element).find(attrs.fancybox).fancybox(context);
}
};
}]); |
3716935789ed49ae905df0d3da6adf8c52e0f966 | platform/wasm/test-server.js | platform/wasm/test-server.js | "use strict";
const http = require("http");
const express = require("express");
let app = express();
// Use Cross-Origin headers so browsers allow SharedArrayBuffer
app.use(function(req, res, next) {
res.header("Cross-Origin-Opener-Policy", "same-origin");
res.header("Cross-Origin-Embedder-Policy", "require-corp");
next();
});
// TODO - Add some logging on each request
// Serve all static files in this folder
app.use(express.static("."));
let server = http.createServer(app);
server.listen(8000, "0.0.0.0");
| "use strict";
const http = require("http");
const express = require("express");
let app = express();
// Add some logging on each request
app.use(function(req, res, next) {
const date = new Date().toISOString();
console.log(
`[${date}] "${cyan(req.method)} ${cyan(req.url)}" "${req.headers["user-agent"]}"`
);
next();
});
// Use Cross-Origin headers so browsers allow SharedArrayBuffer
app.use(function(req, res, next) {
res.header("Cross-Origin-Opener-Policy", "same-origin");
res.header("Cross-Origin-Embedder-Policy", "require-corp");
next();
});
// Serve all static files in this folder
app.use(express.static(".", { fallthrough: false }));
// Add logging on failed requests.
app.use(function (error, req, res, next) {
const date = new Date().toISOString();
console.error(
`[${date}] "${red(req.method)} ${red(req.url)}" Error (${red(error.status.toString())}): "${red(error.message)}"`
);
next(error);
});
let server = http.createServer(app);
server.listen(8000, "0.0.0.0");
function red(string) {
return `\x1b[31m${string}\x1b[0m`;
}
function cyan(string) {
return `\x1b[36m${string}\x1b[0m`;
}
| Add logging to test server | muwasm: Add logging to test server
| JavaScript | agpl-3.0 | ArtifexSoftware/mupdf,ArtifexSoftware/mupdf,ArtifexSoftware/mupdf,ArtifexSoftware/mupdf,ArtifexSoftware/mupdf,ArtifexSoftware/mupdf,ArtifexSoftware/mupdf,ArtifexSoftware/mupdf | ---
+++
@@ -4,6 +4,15 @@
const express = require("express");
let app = express();
+
+// Add some logging on each request
+app.use(function(req, res, next) {
+ const date = new Date().toISOString();
+ console.log(
+ `[${date}] "${cyan(req.method)} ${cyan(req.url)}" "${req.headers["user-agent"]}"`
+ );
+ next();
+});
// Use Cross-Origin headers so browsers allow SharedArrayBuffer
app.use(function(req, res, next) {
@@ -12,10 +21,26 @@
next();
});
-// TODO - Add some logging on each request
// Serve all static files in this folder
-app.use(express.static("."));
+app.use(express.static(".", { fallthrough: false }));
+
+// Add logging on failed requests.
+app.use(function (error, req, res, next) {
+ const date = new Date().toISOString();
+ console.error(
+ `[${date}] "${red(req.method)} ${red(req.url)}" Error (${red(error.status.toString())}): "${red(error.message)}"`
+ );
+ next(error);
+});
let server = http.createServer(app);
server.listen(8000, "0.0.0.0");
+
+function red(string) {
+ return `\x1b[31m${string}\x1b[0m`;
+}
+
+function cyan(string) {
+ return `\x1b[36m${string}\x1b[0m`;
+} |
a1bf63b212b97d8b7e1ad90e7397ab79defe902c | generatorTests/test/directoryStructureSpec.js | generatorTests/test/directoryStructureSpec.js | var path = require('path');
var chai = require('chai');
chai.use(require('chai-fs'));
chai.should();
const ROOT_DIR = path.join(process.cwd(), '..');
describe('As a dev', function() {
describe('When testing generator directory structure', function() {
it('then _config folder should exist', function() {
var pathToTest = path.join(ROOT_DIR, '_config');
pathToTest.should.be.a.directory();
})
it('then routes folder should exist', function() {
var pathToTest = path.join(ROOT_DIR, 'routes');
pathToTest.should.be.a.directory();
})
it('then views folder should exist', function() {
var pathToTest = path.join(ROOT_DIR, 'views');
pathToTest.should.be.a.directory();
})
});
}); | var path = require('path');
var chai = require('chai');
chai.use(require('chai-fs'));
chai.should();
const ROOT_DIR = path.join(process.cwd(), '..');
describe('As a dev', function() {
describe('When testing generator directory structure', function() {
var pathToTest;
it('then _config folder should exist', function() {
pathToTest = path.join(ROOT_DIR, '_config');
pathToTest.should.be.a.directory();
})
it('then _source folder should exist', function() {
pathToTest = path.join(ROOT_DIR, '_source');
pathToTest.should.be.a.directory();
})
it('then gulpTasks folder should exist', function() {
pathToTest = path.join(ROOT_DIR, 'gulpTasks');
pathToTest.should.be.a.directory();
})
it('then routes folder should exist', function() {
pathToTest = path.join(ROOT_DIR, 'routes');
pathToTest.should.be.a.directory();
})
it('then test folder should exist', function() {
pathToTest = path.join(ROOT_DIR, 'views');
pathToTest.should.be.a.directory();
})
it('then views folder should exist', function() {
pathToTest = path.join(ROOT_DIR, 'views');
pathToTest.should.be.a.directory();
})
});
}); | Update directoryStructure test to include all base folders. Refactor order to mirror folder order, minor refactor | test: Update directoryStructure test to include all base folders. Refactor order to mirror folder order, minor refactor
| JavaScript | mit | CodeRichardJohnston/slate-demo,cartridge/cartridge-cli,code-computerlove/quarry,code-computerlove/slate-cli,cartridge/cartridge,code-computerlove/slate,CodeRichardJohnston/slate-demo,code-computerlove/slate | ---
+++
@@ -10,20 +10,38 @@
describe('When testing generator directory structure', function() {
+ var pathToTest;
+
it('then _config folder should exist', function() {
- var pathToTest = path.join(ROOT_DIR, '_config');
+ pathToTest = path.join(ROOT_DIR, '_config');
+ pathToTest.should.be.a.directory();
+ })
+
+ it('then _source folder should exist', function() {
+ pathToTest = path.join(ROOT_DIR, '_source');
+ pathToTest.should.be.a.directory();
+ })
+
+ it('then gulpTasks folder should exist', function() {
+ pathToTest = path.join(ROOT_DIR, 'gulpTasks');
pathToTest.should.be.a.directory();
})
it('then routes folder should exist', function() {
- var pathToTest = path.join(ROOT_DIR, 'routes');
+ pathToTest = path.join(ROOT_DIR, 'routes');
+ pathToTest.should.be.a.directory();
+ })
+
+ it('then test folder should exist', function() {
+ pathToTest = path.join(ROOT_DIR, 'views');
pathToTest.should.be.a.directory();
})
it('then views folder should exist', function() {
- var pathToTest = path.join(ROOT_DIR, 'views');
+ pathToTest = path.join(ROOT_DIR, 'views');
pathToTest.should.be.a.directory();
})
+
});
}); |
eaac19a6be8c660bec896dea0c0968590e3eeee4 | src/js/app/view/history.js | src/js/app/view/history.js | var Backbone = require('backbone');
var url = require('url');
"use strict";
exports.HistoryUpdate = Backbone.View.extend({
initialize : function () {
console.log('HistoryUpdate:initialize');
this.listenTo(this.model, "change:asset", this.assetChanged);
this.listenTo(this.model, "change:activeTemplate", this.assetChanged);
// note that we don't listen for a change in the collection as
// this could lead to an invalid URL (e.g. change the collection to
// something else, URL immediately changes, user saves before asset
// loads)
},
assetChanged: function () {
var u = url.parse(window.location.href.replace('#', '?'), true);
u.search = null;
if (this.model.activeTemplate() == undefined ||
this.model.activeCollection() == undefined ||
this.model.assetIndex() == undefined) {
// only want to set full valid states.
return
}
u.query.t = this.model.activeTemplate();
u.query.c = this.model.activeCollection();
u.query.i = this.model.assetIndex() + 1;
history.replaceState(null, null, url.format(u).replace('?', '#'));
}
});
| var Backbone = require('backbone');
var url = require('url');
"use strict";
exports.HistoryUpdate = Backbone.View.extend({
initialize : function () {
console.log('HistoryUpdate:initialize');
this.listenTo(this.model, "change:asset", this.assetChanged);
this.listenTo(this.model, "change:activeTemplate", this.assetChanged);
// note that we don't listen for a change in the collection as
// this could lead to an invalid URL (e.g. change the collection to
// something else, URL immediately changes, user saves before asset
// loads)
},
assetChanged: function () {
var u = url.parse(window.location.href.replace('#', '?'), true);
u.search = null;
if (this.model.activeTemplate()) {
u.query.t = this.model.activeTemplate();
}
if (this.model.activeCollection()) {
u.query.c = this.model.activeCollection();
}
if (this.model.assetIndex() !== undefined) {
u.query.i = this.model.assetIndex() + 1;
}
history.replaceState(null, null, url.format(u).replace('?', '#'));
}
});
| Allow for more flexible url pattern | Allow for more flexible url pattern
| JavaScript | bsd-3-clause | menpo/landmarker.io,menpo/landmarker.io,menpo/landmarker.io | ---
+++
@@ -18,15 +18,20 @@
assetChanged: function () {
var u = url.parse(window.location.href.replace('#', '?'), true);
u.search = null;
- if (this.model.activeTemplate() == undefined ||
- this.model.activeCollection() == undefined ||
- this.model.assetIndex() == undefined) {
- // only want to set full valid states.
- return
+
+ if (this.model.activeTemplate()) {
+ u.query.t = this.model.activeTemplate();
}
- u.query.t = this.model.activeTemplate();
- u.query.c = this.model.activeCollection();
- u.query.i = this.model.assetIndex() + 1;
+
+ if (this.model.activeCollection()) {
+ u.query.c = this.model.activeCollection();
+ }
+
+ if (this.model.assetIndex() !== undefined) {
+ u.query.i = this.model.assetIndex() + 1;
+ }
+
+
history.replaceState(null, null, url.format(u).replace('?', '#'));
}
}); |
ffae6c6f7c935684a132b191b71bae1919ecffab | src/js/config/config.js | src/js/config/config.js | var url = require("url");
var packageJSON = require("../../../package.json");
var config = {
// @@ENV gets replaced by build system
environment: "@@ENV",
// If the UI is served through a proxied URL, this can be set here.
rootUrl: "",
// Defines the Marathon API URL,
// leave empty to use the same as the UI is served.
apiURL: "../",
// Intervall of API request in ms
updateInterval: 5000,
// Local http server URI while tests run
localTestserverURI: {
address: "localhost",
port: 8181
},
version: ("@@TEAMCITY_UI_VERSION".indexOf("@@TEAMCITY") === -1) ?
"@@TEAMCITY_UI_VERSION" :
`${packageJSON.version}-SNAPSHOT`
};
if (process.env.GULP_ENV === "development") {
try {
var configDev = require("./config.dev");
config = Object.assign(config, configDev);
} catch (e) {
console.info("You could copy config.template.js to config.dev.js " +
"to enable a development configuration.");
}
}
// Convert relative URLs to absolute URLs for node-fetch
if (global.document != null) {
if (config.apiURL.indexOf(":") === -1) {
config.apiURL = url.resolve(
document.location.origin,
document.location.pathname + config.apiURL
);
}
}
module.exports = config;
| var packageJSON = require("../../../package.json");
var config = {
// @@ENV gets replaced by build system
environment: "@@ENV",
// If the UI is served through a proxied URL, this can be set here.
rootUrl: "",
// Defines the Marathon API URL,
// leave empty to use the same as the UI is served.
apiURL: "../",
// Intervall of API request in ms
updateInterval: 5000,
// Local http server URI while tests run
localTestserverURI: {
address: "localhost",
port: 8181
},
version: ("@@TEAMCITY_UI_VERSION".indexOf("@@TEAMCITY") === -1) ?
"@@TEAMCITY_UI_VERSION" :
`${packageJSON.version}-SNAPSHOT`
};
if (process.env.GULP_ENV === "development") {
try {
var configDev = require("./config.dev");
config = Object.assign(config, configDev);
} catch (e) {
console.info("You could copy config.template.js to config.dev.js " +
"to enable a development configuration.");
}
}
module.exports = config;
| Revert "Convert relative apiURL paths to absolute paths" | Revert "Convert relative apiURL paths to absolute paths"
This reverts commit d4649622aecd8d1cae56963fd4f214acf45b0cf3.
| JavaScript | apache-2.0 | cribalik/marathon-ui,mesosphere/marathon-ui,mesosphere/marathon-ui,cribalik/marathon-ui | ---
+++
@@ -1,4 +1,3 @@
-var url = require("url");
var packageJSON = require("../../../package.json");
var config = {
@@ -30,15 +29,4 @@
"to enable a development configuration.");
}
}
-
-// Convert relative URLs to absolute URLs for node-fetch
-if (global.document != null) {
- if (config.apiURL.indexOf(":") === -1) {
- config.apiURL = url.resolve(
- document.location.origin,
- document.location.pathname + config.apiURL
- );
- }
-}
-
module.exports = config; |
0703a2c971dc6fc0e0280c680e539a696fc81f2c | app/directives/player/player.js | app/directives/player/player.js | angular.module('soundmist').directive('player', function (Player) {
return {
restrict: 'E',
scope: false,
replace: false,
templateUrl: 'directives/player/player.html',
link: function (scope, element) {
scope.Player = Player
let slider = angular.element(document.querySelector('#progress'))[0]
let blocking = false
scope.$watch('Player.getActive()', function (track) {
if (track == undefined) return
scope.track = track
// Use the high-res artwork instead of the downscaled one provided
var url = scope.track.artwork_url
if (url) {
url = url.replace('large.jpg', 't500x500.jpg')
}
scope.wallpaper = {
'background': 'linear-gradient(rgba(255, 126, 0, 0.90),rgba(255, 119, 0, 0.75)), url(' + url + ')'
}
})
scope.$watch('Player.getProgress(track)', function (progress) {
if (!blocking) scope.progress = progress * 1000
})
slider.addEventListener('mousedown', event => {
blocking = true
})
slider.addEventListener('mouseup', function (event) {
if (blocking) {
let x = event.pageX - this.offsetLeft
let progress = x / slider.offsetWidth
Player.setProgress(scope.track, progress)
blocking = false
}
})
}
}
})
| angular.module('soundmist').directive('player', function (Player) {
return {
restrict: 'E',
scope: false,
replace: false,
templateUrl: 'directives/player/player.html',
link: function (scope, element) {
scope.Player = Player
let slider = angular.element(document.querySelector('#progress'))[0]
let blocking = false
scope.$watch('Player.getActive()', function (track) {
if (track == undefined) return
scope.track = track
// Use the high-res artwork instead of the downscaled one provided
var url = scope.track.artwork_url
if (url) {
url = url.replace('large.jpg', 't500x500.jpg')
}
scope.wallpaper = {
'background': 'linear-gradient(rgba(255, 126, 0, 0.90),rgba(255, 119, 0, 0.95)), url(' + url + ')'
}
})
scope.$watch('Player.getProgress(track)', function (progress) {
if (!blocking) scope.progress = progress * 1000
})
slider.addEventListener('mousedown', event => {
blocking = true
})
slider.addEventListener('mouseup', function (event) {
if (blocking) {
let x = event.pageX - this.offsetLeft
let progress = x / slider.offsetWidth
Player.setProgress(scope.track, progress)
blocking = false
}
})
}
}
})
| Increase headers background color opacity | Increase headers background color opacity
| JavaScript | cc0-1.0 | Kattjakt/soundmist,Kattjakt/soundmist | ---
+++
@@ -21,7 +21,7 @@
}
scope.wallpaper = {
- 'background': 'linear-gradient(rgba(255, 126, 0, 0.90),rgba(255, 119, 0, 0.75)), url(' + url + ')'
+ 'background': 'linear-gradient(rgba(255, 126, 0, 0.90),rgba(255, 119, 0, 0.95)), url(' + url + ')'
}
})
|
9f2b45cec678d106844359977968c859f1bc9c16 | app/scripts/services/invitation-service.js | app/scripts/services/invitation-service.js | 'use strict';
(function() {
angular.module('ncsaas')
.service('invitationService', ['baseServiceClass', '$http', 'ENV', invitationService]);
function invitationService(baseServiceClass, $http, ENV) {
/*jshint validthis: true */
var vm = this;
var ServiceClass = baseServiceClass.extend({
init: function() {
this._super();
this.endpoint = '/user-invitations/';
},
accept: function(invitation_uuid) {
return vm.executeAction(invitation_uuid, 'accept');
},
cancel: function(invitation_uuid) {
return vm.executeAction(invitation_uuid, 'cancel');
},
resend: function(invitation_uuid) {
return vm.executeAction(invitation_uuid, 'resend');
},
executeAction: function(invitation_uuid, action) {
var url = ENV.apiEndpoint + '/api/user-invitations/' + invitation_uuid + '/' + action + '/';
return $http.post(url);
}
});
return new ServiceClass();
}
})();
| 'use strict';
(function() {
angular.module('ncsaas')
.service('invitationService', ['baseServiceClass', '$http', 'ENV', invitationService]);
function invitationService(baseServiceClass, $http, ENV) {
/*jshint validthis: true */
var ServiceClass = baseServiceClass.extend({
init: function() {
this._super();
this.endpoint = '/user-invitations/';
},
accept: function(invitation_uuid) {
return this.executeAction(invitation_uuid, 'accept');
},
cancel: function(invitation_uuid) {
return this.executeAction(invitation_uuid, 'cancel');
},
resend: function(invitation_uuid) {
return this.executeAction(invitation_uuid, 'resend');
},
executeAction: function(invitation_uuid, action) {
var url = ENV.apiEndpoint + '/api/user-invitations/' + invitation_uuid + '/' + action + '/';
return $http.post(url);
}
});
return new ServiceClass();
}
})();
| Implement invitation data service (WAL-32) | Implement invitation data service (WAL-32)
| JavaScript | mit | opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport | ---
+++
@@ -6,20 +6,19 @@
function invitationService(baseServiceClass, $http, ENV) {
/*jshint validthis: true */
- var vm = this;
var ServiceClass = baseServiceClass.extend({
init: function() {
this._super();
this.endpoint = '/user-invitations/';
},
accept: function(invitation_uuid) {
- return vm.executeAction(invitation_uuid, 'accept');
+ return this.executeAction(invitation_uuid, 'accept');
},
cancel: function(invitation_uuid) {
- return vm.executeAction(invitation_uuid, 'cancel');
+ return this.executeAction(invitation_uuid, 'cancel');
},
resend: function(invitation_uuid) {
- return vm.executeAction(invitation_uuid, 'resend');
+ return this.executeAction(invitation_uuid, 'resend');
},
executeAction: function(invitation_uuid, action) {
var url = ENV.apiEndpoint + '/api/user-invitations/' + invitation_uuid + '/' + action + '/'; |
1e2dacf7b8946f8e97d0ae823cfd00a2cf131819 | src/lib/backend/lib/find_dirs_with_entry.js | src/lib/backend/lib/find_dirs_with_entry.js | "use strict";
const fs = require("fs-extra-promise");
const path = require("path");
const log = require("log");
const findDirsWithEntry = async (baseDir, entryFile = "index.js") => {
const res = [];
const dirContent = await fs.readdirAsync(baseDir);
for (const dirName of dirContent) {
const dirPath = path.join(baseDir, dirName);
const entryPath = path.join(dirPath, entryFile);
try {
fs.accessAsync(entryPath, fs.constants.R_OK);
res.push({
path: entryPath,
name: dirName,
dir: dirPath
});
} catch (error) {
log.warn(`Path ${entryPath} isn't readable, skipping...`, error);
}
}
return res;
};
module.exports = findDirsWithEntry;
| "use strict";
const fs = require("fs-extra-promise");
const path = require("path");
const log = require("log");
const findDirsWithEntry = async (baseDir, entryFile = "index.js") => {
const res = [];
const dirContent = await fs.readdirAsync(baseDir);
for (const dirName of dirContent) {
const dirPath = path.join(baseDir, dirName);
const entryPath = path.join(dirPath, entryFile);
try {
const dirStat = await fs.statAsync(dirPath);
if (dirStat.isDirectory()) {
await fs.accessAsync(entryPath, fs.constants.R_OK);
res.push({
path: entryPath,
name: dirName,
dir: dirPath
});
}
} catch (error) {
log.warn(`Path ${entryPath} isn't accessible, skipping...`, error);
}
}
return res;
};
module.exports = findDirsWithEntry;
| Fix problem with regular files in search paths | backend: Fix problem with regular files in search paths
| JavaScript | mit | Combitech/codefarm,Combitech/codefarm,Combitech/codefarm | ---
+++
@@ -10,15 +10,19 @@
for (const dirName of dirContent) {
const dirPath = path.join(baseDir, dirName);
const entryPath = path.join(dirPath, entryFile);
+
try {
- fs.accessAsync(entryPath, fs.constants.R_OK);
- res.push({
- path: entryPath,
- name: dirName,
- dir: dirPath
- });
+ const dirStat = await fs.statAsync(dirPath);
+ if (dirStat.isDirectory()) {
+ await fs.accessAsync(entryPath, fs.constants.R_OK);
+ res.push({
+ path: entryPath,
+ name: dirName,
+ dir: dirPath
+ });
+ }
} catch (error) {
- log.warn(`Path ${entryPath} isn't readable, skipping...`, error);
+ log.warn(`Path ${entryPath} isn't accessible, skipping...`, error);
}
}
|
0dae84d675d76dafcde86eb1911b9c9f3cf31997 | src/view/table/cell/EditableAmountCell.js | src/view/table/cell/EditableAmountCell.js | /**
* Cell used for showing and allowing the editing of an AmountEntry
*
* Copyright 2015 Ethan Smith
*/
var $ = require('jquery'),
AmountEntryCell = require('./AmountEntryCell');
var EditableAmountCell = AmountEntryCell.extend({
render: function() {
var self = this;
this._super();
this.$el.on('blur', 'input', function() {
self.trigger('editing:ended', $(this));
});
},
_renderContent: function() {
var elem = $('<input />').attr({
type: 'text',
value: this.model.get('amount').readable(),
class: 'jsCurrency'
});
return $('<div>').append(elem.clone()).html();
}
});
module.exports = EditableAmountCell;
| /**
* Cell used for showing and allowing the editing of an AmountEntry
*
* Copyright 2015 Ethan Smith
*/
var $ = require('jquery'),
AmountEntryCell = require('./AmountEntryCell');
var EditableAmountCell = AmountEntryCell.extend({
render: function() {
var self = this;
this._super();
this.$el.on('blur', 'input', function() {
var originalHash = self.model.hash();
self.model.get('amount').set($(this).val());
self.trigger('editing:ended', originalHash, self.model);
});
},
_renderContent: function() {
var elem = $('<input />').attr({
type: 'text',
value: this.model.get('amount').readable(),
class: 'jsCurrency'
});
return $('<div>').append(elem.clone()).html();
}
});
module.exports = EditableAmountCell;
| Update model and trigger edited event on blur | Update model and trigger edited event on blur
| JavaScript | mit | onebytegone/banknote-client,onebytegone/banknote-client | ---
+++
@@ -14,7 +14,9 @@
this._super();
this.$el.on('blur', 'input', function() {
- self.trigger('editing:ended', $(this));
+ var originalHash = self.model.hash();
+ self.model.get('amount').set($(this).val());
+ self.trigger('editing:ended', originalHash, self.model);
});
},
|
6aa462a2d69c71f8813925b65c715d329a912ef0 | packages/react/src/TransitionContainer.js | packages/react/src/TransitionContainer.js | // @flow
import type { Children } from 'react';
import React from 'react';
import { addTransitionListener } from 'yubaba-core';
export default class TransitionContainer extends React.Component {
_detatch: Function;
props: {
pair: string,
children?: Children,
style?: any,
};
state = {
visible: false,
};
componentWillMount () {
// We need to have this be attached before
// everything else is mounted, but we don't want to run this on the server.
// How?
this._detatch = addTransitionListener(this.props.pair, this.setVisibility);
}
componentWillUnmount () {
this._detatch();
}
setVisibility = (visible: boolean) => {
this.setState({
visible,
});
};
render () {
const { pair, style, ...props } = this.props;
return (
<div {...props} style={{ ...style, opacity: this.state.visible ? 1 : 0 }}>
{this.props.children}
</div>
);
}
}
| // @flow
import type { Children } from 'react';
import React from 'react';
import { addTransitionListener } from 'yubaba-core';
export default class TransitionContainer extends React.Component {
_detatch: Function;
props: {
pair: string,
children?: Children,
style?: any,
};
state = {
visible: false,
};
componentWillMount () {
if (document) {
this._detatch = addTransitionListener(this.props.pair, this.setVisibility);
}
}
componentWillUnmount () {
this._detatch();
}
setVisibility = (visible: boolean) => {
this.setState({
visible,
});
};
render () {
const { pair, style, ...props } = this.props;
return (
<div {...props} style={{ ...style, opacity: this.state.visible ? 1 : 0 }}>
{this.props.children}
</div>
);
}
}
| Check for documents existance in transition container | Check for documents existance in transition container
| JavaScript | mit | madou/yubaba,madou/yubaba | ---
+++
@@ -19,10 +19,9 @@
};
componentWillMount () {
- // We need to have this be attached before
- // everything else is mounted, but we don't want to run this on the server.
- // How?
- this._detatch = addTransitionListener(this.props.pair, this.setVisibility);
+ if (document) {
+ this._detatch = addTransitionListener(this.props.pair, this.setVisibility);
+ }
}
componentWillUnmount () { |
2754983001e7a5853620db4d1b13b91a944424c9 | server.js | server.js | require('dotenv').config({silent: true});
const process = require('process');
const http = require('http');
const createHandler = require('github-webhook-handler');
const GitHubApi = require('github');
const Configuration = require('./lib/configuration');
const Dispatcher = require('./lib/dispatcher');
const installations = require('./lib/installations');
const PORT = process.env.PORT || 3000;
const webhook = createHandler({path: '/', secret: process.env.WEBHOOK_SECRET || 'development'});
// Cache installations
installations.load();
// Listen for new installations
installations.listen(webhook);
const github = new GitHubApi({
debug: true
});
github.authenticate({
type: 'oauth',
token: process.env.GITHUB_TOKEN
});
http.createServer((req, res) => {
webhook(req, res, err => {
if (err) {
console.log('ERROR', err);
res.statusCode = 500;
res.end('Something has gone terribly wrong.');
} else {
res.statusCode = 404;
res.end('no such location');
}
});
}).listen(PORT);
webhook.on('*', event => {
if (event.payload.repository) {
const installation = installations.for(event.payload.repository.owner.login);
installations.authAs(installation).then(github => {
const dispatcher = new Dispatcher(github, event);
return Configuration.load(github, event.payload.repository).then(config => {
dispatcher.call(config);
});
});
}
});
console.log('Listening on http://localhost:' + PORT);
| require('dotenv').config({silent: true});
const process = require('process');
const http = require('http');
const createHandler = require('github-webhook-handler');
const Configuration = require('./lib/configuration');
const Dispatcher = require('./lib/dispatcher');
const installations = require('./lib/installations');
const PORT = process.env.PORT || 3000;
const webhook = createHandler({path: '/', secret: process.env.WEBHOOK_SECRET || 'development'});
// Cache installations
installations.load();
// Listen for new installations
installations.listen(webhook);
http.createServer((req, res) => {
webhook(req, res, err => {
if (err) {
console.log('ERROR', err);
res.statusCode = 500;
res.end('Something has gone terribly wrong.');
} else {
res.statusCode = 404;
res.end('no such location');
}
});
}).listen(PORT);
webhook.on('*', event => {
if (event.payload.repository) {
const installation = installations.for(event.payload.repository.owner.login);
installations.authAs(installation).then(github => {
const dispatcher = new Dispatcher(github, event);
return Configuration.load(github, event.payload.repository).then(config => {
dispatcher.call(config);
});
});
}
});
console.log('Listening on http://localhost:' + PORT);
| Remove unused github api instance | Remove unused github api instance
| JavaScript | isc | pholleran-org/probot,probot/probot,bkeepers/PRobot,probot/probot,pholleran-org/probot,probot/probot,pholleran-org/probot,bkeepers/PRobot | ---
+++
@@ -3,7 +3,6 @@
const process = require('process');
const http = require('http');
const createHandler = require('github-webhook-handler');
-const GitHubApi = require('github');
const Configuration = require('./lib/configuration');
const Dispatcher = require('./lib/dispatcher');
const installations = require('./lib/installations');
@@ -15,15 +14,6 @@
installations.load();
// Listen for new installations
installations.listen(webhook);
-
-const github = new GitHubApi({
- debug: true
-});
-
-github.authenticate({
- type: 'oauth',
- token: process.env.GITHUB_TOKEN
-});
http.createServer((req, res) => {
webhook(req, res, err => { |
9f3981cd7e6ba35ee01a5a81e6cd1ba8f6e524f2 | server.js | server.js | var queue = require('queue-async');
var express = require('express');
var request = require('request');
var app = express();
app.use(express.static(__dirname + '/static'));
app.get('/:owner/:repo', function(req, res, next) {
var q = queue();
var repoName = req.params.owner + '/' + req.params.repo;
res.locals.repoName = repoName;
for (var i=1; i<=10; i++) {
q.defer(request,{
url:'https://api.github.com/repos/' + repoName + '/events',
qs: {page: i},
json: true
});
}
q.awaitAll(function(err, pages) {
if (err) return next(err);
res.locals.stargazes = [].concat.apply([], pages).filter(function(v) {
return v.type == 'WatchEvent';
});
res.set('content-type','text/html');
res.render('starwatchcats.jade');
});
});
var server = require('http').createServer(app);
server.listen(process.env.PORT || 5000, process.env.IP);
| var queue = require('queue-async');
var express = require('express');
var request = require('request');
var app = express();
app.use(express.static(__dirname + '/static'));
function renderStargazes(req, res, next) {
var q = queue();
for (var i=1; i<=10; i++) {
q.defer(request,{
url:'https://api.github.com/repos/' + res.local.repoName + '/events',
qs: {page: i},
json: true
});
}
q.awaitAll(function(err, pages) {
if (err) return next(err);
res.locals.stargazes = [].concat.apply([], pages).filter(function(v) {
return v.type == 'WatchEvent';
});
res.set('content-type','text/html');
res.render('starwatchcats.jade');
});
}
app.get('/:owner/:repo', function(req, res, next) {
res.locals.repoName = req.params.owner + '/' + req.params.repo;
renderStargazes(req, res, next);
});
if (process.env.DEFAULT_REPO) {
app.get('/', function(req, res, next) {
res.locals.repoName = process.env.DEFAULT_REPO;
renderStargazes(req, res, next);
});
}
var server = require('http').createServer(app);
server.listen(process.env.PORT || 5000, process.env.IP);
| Add environmental config for root repo | Add environmental config for root repo
| JavaScript | mit | stuartpb/starwatchcats,stuartpb/starwatchcats | ---
+++
@@ -5,13 +5,11 @@
var app = express();
app.use(express.static(__dirname + '/static'));
-app.get('/:owner/:repo', function(req, res, next) {
+function renderStargazes(req, res, next) {
var q = queue();
- var repoName = req.params.owner + '/' + req.params.repo;
- res.locals.repoName = repoName;
for (var i=1; i<=10; i++) {
q.defer(request,{
- url:'https://api.github.com/repos/' + repoName + '/events',
+ url:'https://api.github.com/repos/' + res.local.repoName + '/events',
qs: {page: i},
json: true
});
@@ -24,7 +22,19 @@
res.set('content-type','text/html');
res.render('starwatchcats.jade');
});
+}
+
+app.get('/:owner/:repo', function(req, res, next) {
+ res.locals.repoName = req.params.owner + '/' + req.params.repo;
+ renderStargazes(req, res, next);
});
+
+if (process.env.DEFAULT_REPO) {
+ app.get('/', function(req, res, next) {
+ res.locals.repoName = process.env.DEFAULT_REPO;
+ renderStargazes(req, res, next);
+ });
+}
var server = require('http').createServer(app);
|
27e591f9b15c2b73b3f1ddef7c7c61208f90b53c | karma.config.js | karma.config.js | var _ = require('lodash'),
path = require('path'),
webpackConfig = require('./webpack.config.js');
_.merge(webpackConfig, {
devtool: 'inline-source-map',
module: {
preLoaders: [
{
test: /\.(js|jsx)?$/,
include: path.resolve('src/'),
loader: 'babel-istanbul-instrumenter'
}
]
}
});
module.exports = function(config) {
config.set({
frameworks: ['jasmine'],
browsers: ['PhantomJS'],
plugins: [
'karma-coveralls',
'karma-coverage',
'karma-jasmine',
'karma-phantomjs-launcher',
'karma-sourcemap-loader',
require('karma-webpack')
],
reporters: ['progress', 'coverage', 'coveralls'],
coverageReporter: {
type : 'lcov',
dir: 'coverage/'
},
preprocessors: {
'webpack.tests.js': [
'webpack',
'sourcemap'
]
},
singleRun: false,
webpack: webpackConfig,
webpackServer: {
watchOptions: {
aggregateTimeout: 500,
poll: 1000
},
stats: {
colors: true
},
noInfo: true
},
files: [
'./node_modules/phantomjs-polyfill/bind-polyfill.js',
'webpack.tests.js'
]
});
};
| var _ = require('lodash'),
path = require('path'),
webpackConfig = require('./webpack.config.js');
_.merge(webpackConfig, {
devtool: 'inline-source-map',
module: {
postLoaders: [
{
test: /\.(js|jsx)?$/,
include: path.resolve('src/'),
loader: 'babel-istanbul-instrumenter'
}
]
}
});
module.exports = function(config) {
config.set({
frameworks: ['jasmine'],
browsers: ['PhantomJS'],
plugins: [
'karma-jasmine',
'karma-phantomjs-launcher',
'karma-sourcemap-loader',
require('karma-webpack')
],
reporters: ['progress'],
coverageReporter: {
type : 'lcov',
dir: 'coverage/'
},
preprocessors: {
'webpack.tests.js': [
'webpack',
'sourcemap'
]
},
singleRun: false,
webpack: webpackConfig,
webpackServer: {
watchOptions: {
aggregateTimeout: 500,
poll: 1000
},
stats: {
colors: true
},
noInfo: true
},
files: [
'./node_modules/phantomjs-polyfill/bind-polyfill.js',
'webpack.tests.js'
]
});
};
| Change from `preLoaders` to `postLoaders` | Change from `preLoaders` to `postLoaders`
| JavaScript | mit | ufocoder/WebsocketUI,ufocoder/WebsocketUI | ---
+++
@@ -5,7 +5,7 @@
_.merge(webpackConfig, {
devtool: 'inline-source-map',
module: {
- preLoaders: [
+ postLoaders: [
{
test: /\.(js|jsx)?$/,
include: path.resolve('src/'),
@@ -20,14 +20,12 @@
frameworks: ['jasmine'],
browsers: ['PhantomJS'],
plugins: [
- 'karma-coveralls',
- 'karma-coverage',
'karma-jasmine',
'karma-phantomjs-launcher',
'karma-sourcemap-loader',
require('karma-webpack')
],
- reporters: ['progress', 'coverage', 'coveralls'],
+ reporters: ['progress'],
coverageReporter: {
type : 'lcov',
dir: 'coverage/' |
ecf867bf88ddd300d4dab1ad978db8d0554258d7 | app/assets/javascripts/browser-check.js | app/assets/javascripts/browser-check.js | /*globals $, GOVUK, suchi */
/*jslint
white: true,
browser: true */
$(function() {
"use strict";
function browserWarning() {
var container = $('<div id="global-browser-prompt"></div>'),
text = $('<p><a href="/help/browsers">Upgrade your web browser</a> (the software you use to access the internet), it’s out of date</p>'),
closeLink = $('<a href="#" class="dismiss" title="Dismiss this message">Close</a>');
return container.append(text.append(closeLink));
}
// we don't show the message when the cookie warning is also there
if (GOVUK.cookie('seen_cookie_message')) {
if (suchi.isOld(navigator.userAgent)) {
if(GOVUK.cookie('govuk_not_first_visit') !== null && GOVUK.cookie('govuk_browser_upgrade_dismissed') === null){
var $prompt = browserWarning();
$('#global-cookie-message').after($prompt);
$prompt.show();
$prompt.on("click", ".dismiss", function(e) {
$prompt.hide();
// the warning is dismissable for 2 weeks
GOVUK.cookie('govuk_browser_upgrade_dismissed', 'yes', { days: 14 });
});
}
}
// We're not showing the message on first visit
GOVUK.cookie('govuk_not_first_visit', 'yes', { days: 28 });
}
});
| /*globals $, GOVUK, suchi */
/*jslint
white: true,
browser: true */
$(function() {
"use strict";
function browserWarning() {
var container = $('<div id="global-browser-prompt"></div>'),
text = $('<p><a href="/help/browsers">Upgrade your web browser</a> (the software you use to access the internet), it’s out of date</p>'),
closeLink = $('<a href="#" class="dismiss" title="Dismiss this message">Close</a>');
return container.append(text.append(closeLink));
}
// we don't show the message when the cookie warning is also there
if (GOVUK.cookie('seen_cookie_message')) {
if (suchi.isOld(navigator.userAgent)) {
if(GOVUK.cookie('govuk_not_first_visit') !== null && GOVUK.cookie('govuk_browser_upgrade_dismissed') === null){
var $prompt = browserWarning();
$('#global-cookie-message').after($prompt);
$prompt.show();
$prompt.on("click", ".dismiss", function(e) {
$prompt.hide();
// the warning is dismissable for 4 weeks, for users who are not in a
// position to upgrade right now or unable to (no control of browser)
GOVUK.cookie('govuk_browser_upgrade_dismissed', 'yes', { days: 28 });
});
}
}
// We're not showing the message on first visit
GOVUK.cookie('govuk_not_first_visit', 'yes', { days: 28 });
}
});
| Increase the browser upgrade dismissal duration | Increase the browser upgrade dismissal duration
As some users are not in a position to upgrade, eg, anywhere with restrictive IT policies and slow update rollout.
While we still want to re-remind users, we shouldn't do it too often. A month seems reasonable
| JavaScript | mit | kalleth/static,alphagov/static,tadast/static,alphagov/static,robinwhittleton/static,alphagov/static,robinwhittleton/static,tadast/static,kalleth/static,kalleth/static,tadast/static,tadast/static,kalleth/static,robinwhittleton/static,robinwhittleton/static | ---
+++
@@ -22,8 +22,9 @@
$prompt.show();
$prompt.on("click", ".dismiss", function(e) {
$prompt.hide();
- // the warning is dismissable for 2 weeks
- GOVUK.cookie('govuk_browser_upgrade_dismissed', 'yes', { days: 14 });
+ // the warning is dismissable for 4 weeks, for users who are not in a
+ // position to upgrade right now or unable to (no control of browser)
+ GOVUK.cookie('govuk_browser_upgrade_dismissed', 'yes', { days: 28 });
});
}
} |
4a4a71225c39f12c981f8c1b5962f05154496fa3 | app/common/modules/single-timeseries.js | app/common/modules/single-timeseries.js | define([
'common/collections/single-timeseries'
],
function (Collection) {
return {
requiresSvg: true,
hasDatePicker: true,
collectionClass: Collection,
collectionOptions: function () {
return {
numeratorMatcher: new RegExp(this.model.get('numerator-matcher')),
denominatorMatcher: new RegExp(this.model.get('denominator-matcher')),
matchingAttribute: this.model.get('group-by'),
valueAttr: this.model.get('value-attribute') || 'uniqueEvents',
axisPeriod: this.model.get('axis-period') || this.model.get('period'),
axes: _.merge({
x: {
label: 'Date of Application',
key: ['_start_at', '_end_at'],
format: 'date'
},
y: [
{
label: 'Number of applications',
key: 'uniqueEvents',
format: this.model.get('format-options') || 'integer'
}
]
}, this.model.get('axes')),
defaultValue: this.model.get('default-value')
};
},
visualisationOptions: function () {
return {
valueAttr: 'uniqueEvents',
totalAttr: 'mean',
formatOptions: this.model.get('format-options') || { type: 'number', magnitude: true, pad: true }
};
}
};
});
| define([
'common/collections/single-timeseries'
],
function (Collection) {
return {
requiresSvg: true,
hasDatePicker: true,
collectionClass: Collection,
collectionOptions: function () {
var options = {};
options.numeratorMatcher = new RegExp(this.model.get('numerator-matcher')),
options.denominatorMatcher = new RegExp(this.model.get('denominator-matcher')),
options.matchingAttribute = this.model.get('group-by'),
options.valueAttr = this.model.get('value-attribute') || 'uniqueEvents',
options.axisPeriod = this.model.get('axis-period') || this.model.get('period'),
options.axes = _.merge({
x: {
label: 'Date of Application',
key: ['_start_at', '_end_at'],
format: 'date'
},
y: [
{
label: 'Number of applications',
key: 'uniqueEvents',
format: this.model.get('format-options') || 'integer'
}
]
}, this.model.get('axes')),
options.defaultValue = this.model.get('default-value')
return options;
},
visualisationOptions: function () {
return {
valueAttr: 'uniqueEvents',
totalAttr: 'mean',
formatOptions: this.model.get('format-options') || { type: 'number', magnitude: true, pad: true }
};
}
};
});
| Switch to using options, as with newer module definitions | Switch to using options, as with newer module definitions
- Also allows easier extension of existing objects within the option set
| JavaScript | mit | tijmenb/spotlight,alphagov/spotlight,keithiopia/spotlight,alphagov/spotlight,tijmenb/spotlight,keithiopia/spotlight,keithiopia/spotlight,tijmenb/spotlight,alphagov/spotlight | ---
+++
@@ -8,28 +8,29 @@
collectionClass: Collection,
collectionOptions: function () {
- return {
- numeratorMatcher: new RegExp(this.model.get('numerator-matcher')),
- denominatorMatcher: new RegExp(this.model.get('denominator-matcher')),
- matchingAttribute: this.model.get('group-by'),
- valueAttr: this.model.get('value-attribute') || 'uniqueEvents',
- axisPeriod: this.model.get('axis-period') || this.model.get('period'),
- axes: _.merge({
- x: {
- label: 'Date of Application',
- key: ['_start_at', '_end_at'],
- format: 'date'
- },
- y: [
- {
- label: 'Number of applications',
- key: 'uniqueEvents',
- format: this.model.get('format-options') || 'integer'
- }
- ]
- }, this.model.get('axes')),
- defaultValue: this.model.get('default-value')
- };
+ var options = {};
+ options.numeratorMatcher = new RegExp(this.model.get('numerator-matcher')),
+ options.denominatorMatcher = new RegExp(this.model.get('denominator-matcher')),
+ options.matchingAttribute = this.model.get('group-by'),
+ options.valueAttr = this.model.get('value-attribute') || 'uniqueEvents',
+ options.axisPeriod = this.model.get('axis-period') || this.model.get('period'),
+ options.axes = _.merge({
+ x: {
+ label: 'Date of Application',
+ key: ['_start_at', '_end_at'],
+ format: 'date'
+ },
+ y: [
+ {
+ label: 'Number of applications',
+ key: 'uniqueEvents',
+ format: this.model.get('format-options') || 'integer'
+ }
+ ]
+ }, this.model.get('axes')),
+
+ options.defaultValue = this.model.get('default-value')
+ return options;
},
visualisationOptions: function () { |
133bf86bf81ca9d00acfc33fa62d85cdf04c7598 | src/server/greenlock.js | src/server/greenlock.js | import env from 'dotenv';
import { log, logErr } from './app/shared/utils';
import * as greenlockExpress from 'greenlock-express';
env.config();
let greenlock;
// API_DOMAINS environment variable is a comma-delimited string of domains
if (process.env.API_DOMAINS && process.env.API_DOMAINS.split(",").length > 0) {
log(`API_DOMAINS: ${process.env.API_DOMAINS.split(',')}`);
greenlock = greenlockExpress.create({
version: 'draft-11' // Let's Encrypt v2
// You MUST change this to 'https://acme-v02.api.letsencrypt.org/directory' in production
, server: 'https://acme-staging-v02.api.letsencrypt.org/directory'
, email: ***REMOVED***
, agreeTos: true
, approveDomains: process.env.API_DOMAINS.split(',')
// Uses root in Docker container (/root/app/letsencrypt or ~/app/letsencrypt)
, configDir: require('os').homedir() + '/app/letsencrypt'
, debug: true
});
} else {
log("API_DOMAINS: none");
greenlock = null;
}
export default greenlock;
| import env from 'dotenv';
import { log, logErr } from './app/shared/utils';
import * as greenlockExpress from 'greenlock-express';
env.config();
let greenlock;
// API_DOMAINS environment variable is a comma-delimited string of domains
if (process.env.API_DOMAINS && process.env.API_DOMAINS.split(",").length > 0) {
log(`API_DOMAINS: ${process.env.API_DOMAINS.split(',')}`);
greenlock = greenlockExpress.create({
version: 'draft-11' // Let's Encrypt v2
// You MUST change this to 'https://acme-v02.api.letsencrypt.org/directory' in production
// then rm -rf letsencrypt dir and restart to regenerate certs
, server: 'https://acme-staging-v02.api.letsencrypt.org/directory'
, email: process.env.EMAIL
, agreeTos: true
, approveDomains: process.env.API_DOMAINS.split(',')
// Run Docker with this flag to bind mounts: -v "$(pwd)"/letsencrypt:/root/app/letsencrypt
// Uses root in Docker container:
// (/root/app/letsencrypt or ~/app/letsencrypt)
// Maps to user's repo directory in Docker host:
// (/home/[USERNAME]/redadalertas-api/letsencrypt or ~/redadalertas-api/letsencrypt)
, configDir: require('os').homedir() + '/app/letsencrypt' // In Docker container
// , debug: true
});
} else {
log("API_DOMAINS: none");
greenlock = null;
}
export default greenlock;
| Add comments, remove debug, use process.env email | Add comments, remove debug, use process.env email
| JavaScript | agpl-3.0 | Cosecha/redadalertas-api | ---
+++
@@ -10,17 +10,23 @@
log(`API_DOMAINS: ${process.env.API_DOMAINS.split(',')}`);
greenlock = greenlockExpress.create({
version: 'draft-11' // Let's Encrypt v2
+
// You MUST change this to 'https://acme-v02.api.letsencrypt.org/directory' in production
+ // then rm -rf letsencrypt dir and restart to regenerate certs
, server: 'https://acme-staging-v02.api.letsencrypt.org/directory'
- , email: ***REMOVED***
+ , email: process.env.EMAIL
, agreeTos: true
, approveDomains: process.env.API_DOMAINS.split(',')
- // Uses root in Docker container (/root/app/letsencrypt or ~/app/letsencrypt)
- , configDir: require('os').homedir() + '/app/letsencrypt'
+// Run Docker with this flag to bind mounts: -v "$(pwd)"/letsencrypt:/root/app/letsencrypt
+ // Uses root in Docker container:
+ // (/root/app/letsencrypt or ~/app/letsencrypt)
+ // Maps to user's repo directory in Docker host:
+ // (/home/[USERNAME]/redadalertas-api/letsencrypt or ~/redadalertas-api/letsencrypt)
+ , configDir: require('os').homedir() + '/app/letsencrypt' // In Docker container
- , debug: true
+ // , debug: true
});
} else {
log("API_DOMAINS: none"); |
ba6e39146412a83443c0110af7d77e642c747115 | src/field-inputs/Url.js | src/field-inputs/Url.js | import React, {PropTypes} from 'react'
import FormBuilderPropTypes from '../FormBuilderPropTypes'
import Str from './String'
export default React.createClass({
propTypes: {
field: FormBuilderPropTypes.field.isRequired,
value: PropTypes.string,
onChange: PropTypes.func
},
getDefaultProps() {
return {
value: '',
onChange() {}
}
},
handleChange(event) {
this.props.onChange(event.target.value)
},
render() {
const {value, field} = this.props
return (
<Str field={field} value={value} onChange={this.handleChange} />
)
}
})
| import React, {PropTypes} from 'react'
import FormBuilderPropTypes from '../FormBuilderPropTypes'
import Str from './String'
export default React.createClass({
propTypes: {
field: FormBuilderPropTypes.field.isRequired,
value: PropTypes.string,
onChange: PropTypes.func
},
getDefaultProps() {
return {
value: '',
onChange() {}
}
},
handleChange(event) {
this.props.onChange(event.target.value)
},
render() {
const {value, field} = this.props
return (
<Str type="url" field={field} value={value} onChange={this.handleChange} />
)
}
})
| Set type on url field | Set type on url field
| JavaScript | mit | sanity-io/sanity,sanity-io/sanity,sanity-io/sanity,sanity-io/sanity | ---
+++
@@ -23,7 +23,7 @@
render() {
const {value, field} = this.props
return (
- <Str field={field} value={value} onChange={this.handleChange} />
+ <Str type="url" field={field} value={value} onChange={this.handleChange} />
)
}
}) |
1c93e4d142284de9508da497003bcb34f7ed87b8 | src/data/SubtitlePiece.js | src/data/SubtitlePiece.js | const striptags = require('striptags');
const { convertFormatToSeconds, convertSecondsToFormat, normalizeString } = require('../utils');
class SubtitlePiece {
static fromSubtitlesParserItem(item) {
return new SubtitlePiece(item);
}
constructor({ id, startTime, endTime, text, data }) {
if (!id) throw new Error();
if (!startTime) throw new Error();
if (!endTime) throw new Error();
if (!text) throw new Error();
this.id = id;
this.startTime = typeof startTime === 'number' ? convertSecondsToFormat(startTime) : startTime;
this.endTime = typeof endTime === 'number' ? convertSecondsToFormat(endTime) : endTime;
this.text = text;
this.data = data;
}
get words() {
return striptags(this.text).split(' ');
}
get normalizedWords() {
return this.words.map(normalizeString).filter(word => word.length > 0);
}
get startTimeS() {
return convertFormatToSeconds(this._startTime);
}
get startTimeF() {
return this._startTime;
}
get textLevenshtein() {
return this.normalizedWords.join("");
}
}
module.exports = SubtitlePiece;
| const striptags = require('striptags');
const { convertFormatToSeconds, convertSecondsToFormat, normalizeString } = require('../utils');
class SubtitlePiece {
static fromSubtitlesParserItem(item) {
return new SubtitlePiece(item);
}
constructor({ id, startTime, endTime, text, data }) {
if (!id) throw new Error();
if (!startTime) throw new Error();
if (!endTime) throw new Error();
if (!text) throw new Error();
this.id = id;
this.startTime = typeof startTime === 'number' ? convertSecondsToFormat(startTime) : startTime;
this.endTime = typeof endTime === 'number' ? convertSecondsToFormat(endTime) : endTime;
this.text = text;
this.data = data;
}
get words() {
return striptags(this.text).split(/\s+/);
}
get normalizedWords() {
return this.words.map(normalizeString).filter(word => word.length > 0);
}
get startTimeS() {
return convertFormatToSeconds(this._startTime);
}
get startTimeF() {
return this._startTime;
}
get textLevenshtein() {
return this.normalizedWords.join("");
}
}
module.exports = SubtitlePiece;
| Fix wrong text splitting to words | Fix wrong text splitting to words
| JavaScript | mit | CLUG-kr/ming,CLUG-kr/ming | ---
+++
@@ -21,7 +21,7 @@
}
get words() {
- return striptags(this.text).split(' ');
+ return striptags(this.text).split(/\s+/);
}
get normalizedWords() { |
25b6134a2ced438ec2ab2dbfde6ff7a3003c1ab7 | src/routes/names.js | src/routes/names.js | const thesaurus = require('powerthesaurus-api')
module.exports = (router) => {
router.use('/v1/names', (req, res, next) => {
Promise.all(req.query.bandname.split(' ').map((name) => thesaurus(name)))
.then((results) => {
const wordlist = results.map((item) => {
return item.map((data) => {
return data.word
})
})
res.json(wordlist)
})
.catch(next)
})
}
| const thesaurus = require('powerthesaurus-api')
const ignore = [
'a',
'the',
'of',
'in',
]
module.exports = (router) => {
router.use('/v1/names', (req, res, next) => {
Promise.all(req.query.bandname.split(' ').map((name) => {
if (ignore.indexOf(name) !== -1) return name
return thesaurus(name)
}))
.then((results) => {
const wordlist = results.map((item) => {
return item.map((data) => {
return data.word
})
})
res.json(wordlist)
})
.catch(next)
})
}
| Add ignore list for common words | Add ignore list for common words
| JavaScript | mit | signup-from-bandname/banGen,signup-from-bandname/banGen,signup-from-bandname/banGen | ---
+++
@@ -1,8 +1,18 @@
const thesaurus = require('powerthesaurus-api')
+
+const ignore = [
+ 'a',
+ 'the',
+ 'of',
+ 'in',
+]
module.exports = (router) => {
router.use('/v1/names', (req, res, next) => {
- Promise.all(req.query.bandname.split(' ').map((name) => thesaurus(name)))
+ Promise.all(req.query.bandname.split(' ').map((name) => {
+ if (ignore.indexOf(name) !== -1) return name
+ return thesaurus(name)
+ }))
.then((results) => {
const wordlist = results.map((item) => {
return item.map((data) => { |
a8857834ca63ead1d53c7136ada3f27d77bc7a99 | src/store.js | src/store.js | //@flow
import { createStore, compose, applyMiddleware } from "redux";
import { routerMiddleware } from "react-router-redux";
import createHistory from "history/createBrowserHistory";
import reducers from "./data/reducers";
const defaultState = {};
export const history = createHistory();
const middlewares = [routerMiddleware(history)];
if (process.env.NODE_ENV === `development`) {
const { logger } = require(`redux-logger`);
middlewares.push(logger);
}
const enhancers = compose(
window.devToolsExtension ? window.devToolsExtension() : f => f,
applyMiddleware(...middlewares)
);
const store = createStore(reducers, defaultState, enhancers);
export default function configureStore() {
const store = createStore(reducers, defaultState, enhancers);
if (module.hot) {
module.hot.accept(reducers, () => {
const nextRootReducer = require("./data/reducers").default;
store.replaceReducer(nextRootReducer);
});
}
}
| //@flow
import { createStore, compose, applyMiddleware } from "redux";
import { routerMiddleware } from "react-router-redux";
import createHistory from "history/createBrowserHistory";
import reducers from "./data/reducers";
import cards from "./data/state/cards";
const defaultState = { cards };
export const history = createHistory();
const middlewares = [routerMiddleware(history)];
if (process.env.NODE_ENV === `development`) {
const { logger } = require(`redux-logger`);
middlewares.push(logger);
}
const enhancers = compose(
window.devToolsExtension ? window.devToolsExtension() : f => f,
applyMiddleware(...middlewares)
);
const store = createStore(reducers, defaultState, enhancers);
if (module.hot) {
module.hot.accept("./data/reducers", () => {
store.replaceReducer(reducers);
});
}
export default store;
| Add cards to default state and hot reload reducers | Add cards to default state and hot reload reducers
| JavaScript | mit | slightly-askew/portfolio-2017,slightly-askew/portfolio-2017 | ---
+++
@@ -4,8 +4,9 @@
import { routerMiddleware } from "react-router-redux";
import createHistory from "history/createBrowserHistory";
import reducers from "./data/reducers";
+import cards from "./data/state/cards";
-const defaultState = {};
+const defaultState = { cards };
export const history = createHistory();
const middlewares = [routerMiddleware(history)];
@@ -23,13 +24,10 @@
const store = createStore(reducers, defaultState, enhancers);
-export default function configureStore() {
- const store = createStore(reducers, defaultState, enhancers);
+if (module.hot) {
+ module.hot.accept("./data/reducers", () => {
+ store.replaceReducer(reducers);
+ });
+}
- if (module.hot) {
- module.hot.accept(reducers, () => {
- const nextRootReducer = require("./data/reducers").default;
- store.replaceReducer(nextRootReducer);
- });
- }
-}
+export default store; |
35e083ed2ae2c8e2d0ba286303ee8f3ab120ff2e | src/store.js | src/store.js | // @flow
import type { ThunkOrActionType } from "./actionCreators";
import type { ActionType } from "./actionTypes";
import type { AppState } from "./reducers";
import type { Store as ReduxStore } from "redux";
import { browserHistory } from "react-router";
import { routerMiddleware } from "react-router-redux";
import { compose, createStore, applyMiddleware } from "redux";
import thunk from "redux-thunk";
import persistState from "redux-localstorage";
import reducer from "./reducers";
import { getAuthToken } from "./accessors";
import dropboxMiddleware from "./dropboxMiddleware";
export type Dispatch = (action: ThunkOrActionType) => void;
export type Store = ReduxStore<AppState, ActionType>;
export const getStore = (): Store => {
const slicer = paths => {
return state => {
return Object.assign(
{},
{
dropbox: {
authToken: getAuthToken(state)
}
}
);
};
};
return createStore(
reducer,
window.__REDUX_DEVTOOLS_EXTENSION__ &&
window.__REDUX_DEVTOOLS_EXTENSION__(),
compose(
persistState("dropbox", { slicer }),
applyMiddleware(
thunk,
routerMiddleware(browserHistory),
dropboxMiddleware
)
)
);
};
| // @flow
import type { ThunkOrActionType } from "./actionCreators";
import type { ActionType } from "./actionTypes";
import type { AppState } from "./reducers";
import type { Store as ReduxStore } from "redux";
import { browserHistory } from "react-router";
import { routerMiddleware } from "react-router-redux";
import { compose, createStore, applyMiddleware } from "redux";
import thunk from "redux-thunk";
import persistState from "redux-localstorage";
import reducer from "./reducers";
import { getAuthToken } from "./accessors";
import dropboxMiddleware from "./dropboxMiddleware";
export type Dispatch = (action: ThunkOrActionType) => void;
export type Store = ReduxStore<AppState, ActionType>;
export const getStore = (): Store => {
const slicer = paths => {
return (state: AppState) => {
return Object.assign(
{},
{
dropbox: {
authToken: getAuthToken(state)
}
}
);
};
};
return createStore(
reducer,
window.__REDUX_DEVTOOLS_EXTENSION__ &&
window.__REDUX_DEVTOOLS_EXTENSION__(),
compose(
persistState("dropbox", { slicer }),
applyMiddleware(
thunk,
routerMiddleware(browserHistory),
dropboxMiddleware
)
)
);
};
| Add AppState annotation to slicer | Add AppState annotation to slicer
| JavaScript | mit | captbaritone/markdown.today,captbaritone/markdown.today,captbaritone/markdown.today | ---
+++
@@ -19,7 +19,7 @@
export const getStore = (): Store => {
const slicer = paths => {
- return state => {
+ return (state: AppState) => {
return Object.assign(
{},
{ |
809aaa2d1cd4007e36c1518d8a44944e3b88a9d6 | src/modules/mymodule.js | src/modules/mymodule.js | // ------------------------------------
// Constants
const COUNTER_INCREMENT = 'COUNTER_INCREMENT';
// ------------------------------------
// Action creators
export function increment(value = 1) {
return {
type: COUNTER_INCREMENT,
payload: value
};
}
// ------------------------------------
// Selectors
export const getCounter = state => state.mymodule.counter;
// ------------------------------------
// Store & reducer
const initialState = {
counter: 0
};
export default function reducer(state = initialState, action = {}) {
switch (action.type) {
case COUNTER_INCREMENT:
return Object.assign(
{},
state,
{counter: state.counter + action.payload});
default:
return state;
}
}
| // ------------------------------------
// Constants
const COUNTER_INCREMENT = 'COUNTER_INCREMENT';
// ------------------------------------
// Action creators
export function increment(value = 1) {
return {
type: COUNTER_INCREMENT,
payload: value
};
}
// ------------------------------------
// Selectors
export const getCounter = state => state.mymodule.counter;
// ------------------------------------
// Store & reducer
const initialState = {
counter: 0
};
export default function reducer(state = initialState, action = {}) {
switch (action.type) {
case COUNTER_INCREMENT:
return {
...state,
counter: state.counter + action.payload
};
default:
return state;
}
}
| Replace Object.assign with the spread object operator (supported by CRA) | Replace Object.assign with the spread object operator (supported by CRA)
Signed-off-by: Gianni Valdambrini <c5d749f9a9fad12805bcb3c96e57c90355771f56@develer.com>
| JavaScript | mit | nbschool/ecommerce_web,nbschool/ecommerce_web | ---
+++
@@ -28,10 +28,10 @@
export default function reducer(state = initialState, action = {}) {
switch (action.type) {
case COUNTER_INCREMENT:
- return Object.assign(
- {},
- state,
- {counter: state.counter + action.payload});
+ return {
+ ...state,
+ counter: state.counter + action.payload
+ };
default:
return state;
} |
d78e7efdadd90cb3a167fce2d60043693e4c32e9 | server/init/default-users.js | server/init/default-users.js | var mongoose = require('mongoose'),
User = mongoose.model('User'),
constants = require('../common/constants'),
SHA256 = require('crypto-js/sha256');
User.findOne({username: 'admin'})
.exec(function (err, user) {
'use strict';
if (!user && !err) {
User({
username: 'admin',
hashPassword: SHA256('admin'),
cars: [],
level: constants.models.user.defaultLevel,
respect: constants.models.user.defaultRespect,
money: constants.models.user.defaultMoney,
dateRegistered: new Date(),
role: constants.roles.administrator
}).save(function (err) {
if (err) {
console.log('Default user with admin role was not saved!');
}
});
}
}); | var mongoose = require('mongoose'),
User = mongoose.model('User'),
constants = require('../common/constants'),
SHA256 = require('crypto-js/sha256');
User.findOne({username: 'admin'})
.exec(function (err, user) {
'use strict';
if (!user && !err) {
User({
username: 'administrator',
hashPassword: SHA256('administrator'),
cars: [],
level: constants.models.user.defaultLevel,
respect: constants.models.user.defaultRespect,
money: constants.models.user.defaultMoney,
dateRegistered: new Date(),
role: constants.roles.administrator
}).save(function (err) {
if (err) {
console.log('Default user with admin role was not saved!');
}
});
}
}); | Fix default-user to have adequate length for username and password. | Fix default-user to have adequate length for username and password.
| JavaScript | mit | TA-2016-NodeJs-Team2/Telerik-Racer,TA-2016-NodeJs-Team2/Telerik-Racer | ---
+++
@@ -9,8 +9,8 @@
if (!user && !err) {
User({
- username: 'admin',
- hashPassword: SHA256('admin'),
+ username: 'administrator',
+ hashPassword: SHA256('administrator'),
cars: [],
level: constants.models.user.defaultLevel,
respect: constants.models.user.defaultRespect, |
2ae406a61f6bbe200c7e5a4c6fcb1d6422d32fc9 | tools/tool-env/install-runtime.js | tools/tool-env/install-runtime.js | // Install ES2015-complaint polyfills for Object, Array, String, Function,
// Symbol, Map, Set, and Promise, patching the native implementations when
// they are available.
require("./install-promise.js");
var Mp = module.constructor.prototype;
var moduleLoad = Mp.load;
Mp.load = function (filename) {
var result = moduleLoad.apply(this, arguments);
var runSetters = this.runSetters || this.runModuleSetters;
if (typeof runSetters === "function") {
// Make sure we call module.runSetters (or module.runModuleSetters, a
// legacy synonym) whenever a module finishes loading.
runSetters.call(this);
}
return result;
};
// Installs source map support with a hook to add functions to look for
// source maps in custom places.
require('./source-map-retriever-stack.js');
| // Install ES2015-complaint polyfills for Object, Array, String, Function,
// Symbol, Map, Set, and Promise, patching the native implementations when
// they are available.
require("./install-promise.js");
// Enable the module.{watch,export,...} runtime API needed by Reify.
require("reify/lib/runtime").enable(module.constructor);
var Mp = module.constructor.prototype;
var moduleLoad = Mp.load;
Mp.load = function (filename) {
var result = moduleLoad.apply(this, arguments);
var runSetters = this.runSetters || this.runModuleSetters;
if (typeof runSetters === "function") {
// Make sure we call module.runSetters (or module.runModuleSetters, a
// legacy synonym) whenever a module finishes loading.
runSetters.call(this);
}
return result;
};
// Installs source map support with a hook to add functions to look for
// source maps in custom places.
require('./source-map-retriever-stack.js');
| Enable the Reify runtime API even if meteor-babel/register does not. | Enable the Reify runtime API even if meteor-babel/register does not.
| JavaScript | mit | Hansoft/meteor,Hansoft/meteor,Hansoft/meteor,Hansoft/meteor,Hansoft/meteor,Hansoft/meteor,Hansoft/meteor | ---
+++
@@ -2,6 +2,9 @@
// Symbol, Map, Set, and Promise, patching the native implementations when
// they are available.
require("./install-promise.js");
+
+// Enable the module.{watch,export,...} runtime API needed by Reify.
+require("reify/lib/runtime").enable(module.constructor);
var Mp = module.constructor.prototype;
var moduleLoad = Mp.load; |
4de0a8456b92488180954f2994f987bdb5798256 | resources/assets/js/services/info/song.js | resources/assets/js/services/info/song.js | import http from '../http';
import albumInfo from './album';
import artistInfo from './artist';
export default {
/**
* Get extra song information (lyrics, artist info, album info).
*
* @param {Object} song
* @param {?Function} cb
*/
fetch(song, cb = null) {
// Check if the song's info has been retrieved before.
if (song.infoRetrieved) {
cb && cb();
return;
}
http.get(`${song.id}/info`, response => {
const data = response.data;
song.lyrics = data.lyrics;
data.artist_info && artistInfo.merge(song.album.artist, data.artist_info);
data.album_info && albumInfo.merge(song.album, data.album_info);
song.infoRetrieved = true;
cb && cb();
});
},
};
| import http from '../http';
import albumInfo from './album';
import artistInfo from './artist';
export default {
/**
* Get extra song information (lyrics, artist info, album info).
*
* @param {Object} song
* @param {?Function} cb
*/
fetch(song, cb = null) {
// Check if the song's info has been retrieved before.
if (song.infoRetrieved) {
cb && cb();
return;
}
http.get(`${song.id}/info`, response => {
const data = response.data;
song.lyrics = data.lyrics;
data.artist_info && artistInfo.merge(song.artist, data.artist_info);
data.album_info && albumInfo.merge(song.album, data.album_info);
song.infoRetrieved = true;
cb && cb();
});
},
};
| Fix the artist loading & info bug | Fix the artist loading & info bug
| JavaScript | mit | X-Ryl669/kutr,phanan/koel,alex-phillips/koel,X-Ryl669/kutr,phanan/koel,mikifus/koel,mikifus/koel,phanan/koel,alex-phillips/koel,alex-phillips/koel,mikifus/koel,X-Ryl669/kutr | ---
+++
@@ -23,7 +23,7 @@
song.lyrics = data.lyrics;
- data.artist_info && artistInfo.merge(song.album.artist, data.artist_info);
+ data.artist_info && artistInfo.merge(song.artist, data.artist_info);
data.album_info && albumInfo.merge(song.album, data.album_info);
song.infoRetrieved = true; |
36c5d3a4f84a02c2ae467fb09e57e9db4f6c36dc | lib/bindings.js | lib/bindings.js | var fs = require('fs'),
path = require('path');
// normalize node 0.6 and 0.8
fs.existsSync || (fs.existsSync = path.existsSync);
var platforms = {
win32: function(folder){
process.env.PATH += ';' + folder;
}
};
// derive a distributable path from the node version, platform, and arch
function distribPath(){
return [ '..',
'compiled',
process.version.slice(1, 4),
process.platform,
process.arch,
'bindings/'].join('/');
}
// resolve a path relative the directory this .js file is in
function absolutelyRelative(pathname){
return path.resolve(__dirname, pathname);
}
// find the binary file for a given name
function requireBindings(lib){
var folder = [ '../build/Release/', // self-compiled release
'../build/Debug/', // self-compiled debug
distribPath() // system-relative pre-compiled
].map(absolutelyRelative)
.filter(fs.existsSync)[0];
if (!folder) {
throw new Error('Unable to locate binaries for '+lib);
}
if (process.platform in platforms) {
platforms[process.platform](folder);
}
return require(folder + '/' + lib);
}
module.exports = requireBindings('appjs');
| var fs = require('fs'),
path = require('path');
// normalize node 0.6 and 0.8
fs.existsSync || (fs.existsSync = path.existsSync);
var platforms = {
win32: function(folder, file){
process.env.PATH += ';' + folder;
}
};
// derive a distributable path from the node version, platform, and arch
function distribPath(){
return [ '..',
'compiled',
process.version.slice(1, 4),
process.platform,
process.arch,
'bindings'].join('/');
}
// resolve a path relative the directory this .js file is in
function absolutelyRelative(pathname){
return path.resolve(__dirname, pathname);
}
// find the binary file for a given name
function requireBindings(lib){
var folder = [ '../build/Release', // self-compiled release
'../build/Debug', // self-compiled debug
distribPath() // system-relative pre-compiled
].map(absolutelyRelative)
.filter(fs.existsSync)[0];
if (!folder) {
throw new Error("Unable to locate bindings for " + lib);
}
var libPath = folder + '/' + lib + '.node';
if (!fs.existsSync(libPath)) {
throw new Error("Binaries for " + lib + " not found in '" + folder + "'");
}
if (process.platform in platforms) {
platforms[process.platform](folder, libPath);
}
return require(libPath);
}
module.exports = requireBindings('appjs');
| Check that the .node file actually exists | Check that the .node file actually exists
| JavaScript | mit | modulexcite/appjs,appjs/appjs,eric-seekas/appjs,appjs/appjs,reekoheek/appjs,SaravananRajaraman/appjs,SaravananRajaraman/appjs,milani/appjs,tempbottle/appjs,tempbottle/appjs,SaravananRajaraman/appjs,yuhangwang/appjs,eric-seekas/appjs,reekoheek/appjs,reekoheek/appjs,milani/appjs,imshibaji/appjs,modulexcite/appjs,yuhangwang/appjs,SaravananRajaraman/appjs,modulexcite/appjs,milani/appjs,yuhangwang/appjs,imshibaji/appjs,appjs/appjs,eric-seekas/appjs,imshibaji/appjs,tempbottle/appjs,eric-seekas/appjs,imshibaji/appjs,yuhangwang/appjs,modulexcite/appjs,SaravananRajaraman/appjs,SaravananRajaraman/appjs,appjs/appjs,tempbottle/appjs | ---
+++
@@ -7,7 +7,7 @@
var platforms = {
- win32: function(folder){
+ win32: function(folder, file){
process.env.PATH += ';' + folder;
}
};
@@ -19,7 +19,7 @@
process.version.slice(1, 4),
process.platform,
process.arch,
- 'bindings/'].join('/');
+ 'bindings'].join('/');
}
// resolve a path relative the directory this .js file is in
@@ -29,20 +29,25 @@
// find the binary file for a given name
function requireBindings(lib){
- var folder = [ '../build/Release/', // self-compiled release
- '../build/Debug/', // self-compiled debug
- distribPath() // system-relative pre-compiled
+ var folder = [ '../build/Release', // self-compiled release
+ '../build/Debug', // self-compiled debug
+ distribPath() // system-relative pre-compiled
].map(absolutelyRelative)
.filter(fs.existsSync)[0];
if (!folder) {
- throw new Error('Unable to locate binaries for '+lib);
+ throw new Error("Unable to locate bindings for " + lib);
+ }
+
+ var libPath = folder + '/' + lib + '.node';
+ if (!fs.existsSync(libPath)) {
+ throw new Error("Binaries for " + lib + " not found in '" + folder + "'");
}
if (process.platform in platforms) {
- platforms[process.platform](folder);
+ platforms[process.platform](folder, libPath);
}
- return require(folder + '/' + lib);
+ return require(libPath);
}
|
e356d1dda09d7303b8fead6c158c308a154607ee | client/app/i18n/container_helper.service.js | client/app/i18n/container_helper.service.js | 'use strict';
angular.module('arethusaTranslateGuiApp').service('containerHelper', [
function() {
var self = this;
var DIRTY = 'dirty-bg';
var CLEAN = 'clean-bg';
function stats(scope) {
return scope.getStats(scope.container);
}
this.checkStatus = function(scope) {
var cont = scope.container;
if (cont.name && !stats(scope).dirty) {
scope.container.dirty = false;
} else {
scope.container.dirty = true;
}
scope.deferredUpdate();
};
this.nameWatch = function(scope) {
scope.$watch('container.name', function(newVal, oldVal) {
if (!oldVal) self.checkStatus(scope);
if (!newVal) scope.container.dirty = true;
});
};
this.dirtyWatch = function(scope, fn) {
scope.$watch('container.dirty', function(newVal) {
scope.statusClass = newVal ? DIRTY : CLEAN;
if (fn) fn();
});
};
}
]);
| 'use strict';
angular.module('arethusaTranslateGuiApp').service('containerHelper', [
function() {
var self = this;
var DIRTY = 'dirty-bg';
var CLEAN = 'clean-bg';
function stats(scope) {
return scope.getStats(scope.container);
}
function isDirty(scope) {
return stats(scope).dirty || _.find(scope.container.containers, function(el) {
return el.dirty;
});
}
this.checkStatus = function(scope) {
var cont = scope.container;
if (cont.name && !isDirty(scope)) {
scope.container.dirty = false;
} else {
scope.container.dirty = true;
}
scope.deferredUpdate();
};
this.nameWatch = function(scope) {
scope.$watch('container.name', function(newVal, oldVal) {
if (!oldVal) self.checkStatus(scope);
if (!newVal) scope.container.dirty = true;
});
};
this.dirtyWatch = function(scope, fn) {
scope.$watch('container.dirty', function(newVal) {
scope.statusClass = newVal ? DIRTY : CLEAN;
if (fn) fn();
});
};
}
]);
| Fix dirty check in containerHelper | Fix dirty check in containerHelper
| JavaScript | mit | LFDM/angular-translate-gui | ---
+++
@@ -11,9 +11,15 @@
return scope.getStats(scope.container);
}
+ function isDirty(scope) {
+ return stats(scope).dirty || _.find(scope.container.containers, function(el) {
+ return el.dirty;
+ });
+ }
+
this.checkStatus = function(scope) {
var cont = scope.container;
- if (cont.name && !stats(scope).dirty) {
+ if (cont.name && !isDirty(scope)) {
scope.container.dirty = false;
} else {
scope.container.dirty = true; |
beffff1c70d6bc7b7dfd56144d98f3f37fd179dd | client/src/components/HopscotchLauncher.js | client/src/components/HopscotchLauncher.js | import React from 'react'
import {Button} from 'react-bootstrap'
import tourIcon from 'resources/tour-icon.svg'
import ReactSVG from 'react-svg'
export default function HopscotchLauncher(props) {
return <Button bsStyle="link" className="persistent-tour-launcher" onClick={props.onClick}>
New to ANET? Take a guided tour.
<ReactSVG path={tourIcon} className="tour-icon" />
</Button>
}
| import React from 'react'
import {Button} from 'react-bootstrap'
import tourIcon from 'resources/tour-icon.svg'
import ReactSVG from 'react-svg'
export default function HopscotchLauncher(props) {
return <Button bsStyle="link" className="persistent-tour-launcher" onClick={props.onClick}>
New to ANET? Take a guided tour
<ReactSVG path={tourIcon} className="tour-icon" />
</Button>
}
| Remove period from "Take a guided tour" | Remove period from "Take a guided tour"
| JavaScript | mit | NCI-Agency/anet,NCI-Agency/anet,NCI-Agency/anet,NCI-Agency/anet,NCI-Agency/anet | ---
+++
@@ -5,7 +5,7 @@
export default function HopscotchLauncher(props) {
return <Button bsStyle="link" className="persistent-tour-launcher" onClick={props.onClick}>
- New to ANET? Take a guided tour.
+ New to ANET? Take a guided tour
<ReactSVG path={tourIcon} className="tour-icon" />
</Button>
} |
e189c3bef0dfa572e4d966635475d8c23bfda79e | client/src/components/forms/FormActions.js | client/src/components/forms/FormActions.js | import React from 'react';
import PropTypes from 'prop-types';
import { translate } from 'react-i18next';
import Button from 'react-bootstrap/lib/Button';
import Glyphicon from 'react-bootstrap/lib/Glyphicon';
const ActionsButtons = ({ t, resetForm, saving }) => (
<p>
<Button bsStyle="danger" onClick={resetForm}>
{t('Annuler')}
</Button>{" "}
<Button bsStyle="success" type="submit" disabled={saving}>
{saving &&
<Glyphicon glyph="refresh" className="glyphicon-spin" />
} {t('Enregistrer')}
</Button>
</p>
);
ActionsButtons.propTypes = {
t: PropTypes.func.isRequired,
resetForm: PropTypes.func.isRequired,
saving: PropTypes.bool.isRequired,
};
ActionsButtons.defaultProps = {
saving: false,
};
export default translate()(ActionsButtons);
| import React from 'react';
import PropTypes from 'prop-types';
import { translate } from 'react-i18next';
import Button from 'react-bootstrap/lib/Button';
import Glyphicon from 'react-bootstrap/lib/Glyphicon';
const ActionsButtons = ({ t, saving }) => (
<p>
{/* Bug for the moment */}
{/* <Button bsStyle="danger" onClick={resetForm}>
{t('Annuler')}
</Button>{" "} */}
<Button bsStyle="success" type="submit" disabled={saving}>
{saving &&
<Glyphicon glyph="refresh" className="glyphicon-spin" />
} {t('Enregistrer')}
</Button>
</p>
);
ActionsButtons.propTypes = {
t: PropTypes.func.isRequired,
resetForm: PropTypes.func.isRequired,
saving: PropTypes.bool.isRequired,
};
ActionsButtons.defaultProps = {
saving: false,
};
export default translate()(ActionsButtons);
| Disable reset for the moment | [Client] Disable reset for the moment
| JavaScript | mit | DjLeChuck/recalbox-manager,DjLeChuck/recalbox-manager,DjLeChuck/recalbox-manager | ---
+++
@@ -4,11 +4,12 @@
import Button from 'react-bootstrap/lib/Button';
import Glyphicon from 'react-bootstrap/lib/Glyphicon';
-const ActionsButtons = ({ t, resetForm, saving }) => (
+const ActionsButtons = ({ t, saving }) => (
<p>
- <Button bsStyle="danger" onClick={resetForm}>
+ {/* Bug for the moment */}
+ {/* <Button bsStyle="danger" onClick={resetForm}>
{t('Annuler')}
- </Button>{" "}
+ </Button>{" "} */}
<Button bsStyle="success" type="submit" disabled={saving}>
{saving &&
<Glyphicon glyph="refresh" className="glyphicon-spin" /> |
0da020c61817474e15c63bd6dc40d4b65a40fda9 | web/src/js/components/General/Fireworks.js | web/src/js/components/General/Fireworks.js | import React, { useRef } from 'react'
import * as FireworksCanvas from 'fireworks-canvas'
import { withStyles } from '@material-ui/core/styles'
import FadeInDashboardAnimation from 'js/components/General/FadeInDashboardAnimation'
const styles = {
container: {
position: 'absolute',
zIndex: 5000,
top: 0,
right: 0,
bottom: 0,
left: 0,
background: 'rgba(0, 0, 0, 0.85)',
},
}
const Fireworks = ({ classes, children, options }) => {
const containerEl = useRef(null)
if (containerEl.current) {
const fireworks = new FireworksCanvas(containerEl.current, options)
fireworks.start()
}
return (
<FadeInDashboardAnimation>
<div ref={containerEl} className={classes.container}>
{children}
</div>
</FadeInDashboardAnimation>
)
}
export default withStyles(styles)(Fireworks)
| import React, { useRef, useState } from 'react'
import * as FireworksCanvas from 'fireworks-canvas'
import { withStyles } from '@material-ui/core/styles'
import FadeInDashboardAnimation from 'js/components/General/FadeInDashboardAnimation'
import IconButton from '@material-ui/core/IconButton'
import CloseIcon from '@material-ui/icons/Close'
const styles = {
container: {
position: 'absolute',
zIndex: 5000,
top: 0,
right: 0,
bottom: 0,
left: 0,
background: 'rgba(0, 0, 0, 0.85)',
},
closeIconButton: {
position: 'absolute',
zIndex: 6000,
top: 10,
right: 10,
},
closeIcon: {
color: 'rgba(255, 255, 255, 0.8)',
width: 36,
height: 36,
},
}
const Fireworks = ({ classes, children, options }) => {
const [active, setActive] = useState(true)
const containerEl = useRef(null)
if (containerEl.current) {
const fireworks = new FireworksCanvas(containerEl.current, options)
fireworks.start()
}
return (
<FadeInDashboardAnimation>
{active ? (
<div ref={containerEl} className={classes.container}>
<IconButton
className={classes.closeIconButton}
onClick={() => {
setActive(false)
}}
>
<CloseIcon className={classes.closeIcon} />
</IconButton>
{children}
</div>
) : null}
</FadeInDashboardAnimation>
)
}
export default withStyles(styles)(Fireworks)
| Add a close button to the fireworks | Add a close button to the fireworks
| JavaScript | mpl-2.0 | gladly-team/tab,gladly-team/tab,gladly-team/tab | ---
+++
@@ -1,7 +1,9 @@
-import React, { useRef } from 'react'
+import React, { useRef, useState } from 'react'
import * as FireworksCanvas from 'fireworks-canvas'
import { withStyles } from '@material-ui/core/styles'
import FadeInDashboardAnimation from 'js/components/General/FadeInDashboardAnimation'
+import IconButton from '@material-ui/core/IconButton'
+import CloseIcon from '@material-ui/icons/Close'
const styles = {
container: {
@@ -13,9 +15,21 @@
left: 0,
background: 'rgba(0, 0, 0, 0.85)',
},
+ closeIconButton: {
+ position: 'absolute',
+ zIndex: 6000,
+ top: 10,
+ right: 10,
+ },
+ closeIcon: {
+ color: 'rgba(255, 255, 255, 0.8)',
+ width: 36,
+ height: 36,
+ },
}
const Fireworks = ({ classes, children, options }) => {
+ const [active, setActive] = useState(true)
const containerEl = useRef(null)
if (containerEl.current) {
const fireworks = new FireworksCanvas(containerEl.current, options)
@@ -23,9 +37,19 @@
}
return (
<FadeInDashboardAnimation>
- <div ref={containerEl} className={classes.container}>
- {children}
- </div>
+ {active ? (
+ <div ref={containerEl} className={classes.container}>
+ <IconButton
+ className={classes.closeIconButton}
+ onClick={() => {
+ setActive(false)
+ }}
+ >
+ <CloseIcon className={classes.closeIcon} />
+ </IconButton>
+ {children}
+ </div>
+ ) : null}
</FadeInDashboardAnimation>
)
} |
cf269a26ac586a948b7cbb332e1f88113f15221b | src/routes/index.js | src/routes/index.js | const router = require('express').Router()
const nonUser = require('./non-user')
const user = require('./user-only')
router.use('/', nonUser)
router.use('/', user)
module.exports = router
| const router = require('express').Router()
const nonUser = require('./non-user')
const user = require('./user-only')
router.use((req, res, next) => {
console.log('middleware stuff')
next()
})
router.use('/', nonUser)
router.use('/', user)
module.exports = router
| Add middleware function that's console logging to make sure it's working | Add middleware function that's console logging to make sure it's working
| JavaScript | mit | Maighdlyn/phase-4-challenge,Maighdlyn/phase-4-challenge,Maighdlyn/phase-4-challenge | ---
+++
@@ -1,6 +1,11 @@
const router = require('express').Router()
const nonUser = require('./non-user')
const user = require('./user-only')
+
+router.use((req, res, next) => {
+ console.log('middleware stuff')
+ next()
+})
router.use('/', nonUser)
router.use('/', user) |
a9e219a5e5be3b18335b5031b5c0450b1e54bd5b | src/text-grabber.js | src/text-grabber.js | ;(function(exports) {
var TextGrabber = function() {
this.submittedText = "";
this.currentLine = "";
};
TextGrabber.prototype = {
write: function(e) {
if (e.event === "submit") {
this.submittedText += e.text + "\n";
this.currentLine = "";
} else {
this.currentLine = e.text + "\n";
}
},
getText: function() {
return this.submittedText + this.currentLine;
}
};
exports.TextGrabber = TextGrabber;
})(typeof exports === 'undefined' ? this : exports)
| ;(function(exports) {
var TextGrabber = function() {
this.submittedText = [];
this.currentLine = {};
};
TextGrabber.prototype = {
write: function(e) {
if (e.event === "permanent") {
var lines = e.text.split("\n");
for (var i = 0; i < lines.length; i++) {
if (lines[i] !== "") {
this.submittedText.push(newLine(lines[i] + "\n", e.io));
}
}
this.currentLine = newLine("", "input");
} else {
this.currentLine = newLine(e.text + "\n", e.io);
}
},
getPlainText: function() {
var out = "";
for (var i = 0; i < this.submittedText.length; i++) {
out += this.submittedText[i].text;
}
out += this.currentLine.text;
return out;
},
// returns text as array of lines, each line labelled as input or output
getCategorisedText: function() {
var out = [];
for (var i = 0; i < this.submittedText.length; i++) {
out.push(this.submittedText[i]);
}
out.push(this.currentLine);
return out;
}
};
var newLine = function(text, io) {
return { text:text, io:io };
};
exports.TextGrabber = TextGrabber;
})(typeof exports === 'undefined' ? this : exports)
| Make text grabber categorise text in input and output. | Make text grabber categorise text in input and output. | JavaScript | mit | maryrosecook/codewithisla | ---
+++
@@ -1,22 +1,48 @@
;(function(exports) {
var TextGrabber = function() {
- this.submittedText = "";
- this.currentLine = "";
+ this.submittedText = [];
+ this.currentLine = {};
};
TextGrabber.prototype = {
write: function(e) {
- if (e.event === "submit") {
- this.submittedText += e.text + "\n";
- this.currentLine = "";
+ if (e.event === "permanent") {
+ var lines = e.text.split("\n");
+ for (var i = 0; i < lines.length; i++) {
+ if (lines[i] !== "") {
+ this.submittedText.push(newLine(lines[i] + "\n", e.io));
+ }
+ }
+ this.currentLine = newLine("", "input");
} else {
- this.currentLine = e.text + "\n";
+ this.currentLine = newLine(e.text + "\n", e.io);
}
},
- getText: function() {
- return this.submittedText + this.currentLine;
+ getPlainText: function() {
+ var out = "";
+ for (var i = 0; i < this.submittedText.length; i++) {
+ out += this.submittedText[i].text;
+ }
+
+ out += this.currentLine.text;
+ return out;
+ },
+
+ // returns text as array of lines, each line labelled as input or output
+ getCategorisedText: function() {
+ var out = [];
+ for (var i = 0; i < this.submittedText.length; i++) {
+ out.push(this.submittedText[i]);
+ }
+
+ out.push(this.currentLine);
+ return out;
}
+ };
+
+ var newLine = function(text, io) {
+ return { text:text, io:io };
};
exports.TextGrabber = TextGrabber; |
b62d9b600dda1e65bf23aeaa1eb5578acfbd9f6d | start.js | start.js | #!/usr/bin/env node
var cp = require('child_process')
var BIN = '/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary'
var ARGS = ['--load-and-launch-app=chrome']
var child = cp.spawn(BIN, ARGS)
// Nodemon is trying to kill us, so kill Chrome
process.once('SIGUSR2', function () {
child.kill()
process.kill(process.pid, 'SIGUSR2')
}) | #!/usr/bin/env node
var cp = require('child_process')
var BIN = process.platform=='linux' ? '/bin/google-chrome' : '/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary';
var ARGS = ['--load-and-launch-app=chrome']
var child = cp.spawn(BIN, ARGS)
// Nodemon is trying to kill us, so kill Chrome
process.once('SIGUSR2', function () {
child.kill()
process.kill(process.pid, 'SIGUSR2')
})
| Improve the accessibility of the project for linux users. | Improve the accessibility of the project for linux users.
| JavaScript | mit | feross/webtorrent-cli,feross/webtorrent-cli | ---
+++
@@ -2,7 +2,7 @@
var cp = require('child_process')
-var BIN = '/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary'
+var BIN = process.platform=='linux' ? '/bin/google-chrome' : '/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary';
var ARGS = ['--load-and-launch-app=chrome']
var child = cp.spawn(BIN, ARGS) |
b163c12143f332b276cd1104ab42598489994c6e | client/lecturer/app/courses.factory.js | client/lecturer/app/courses.factory.js | (function() {
'use strict';
angular
.module('lecturer')
.factory('coursesFactory', coursesFactory);
/* @ngInject */
function coursesFactory(coursesService) {
var selectedCourse = {};
var Course = false;
var service = {
getCourses: getCourses,
addCourse: addCourse,
setCourse: setCourse,
getCourse: getCourse
};
return service;
function getCourses(onSuccess) {
if (!Course) {
Course = coursesService.course;
}
Course.query({lecturer: 1}, onSuccess);
}
function addCourse(course, onSuccess) {
if (!Course) {
Course = coursesService.course;
}
Course.save(course, onSuccess);
}
function setCourse(course) {
selectedCourse = course;
}
function getCourse() {
return selectedCourse;
}
}
})(); | (function() {
'use strict';
angular
.module('lecturer')
.factory('coursesFactory', coursesFactory);
/* @ngInject */
function coursesFactory(coursesService, lecturerFactory) {
var selectedCourse = {};
var Course = false;
var service = {
getCourses: getCourses,
addCourse: addCourse,
setCourse: setCourse,
getCourse: getCourse
};
return service;
function getCourses(onSuccess) {
if (!Course) {
Course = coursesService.course;
}
Course.query({lecturer: lecturerFactory.getLecturerId()}, onSuccess);
}
function addCourse(course, onSuccess) {
if (!Course) {
Course = coursesService.course;
}
Course.save(course, onSuccess);
}
function setCourse(course) {
selectedCourse = course;
}
function getCourse() {
return selectedCourse;
}
}
})();
| Fix all courses being displayed for all lecturers | Fix all courses being displayed for all lecturers
| JavaScript | mit | MACSIFS/IFS,MACSIFS/IFS,MACSIFS/IFS,MACSIFS/IFS | ---
+++
@@ -6,7 +6,7 @@
.factory('coursesFactory', coursesFactory);
/* @ngInject */
- function coursesFactory(coursesService) {
+ function coursesFactory(coursesService, lecturerFactory) {
var selectedCourse = {};
var Course = false;
@@ -24,7 +24,7 @@
Course = coursesService.course;
}
- Course.query({lecturer: 1}, onSuccess);
+ Course.query({lecturer: lecturerFactory.getLecturerId()}, onSuccess);
}
function addCourse(course, onSuccess) { |
e6a72cd9754ea4bf2332c8a5262614295f10ebef | bot.js | bot.js | var telegramBot = require('node-telegram-bot-api');
var twitter = require('twitter');
var aws = require('aws-sdk');
var nconf = require('nconf');
var log4js = require('log4js');
nconf.file('config', __dirname + '/config/config.json');
var botToken = nconf.get('telegram').bot_token;
var bot = new TelegramBot(botToken, {
polling: true
});
var awsAccessKeyId = nconf.get('database')['aws'].access_key_id;
var awsSecretAccessKey = nconf.get('database')['aws'].secret_access_key;
aws.config.update{accessKeyId: awsAccessKeyId, secretAccessKey: awsSecretAccessKey, region: 'ap-southeast-1'};
bot.onText('/register', function(msg, match) {
var msgId = msg.from.id;
}
| var telegramBot = require('node-telegram-bot-api');
var twitter = require('twitter');
var aws = require('aws-sdk');
var nconf = require('nconf');
var log4js = require('log4js');
nconf.file('config', __dirname + '/config/config.json');
var botToken = nconf.get('telegram').bot_token;
var bot = new TelegramBot(botToken, {
polling: true
});
var awsAccessKeyId = nconf.get('database')['aws'].access_key_id;
var awsSecretAccessKey = nconf.get('database')['aws'].secret_access_key;
aws.config.update{accessKeyId: awsAccessKeyId, secretAccessKey: awsSecretAccessKey, region: 'ap-southeast-1'};
var dyDb = new aws.DynamoDB();
bot.onText('/register', function(msg, match) {
var userId = msg.from.id;
updateUserList(dyDb, userId);
}
| Add dydb object and put updateUserList function again | Add dydb object and put updateUserList function again
| JavaScript | mit | dollars0427/mtrupdate-bot | ---
+++
@@ -16,10 +16,12 @@
aws.config.update{accessKeyId: awsAccessKeyId, secretAccessKey: awsSecretAccessKey, region: 'ap-southeast-1'};
-
+var dyDb = new aws.DynamoDB();
bot.onText('/register', function(msg, match) {
- var msgId = msg.from.id;
+ var userId = msg.from.id;
+
+ updateUserList(dyDb, userId);
} |
962b29531ef90a415ee062a45b81c5dd927e3f18 | app/js/components/Alert.js | app/js/components/Alert.js | 'use strict'
import {Component} from 'react'
import {Link} from 'react-router'
import Countdown from 'react-countdown-now';
import CountdownTimer from './CountdownTimer'
const registrationEndDate = "Wednesday, November 15 2017 15:00:00 EST"
class Alert extends Component {
constructor(props) {
super(props)
}
render() {
return (
<a href="http://blockstack.com" target="_blank" className="alert alert-primary alert-dismissible fade show text-center text-white" role="alert" style={{ marginBottom: '0', display: "block", paddingBottom: '21px' }}>
<div>
<button type="button" className="close close-primary d-none d-sm-block" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<span className="" style={{ marginLeft: "26px" }}>Blockstack Token Main Sale Starts - Thu, Nov 16 at 11AM EST</span>
</div>
</a>
)
}
}
export default Alert
| 'use strict'
import {Component} from 'react'
import {Link} from 'react-router'
import Countdown from 'react-countdown-now';
import CountdownTimer from './CountdownTimer'
const registrationEndDate = "Wednesday, November 15 2017 15:00:00 EST"
class Alert extends Component {
constructor(props) {
super(props)
}
render() {
return (
<a href="http://blockstack.com" target="_blank" className="alert alert-primary alert-dismissible fade show text-center text-white" role="alert" style={{ marginBottom: '0', display: "block", paddingBottom: '21px' }}>
<div>
<button type="button" className="close close-primary d-none d-sm-block" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<span className="" style={{ marginLeft: "26px" }}>Blockstack Token Main Sale Starts - Thu, Nov 16 at 11AM EDT</span>
</div>
</a>
)
}
}
export default Alert
| Correct token sale banner timezone. | Correct token sale banner timezone.
| JavaScript | mit | blockstack/blockstack-site,blockstack/blockstack-site | ---
+++
@@ -20,7 +20,7 @@
<button type="button" className="close close-primary d-none d-sm-block" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
- <span className="" style={{ marginLeft: "26px" }}>Blockstack Token Main Sale Starts - Thu, Nov 16 at 11AM EST</span>
+ <span className="" style={{ marginLeft: "26px" }}>Blockstack Token Main Sale Starts - Thu, Nov 16 at 11AM EDT</span>
</div>
</a>
) |
86a611bf64d3fb18bde62e3457c1c09953c4b158 | test/file-collection.js | test/file-collection.js | import test from 'ava';
import '../src/index';
import FileCollection from '../src/FileCollection';
test('that it sets the output file if a src file and output directory are provided', t => {
let src = new File('src/file.txt').parsePath();
let files = new FileCollection(src.path);
files.destination = 'output';
t.is('output/file.txt', files.outputPath(src));
});
test('that it sets the output file if a src file and output directory are provided', t => {
let src = new File('node_modules/path/to/it').parsePath();
let files = new FileCollection(src.path);
files.destination = 'public/output';
t.is('public/output/nested/file.txt', files.outputPath(
new File('node_modules/path/to/it/nested/file.txt').parsePath()
));
});
| import test from 'ava';
import '../src/index';
import FileCollection from '../src/FileCollection';
test('that it sets the output file if a src file and output directory are provided', t => {
let src = new File('src/file.txt').parsePath();
let files = new FileCollection(src.path);
files.destination = 'output';
t.is('output/file.txt', files.outputPath(src));
});
test('that it sets the output file if a src file and output directory are provided', t => {
let src = new File('node_modules/path/to/it').parsePath();
let files = new FileCollection(src.path);
files.destination = 'public/output';
t.is('public/output/nested/file.txt', files.outputPath(
new File('node_modules/path/to/it/nested/file.txt').parsePath()
));
});
test('that it sets the output path for an array of src files properly', t => {
let collection = new FileCollection([
'resources/assets/img/one.jpg',
'resources/assets/img/two.jpg'
]);
collection.destination = 'public/img';
let output = collection.outputPath(
new File('resources/assets/img/one.jpg').parsePath()
);
t.is('public/img/one.jpg', output);
});
| Add test for file collection | Add test for file collection
| JavaScript | mit | JeffreyWay/laravel-mix | ---
+++
@@ -20,3 +20,19 @@
new File('node_modules/path/to/it/nested/file.txt').parsePath()
));
});
+
+
+test('that it sets the output path for an array of src files properly', t => {
+ let collection = new FileCollection([
+ 'resources/assets/img/one.jpg',
+ 'resources/assets/img/two.jpg'
+ ]);
+
+ collection.destination = 'public/img';
+
+ let output = collection.outputPath(
+ new File('resources/assets/img/one.jpg').parsePath()
+ );
+
+ t.is('public/img/one.jpg', output);
+}); |
c4e98094e2250d556566d76512f502e382d05ae5 | test/functional/conf.js | test/functional/conf.js | exports.config = {
baseUrl: 'http://dev.hmda-pilot.ec2.devis.com/',
specs: ['cucumber/*.feature'],
allScriptsTimeout: 30000,
getPageTimeout: 30000,
capabilities: {
browserName: 'chrome'
},
framework: 'cucumber',
cucumberOpts: {
require: 'cucumber/step_definitions/*.js',
tags: ['~@wip', '~@ignore'],
format: 'progress'
}
};
| 'use strict';
exports.config = {
baseUrl: 'http://dev.hmda-pilot.ec2.devis.com/',
specs: ['cucumber/*.feature'],
allScriptsTimeout: 30000,
getPageTimeout: 30000,
capabilities: {
browserName: 'chrome'
},
framework: 'cucumber',
cucumberOpts: {
require: 'cucumber/step_definitions/*.js',
tags: ['~@wip', '~@ignore'],
format: 'progress'
},
onPrepare: function() {
var width = 1280;
var height = 1024;
browser.driver.manage().window().setSize(width, height);
}
};
| Set the browser size to 1280x1024 | Set the browser size to 1280x1024
| JavaScript | cc0-1.0 | cfpb/hmda-pilot,LinuxBozo/hmda-pilot,LinuxBozo/hmda-pilot,cfpb/hmda-pilot,cfpb/hmda-pilot,LinuxBozo/hmda-pilot | ---
+++
@@ -1,3 +1,5 @@
+'use strict';
+
exports.config = {
baseUrl: 'http://dev.hmda-pilot.ec2.devis.com/',
@@ -16,5 +18,11 @@
require: 'cucumber/step_definitions/*.js',
tags: ['~@wip', '~@ignore'],
format: 'progress'
+ },
+
+ onPrepare: function() {
+ var width = 1280;
+ var height = 1024;
+ browser.driver.manage().window().setSize(width, height);
}
}; |
122abc843a93c20ccaa48deea0675cbd281f3c41 | sencha-workspace/SlateAdmin/app/view/progress/NavPanel.js | sencha-workspace/SlateAdmin/app/view/progress/NavPanel.js | Ext.define('SlateAdmin.view.progress.NavPanel', {
extend: 'SlateAdmin.view.LinksNavPanel',
xtype: 'progress-navpanel',
title: 'Student Progress',
data: true,
applyData: function(data) {
if (data !== true) {
return data;
}
return [
{
text: 'Section Interim Reports',
href: '#progress/interims/report',
children: [
{
text: 'Print / Export',
href: '#progress/interims/print'
},
{
text: 'Email',
href: '#progress/interims/email'
}
]
},
{
text: 'Section Term Reports',
href: '#progress/terms/report',
children: [
{
text: 'Search & Print',
href: '#progress/terms/print'
},
{
text: 'Email',
href: '#progress/terms/email'
}
]
}
];
}
}); | Ext.define('SlateAdmin.view.progress.NavPanel', {
extend: 'SlateAdmin.view.LinksNavPanel',
xtype: 'progress-navpanel',
title: 'Student Progress',
data: true,
applyData: function(data) {
if (data !== true) {
return data;
}
return [
{
text: 'Section Interim Reports',
href: '#progress/interims/report',
children: [
{
text: 'Print / Export',
href: '#progress/interims/print'
},
{
text: 'Email',
href: '#progress/interims/email'
}
]
},
{
text: 'Section Term Reports',
href: '#progress/terms/report',
children: [
{
text: 'Print / Export',
href: '#progress/terms/print'
},
{
text: 'Email',
href: '#progress/terms/email'
}
]
}
];
}
}); | Use consistent naming for 'Print / Export' section | Use consistent naming for 'Print / Export' section
| JavaScript | mit | SlateFoundation/slate,SlateFoundation/slate-admin,SlateFoundation/slate,SlateFoundation/slate,SlateFoundation/slate,SlateFoundation/slate-admin,SlateFoundation/slate-admin,SlateFoundation/slate,SlateFoundation/slate-admin,SlateFoundation/slate-admin | ---
+++
@@ -31,7 +31,7 @@
href: '#progress/terms/report',
children: [
{
- text: 'Search & Print',
+ text: 'Print / Export',
href: '#progress/terms/print'
},
{ |
796a9e6f66b019fbe102c79ed2c0836369cde36f | src/sw-precache-config.js | src/sw-precache-config.js | /* eslint-env node */
'use strict';
module.exports = {
staticFileGlobs: [
'index.html',
'bower_components/webcomponentsjs/webcomponents-*.js',
'images/*',
'favicon.ico'
],
navigateFallback: 'index.html'
};
| /* eslint-env node */
'use strict';
module.exports = {
staticFileGlobs: [
'index.html',
'bower_components/webcomponentsjs/webcomponents-*.js',
'images/*',
'favicon.ico'
],
navigateFallback: 'index.html',
navigateFallbackWhitelist: [/^\/(projects|posts|impress)\//]
};
| Exclude "/demo" from SW navigateFallback. | Exclude "/demo" from SW navigateFallback.
| JavaScript | mit | frigus02/website,frigus02/website | ---
+++
@@ -9,5 +9,6 @@
'images/*',
'favicon.ico'
],
- navigateFallback: 'index.html'
+ navigateFallback: 'index.html',
+ navigateFallbackWhitelist: [/^\/(projects|posts|impress)\//]
}; |
9e7379f863ab7bb8b4ae2fd39530692a427df5a1 | test/loader.js | test/loader.js | /*globals mocha*/
require.config({
baseUrl: '/',
paths: {
'tabler': '../',
'jquery': 'test/lib/jquery-1.7.1',
'underscore': 'test/lib/underscore'
}
});
mocha.setup({
ui: 'bdd',
globals: ['jQuery']
});
require(['jquery',
'test/tabler.tests',
'test/tabler.aggregator.tests',
'test/tabler.columnGrouper.tests',
'test/tabler.jumpToPage.tests',
'test/tabler.pageSize.tests',
'test/tabler.pager.tests',
'test/tabler.toggleColumns.tests',
'test/tabler.sortable.tests',
'test/tabler.columnGrouper.tests'
], function(){
'use strict';
mocha.run();
});
| /*globals mocha*/
require.config({
baseUrl: '/',
paths: {
'tabler': '../',
'jquery': 'test/lib/jquery-1.7.1',
'underscore': 'test/lib/underscore'
}
});
mocha.setup({
ui: 'bdd',
globals: ['jQuery']
});
require(['jquery',
'test/tabler.tests',
'test/tabler.aggregator.tests',
'test/tabler.columnGrouper.tests',
'test/tabler.jumpToPage.tests',
'test/tabler.pageSize.tests',
'test/tabler.pager.tests',
'test/tabler.toggleColumns.tests',
'test/tabler.removeColumns.tests',
'test/tabler.sortable.tests',
'test/tabler.columnGrouper.tests'
], function(){
'use strict';
mocha.run();
});
| Add removeColumns plugin to the test suite | Add removeColumns plugin to the test suite
| JavaScript | mit | BrandwatchLtd/tabler,BrandwatchLtd/tabler,BrandwatchLtd/tabler | ---
+++
@@ -19,6 +19,7 @@
'test/tabler.pageSize.tests',
'test/tabler.pager.tests',
'test/tabler.toggleColumns.tests',
+ 'test/tabler.removeColumns.tests',
'test/tabler.sortable.tests',
'test/tabler.columnGrouper.tests'
], function(){ |
cd2e472740ea42928b635d79a22d71d1f24024d9 | src/activity-logger/index.js | src/activity-logger/index.js | export const PAUSE_STORAGE_KEY = 'is-logging-paused'
export function isLoggable({ url }) {
// Just remember http(s) pages, ignoring data uris, newtab, ...
const loggableUrlPattern = /^https?:\/\/\w+([-/.#=$^@&%?+(),]\w*\/?([-/.#=$^@&:%?+(),]\w*\/?)*)*$/
const urlEndings = ['.svg', '.jpg', '.png', '.jpeg', '.gif']
// Ignore all pages that are image files
for (const urlEnding of urlEndings) {
if (url.endsWith(urlEnding)) {
return false
}
}
return loggableUrlPattern.test(url)
}
export const getPauseState = async () => {
const state = (await browser.storage.local.get(PAUSE_STORAGE_KEY))[
PAUSE_STORAGE_KEY
]
switch (state) {
case 0:
case 1:
return true
case 2:
default:
return false
}
}
| export const PAUSE_STORAGE_KEY = 'is-logging-paused'
export function isLoggable({ url }) {
// Just remember http(s) pages, ignoring data uris, newtab, ...
const loggableUrlPattern = /^https?:\/\/\w+(?:[-/.#=$^@&%?+(),]\w*\/?(?:[-/.#=$^@&:%?+(),]\w*\/?)*)*$/
const urlEndings = ['.svg', '.jpg', '.png', '.jpeg', '.gif']
// Ignore all pages that are image files
for (const urlEnding of urlEndings) {
if (url.endsWith(urlEnding)) {
return false
}
}
return loggableUrlPattern.test(url)
}
export const getPauseState = async () => {
const state = (await browser.storage.local.get(PAUSE_STORAGE_KEY))[
PAUSE_STORAGE_KEY
]
switch (state) {
case 0:
case 1:
return true
case 2:
default:
return false
}
}
| Make loggability regex groups non-capturing | Make loggability regex groups non-capturing
- captured groups have a performance overhead, which we seem to have been impacted by through the addition of this nested group when it comes to its use in imports calculations
- we never actually attempt any matches with the pattern, only test it against strings, so there's no need for us to have the capturing functionality
- adding `?:` to the start of a group makes in non-capturing
| JavaScript | mit | WorldBrain/WebMemex,WorldBrain/WebMemex | ---
+++
@@ -2,7 +2,7 @@
export function isLoggable({ url }) {
// Just remember http(s) pages, ignoring data uris, newtab, ...
- const loggableUrlPattern = /^https?:\/\/\w+([-/.#=$^@&%?+(),]\w*\/?([-/.#=$^@&:%?+(),]\w*\/?)*)*$/
+ const loggableUrlPattern = /^https?:\/\/\w+(?:[-/.#=$^@&%?+(),]\w*\/?(?:[-/.#=$^@&:%?+(),]\w*\/?)*)*$/
const urlEndings = ['.svg', '.jpg', '.png', '.jpeg', '.gif']
// Ignore all pages that are image files |
b08269f679a78d1f24774a687706927a8b00bd57 | tests/index.js | tests/index.js | 'use strict';
var path = require('path');
var expect = require('expect.js');
var walkSync = require('walk-sync');
var broccoli = require('broccoli');
var fs = require('fs');
// require('mocha-jshint')();
var Tar = require('..');
describe('broccoli-targz', function(){
var fixturePath = path.join(__dirname, 'fixtures');
var builder;
afterEach(function() {
if (builder) {
return builder.cleanup();
}
});
it('emits an archive.gz file', function() {
var inputPath = path.join(fixturePath);
var tree = new Tar(inputPath);
builder = new broccoli.Builder(tree);
return builder.build()
.then(function(results) {
var outputPath = results.directory;
expect(fs.existsSync(outputPath + '/archive.tar.gz'));
});
});
it('the tar contains the file from input the input tree');
it('emits an <name>.gz file if options.name is set', function(){
var inputPath = path.join(fixturePath);
var tree = new Tar(inputPath);
builder = new broccoli.Builder(tree, 'name');
return builder.build()
.then(function(results) {
var outputPath = results.directory;
expect(fs.existsSync(outputPath + '/name.tar.gz'));
});
})
});
| 'use strict';
var path = require('path');
var expect = require('expect.js');
var walkSync = require('walk-sync');
var broccoli = require('broccoli');
var fs = require('fs');
// require('mocha-jshint')();
var Tar = require('..');
describe('broccoli-targz', function(){
var fixturePath = path.join(__dirname, 'fixtures');
var builder;
afterEach(function() {
if (builder) {
return builder.cleanup();
}
});
it('emits an archive.gz file', function() {
var inputPath = path.join(fixturePath);
var tree = new Tar(inputPath);
builder = new broccoli.Builder(tree);
return builder.build()
.then(function(results) {
var outputPath = results.directory;
expect(fs.existsSync(outputPath + '/archive.tar.gz'));
});
});
it('the tar contains the file from input the input tree');
it('emits an <name>.gz file if options.name is set', function(){
var inputPath = path.join(fixturePath);
var tree = new Tar(inputPath);
builder = new broccoli.Builder(tree, 'name');
return builder.build()
.then(function(results) {
var outputPath = results.directory;
expect(fs.existsSync(outputPath + '/name.tar.gz'));
});
});
it('supports non-constructor pattern', function () {
var inputPath = path.join(fixturePath);
var tree = Tar(inputPath);
expect(tree).to.be.a(Tar);
});
});
| Add tests for non-constructor pattern. | Add tests for non-constructor pattern. | JavaScript | mit | trek/broccoli-tar,vasman/broccoli-zip | ---
+++
@@ -45,5 +45,11 @@
var outputPath = results.directory;
expect(fs.existsSync(outputPath + '/name.tar.gz'));
});
- })
+ });
+
+ it('supports non-constructor pattern', function () {
+ var inputPath = path.join(fixturePath);
+ var tree = Tar(inputPath);
+ expect(tree).to.be.a(Tar);
+ });
}); |
d938dec90ecc359be562851b91223e3512dd0dea | src/ui/mixin/element.js | src/ui/mixin/element.js | /** section: scripty2 ui
* mixin S2.UI.Mixin.Element
*
* Provides a few convenience methods for widgets that map easily to a
* single element.
**/
(function() {
var METHODS = $w('observe stopObserving show hide ' +
'addClassName removeClassName hasClassName setStyle getStyle' +
'writeAttribute readAttribute on fire');
var E = {};
METHODS.each( function(name) {
E[name] = function() {
var element = this.toElement();
return element[name].apply(element, arguments);
};
});
window.S2.UI.Mixin.Element = E;
})();
| /** section: scripty2 ui
* mixin S2.UI.Mixin.Element
*
* Provides a few convenience methods for widgets that map easily to a
* single element.
**/
(function() {
var METHODS = $w('observe stopObserving show hide ' +
'addClassName removeClassName hasClassName setStyle getStyle' +
'writeAttribute readAttribute fire');
var E = {};
METHODS.each( function(name) {
E[name] = function() {
var element = this.toElement();
return element[name].apply(element, arguments);
};
});
E.on = function() {
if (!this.__observers) this.__observers = [];
var element = this.toElement();
var result = element.on.apply(element, arguments);
this.__observers.push(result);
};
window.S2.UI.Mixin.Element = E;
})();
| Redefine `S2.UI.Mixin.Element.on` so that it caches its observers. | Redefine `S2.UI.Mixin.Element.on` so that it caches its observers. | JavaScript | mit | madrobby/scripty2,madrobby/scripty2 | ---
+++
@@ -8,7 +8,7 @@
(function() {
var METHODS = $w('observe stopObserving show hide ' +
'addClassName removeClassName hasClassName setStyle getStyle' +
- 'writeAttribute readAttribute on fire');
+ 'writeAttribute readAttribute fire');
var E = {};
@@ -18,7 +18,14 @@
return element[name].apply(element, arguments);
};
});
-
+
+ E.on = function() {
+ if (!this.__observers) this.__observers = [];
+ var element = this.toElement();
+ var result = element.on.apply(element, arguments);
+ this.__observers.push(result);
+ };
+
window.S2.UI.Mixin.Element = E;
})();
|
8b5a0f5a1d7f435d23e3c220a85e4180531f3aeb | Kwc/Basic/LinkTag/Extern/Component.defer.js | Kwc/Basic/LinkTag/Extern/Component.defer.js | $(document).on('click', 'a', function(event) {
var lnk = event.currentTarget;
//for backwards compatibility
var rels = lnk.rel.split(' ');
$.each(rels, function() {
if (this.match(/^popup/)) {
var relProperties = this.split('_');
//$(lnk).addClass('webLinkPopup');
if (relProperties[1] == 'blank') {
window.open(lnk.href, '_blank');
} else {
window.open(lnk.href, '_blank', relProperties[1]);
}
event.preventDefault();
}
});
if (lnk.data('kwc-popup')) {
if (lnk.data('kwc-popup') == 'blank') {
window.open(lnk.href, '_blank');
} else {
window.open(lnk.href, '_blank', lnk.data('kwc-popup'));
}
}
});
| $(document).on('click', 'a', function(event) {
var lnk = event.currentTarget;
//for backwards compatibility
var rels = lnk.rel.split(' ');
$.each(rels, function() {
if (this.match(/^popup/)) {
var relProperties = this.split('_');
//$(lnk).addClass('webLinkPopup');
if (relProperties[1] == 'blank') {
window.open(lnk.href, '_blank');
} else {
window.open(lnk.href, '_blank', relProperties[1]);
}
event.preventDefault();
}
});
if ($(lnk).data('kwc-popup')) {
if ($(lnk).data('kwc-popup') == 'blank') {
window.open(lnk.href, '_blank');
} else {
window.open(lnk.href, '_blank', $(lnk).data('kwc-popup'));
}
}
});
| Fix data attribute usage for external links | Fix data attribute usage for external links
| JavaScript | bsd-2-clause | kaufmo/koala-framework,nsams/koala-framework,koala-framework/koala-framework,nsams/koala-framework,kaufmo/koala-framework,nsams/koala-framework,koala-framework/koala-framework,kaufmo/koala-framework | ---
+++
@@ -16,11 +16,11 @@
}
});
- if (lnk.data('kwc-popup')) {
- if (lnk.data('kwc-popup') == 'blank') {
+ if ($(lnk).data('kwc-popup')) {
+ if ($(lnk).data('kwc-popup') == 'blank') {
window.open(lnk.href, '_blank');
} else {
- window.open(lnk.href, '_blank', lnk.data('kwc-popup'));
+ window.open(lnk.href, '_blank', $(lnk).data('kwc-popup'));
}
}
}); |
cb68b3bb815013c4f933665da4d1c9805e64b899 | examples/webpack.config.js | examples/webpack.config.js | var webpack = require("webpack");
var path = require("path");
module.exports = {
devtool: "source-map",
entry: path.join(__dirname, "src/main.js"),
output: {
path: path.join(__dirname, "build"),
publicPath: "/js/",
filename: "main.js"
},
resolve: { extensions: ["", ".js"] },
module: {
loaders: [{
test: /\.js?$/,
exclude: /(node_modules)/,
loaders: ["babel"]
}, {
test: /\.css$/,
loaders: ["style", "css", "autoprefixer-loader?browsers=last 2 version"]
}]
},
plugins: [
// ignore moment locales
new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
new webpack.DefinePlugin({
"process.env": {
NODE_ENV: JSON.stringify("production")
}
}),
new webpack.optimize.UglifyJsPlugin({
mangle: {
except: ["Birthdays", "InputField", "Localized", "Range", "SelectableDay", "SimpleCalendar", "YearCalendar", "TouchEvents"]
},
compress: {
warnings: false
}
})
]
};
| var webpack = require("webpack");
var path = require("path");
module.exports = {
devtool: "source-map",
entry: path.join(__dirname, "src/main.js"),
output: {
path: "./built/js",
publicPath: "/js/",
filename: "main.js"
},
resolve: { extensions: ["", ".js"] },
module: {
loaders: [{
test: /\.js?$/,
exclude: /(node_modules)/,
loaders: ["babel"]
}, {
test: /\.css$/,
loaders: ["style", "css", "autoprefixer-loader?browsers=last 2 version"]
}]
},
plugins: [
// ignore moment locales
new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
new webpack.DefinePlugin({
"process.env": {
NODE_ENV: JSON.stringify("production")
}
}),
new webpack.optimize.UglifyJsPlugin({
mangle: {
except: ["Birthdays", "InputField", "Localized", "Range", "SelectableDay", "SimpleCalendar", "YearCalendar", "TouchEvents"]
},
compress: {
warnings: false
}
})
]
};
| Return to the right build dir | Return to the right build dir
| JavaScript | mit | gpbl/react-day-picker,saenglert/react-day-picker,gpbl/react-day-picker,gpbl/react-day-picker | ---
+++
@@ -6,7 +6,7 @@
entry: path.join(__dirname, "src/main.js"),
output: {
- path: path.join(__dirname, "build"),
+ path: "./built/js",
publicPath: "/js/",
filename: "main.js"
}, |
e25af70c3c3043e7028fa6c85d06ea976c35997e | server/votes/countVotes.js | server/votes/countVotes.js | var countVotes = function () {
"use strict";
// find votes for object
var deltaVotesQuery = {
delta: {
$exists: true
}
};
var deltaVotes = Votes.find(deltaVotesQuery).fetch();
var voteTable = {};
// count how many votes each object has
_.forEach(deltaVotes, function (vote) {
var post = voteTable[vote.obj];
if (typeof post === 'undefined') {
// first vote for this post
voteTable[vote.obj] = vote.delta;
} else {
// not first vote for the post
voteTable[vote.obj] += vote.delta;
}
Votes.update({
_id: vote._id
}, {
$unset : {
delta: ''
}
});
});
_.forEach(voteTable, function (value, key) {
Posts.update({_id: key}, { $inc: {votes: value}});
});
console.log('Counting votes:', voteTable);
};
Meteor.startup(countVotes);
// run every 2 minutes
Meteor.setInterval(countVotes, 2*1000);
| var countVotes = function () {
"use strict";
// find votes for object
var deltaVotesQuery = {
delta: {
$exists: true
}
};
var deltaVotes = Votes.find(deltaVotesQuery).fetch();
var voteTable = {};
// count how many votes each object has
_.forEach(deltaVotes, function (vote) {
var post = voteTable[vote.obj];
if (typeof post === 'undefined') {
// first vote for this post
voteTable[vote.obj] = vote.delta;
} else {
// not first vote for the post
voteTable[vote.obj] += vote.delta;
}
Votes.update({
_id: vote._id
}, {
$unset : {
delta: ''
}
});
});
var i = 0;
_.forEach(voteTable, function (value, key) {
Posts.update({_id: key}, { $inc: {votes: value}});
i++;
});
if (i > 0) {
var str = 'Applying ' + i + ' vote';
if (i > 1) {
str += 's';
}
console.log(str);
}
};
Meteor.startup(countVotes);
// run every 5 seconds
Meteor.setInterval(countVotes, 5 * 1000);
| Apply votes quietly every 5 seconds | Apply votes quietly every 5 seconds
| JavaScript | mit | rrevanth/news,rrevanth/news | ---
+++
@@ -30,15 +30,23 @@
});
});
+ var i = 0;
_.forEach(voteTable, function (value, key) {
Posts.update({_id: key}, { $inc: {votes: value}});
+ i++;
});
- console.log('Counting votes:', voteTable);
+
+ if (i > 0) {
+ var str = 'Applying ' + i + ' vote';
+ if (i > 1) {
+ str += 's';
+ }
+ console.log(str);
+ }
};
-
Meteor.startup(countVotes);
-// run every 2 minutes
-Meteor.setInterval(countVotes, 2*1000);
+// run every 5 seconds
+Meteor.setInterval(countVotes, 5 * 1000); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.