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
cc6b9e82123d9a9f75075ed0e843227ea9c74e4d
src/timer.js
src/timer.js
var Timer = (function(Util) { 'use strict'; // Internal constants for the various timer states. var Waiting = 0, Inspecting = 1, Ready = 2, Running = 3, Delay = 4; var state = Waiting; var startTime = undefined, endTime = undefined, solveTime = undefined; var intervalID = undefined; function isWaiting() { return state == Waiting; } function isReady() { return state == Ready; } function isRunning() { return state == Running; } function runningEmitter() { Event.emit("timer/running"); } function trigger() { if (isWaiting()) { state = Ready; } else if (isReady()) { state = Running; startTime = Util.getMilli(); intervalID = setInterval(runningEmitter, 100); } else if (isRunning()) { state = Waiting; endTime = Util.getMilli(); clearInterval(intervalID); } } function getCurrent() { return Util.getMill() - startTime; } return { trigger: trigger, getCurrent: getCurrent }; });
var Timer = (function(Util) { 'use strict'; // Internal constants for the various timer states. var Waiting = 0, Inspecting = 1, Ready = 2, Running = 3, Delay = 4; var state = Waiting; var startTime = undefined, endTime = undefined, solveTime = undefined; var intervalID = undefined; function isWaiting() { return state === Waiting; } function isReady() { return state === Ready; } function isRunning() { return state === Running; } function onWaiting() { endTime = Util.getMilli(); clearInterval(intervalID); } function onRunning() { startTime = Util.getMilli(); intervalID = setInterval(runningEmitter, 100); } function setState(new_state) { state = new_state; switch(state) { case Waiting: onWaiting(); break; case Running: onRunning(); break; } } function runningEmitter() { Event.emit("timer/running"); } function trigger() { if (isWaiting()) { setState(Ready); } else if (isReady()) { setState(Running); } else if (isRunning()) { setState(Waiting); } } function getCurrent() { return Util.getMill() - startTime; } return { trigger: trigger, getCurrent: getCurrent }; });
Move the functionality out of trigger(), to make it do as little as possible. Also, use '===' instead of '=='.
Move the functionality out of trigger(), to make it do as little as possible. Also, use '===' instead of '=='.
JavaScript
mit
jjtimer/jjtimer-core
--- +++ @@ -8,9 +8,27 @@ var startTime = undefined, endTime = undefined, solveTime = undefined; var intervalID = undefined; - function isWaiting() { return state == Waiting; } - function isReady() { return state == Ready; } - function isRunning() { return state == Running; } + function isWaiting() { return state === Waiting; } + function isReady() { return state === Ready; } + function isRunning() { return state === Running; } + + function onWaiting() { + endTime = Util.getMilli(); + clearInterval(intervalID); + } + + function onRunning() { + startTime = Util.getMilli(); + intervalID = setInterval(runningEmitter, 100); + } + + function setState(new_state) { + state = new_state; + switch(state) { + case Waiting: onWaiting(); break; + case Running: onRunning(); break; + } + } function runningEmitter() { Event.emit("timer/running"); @@ -18,15 +36,11 @@ function trigger() { if (isWaiting()) { - state = Ready; + setState(Ready); } else if (isReady()) { - state = Running; - startTime = Util.getMilli(); - intervalID = setInterval(runningEmitter, 100); + setState(Running); } else if (isRunning()) { - state = Waiting; - endTime = Util.getMilli(); - clearInterval(intervalID); + setState(Waiting); } }
8b5307e97bf54da9b97f1fbe610daf6ca3ebf7aa
src/server/app.js
src/server/app.js
import upload from './upload'; import express from 'express'; import logger from 'winston'; const app = express(); export default app; app.set('port', process.env.PORT || 3000); logger.remove(logger.transports.Console); logger.add(logger.transports.Console, {'timestamp':true,}); app.use((req, res, next) => { // eslint-disable-line no-unused-vars res.header('Access-Control-Allow-Origin', 'angeleandgus.com'); res.header('Access-Control-Allow-Headers', 'Content-Type'); }); app.use('/upload', upload); app.use((err, req, res, next) => { const status = err.statusCode || err.status || 500; res.status(status); const ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress || req.socket.remoteAddress || req.connection.socket.remoteAddress; logger.error(`ip: ${ip} err: ${err}`); res.end(`Error ${status}: ${err.shortMessage}`); next(err); }); app.listen(app.get('port'), () => { logger.info(`Server started: http://localhost:${app.get('port')}/`); });
import upload from './upload'; import express from 'express'; import logger from 'winston'; const app = express(); export default app; app.set('port', process.env.PORT || 3000); logger.remove(logger.transports.Console); logger.add(logger.transports.Console, {'timestamp':true,}); app.use((req, res, next) => { res.header('Access-Control-Allow-Origin', 'angeleandgus.com'); res.header('Access-Control-Allow-Headers', 'Content-Type'); next(); }); app.use('/upload', upload); app.use((err, req, res, next) => { const status = err.statusCode || err.status || 500; res.status(status); const ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress || req.socket.remoteAddress || req.connection.socket.remoteAddress; logger.error(`ip: ${ip} err: ${err}`); res.end(`Error ${status}: ${err.shortMessage}`); next(err); }); app.listen(app.get('port'), () => { logger.info(`Server started: http://localhost:${app.get('port')}/`); });
Fix endless loop in server
Fix endless loop in server
JavaScript
agpl-3.0
gusmonod/aag,gusmonod/aag
--- +++ @@ -11,9 +11,11 @@ logger.remove(logger.transports.Console); logger.add(logger.transports.Console, {'timestamp':true,}); -app.use((req, res, next) => { // eslint-disable-line no-unused-vars +app.use((req, res, next) => { res.header('Access-Control-Allow-Origin', 'angeleandgus.com'); res.header('Access-Control-Allow-Headers', 'Content-Type'); + + next(); }); app.use('/upload', upload);
6a6df1b256978c460ec823ee019c2028806d5bd1
sashimi-webapp/src/database/storage.js
sashimi-webapp/src/database/storage.js
/* * CS3283/4 storage.js * This is a facade class for other components */
/** * * CS3283/4 storage.js * This class acts as a facade for other developers to access to the database. * The implementation is a non-SQL local storage to support the WebApp. * */ const entitiesCreator = require('./create/entitiesCreator'); class Storage { static constructor() {} static initializeDatabase() { entitiesCreator.createUserTable(); entitiesCreator.createOrganizationTable(); entitiesCreator.createFolderTable(); entitiesCreator.createFileManagerTable(); entitiesCreator.clearDatabase(); } } Storage.initializeDatabase();
Add initializeDatabase function facade class
Add initializeDatabase function facade class
JavaScript
mit
nus-mtp/sashimi-note,nus-mtp/sashimi-note,nus-mtp/sashimi-note
--- +++ @@ -1,5 +1,23 @@ -/* - * CS3283/4 storage.js - * This is a facade class for other components +/** + * + * CS3283/4 storage.js + * This class acts as a facade for other developers to access to the database. + * The implementation is a non-SQL local storage to support the WebApp. + * */ +const entitiesCreator = require('./create/entitiesCreator'); + +class Storage { + static constructor() {} + + static initializeDatabase() { + entitiesCreator.createUserTable(); + entitiesCreator.createOrganizationTable(); + entitiesCreator.createFolderTable(); + entitiesCreator.createFileManagerTable(); + entitiesCreator.clearDatabase(); + } +} + +Storage.initializeDatabase();
60bd0a8274ec5e922bdaaba82c8c9e1054cea5f5
backend/src/routes/users/index.js
backend/src/routes/users/index.js
const express = require('express') const ERRORS = require('../../errors') const User = require('../../models/User') const utils = require('../../utils') const router = express.Router() router.post('/', register) function register(req, res, next) { const { body: { username, password } } = req if (!username || !password) { next(ERRORS.MISSING_PARAMETERS(['username', 'password'])) } else { User.register(username, password) .then(user => ({ id: user.id, username: user.username, token: utils.genToken(user.id) })) .then(data => { res.status(201) res.json(data) }) .catch(err => next(ERRORS.REGISTRATION_FAILED(err))) } } module.exports = router
const express = require('express') const ERRORS = require('../../errors') const User = require('../../models/User') const utils = require('../../utils') const router = express.Router() router.post('/', register) function register(req, res, next) { const { body: { username, password } } = req if (!username || !password) { next(ERRORS.MISSING_PARAMETERS(['username', 'password'])) } else { User.register(username, password) .then(user => ({ id: user.id, username: user.username, token: utils.genToken(user.id), createdAt: user.createdAt })) .then(data => { res.status(201) res.json(data) }) .catch(err => next(ERRORS.REGISTRATION_FAILED(err))) } } module.exports = router
Fix missing parameter to pass tests
Fix missing parameter to pass tests
JavaScript
mit
14Plumes/Hexode,14Plumes/Hexode,KtorZ/Hexode,14Plumes/Hexode,KtorZ/Hexode,KtorZ/Hexode
--- +++ @@ -14,7 +14,8 @@ .then(user => ({ id: user.id, username: user.username, - token: utils.genToken(user.id) + token: utils.genToken(user.id), + createdAt: user.createdAt })) .then(data => { res.status(201)
c98265f61bae81b9de01ac423f7a2b57a7f83e0f
tests/CoreSpec.js
tests/CoreSpec.js
describe("Core Bliss", function () { "use strict"; before(function() { fixture.setBase('tests/fixtures'); }); beforeEach(function () { this.fixture = fixture.load('core.html'); document.body.innerHTML += this.fixture[0]; }); // testing setup it("has the fixture on the dom", function () { expect($('#fixture-container')).to.not.be.null; }); it("has global methods and aliases", function() { expect(Bliss).to.exist; expect($).to.exist; expect($$).to.exist; expect($).to.equal(Bliss); expect($$).to.equal($.$); }); });
describe("Core Bliss", function () { "use strict"; before(function() { fixture.setBase('tests/fixtures'); }); beforeEach(function () { this.fixture = fixture.load('core.html'); }); // testing setup it("has the fixture on the dom", function () { expect($('#fixture-container')).to.not.be.null; }); it("has global methods and aliases", function() { expect(Bliss).to.exist; expect($).to.exist; expect($$).to.exist; expect($).to.equal(Bliss); expect($$).to.equal($.$); }); });
Remove appending of fixture to dom
Remove appending of fixture to dom This is not needed as far as I can tell, the test below works without it, and loading other fixtures elsewhere doesn't seem to work with this here.
JavaScript
mit
zdfs/bliss,zdfs/bliss,LeaVerou/bliss,dperrymorrow/bliss,LeaVerou/bliss,dperrymorrow/bliss
--- +++ @@ -7,7 +7,6 @@ beforeEach(function () { this.fixture = fixture.load('core.html'); - document.body.innerHTML += this.fixture[0]; }); // testing setup
3f85aa402425340b7476aba9873af2bb3bc3534e
next/pages/index.js
next/pages/index.js
// This is the Link API import Link from 'next/link' const Index = () => ( <div> <Link href="/about"> <a>About Page</a> </Link> <p>Hello Next.js</p> </div> ) export default Index
// This is the Link API import Link from 'next/link' const Index = () => ( <div> <Link href="/about"> <a style={{fontSize: 20}}>About Page</a> </Link> <p>Hello Next.js</p> </div> ) export default Index
Add style to anchor link
Add style to anchor link
JavaScript
mit
yukihirai0505/tutorial-program,yukihirai0505/tutorial-program,yukihirai0505/tutorial-program,yukihirai0505/tutorial-program,yukihirai0505/tutorial-program,yukihirai0505/tutorial-program,yukihirai0505/tutorial-program,yukihirai0505/tutorial-program,yukihirai0505/tutorial-program
--- +++ @@ -4,7 +4,7 @@ const Index = () => ( <div> <Link href="/about"> - <a>About Page</a> + <a style={{fontSize: 20}}>About Page</a> </Link> <p>Hello Next.js</p> </div>
2ad2196880708ceaf1870c89a5080f65efb66e8b
example/hoppfile.js
example/hoppfile.js
import hopp from 'hopp' export const css = hopp([ 'src/css/*.css' ]) .dest('dist/css') export const js = hopp([ 'src/js/*.js' ]) // create fs streams // .babel() // pipe to (create babel stream) .dest('dist/js') // pipe to (create dest stream) export default [ 'js', 'css' ]
import hopp from 'hopp' export const css = hopp([ 'src/css/*.css' ]) .dest('dist/css') export const js = hopp([ 'src/js/*.js' ]) .dest('dist/js') export const watch = hopp.watch([ 'js', 'css' ]) export default [ 'js', 'css' ]
Add sample watch task to example
Add sample watch task to example
JavaScript
mit
hoppjs/hopp
--- +++ @@ -5,9 +5,11 @@ .dest('dist/css') export const js = - hopp([ 'src/js/*.js' ]) // create fs streams - // .babel() // pipe to (create babel stream) - .dest('dist/js') // pipe to (create dest stream) + hopp([ 'src/js/*.js' ]) + .dest('dist/js') + +export const watch = + hopp.watch([ 'js', 'css' ]) export default [ 'js',
ab13702e08dd3daa943b08bb4a2cc014128b0ee0
wolf.js
wolf.js
var irc = require('irc'); // IRC Client require('js-yaml'); // JavaScript YAML parser (for settings) // Import settings file var settings = require('./config/bot.yaml'); var client = new irc.Client(settings.server, settings.nick, { userName: settings.username, realName: settings.realname, port: settings.port, channels: [settings.channel], }); // Original IRC output to console (for debugging) client.addListener('raw', function (message) { if (message.server) { console.log(':' + message.server + ' ' + message.command + ' ' + message.args.join(' :') ); } else { console.log(':' + message.nick + '!' + message.user + '@' + message.host + ' ' + message.command + ' ' + message.args.join(' :') ); } });
var irc = require('irc'); // IRC Client require('js-yaml'); // JavaScript YAML parser (for settings) // Gr__dirnameab configuration files var settings = require(__dirname + '/config/bot.yaml'); var werewolf = require(__dirname + '/config/werewolf.yaml'); var client = new irc.Client(settings.server, settings.nick, { userName: settings.username, realName: settings.realname, port: settings.port, channels: [settings.channel], }); // Original IRC output to console (for debugging) client.addListener('raw', function (message) { if (message.server) { console.log(':' + message.server + ' ' + message.command + ' ' + message.args.join(' :') ); } else { console.log(':' + message.nick + '!' + message.user + '@' + message.host + ' ' + message.command + ' ' + message.args.join(' :') ); } }); // The Locale handler var Locale = require(__dirname + '/components/locale.js'); var locale = Locale.createInstance(__dirname + '/locales', '.yaml'); locale.setLanguage(settings.language); setTimeout(function() { console.log(locale.languages); }, 100);
Use the new locale handler
Use the new locale handler
JavaScript
mpl-2.0
gluxon/wolf.js
--- +++ @@ -1,8 +1,9 @@ var irc = require('irc'); // IRC Client require('js-yaml'); // JavaScript YAML parser (for settings) -// Import settings file -var settings = require('./config/bot.yaml'); +// Gr__dirnameab configuration files +var settings = require(__dirname + '/config/bot.yaml'); +var werewolf = require(__dirname + '/config/werewolf.yaml'); var client = new irc.Client(settings.server, settings.nick, { userName: settings.username, @@ -20,3 +21,13 @@ message.command + ' ' + message.args.join(' :') ); } }); + +// The Locale handler +var Locale = require(__dirname + '/components/locale.js'); + +var locale = Locale.createInstance(__dirname + '/locales', '.yaml'); +locale.setLanguage(settings.language); + +setTimeout(function() { + console.log(locale.languages); +}, 100);
b1030675d9b6432dfaf2bd76b395c28491bc32a8
src/main/server/Stats.js
src/main/server/Stats.js
import bunyan from 'bunyan'; import Promise from 'bluebird'; import SDC from 'statsd-client'; const logger = bunyan.createLogger({name: 'Stats'}); export default class Stats { constructor(config) { const stats = config.statsd; logger.info('Starting StatsD client.'); this._statsd = new SDC({ host: stats.host }); } /** * Get the underlying stats client. * You should not rely on the type of this, only that it can be used * as a middleware for express. **/ get client() { return this._statsd; } close() { this._statsd.close(); } counter(name, value = 1) { logger.info('Updating counter %s by %s.', name, value); this._statsd.counter(name, value); } gauge(name, value) { logger.info('Gauging %s at %s.', name, value); this._statsd.gauge(name, value); } }
import bunyan from 'bunyan'; import Promise from 'bluebird'; import SDC from 'statsd-client'; const logger = bunyan.createLogger({name: 'Stats'}); export default class Stats { constructor(config) { const stats = config.statsd; logger.info('Starting StatsD client.'); this._statsd = new SDC({ host: stats.host }); } /** * Get the underlying stats client. * You should not rely on the type of this, only that it can be used * as a middleware for express. **/ get client() { return this._statsd; } close() { this._statsd.close(); } counter(name, value = 1) { logger.debug('Updating counter %s by %s.', name, value); this._statsd.counter(name, value); } gauge(name, value) { logger.debug('Gauging %s at %s.', name, value); this._statsd.gauge(name, value); } }
Make stats quieter in logs.
Make stats quieter in logs.
JavaScript
mit
ssube/eveningdriver,ssube/eveningdriver
--- +++ @@ -27,12 +27,12 @@ } counter(name, value = 1) { - logger.info('Updating counter %s by %s.', name, value); + logger.debug('Updating counter %s by %s.', name, value); this._statsd.counter(name, value); } gauge(name, value) { - logger.info('Gauging %s at %s.', name, value); + logger.debug('Gauging %s at %s.', name, value); this._statsd.gauge(name, value); } }
b268879770a80c260b68e7a5925f988b713bea09
src/components/FormInput.js
src/components/FormInput.js
import React, { Component } from 'react'; import ReactDOM from 'react-dom'; import { Form, Label, Input } from 'semantic-ui-react'; class FormInput extends Component { componentWillReceiveProps(nextProps) { const { input: { value, onChange }, meta: { visited }, defaultValue } = nextProps; if (!value && !visited && defaultValue) onChange(defaultValue); } render() { const { input, meta: { error, touched }, readOnly, width, label, defaultValue, required, errorPosition, inline, ...rest } = this.props; const hasError = touched && Boolean(error); if (readOnly) { return ( <span className="read-only"> {input && input.value && input.value.toLocaleString()} </span> ); } return ( <Form.Field error={hasError} width={width} required={required} style={{ position: 'relative' }} inline={inline} > {label && <label>{label}</label>} <Input {...input} {...rest} value={input.value || ''} error={hasError} /> {hasError && ( <Label pointing={inline ? 'left' : true}> {error} </Label> )} </Form.Field> ); } } export default FormInput;
import React, { Component } from 'react'; import ReactDOM from 'react-dom'; import { Form, Label, Input } from 'semantic-ui-react'; class FormInput extends Component { componentWillReceiveProps(nextProps) { const { input: { value, onChange }, meta: { visited }, defaultValue } = nextProps; if (!value && !visited && defaultValue) onChange(defaultValue); } render() { const { input, meta: { error, touched }, readOnly, width, label, defaultValue, required, inline, errorMessageStyle, ...rest } = this.props; const hasError = touched && Boolean(error); if (readOnly) { return ( <span className="read-only"> {input && input.value && input.value.toLocaleString()} </span> ); } return ( <Form.Field error={hasError} width={width} required={required} inline={inline} > {label && <label>{label}</label>} <Input {...input} {...rest} value={input.value || ''} error={hasError} /> {hasError && ( <Label className="error-message" pointing={inline ? 'left' : true} style={errorMessageStyle}> {error} </Label> )} </Form.Field> ); } } export default FormInput;
Add ability to customize error message styles
Add ability to customize error message styles
JavaScript
mit
mariusespejo/semantic-redux-form-fields
--- +++ @@ -21,8 +21,8 @@ label, defaultValue, required, - errorPosition, inline, + errorMessageStyle, ...rest } = this.props; @@ -41,7 +41,6 @@ error={hasError} width={width} required={required} - style={{ position: 'relative' }} inline={inline} > {label && <label>{label}</label>} @@ -53,7 +52,7 @@ /> {hasError && ( - <Label pointing={inline ? 'left' : true}> + <Label className="error-message" pointing={inline ? 'left' : true} style={errorMessageStyle}> {error} </Label> )}
e3a8c773cc63a8263f8fe9bb98be8326671bbdcc
src/components/posts_new.js
src/components/posts_new.js
import React from 'react'; class PostsNew extends React.Component { render() { return ( <div className='posts-new'> Posts new </div> ); } } export default PostsNew;
import React from 'react'; import { Field, reduxForm } from 'redux-form'; class PostsNew extends React.Component { render() { return ( <form className='posts-new'> <Field name='title' component={} /> </form> ); } } export default reduxForm({ form: 'PostsNewForm' })(PostsNew);
Add initial posts new form elements
Add initial posts new form elements
JavaScript
mit
monsteronfire/redux-learning-blog,monsteronfire/redux-learning-blog
--- +++ @@ -1,13 +1,19 @@ import React from 'react'; +import { Field, reduxForm } from 'redux-form'; class PostsNew extends React.Component { render() { return ( - <div className='posts-new'> - Posts new - </div> + <form className='posts-new'> + <Field + name='title' + component={} + /> + </form> ); } } -export default PostsNew; +export default reduxForm({ + form: 'PostsNewForm' +})(PostsNew);
6874f190611009228ea9d6901fcdd6b951c66198
tests/unit/tooltip/tooltip_common.js
tests/unit/tooltip/tooltip_common.js
TestHelpers.commonWidgetTests( "tooltip", { defaults: { content: function() {}, disabled: false, hide: true, items: "[title]:not([disabled])", position: { my: "left top+15", at: "left bottom", collision: "flipfit flipfit" }, show: true, tooltipClass: null, track: false, // callbacks close: null, create: null, open: null } });
TestHelpers.commonWidgetTests( "tooltip", { defaults: { content: function() {}, disabled: false, hide: true, items: "[title]:not([disabled])", position: { my: "left top+15", at: "left bottom", collision: "flipfit flip" }, show: true, tooltipClass: null, track: false, // callbacks close: null, create: null, open: null } });
Fix default for position option, follow-up to 1d9eab1.
Tooltip: Fix default for position option, follow-up to 1d9eab1.
JavaScript
mit
GrayYoung/jQuery.UI.Extension,GrayYoung/jQuery.UI.Extension
--- +++ @@ -7,7 +7,7 @@ position: { my: "left top+15", at: "left bottom", - collision: "flipfit flipfit" + collision: "flipfit flip" }, show: true, tooltipClass: null,
4fce90c61e7b0c363261866d4d47268403c634ba
lib/models/relatedResource.js
lib/models/relatedResource.js
var mongoose = require('mongoose'); var Schema = mongoose.Schema; var ObjectId = Schema.Types.ObjectId; var ORIGIN_TYPES = [ 'srv:coupledResource', 'gmd:onLine' ]; var RESOURCE_TYPES = [ 'feature-type', 'link', 'atom-feed' ]; var RelatedResourceSchema = new Schema({ type: { type: String, required: true, index: true, enum: RESOURCE_TYPES }, updatedAt: { type: Date, required: true, index: true }, // touchedAt: { type: Date, required: true }, name: { type: String }, /* Origin */ originType: { type: String, enum: ORIGIN_TYPES, required: true, index: true }, originId: { type: ObjectId, required: true, index: true }, originCatalog: { type: ObjectId, ref: 'Service', index: true, sparse: true }, /* Record */ record: { type: String, required: true, index: true }, /* FeatureType */ featureType: { candidateName: { type: String }, candidateLocation: { type: String }, matchingName: { type: String, index: true, sparse: true }, matchingService: { type: ObjectId, index: true, sparse: true } } /* */ }); mongoose.model('RelatedResource', RelatedResourceSchema);
var mongoose = require('mongoose'); var Schema = mongoose.Schema; var ObjectId = Schema.Types.ObjectId; var ORIGIN_TYPES = [ 'srv:coupledResource', 'gmd:onLine' ]; var RESOURCE_TYPES = [ 'feature-type', 'link', 'atom-feed' ]; var RelatedResourceSchema = new Schema({ type: { type: String, required: true, index: true, enum: RESOURCE_TYPES }, updatedAt: { type: Date, required: true, index: true }, checking: { type: Boolean, index: true, sparse: true }, name: { type: String }, /* Origin */ originType: { type: String, enum: ORIGIN_TYPES, required: true, index: true }, originId: { type: ObjectId, required: true, index: true }, originCatalog: { type: ObjectId, ref: 'Service', index: true, sparse: true }, /* Record */ record: { type: String, required: true, index: true }, /* FeatureType */ featureType: { candidateName: { type: String }, candidateLocation: { type: String }, matchingName: { type: String, index: true, sparse: true }, matchingService: { type: ObjectId, index: true, sparse: true } } }); /* ** Statics */ RelatedResourceSchema.statics = { markAsChecking: function (query, done) { this.update(query, { $set: { checking: true } }, { multi: true }, done); } }; mongoose.model('RelatedResource', RelatedResourceSchema);
Add checking flag to RelatedResource model
Add checking flag to RelatedResource model
JavaScript
agpl-3.0
jdesboeufs/geogw,inspireteam/geogw
--- +++ @@ -19,7 +19,7 @@ type: { type: String, required: true, index: true, enum: RESOURCE_TYPES }, updatedAt: { type: Date, required: true, index: true }, - // touchedAt: { type: Date, required: true }, + checking: { type: Boolean, index: true, sparse: true }, name: { type: String }, @@ -39,7 +39,19 @@ matchingService: { type: ObjectId, index: true, sparse: true } } - /* */ }); + +/* +** Statics +*/ +RelatedResourceSchema.statics = { + + markAsChecking: function (query, done) { + this.update(query, { $set: { checking: true } }, { multi: true }, done); + } + +}; + + mongoose.model('RelatedResource', RelatedResourceSchema);
20f511a5e77972396b3ba9496283900bcbb6cbf6
webpack.common.js
webpack.common.js
var path = require('path'); module.exports = { /** * Path from which all relative webpack paths will be resolved. */ context: path.resolve(__dirname), /** * Entry point to the application, webpack will bundle all imported modules. */ entry: './src/index.ts', /** * Rule for which files should be transpiled via typescript loader. */ module: { rules: [ { test: /\.ts$/, use: [{ loader: 'ts-loader' }] } ] }, resolve: { /** * Resolve the following extensions when requiring/importing modules. */ extensions: ['.ts', '.js'] }, /** * Specify output as an UMD library. */ output: { path: 'build/dist', filename: 'baasic-sdk-javascript.js', library: 'baasicSdkJavaScript', libraryTarget: 'umd' } }
var path = require('path'); var rootDir = path.resolve(__dirname); function getRootPath(args) { args = Array.prototype.slice.call(arguments, 0); return path.join.apply(path, [rootDir].concat(args)); } module.exports = { /** * Path from which all relative webpack paths will be resolved. */ context: path.resolve(__dirname), /** * Entry point to the application, webpack will bundle all imported modules. */ entry: './src/index.ts', /** * Rule for which files should be transpiled via typescript loader. */ module: { rules: [ { test: /\.ts$/, use: [{ loader: 'ts-loader' }] } ] }, resolve: { /** * Resolve the following extensions when requiring/importing modules. */ extensions: ['.ts', '.js'], /** * Resolve modules using following folders. */ modules: [getRootPath('src'), getRootPath('node_modules')] }, /** * Specify output as an UMD library. */ output: { path: 'build/dist', filename: 'baasic-sdk-javascript.js', library: 'baasicSdkJavaScript', libraryTarget: 'umd' } }
Add module loading from src to webpack configuration.
Add module loading from src to webpack configuration.
JavaScript
mit
Baasic/baasic-sdk-javascript,Baasic/baasic-sdk-javascript
--- +++ @@ -1,4 +1,10 @@ var path = require('path'); +var rootDir = path.resolve(__dirname); + +function getRootPath(args) { + args = Array.prototype.slice.call(arguments, 0); + return path.join.apply(path, [rootDir].concat(args)); +} module.exports = { /** @@ -26,7 +32,11 @@ /** * Resolve the following extensions when requiring/importing modules. */ - extensions: ['.ts', '.js'] + extensions: ['.ts', '.js'], + /** + * Resolve modules using following folders. + */ + modules: [getRootPath('src'), getRootPath('node_modules')] }, /** * Specify output as an UMD library.
b8a2c85d3191879b74520499dbe768ddf487adc0
src/frontend/container/Resources/SwitchResource.js
src/frontend/container/Resources/SwitchResource.js
import React from 'react'; import PropTypes from 'prop-types'; import * as action from '../../action/'; import Switch from '@material-ui/core/Switch'; import Typography from '@material-ui/core/Typography'; import { connect } from 'react-redux'; class SwitchResource extends React.Component { handleChange = (field, value) => { if (this.props.isWriteable === true) { this.props.toggleSwitch(this.props.objectID, this.props.instanceID, this.props.resource.resourceID, value); } }; render () { return ( <div> <Typography variant='subheading' align='center'>{this.props.resource.name}</Typography> <Switch checked={this.props.currentValue} onChange={this.handleChange.bind(this, 'switch')} /> </div> ); } } SwitchResource.propTypes = { currentValue: PropTypes.any, instanceID: PropTypes.number, isWriteable: PropTypes.bool, objectID: PropTypes.number, resource: PropTypes.object, toggleSwitch: PropTypes.func.isRequired }; const mapStateToProps = (state) => { return { }; }; const mapDispatchToProps = (dispatch) => { return { toggleSwitch: (objectID, instanceID, resourceID, value) => dispatch(action.sendRequest(objectID, instanceID, resourceID, value)) }; }; export default connect(mapStateToProps, mapDispatchToProps)(SwitchResource);
import React from 'react'; import PropTypes from 'prop-types'; import * as action from '../../action/'; import Switch from '@material-ui/core/Switch'; import Typography from '@material-ui/core/Typography'; import { connect } from 'react-redux'; class SwitchResource extends React.Component { handleChange = (field, value) => { if (this.props.isWriteable === true) { this.props.toggleSwitch(this.props.objectID, this.props.instanceID, this.props.resource.resourceID, this.props.currentValue); } }; render () { return ( <div> <Typography variant='subheading' align='center'>{this.props.resource.name}</Typography> <Switch checked={this.props.currentValue} onChange={this.handleChange.bind(this, 'switch')} /> </div> ); } } SwitchResource.propTypes = { currentValue: PropTypes.any, instanceID: PropTypes.number, isWriteable: PropTypes.bool, objectID: PropTypes.number, resource: PropTypes.object, toggleSwitch: PropTypes.func.isRequired }; const mapStateToProps = (state) => { return { }; }; const mapDispatchToProps = (dispatch) => { return { toggleSwitch: (objectID, instanceID, resourceID, value) => dispatch(action.sendRequest(objectID, instanceID, resourceID, !value)) }; }; export default connect(mapStateToProps, mapDispatchToProps)(SwitchResource);
Fix bug with unresponsive switch due to new framework
Fix bug with unresponsive switch due to new framework
JavaScript
apache-2.0
doemski/cblocks,doemski/cblocks
--- +++ @@ -9,7 +9,7 @@ handleChange = (field, value) => { if (this.props.isWriteable === true) { - this.props.toggleSwitch(this.props.objectID, this.props.instanceID, this.props.resource.resourceID, value); + this.props.toggleSwitch(this.props.objectID, this.props.instanceID, this.props.resource.resourceID, this.props.currentValue); } }; @@ -42,7 +42,7 @@ const mapDispatchToProps = (dispatch) => { return { - toggleSwitch: (objectID, instanceID, resourceID, value) => dispatch(action.sendRequest(objectID, instanceID, resourceID, value)) + toggleSwitch: (objectID, instanceID, resourceID, value) => dispatch(action.sendRequest(objectID, instanceID, resourceID, !value)) }; };
06b3319ea0b7add2e69eecc473927034521bd7e5
lib/languages/rust.js
lib/languages/rust.js
var DocsParser = require("../docsparser"); var xregexp = require('../xregexp').XRegExp; function RustParser(settings) { DocsParser.call(this, settings); } RustParser.prototype = Object.create(DocsParser.prototype); RustParser.prototype.setup_settings = function() { this.settings = { 'curlyTypes': false, 'typeInfo': false, 'typeTag': false, 'varIdentifier': '.*', 'fnIdentifier': '.*', 'fnOpener': '^\\s*fn', 'commentCloser': ' */', 'bool': 'Boolean', 'function': 'Function' }; }; RustParser.prototype.parse_function = function(line) { var regex = xregexp('\\s*fn\\s+(?P<name>\\S+)'); var matches = xregexp.exec(line, regex); if(matches === null) return null; var name = matches.name || ''; return [ name, []]; }; RustParser.prototype.parse_var = function(line) { return null; }; RustParser.prototype.format_function = function(name, args) { return name; }; module.exports = RustParser;
var DocsParser = require("../docsparser"); var xregexp = require('../xregexp').XRegExp; function RustParser(settings) { DocsParser.call(this, settings); } RustParser.prototype = Object.create(DocsParser.prototype); RustParser.prototype.setup_settings = function() { this.settings = { 'curlyTypes': false, 'typeInfo': false, 'typeTag': false, 'varIdentifier': '.*', 'fnIdentifier': '[a-zA-Z_][a-zA-Z_0-9]*', 'fnOpener': '^\\s*fn', 'commentCloser': ' */', 'bool': 'Boolean', 'function': 'Function' }; }; RustParser.prototype.parse_function = function(line) { // TODO: add regexp for closures syntax // TODO: parse params var regex = xregexp('\\s*fn\\s+(?P<name>' + this.settings.fnIdentifier + ')'); var matches = xregexp.exec(line, regex); if(matches === null || matches.name === undefined) { return null; } var name = matches.name; return [name, null]; }; RustParser.prototype.parse_var = function(line) { return null; }; RustParser.prototype.format_function = function(name, args) { return name; }; module.exports = RustParser;
Improve Rust function parser (Use correct identifier)
Improve Rust function parser (Use correct identifier)
JavaScript
mit
NikhilKalige/docblockr
--- +++ @@ -13,7 +13,7 @@ 'typeInfo': false, 'typeTag': false, 'varIdentifier': '.*', - 'fnIdentifier': '.*', + 'fnIdentifier': '[a-zA-Z_][a-zA-Z_0-9]*', 'fnOpener': '^\\s*fn', 'commentCloser': ' */', 'bool': 'Boolean', @@ -22,12 +22,16 @@ }; RustParser.prototype.parse_function = function(line) { - var regex = xregexp('\\s*fn\\s+(?P<name>\\S+)'); + // TODO: add regexp for closures syntax + // TODO: parse params + var regex = xregexp('\\s*fn\\s+(?P<name>' + this.settings.fnIdentifier + ')'); + var matches = xregexp.exec(line, regex); - if(matches === null) + if(matches === null || matches.name === undefined) { return null; - var name = matches.name || ''; - return [ name, []]; + } + var name = matches.name; + return [name, null]; }; RustParser.prototype.parse_var = function(line) {
8c7a1ff64829876ee7d3815a7dd2bc32c6d7ec44
lib/testExecutions.js
lib/testExecutions.js
"use strict"; const file = require("./file"); module.exports = function testExecutions(data, formatForSonar56 = false) { const aTestExecution = [{ _attr: { version: "1" } }]; const testResults = data.testResults.map(file); return formatForSonar56 ? { unitTest: aTestExecution.concat(testResults) } : { testExecutions: aTestExecution.concat(testResults) }; };
'use strict' const file = require('./file') module.exports = function testExecutions(data, formatForSonar56 = false) { const aTestExecution = [{_attr: {version: '1'}}] const testResults = data.testResults.map(file) return formatForSonar56 ? { unitTest: aTestExecution.concat(testResults) } : { testExecutions: aTestExecution.concat(testResults) }; };
Undo changes done by prettier
Undo changes done by prettier old habbits die hard! Ran the prettier on Atom on the whole file, this commit undoes it.
JavaScript
mit
3dmind/jest-sonar-reporter,3dmind/jest-sonar-reporter
--- +++ @@ -1,10 +1,10 @@ -"use strict"; +'use strict' -const file = require("./file"); +const file = require('./file') module.exports = function testExecutions(data, formatForSonar56 = false) { - const aTestExecution = [{ _attr: { version: "1" } }]; - const testResults = data.testResults.map(file); + const aTestExecution = [{_attr: {version: '1'}}] + const testResults = data.testResults.map(file) return formatForSonar56 ? { unitTest: aTestExecution.concat(testResults) }
fe71f0ef2c920712e3b33f5002a18ab87ff52544
src/index.js
src/index.js
export function onConnect(respond, connections = {}, tab, error) { chrome.runtime.onConnect.addListener(function(port) { function extensionListener(message) { if (message.name === 'init') { connections[message.tabId] = port; if (tab && message.tabId !== tab.id) { error(port); return; } connections[message.tabId].postMessage(respond()); } } port.onMessage.addListener(extensionListener); port.onDisconnect.addListener(function(portDiscon) { portDiscon.onMessage.removeListener(extensionListener); Object.keys(connections).forEach(function(id) { if (connections[id] === portDiscon) { delete connections[id]; } }); }); }); } export const connect = chrome.runtime.connect; export function onMessage(messaging) { if (chrome.runtime.onMessage) chrome.runtime.onMessage.addListener(messaging); } export const sendToBg = chrome.runtime.sendMessage; export function sendToTab(...args) { chrome.tabs.sendMessage(...args); }
export function onConnect(respond, connections = {}, tab, error) { chrome.runtime.onConnect.addListener(function(port) { function extensionListener(message) { if (message.name === 'init') { connections[message.tabId || port.sender.tab.id] = port; if (tab && message.tabId !== tab.id) { error(port); return; } port.postMessage(respond()); } } port.onMessage.addListener(extensionListener); port.onDisconnect.addListener(function(portDiscon) { portDiscon.onMessage.removeListener(extensionListener); Object.keys(connections).forEach(function(id) { if (connections[id] === portDiscon) { delete connections[id]; } }); }); }); } export const connect = chrome.runtime.connect; export function onMessage(messaging) { if (chrome.runtime.onMessage) chrome.runtime.onMessage.addListener(messaging); } export const sendToBg = chrome.runtime.sendMessage; export function sendToTab(...args) { chrome.tabs.sendMessage(...args); }
Allow not to specify sender tab id. Detect it implicitly
Allow not to specify sender tab id. Detect it implicitly
JavaScript
mit
zalmoxisus/crossmessaging
--- +++ @@ -2,13 +2,13 @@ chrome.runtime.onConnect.addListener(function(port) { function extensionListener(message) { if (message.name === 'init') { - connections[message.tabId] = port; + connections[message.tabId || port.sender.tab.id] = port; if (tab && message.tabId !== tab.id) { error(port); return; } - connections[message.tabId].postMessage(respond()); + port.postMessage(respond()); } }
e2925bec159f6fc40317b40b3036cd669a23ddfb
app/Artist.js
app/Artist.js
const https = require("https"); const fs = require("fs"); module.exports = class Artist { constructor(artistObject) { this.id = artistObject.id; this.name = artistObject.name; this.tracks = []; this.artistObject = artistObject; this.artId = artistObject.picture; } async updateTracks(tidalApi) { this.tracks = await tidalApi.getArtistTopTracks(this); } updateArt(tidalApi) { return new Promise((resolve, reject) => { this.mkdirSync("/tmp/tidal-cli-client"); this.artURL = tidalApi.getArtURL(this.artId, 750, 750); this.artSrc = "/tmp/tidal-cli-client/" + this.artId + ".jpg"; let artFile = fs.createWriteStream(this.artSrc); https.get(this.artURL, response => { response.pipe(artFile); resolve(); }); }); } mkdirSync(dirPath) { try { fs.mkdirSync(dirPath) } catch (err) { if (err.code !== "EXIST") throw err; } } };
const https = require("https"); const fs = require("fs"); module.exports = class Artist { constructor(artistObject) { this.id = artistObject.id; this.name = artistObject.name; this.tracks = []; this.artistObject = artistObject; this.artId = artistObject.picture; } async updateTracks(tidalApi) { this.tracks = await tidalApi.getArtistTopTracks(this); } updateArt(tidalApi) { return new Promise((resolve, reject) => { this.mkdirSync("/tmp/tidal-cli-client"); this.artURL = tidalApi.getArtURL(this.artId, 750, 750); this.artSrc = "/tmp/tidal-cli-client/" + this.artId + ".jpg"; let artFile = fs.createWriteStream(this.artSrc); https.get(this.artURL, response => { response.pipe(artFile); resolve(); }); }); } mkdirSync(dirPath) { if(!fs.existsSync(dirPath)) { try { fs.mkdirSync(dirPath) } catch (err) { if (err.code !== "EEXIST") throw err; } } } };
Check if directory exists before creating
Check if directory exists before creating
JavaScript
mit
okonek/tidal-cli-client,okonek/tidal-cli-client
--- +++ @@ -28,10 +28,12 @@ } mkdirSync(dirPath) { - try { - fs.mkdirSync(dirPath) - } catch (err) { - if (err.code !== "EXIST") throw err; + if(!fs.existsSync(dirPath)) { + try { + fs.mkdirSync(dirPath) + } catch (err) { + if (err.code !== "EEXIST") throw err; + } } }
128f6c14cc4562a43bd929080691a4c764cb9b8d
gulpfile.js
gulpfile.js
'use strict'; var gulp = require('gulp'); var sass = require('gulp-sass'); gulp.task('compile', function () { return gulp.src('./scss/*.scss') .pipe(gulp.dest('./dist/')); }); gulp.task('watch', function () { gulp.watch('./scss/*.scss', ['compile']); });
'use strict'; var gulp = require('gulp'); var sass = require('gulp-sass'); gulp.task('compile', function () { return gulp.src('./scss/*.scss') .pipe(sass()) .pipe(gulp.dest('./dist/')); }); gulp.task('watch', function () { gulp.watch('./scss/*.scss', ['compile']); });
Add sass compilation back to gulp file, tweaked output
Add sass compilation back to gulp file, tweaked output
JavaScript
mit
MikeBallan/Amazium,aoimedia/Amazium,aoimedia/Amazium,catchamonkey/amazium,OwlyStuff/Amazium,OwlyStuff/Amazium
--- +++ @@ -5,6 +5,7 @@ gulp.task('compile', function () { return gulp.src('./scss/*.scss') + .pipe(sass()) .pipe(gulp.dest('./dist/')); });
13526036cd2f742c1ef744cbd87debdcea70e1ea
gulpfile.js
gulpfile.js
'use strict'; var gulp = require('gulp'); var sass = require('gulp-sass'); var minifycss = require('gulp-minify-css'); var autoprefixer = require('gulp-autoprefixer'); var sourcemaps = require('gulp-sourcemaps'); var paths = { sass: 'wye/static/sass/*.scss', css: 'wye/static/css' }; gulp.task('css', function() { return gulp.src(paths.sass) .pipe(sourcemaps.init()) .pipe(sass() .on('error', sass.logError)) .pipe(autoprefixer({ browsers: ['> 1%'] })) .pipe(minifycss({ debug: true })) .pipe(sourcemaps.write('.')) .pipe(gulp.dest(paths.css)); }); gulp.task('watch', function() { gulp.watch(paths.sass, ['css']); }); gulp.task('default', ['watch']);
'use strict'; var gulp = require('gulp'); var sass = require('gulp-sass'); var minifycss = require('gulp-minify-css'); var autoprefixer = require('gulp-autoprefixer'); var sourcemaps = require('gulp-sourcemaps'); var paths = { sass: 'wye/static/sass/**/*.scss', css: 'wye/static/css' }; gulp.task('css', function() { return gulp.src(paths.sass) .pipe(sourcemaps.init()) .pipe(sass() .on('error', sass.logError)) .pipe(autoprefixer({ browsers: ['> 1%'] })) .pipe(minifycss({ debug: true })) .pipe(sourcemaps.write('.')) .pipe(gulp.dest(paths.css)); }); gulp.task('watch', function() { gulp.watch(paths.sass, ['css']); }); gulp.task('default', ['watch']);
Include all sass dirs to compile
Include all sass dirs to compile
JavaScript
mit
pythonindia/wye,pythonindia/wye,pythonindia/wye,pythonindia/wye
--- +++ @@ -6,7 +6,7 @@ var sourcemaps = require('gulp-sourcemaps'); var paths = { - sass: 'wye/static/sass/*.scss', + sass: 'wye/static/sass/**/*.scss', css: 'wye/static/css' };
0f21e31f84a1fececa6b8220eb2049651630e58e
gulpfile.js
gulpfile.js
var gulp = require('gulp'), gulpCopy = require('gulp-file-copy'); gulp.task('copy', function() { gulp.src('./bower_components/jquery/jquery.min.js') .pipe(gulp.dest('./js/lib/')); gulp.src('./jquery-mobile/jquery.mobile-1.4.5.js') .pipe(gulp.dest('./js/lib/')); gulp.src('./bower_components/moment/min/moment-with-locales.min.js') .pipe(gulp.dest('./js/lib/')); gulp.src('./bower_components/local-storage/src/LocalStorage.js') .pipe(gulp.dest('./js/lib/')); gulp.src('./jquery-mobile/jquery.mobile-1.4.5.css') .pipe(gulp.dest('./css/lib/')); });
var gulp = require('gulp'), gulpCopy = require('gulp-file-copy'); gulp.task('copy', function() { gulp.src('./bower_components/jquery/jquery.min.js') .pipe(gulp.dest('./js/lib/')); gulp.src('./jquery-mobile/jquery.mobile-1.4.5.js') .pipe(gulp.dest('./js/lib/')); gulp.src('./bower_components/moment/min/moment-with-locales.min.js') .pipe(gulp.dest('./js/lib/')); gulp.src('./bower_components/local-storage/src/LocalStorage.js') .pipe(gulp.dest('./js/lib/')); gulp.src('./jquery-mobile/jquery.mobile-1.4.5.css') .pipe(gulp.dest('./css/lib/')); gulp.src('./jquery-mobile/images/ajax-loader.gif') .pipe(gulp.dest('./js/lib/images/')); });
Add copy image in gulp
Add copy image in gulp
JavaScript
mit
jeremy5189/payWhichClient,jeremy5189/payWhichClient
--- +++ @@ -16,4 +16,7 @@ gulp.src('./jquery-mobile/jquery.mobile-1.4.5.css') .pipe(gulp.dest('./css/lib/')); + + gulp.src('./jquery-mobile/images/ajax-loader.gif') + .pipe(gulp.dest('./js/lib/images/')); });
80469cdd650849ad6775f5d0a2bfad6a1cb445db
desktop/app/shared/database/parse.js
desktop/app/shared/database/parse.js
/** * Parse task and return task info if * the task is valid, otherwise throw * error. * @param {string} query Enetered task * @return {object} Task info containing * task text, start time * and dealine */ function parse(query) { /** * Day, week or month coefficient * @type {Object} */ const dwm = { d: 1, '': 1, w: 7, m: 30, }; const regex = /@(\d+)([dwmDWM]?)(\+(\d+)([dwmDWM]?))?\s?(!{0,2})$/; const regexResult = regex.exec(query); const text = query.slice(0, regexResult.index); let start = Date.now(); if (regexResult[3]) { start += 86400000 * regexResult[4] * dwm[regexResult[5]]; } const end = start + (86400000 * regexResult[1] * dwm[regexResult[2]]); const importance = regexResult[6].length + 1; const status = 0; return { text: text.trim(), start, end, importance, status, }; } module.exports = parse;
/** * Parse task and return task info if * the task is valid, otherwise throw * error. * @param {string} query Enetered task * @return {object} Task info containing * task text, start time * and dealine */ function parse(query) { /** * Day, week or month coefficient * @type {Object} */ const dwm = { d: 1, '': 1, w: 7, m: 30, }; const regex = /@(\d+)([dwmDWM]?)(\+(\d+)([dwmDWM]?))?\s?(!{0,2})$/; const regexResult = regex.exec(query); const text = query.slice(0, regexResult.index); let start = Date.now() - ((Date.now() % 86400000) + (new Date().getTimezoneOffset() * 60000)); if (regexResult[3]) { start += 86400000 * regexResult[4] * dwm[regexResult[5]]; } const end = start + (86400000 * regexResult[1] * dwm[regexResult[2]]); const importance = regexResult[6].length + 1; const status = 0; return { text: text.trim(), start, end, importance, status, }; } module.exports = parse;
Move task starting and ending points to start of days
Move task starting and ending points to start of days
JavaScript
mit
mkermani144/wanna,mkermani144/wanna
--- +++ @@ -21,7 +21,7 @@ const regex = /@(\d+)([dwmDWM]?)(\+(\d+)([dwmDWM]?))?\s?(!{0,2})$/; const regexResult = regex.exec(query); const text = query.slice(0, regexResult.index); - let start = Date.now(); + let start = Date.now() - ((Date.now() % 86400000) + (new Date().getTimezoneOffset() * 60000)); if (regexResult[3]) { start += 86400000 * regexResult[4] * dwm[regexResult[5]]; }
f9089bd10a8283fb2cd9f9914c39dc61f5c670fa
tasks/css_flip.js
tasks/css_flip.js
/* * grunt-css-flip * https://github.com/twbs/grunt-css-flip * * Copyright (c) 2014 Chris Rebert * Licensed under the MIT License. */ 'use strict'; var flip = require('css-flip'); module.exports = function(grunt) { grunt.registerMultiTask('cssflip', "Grunt plugin for Twitter's css-flip", function () { var options = this.options({}); this.files.forEach(function (f) { var originalCss = grunt.file.read(f.src); var flippedCss = null; try { flippedCss = flip(originalCss, options); } catch (err) { grunt.fail.warn(err); } grunt.file.write(f.dest, flippedCss); grunt.log.writeln('File "' + f.dest.cyan + '" created.'); }); }); };
/* * grunt-css-flip * https://github.com/twbs/grunt-css-flip * * Copyright (c) 2014 Chris Rebert * Licensed under the MIT License. */ 'use strict'; var flip = require('css-flip'); module.exports = function (grunt) { grunt.registerMultiTask('cssflip', "Grunt plugin for Twitter's css-flip", function () { var options = this.options({}); this.files.forEach(function (f) { var originalCss = grunt.file.read(f.src); var flippedCss = null; try { flippedCss = flip(originalCss, options); } catch (err) { grunt.fail.warn(err); } grunt.file.write(f.dest, flippedCss); grunt.log.writeln('File "' + f.dest.cyan + '" created.'); }); }); };
Add missing space before paren
Add missing space before paren
JavaScript
mit
twbs/grunt-css-flip
--- +++ @@ -11,7 +11,7 @@ var flip = require('css-flip'); -module.exports = function(grunt) { +module.exports = function (grunt) { grunt.registerMultiTask('cssflip', "Grunt plugin for Twitter's css-flip", function () { var options = this.options({});
286b7f561655fdf75e0fe53d888d95082605ef3f
src/index.js
src/index.js
export default function({ types }) { return { visitor: { Function: function parseFunctionPath(path) { (path.get('params') || []).reverse().forEach(function(param) { const decorators = param.node.decorators.reverse(); if (param.node && Array.isArray(decorators)) { let currentDecorator; decorators.forEach(function(decorator) { /** * TODO: Validate the name of the decorator is not * the same as any of the passed params */ const callNode = types.callExpression( decorator.expression, [ currentDecorator || types.Identifier(`_${param.node.name}`) ] ); currentDecorator = callNode; }); param.parentPath.get('body').unshiftContainer( 'body', types.variableDeclaration('var', [ types.variableDeclarator( types.Identifier(param.node.name), currentDecorator ) ]) ); param.replaceWith( types.Identifier(`_${param.node.name}`) ); } }); } } }; }
export default function({ types }) { return { visitor: { Function: function parseFunctionPath(path) { (path.get('params') || []).reverse().forEach(function(param) { let currentDecorator; (param.node.decorators || []).reverse() .forEach(function(decorator) { /** * TODO: Validate the name of the decorator is not * the same as any of the passed params */ currentDecorator = types.callExpression( decorator.expression, [ currentDecorator || types.Identifier(`_${param.node.name}`) ] ); }); param.parentPath.get('body').unshiftContainer( 'body', types.variableDeclaration('var', [ types.variableDeclarator( types.Identifier(param.node.name), currentDecorator ) ]) ); param.replaceWith( types.Identifier(`_${param.node.name}`) ); }); } } }; }
Fix issue with the existence of the decorators array introduced by syntax changes
Fix issue with the existence of the decorators array introduced by syntax changes
JavaScript
mit
benderTheCrime/babel-plugin-transform-function-parameter-decorators
--- +++ @@ -3,40 +3,35 @@ visitor: { Function: function parseFunctionPath(path) { (path.get('params') || []).reverse().forEach(function(param) { - const decorators = param.node.decorators.reverse(); + let currentDecorator; - if (param.node && Array.isArray(decorators)) { - let currentDecorator; - - decorators.forEach(function(decorator) { + (param.node.decorators || []).reverse() + .forEach(function(decorator) { /** * TODO: Validate the name of the decorator is not * the same as any of the passed params */ - const callNode = types.callExpression( + currentDecorator = types.callExpression( decorator.expression, [ currentDecorator || types.Identifier(`_${param.node.name}`) ] ); - - currentDecorator = callNode; }); - param.parentPath.get('body').unshiftContainer( - 'body', types.variableDeclaration('var', [ - types.variableDeclarator( - types.Identifier(param.node.name), - currentDecorator - ) - ]) - ); + param.parentPath.get('body').unshiftContainer( + 'body', types.variableDeclaration('var', [ + types.variableDeclarator( + types.Identifier(param.node.name), + currentDecorator + ) + ]) + ); - param.replaceWith( - types.Identifier(`_${param.node.name}`) - ); - } + param.replaceWith( + types.Identifier(`_${param.node.name}`) + ); }); } }
45263d5abdd81c9ce15c52835d98b4998ccbe337
src/index.js
src/index.js
import Promise from 'bluebird'; import process from 'process'; import util from 'util'; import { withRetries } from 'killrvideo-nodejs-common'; import { Scheduler } from './scheduler'; import * as availableTasks from './tasks'; import { initCassandraAsync } from './utils/cassandra'; import { initializeSampleDataAsync } from './sample-data/initialize'; // Allow promise cancellation Promise.config({ cancellation: true }); /** * Async start the application. */ async function startAsync() { let scheduler = null; try { // Make sure C* is ready to go await withRetries(initCassandraAsync, 10, 10, 'Could not initialize Cassandra keyspace', false); // Initialize sample data await initializeSampleDataAsync(); // Start scheduled tasks scheduler = new Scheduler(availableTasks); scheduler.start(); return scheduler; } catch (err) { if (scheduler !== null) scheduler.stop(); console.error('Unable to start Sample Data Generator'); console.error(err); process.exitCode = 1; } } // Start the app let startPromise = startAsync(); // Handler for attempting to gracefully shutdown function onStop() { console.log('Attempting to shutdown'); if (startPromise.isFulfilled()) { let s = startPromise.value(); s.stop(); } else { startPromise.cancel(); } process.exit(0); } // Attempt to shutdown on SIGINT process.on('SIGINT', onStop);
import Promise from 'bluebird'; import process from 'process'; import util from 'util'; import { withRetries } from 'killrvideo-nodejs-common'; import { Scheduler } from './scheduler'; import * as availableTasks from './tasks'; import { initCassandraAsync } from './utils/cassandra'; import { initializeSampleDataAsync } from './sample-data/initialize'; // Allow promise cancellation Promise.config({ cancellation: true }); /** * Async start the application. */ async function startAsync() { let scheduler = null; try { // Make sure C* is ready to go await withRetries(initCassandraAsync, 10, 10, 'Could not initialize Cassandra keyspace', false); // Initialize sample data await initializeSampleDataAsync(); // Start scheduled tasks scheduler = new Scheduler(availableTasks); scheduler.start(); return scheduler; } catch (err) { if (scheduler !== null) scheduler.stop(); console.error('Unable to start Sample Data Generator'); console.error(err); process.exit(1); } } // Start the app let startPromise = startAsync(); // Handler for attempting to gracefully shutdown function onStop() { console.log('Attempting to shutdown'); if (startPromise.isFulfilled()) { let s = startPromise.value(); s.stop(); } else { startPromise.cancel(); } process.exit(0); } // Attempt to shutdown on SIGINT process.on('SIGINT', onStop);
Make sure we actually exit when we fail on startup
Make sure we actually exit when we fail on startup
JavaScript
apache-2.0
KillrVideo/killrvideo-generator,KillrVideo/killrvideo-generator
--- +++ @@ -32,7 +32,7 @@ console.error('Unable to start Sample Data Generator'); console.error(err); - process.exitCode = 1; + process.exit(1); } }
11086bca7cb8b43fb099e70ab70fc548bcba9683
src/index.js
src/index.js
/** * @copyright 2015, Prometheus Research, LLC */ import {createValue} from './Value'; export Fieldset from './Fieldset'; export Field from './Field'; export {createValue}; export WithFormValue from './WithFormValue'; export * as Schema from './Schema'; export Input from './Input'; export ErrorList from './ErrorList'; export function Value(schema, value, onChange, params, errorList) { console.error("`import {Value} from 'react-forms'` is deprecated, \ change it to 'import {createvalue} from `'react-forms'`"); return createValue({schema, value, onChange, params, errorList}); }
/** * @copyright 2015, Prometheus Research, LLC */ import {createValue} from './Value'; export Fieldset from './Fieldset'; export Field from './Field'; export {createValue}; export WithFormValue from './WithFormValue'; export * as Schema from './Schema'; export Input from './Input'; export ErrorList from './ErrorList'; export function Value(schema, value, onChange, params, errorList) { console.error("`import {Value} from 'react-forms'` is deprecated, \ change it to 'import {createValue} from `'react-forms'`"); return createValue({schema, value, onChange, params, errorList}); }
Fix typo: createvalue -> createValue
Fix typo: createvalue -> createValue
JavaScript
mit
prometheusresearch/react-forms
--- +++ @@ -14,6 +14,6 @@ export function Value(schema, value, onChange, params, errorList) { console.error("`import {Value} from 'react-forms'` is deprecated, \ - change it to 'import {createvalue} from `'react-forms'`"); + change it to 'import {createValue} from `'react-forms'`"); return createValue({schema, value, onChange, params, errorList}); }
b394877b0b152d43656c5dfc18e667111273668e
src/utils.js
src/utils.js
/** * Create a copy of an object, omitting provided keys. * @param {Object} obj Object to copy * @param {Array} arr Keys to omit * @returns {Object} */ export const omit = (obj, arr) => Object.keys(obj).reduce((res, key) => { if (arr.indexOf(key) === -1) { res[key] = obj[key] } return res }, {}) export const getQueryStringValue = (key) => { return decodeURIComponent(window.location.search.replace(new RegExp('^(?:.*[&\\?]' + encodeURIComponent(key).replace(/[.+*]/g, '\\$&') + '(?:\\=([^&]*))?)?.*$', 'i'), '$1')) } /** * Get key value from location hash * @param {string} key Key to get value from * @returns {string|null} */ export const getHashValue = (key) => { const matches = window.location.hash.match(new RegExp(`${key}=([^&]*)`)) return matches ? matches[1] : null }
/** * Create a copy of an object, omitting provided keys. * @param {Object} obj Object to copy * @param {Array} arr Keys to omit * @returns {Object} */ export const omit = (obj, arr) => Object.keys(obj).reduce((res, key) => { if (arr.indexOf(key) === -1) { res[key] = obj[key] } return res }, {}) /** * Get key value from url query strings * @param {string} key Key to get value from * @returns {string} */ export const getQueryStringValue = (key) => { return decodeURIComponent(window.location.search.replace(new RegExp('^(?:.*[&\\?]' + encodeURIComponent(key).replace(/[.+*]/g, '\\$&') + '(?:\\=([^&]*))?)?.*$', 'i'), '$1')) } /** * Get key value from location hash * @param {string} key Key to get value from * @returns {string|null} */ export const getHashValue = (key) => { const matches = window.location.hash.match(new RegExp(`${key}=([^&]*)`)) return matches ? matches[1] : null } export const responseTextToObject = (text, key) => { const keyValuePairs = text.split('&') if (!keyValuePairs || keyValuePairs.length === 0) { return {} } return keyValuePairs.reduce((result, pair) => { const [key, value] = pair.split('=') result[key] = decodeURIComponent(value) return result }, {}) }
Add util to parse response from GitHub access token request
Add util to parse response from GitHub access token request
JavaScript
mit
nicolas-goudry/react-social-login,deepakaggarwal7/react-social-login,deepakaggarwal7/react-social-login,nicolas-goudry/react-social-login,deepakaggarwal7/react-social-login,nicolas-goudry/react-social-login
--- +++ @@ -12,6 +12,11 @@ return res }, {}) +/** + * Get key value from url query strings + * @param {string} key Key to get value from + * @returns {string} + */ export const getQueryStringValue = (key) => { return decodeURIComponent(window.location.search.replace(new RegExp('^(?:.*[&\\?]' + encodeURIComponent(key).replace(/[.+*]/g, '\\$&') + '(?:\\=([^&]*))?)?.*$', 'i'), '$1')) } @@ -26,3 +31,19 @@ return matches ? matches[1] : null } + +export const responseTextToObject = (text, key) => { + const keyValuePairs = text.split('&') + + if (!keyValuePairs || keyValuePairs.length === 0) { + return {} + } + + return keyValuePairs.reduce((result, pair) => { + const [key, value] = pair.split('=') + + result[key] = decodeURIComponent(value) + + return result + }, {}) +}
61328d83b9671c066913c301bc4bc449ea427eb7
src/utils.js
src/utils.js
export function getInterfaceLanguage() { if (!!navigator && !!navigator.language) { return navigator.language; } else if (!!navigator && !!navigator.languages && !!navigator.languages[0]) { return navigator.languages[0]; } else if (!!navigator && !!navigator.userLanguage) { return navigator.userLanguage; } else if (!!navigator && !!navigator.browserLanguage) { return navigator.browserLanguage; } return 'en-US'; } export function validateProps(props) { const reservedNames = [ '_interfaceLanguage', '_language', '_defaultLanguage', '_defaultLanguageFirstLevelKeys', '_props', ]; Object.keys(props).forEach(key => { if (reservedNames.indexOf(key)>=0) throw new Error(`${key} cannot be used as a key. It is a reserved word.`) }); }
export function getInterfaceLanguage() { if (!!navigator && !!navigator.language) { return navigator.language; } else if (!!navigator && !!navigator.languages && !!navigator.languages[0]) { return navigator.languages[0]; } else if (!!navigator && !!navigator.userLanguage) { return navigator.userLanguage; } else if (!!navigator && !!navigator.browserLanguage) { return navigator.browserLanguage; } return 'en-US'; } export function validateProps(props) { const reservedNames = [ '_interfaceLanguage', '_language', '_defaultLanguage', '_defaultLanguageFirstLevelKeys', '_props', ]; Object.keys(props).forEach(key => { if (reservedNames.includes(key)) throw new Error(`${key} cannot be used as a key. It is a reserved word.`) }); }
Use includes to make code simplier
Use includes to make code simplier
JavaScript
mit
stefalda/react-localization
--- +++ @@ -20,6 +20,6 @@ '_props', ]; Object.keys(props).forEach(key => { - if (reservedNames.indexOf(key)>=0) throw new Error(`${key} cannot be used as a key. It is a reserved word.`) + if (reservedNames.includes(key)) throw new Error(`${key} cannot be used as a key. It is a reserved word.`) }); }
b44c58ba61808077ae22d1e4e3030d0aeb84c97a
face-read.js
face-read.js
'use strict'; var fs = require('fs'); /* * read *.<type> files at given `path', * return array of files and their * textual content */ exports.read = function (path, type, callback) { var textFiles = {}; var regex = new RegExp("\\." + type); fs.readdir(path, function (error, files) { if (error) throw new Error("Error reading from path: " + path); for (var file = 0; file < files.length; file++) { if (files[file].match(regex)) { textFiles[files[file] .slice(0, (type.length * -1) - 1 )] = fs.readFileSync(path + '/' + files[file] , 'utf8'); } } if (typeof callback === 'function') { callback(textFiles); } }); }
'use strict'; var fs = require('fs'); /* * read *.<type> files at given `path', * return array of files and their * textual content */ exports.read = function (path, type, callback) { var textFiles = {}; var regex = new RegExp("\\." + type); var typeLen = (type.length * -1) -1; fs.readdir(path, function (error, files) { if (error) throw new Error("Error reading from path: " + path); for (var file = 0; file < files.length; file++) { if (files[file].match(regex)) { // load textFiles with content textFiles[files[file] .slice(0, typeLen] = fs.readFileSync(path + '/' + files[file] , 'utf8'); } } if (typeof callback === 'function') { callback(textFiles); } }); }
Split up assignment logic and add elucidating comment
Split up assignment logic and add elucidating comment This is the first in a line of commit intended to make this module more useable
JavaScript
mit
jm-janzen/EC2-facer,jm-janzen/EC2-facer,jm-janzen/EC2-facer
--- +++ @@ -11,14 +11,16 @@ var textFiles = {}; var regex = new RegExp("\\." + type); + var typeLen = (type.length * -1) -1; fs.readdir(path, function (error, files) { if (error) throw new Error("Error reading from path: " + path); for (var file = 0; file < files.length; file++) { if (files[file].match(regex)) { + // load textFiles with content textFiles[files[file] - .slice(0, (type.length * -1) - 1 )] = fs.readFileSync(path + .slice(0, typeLen] = fs.readFileSync(path + '/' + files[file] , 'utf8');
db859ac95909fe575ffeab45892c67b4f910f6c4
config/_constant.js
config/_constant.js
/** * @author {{{author}}} * @since {{{date}}} */ (function () { 'use strict'; angular .module({{{moduleName}}}) .constant({{{elementName}}}, // Add your values here ); }); })();
/** * @author {{{author}}} * @since {{{date}}} */ (function () { 'use strict'; angular .module('{{{moduleName}}}') .constant('{{{elementName}}}', // Add your values here ); }); })();
Add missing quotes to template
Add missing quotes to template
JavaScript
mit
natete/angular-file-templates,natete/angular-file-templates
--- +++ @@ -7,8 +7,8 @@ 'use strict'; angular - .module({{{moduleName}}}) - .constant({{{elementName}}}, + .module('{{{moduleName}}}') + .constant('{{{elementName}}}', // Add your values here ); });
edc62580aaa114c7b87938a2e275acdef3562981
tests/js/index.js
tests/js/index.js
/*global mocha, mochaPhantomJS, sinon:true, window */ 'use strict'; var $ = require('jquery'), chai = require('chai'), sinon = require('sinon'), sinonChai = require('sinon-chai'), toggles; // Expose jQuery globals window.$ = window.jQuery = $; toggles = require('../../libs/jquery-toggles/toggles.min'); // Load Sinon-Chai chai.use(sinonChai); mocha.timeout(2000); // Expose tools in the global scope window.chai = chai; window.describe = describe; window.expect = chai.expect; window.it = it; window.sinon = sinon; <<<<<<< HEAD ======= require('./tabbedLayoutTest'); require('./ButtonComponentTest.js'); require('./FlashMessageComponentTest.js'); require('./PulsarFormComponentTest.js'); require('./HelpTextComponentTest.js'); require('./PulsarUIComponentTest.js'); // require('./signinTest'); //require('./MasterSwitchComponentTest'); if (typeof mochaPhantomJS !== 'undefined') { mochaPhantomJS.run(); } else { mocha.run(); } >>>>>>> develop
/*global mocha, mochaPhantomJS, sinon:true, window */ 'use strict'; var $ = require('jquery'), chai = require('chai'), sinon = require('sinon'), sinonChai = require('sinon-chai'), toggles; // Expose jQuery globals window.$ = window.jQuery = $; toggles = require('../../libs/jquery-toggles/toggles.min'); // Load Sinon-Chai chai.use(sinonChai); mocha.timeout(2000); // Expose tools in the global scope window.chai = chai; window.describe = describe; window.expect = chai.expect; window.it = it; window.sinon = sinon; require('./tabbedLayoutTest'); require('./ButtonComponentTest.js'); require('./FlashMessageComponentTest.js'); require('./PulsarFormComponentTest.js'); require('./HelpTextComponentTest.js'); require('./PulsarUIComponentTest.js'); if (typeof mochaPhantomJS !== 'undefined') { mochaPhantomJS.run(); } else { mocha.run(); }
Fix merge conflict in js tests
Fix merge conflict in js tests
JavaScript
mit
jadu/pulsar,jadu/pulsar,jadu/pulsar
--- +++ @@ -23,8 +23,6 @@ window.expect = chai.expect; window.it = it; window.sinon = sinon; -<<<<<<< HEAD -======= require('./tabbedLayoutTest'); require('./ButtonComponentTest.js'); @@ -32,12 +30,9 @@ require('./PulsarFormComponentTest.js'); require('./HelpTextComponentTest.js'); require('./PulsarUIComponentTest.js'); -// require('./signinTest'); -//require('./MasterSwitchComponentTest'); if (typeof mochaPhantomJS !== 'undefined') { mochaPhantomJS.run(); } else { mocha.run(); } ->>>>>>> develop
12cfd7069c6513186bffdc073c1fd5264d077754
app/js/arethusa.core/conf_url.js
app/js/arethusa.core/conf_url.js
'use strict'; // Handles params concerning configuration files in the $routeProvider phase angular.module('arethusa.core').factory('confUrl', [ 'CONF_PATH', '$route', function (CONF_PATH, $route) { return function (useDefault) { var params = $route.current.params; var confPath = CONF_PATH + '/'; // Fall back to default and wrong paths to conf files // need to be handled separately eventually if (params.conf) { return confPath + params.conf + '.json'; } else if (params.conf_file) { return params.conf_file; } else { if (useDefault) { return confPath + 'default.json'; } } }; } ]);
'use strict'; // Handles params concerning configuration files in the $routeProvider phase angular.module('arethusa.core').factory('confUrl', [ 'CONF_PATH', '$route', function (CONF_PATH, $route) { // The default route is deprectated and can be refactored away return function (useDefault) { var params = $route.current.params; var confPath = CONF_PATH + '/'; // Fall back to default and wrong paths to conf files // need to be handled separately eventually if (params.conf) { return confPath + params.conf + '.json'; } else if (params.conf_file) { return params.conf_file; } else { if (useDefault) { return confPath + 'default.json'; } } }; } ]);
Add comment about future work in confUrl
Add comment about future work in confUrl
JavaScript
mit
Masoumeh/arethusa,PonteIneptique/arethusa,alpheios-project/arethusa,alpheios-project/arethusa,PonteIneptique/arethusa,Masoumeh/arethusa,latin-language-toolkit/arethusa,fbaumgardt/arethusa,latin-language-toolkit/arethusa,fbaumgardt/arethusa,fbaumgardt/arethusa,alpheios-project/arethusa
--- +++ @@ -4,6 +4,7 @@ 'CONF_PATH', '$route', function (CONF_PATH, $route) { + // The default route is deprectated and can be refactored away return function (useDefault) { var params = $route.current.params; var confPath = CONF_PATH + '/';
1378fbb1df3684e9674a2fb9836d8516b624e7a4
grunt/css.js
grunt/css.js
module.exports = function(grunt) { //grunt-sass grunt.config('sass', { options: { outputStyle: 'expanded', imagePath: '../<%= config.image.dir %>' }, dist: { files: { '<%= config.css.dir %>/<%= config.css.file %>': '<%= config.scss.dir %>/<%= config.scss.file %>' } } }); //grunt-autoprefixer grunt.config('autoprefixer', { options: { browsers: ['> 1%', 'last 2 versions', 'ie 8', 'ie 9', 'ie 10'] }, dist: { files: { '<%= config.css.dir %>/<%= config.css.file %>': '<%= config.css.dir %>/<%= config.css.file %>' } } }); //grunt-contrib-cssmin grunt.config('cssmin', { target: { src: '<%= config.css.dir %>/<%= config.css.file %>', dest: '<%= config.css.dir %>/<%= config.css.file %>' } }); //grunt-contrib-csslint grunt.config('csslint', { options: { csslintrc: 'grunt/.csslintrc' }, strict: { src: ['<%= config.css.dir %>/*.css'] } }); };
module.exports = function(grunt) { //grunt-sass grunt.config('sass', { options: { outputStyle: 'expanded', //includePaths: ['<%= config.scss.includePaths %>'], imagePath: '../<%= config.image.dir %>' }, dist: { files: { '<%= config.css.dir %>/<%= config.css.file %>': '<%= config.scss.dir %>/<%= config.scss.file %>' } } }); //grunt-autoprefixer grunt.config('autoprefixer', { options: { browsers: ['> 1%', 'last 2 versions', 'ie 8', 'ie 9', 'ie 10'] }, dist: { files: { '<%= config.css.dir %>/<%= config.css.file %>': '<%= config.css.dir %>/<%= config.css.file %>' } } }); //grunt-contrib-cssmin grunt.config('cssmin', { target: { src: '<%= config.css.dir %>/<%= config.css.file %>', dest: '<%= config.css.dir %>/<%= config.css.file %>' } }); //grunt-contrib-csslint grunt.config('csslint', { options: { csslintrc: 'grunt/.csslintrc' }, strict: { src: ['<%= config.css.dir %>/*.css'] } }); };
Add commented includePaths parameters for grunt-sass in case of Foundation usage
Add commented includePaths parameters for grunt-sass in case of Foundation usage
JavaScript
mit
SnceGroup/grunt-config-for-websites,SnceGroup/grunt-config-for-websites
--- +++ @@ -4,6 +4,7 @@ grunt.config('sass', { options: { outputStyle: 'expanded', + //includePaths: ['<%= config.scss.includePaths %>'], imagePath: '../<%= config.image.dir %>' }, dist: {
79ddea43a8e7217f974dc183e4f9bdb6732d2d11
controllers/users/collection.js
controllers/users/collection.js
module.exports = (function(){ // GET /users/:id/media?lat=<LAT>&lng=<LNG>&time=<TIME> return function* collection(id) { // Twitter Requests var TwitterManager = require('../media/twitter'); var twitterGranuals = yield TwitterManager.search(this.request.url) var InstagramManager = require('../media/instagram'); var instagramGranuals = yield InstagramManager.search(this.request.url) // Flickr Requests // var FlickrManager = require('../media/flickr'); // var flickrGranuals = yield FlickrManager.search(this.request.url); // Creating a universal capsul object var capsul = { "user_id": id, "latitude": require('../../helpers').paramsForUrl(this.request.url).lat, "longitude": require('../../helpers').paramsForUrl(this.request.url).lng, "timestamp": require('../../helpers').paramsForUrl(this.request.url).time, "data": [] } capsul.data.push(instagramGranuals); capsul.data.push(twitterGranuals); delete instagramGranuals; delete twitterGranuals; this.body = yield capsul; } })();
module.exports = (function(){ // GET /users/:id/media?lat=<LAT>&lng=<LNG>&time=<TIME> return function* collection(id) { // Twitter Requests var twitterDef = require('q').defer() var TwitterManager = require('../media/twitter'); var twitterGranuals = twitterDef.promise.then(TwitterManager.search); // var twitterDef = require('q').defer() // var instagramDef = require('q').defer() var InstagramManager = require('../media/instagram'); // var instagramGranuals = instagramDef.promise.then(InstagramManager.search); var instagramGranuals = InstagramManager.search(this.request.url); // Flickr Requests // var FlickrManager = require('../media/flickr'); // var flickrGranuals = yield FlickrManager.search(this.request.url); // Creating a universal capsul object var capsul = { "user_id": id, "latitude": require('../../helpers').paramsForUrl(this.request.url).lat, "longitude": require('../../helpers').paramsForUrl(this.request.url).lng, "timestamp": require('../../helpers').paramsForUrl(this.request.url).time, "data": [] } // def.resolve(this.request.url) // var instaGranuals = def.promise.then(InstagramManager.search); // capsul.data.push(instagramGranuals) twitterDef.resolve(this.request.url) // instagramDef.resolve(this.request.url) capsul.data.push(twitterGranuals); capsul.data.push(instagramGranuals) this.body = yield capsul; } })();
Refactor the twitter manager search methods with promises.
Refactor the twitter manager search methods with promises.
JavaScript
mit
capsul/capsul-api
--- +++ @@ -4,15 +4,19 @@ return function* collection(id) { // Twitter Requests - var TwitterManager = require('../media/twitter'); - var twitterGranuals = yield TwitterManager.search(this.request.url) + var twitterDef = require('q').defer() + var TwitterManager = require('../media/twitter'); + var twitterGranuals = twitterDef.promise.then(TwitterManager.search); + // var twitterDef = require('q').defer() - var InstagramManager = require('../media/instagram'); - var instagramGranuals = yield InstagramManager.search(this.request.url) + // var instagramDef = require('q').defer() + var InstagramManager = require('../media/instagram'); + // var instagramGranuals = instagramDef.promise.then(InstagramManager.search); + var instagramGranuals = InstagramManager.search(this.request.url); - // Flickr Requests - // var FlickrManager = require('../media/flickr'); - // var flickrGranuals = yield FlickrManager.search(this.request.url); + // Flickr Requests + // var FlickrManager = require('../media/flickr'); + // var flickrGranuals = yield FlickrManager.search(this.request.url); // Creating a universal capsul object var capsul = { @@ -23,10 +27,15 @@ "data": [] } - capsul.data.push(instagramGranuals); + // def.resolve(this.request.url) + // var instaGranuals = def.promise.then(InstagramManager.search); + // capsul.data.push(instagramGranuals) + + twitterDef.resolve(this.request.url) + // instagramDef.resolve(this.request.url) + capsul.data.push(twitterGranuals); - delete instagramGranuals; - delete twitterGranuals; + capsul.data.push(instagramGranuals) this.body = yield capsul; }
3dd759f1b7756e34f94a66ae361c44c6a2781c8d
client/js/directives/give-focus-directive.js
client/js/directives/give-focus-directive.js
"use strict"; angular.module("hikeio"). directive("giveFocus", function() { return { link: function(scope, element, attributes) { scope.$watch(attributes.giveFocus, function(value) { if (value) { setTimeout(function() { element.focus(); }); } }); } }; });
"use strict"; angular.module("hikeio"). directive("giveFocus", ["$timeout", function($timeout) { return { link: function(scope, element, attributes) { scope.$watch(attributes.giveFocus, function(value) { if (value) { $timeout(function() { element.focus(); }); } }); } }; }]);
Use angular timeout directive instead of setTimeout.
Use angular timeout directive instead of setTimeout.
JavaScript
mit
zaknelson/hike.io,zaknelson/hike.io,zaknelson/hike.io,zaknelson/hike.io
--- +++ @@ -1,16 +1,16 @@ "use strict"; angular.module("hikeio"). - directive("giveFocus", function() { + directive("giveFocus", ["$timeout", function($timeout) { return { link: function(scope, element, attributes) { scope.$watch(attributes.giveFocus, function(value) { if (value) { - setTimeout(function() { + $timeout(function() { element.focus(); }); } }); } }; -}); +}]);
13b62a9096c0e81efeaabfe7f603051a246fd22d
tasks/defaults.js
tasks/defaults.js
/******************************* Default Paths *******************************/ module.exports = { base : '', theme : './src/theme.config', docs : { source : '../docs/server/files/release/', output : '../docs/release/' }, // files cleaned after install setupFiles: [ './src/theme.config.example', './semantic.json.example', './src/_site' ], // modified to create configs templates: { config : './semantic.json.example', site : './src/_site', theme : './src/theme.config.example' }, regExp: { themeRoot: /.*\/themes\/.*?\//mg }, // folder pathsr folders: { config : './', site : './src/site', theme : './src/' }, // file paths files: { composer : 'composer.json', config : './semantic.json', npm : './package.json', site : './src/site', theme : './src/theme.config' }, // same as semantic.json.example paths: { source: { config : 'src/theme.config', definitions : 'src/definitions/', site : 'src/site/', themes : 'src/themes/' }, output: { packaged : 'dist/', uncompressed : 'dist/components/', compressed : 'dist/components/', themes : 'dist/themes/' }, clean : 'dist/' } };
/******************************* Default Paths *******************************/ module.exports = { base : '', theme : './src/theme.config', docs : { source : '../docs/server/files/release/', output : '../docs/release/' }, // files cleaned after install setupFiles: [ './src/theme.config.example', './semantic.json.example', './src/_site' ], // modified to create configs templates: { config : './semantic.json.example', site : './src/_site', theme : './src/theme.config.example' }, regExp: { themePath: /.*\/themes\/.*?\//mg }, // folder pathsr folders: { config : './', site : './src/site', theme : './src/' }, // file paths files: { composer : 'composer.json', config : './semantic.json', npm : './package.json', site : './src/site', theme : './src/theme.config' }, // same as semantic.json.example paths: { source: { config : 'src/theme.config', definitions : 'src/definitions/', site : 'src/site/', themes : 'src/themes/' }, output: { packaged : 'dist/', uncompressed : 'dist/components/', compressed : 'dist/components/', themes : 'dist/themes/' }, clean : 'dist/' } };
Fix regexp for theme changes
Fix regexp for theme changes
JavaScript
mit
lucienevans/Semantic-UI,avorio/Semantic-UI,Dineshs91/Semantic-UI,CapeSepias/Semantic-UI,bradbird1990/Semantic-UI,techpool/Semantic-UI,vibhatha/Semantic-UI,dhj2020/Semantic-UI,Keystion/Semantic-UI,nik4152/Semantic-UI,raoenhui/Semantic-UI-DIV,zcodes/Semantic-UI,CapsuleHealth/Semantic-UI,davialexandre/Semantic-UI,86yankai/Semantic-UI,Semantic-Org/Semantic-UI,Jiasm/Semantic-UI,lucienevans/Semantic-UI,androidesk/Semantic-UI,Illyism/Semantic-UI,JonathanRamier/Semantic-UI,Chrismarcel/Semantic-UI,tarvos21/Semantic-UI,kevinrodbe/Semantic-UI,jcdc21/Semantic-UI,abbasmhd/Semantic-UI,MathB/Semantic-UI,raphaelfruneaux/Semantic-UI,gangeshwark/Semantic-UI,imtapps-dev/imt-semantic-ui,SeanOceanHu/Semantic-UI,newsiberian/Semantic-UI,imtapps-dev/imt-semantic-ui,sunseth/Semantic-UI,Azzurrio/Semantic-UI,Pyrotoxin/Semantic-UI,guiquanz/Semantic-UI,Semantic-Org/Semantic-UI,zcodes/Semantic-UI,snwfog/hamijia-semantic,jcdc21/Semantic-UI,techpool/Semantic-UI,chrismoulton/Semantic-UI,not001praween001/Semantic-UI,openbizgit/Semantic-UI,listepo/Semantic-UI,kk9599/Semantic-UI,TangereJs/Semantic-UI,wang508x102/Semantic-UI,rwoll/Semantic-UI,AlbertoBarrago/Semantic-UI,liangxiaojuan/Semantic-UI,r14r-work/fork_javascript_semantic_ui,m2lan/Semantic-UI,86yankai/Semantic-UI,antyang/Semantic-UI,sudhakar/Semantic-UI,codeRuth/Semantic-UI,akinsella/Semantic-UI,artemkaint/Semantic-UI,akinsella/Semantic-UI,ShanghaitechGeekPie/Semantic-UI,yangyitao/Semantic-UI,schmiddd/Semantic-UI,ListnPlay/Semantic-UI,mnquintana/Semantic-UI,xiwc/semantic-ui.src,codeRuth/Semantic-UI,guodong/Semantic-UI,shengwenming/Semantic-UI,CapsuleHealth/Semantic-UI,leguian/SUI-Less,avorio/Semantic-UI,FlyingWHR/Semantic-UI,gextech/Semantic-UI,martindale/Semantic-UI,BobJavascript/Semantic-UI,Chrismarcel/Semantic-UI,jahnaviancha/Semantic-UI,Sweetymeow/Semantic-UI,teefresh/Semantic-UI,IveWong/Semantic-UI,taihuoniao/Semantic-UI-V2,marciovicente/Semantic-UI,flashadicts/Semantic-UI,Faisalawanisee/Semantic-UI,ryancanhelpyou/Semantic-UI,abbasmhd/Semantic-UI,raoenhui/Semantic-UI-DIV,sunseth/Semantic-UI,maher17/Semantic-UI,elliottisonfire/Semantic-UI,neomadara/Semantic-UI,wildKids/Semantic-UI,youprofit/Semantic-UI,jayphelps/Semantic-UI,eyethereal/archer-Semantic-UI,IveWong/Semantic-UI,manukall/Semantic-UI,m4tx/egielda-Semantic-UI,zanjs/Semantic-UI,1246419375/git-ui,CapeSepias/Semantic-UI,AlbertoBarrago/Semantic-UI,dieface/Semantic-UI,MichelSpanholi/Semantic-UI,eyethereal/archer-Semantic-UI,johnschult/Semantic-UI,exicon/Semantic-UI,MichelSpanholi/Semantic-UI,kongdw/Semantic-UI,edumucelli/Semantic-UI,jahnaviancha/Semantic-UI,anyroadcom/Semantic-UI,kongdw/Semantic-UI,snwfog/hamijia-semantic,r14r/fork_javascript_semantic_ui,bandzoogle/Semantic-UI,marciovicente/Semantic-UI,TangereJs/Semantic-UI,m2lan/Semantic-UI,Pro4People/Semantic-UI,SungDiYen/Semantic-UI,ilovezy/Semantic-UI,Acceptd/Semantic-UI,TangereJs/Semantic-UI,elliottisonfire/Semantic-UI,Centiq/semantic-ui,Jiasm/Semantic-UI,wlzc/semantic-ui.src,Illyism/Semantic-UI,Neaox/Semantic-UI,sudhakar/Semantic-UI,vibhatha/Semantic-UI,gsls1817/Semantic-UI,davialexandre/Semantic-UI,taihuoniao/Semantic-UI-V2,TagNewk/Semantic-UI,MrFusion42/Semantic-UI,tareq-s/Semantic-UI,napalmdev/Semantic-UI,1246419375/git-ui,shengwenming/Semantic-UI,flashadicts/Semantic-UI,FlyingWHR/Semantic-UI,larsbo/Semantic-UI,johnschult/Semantic-UI,r14r/fork_javascript_semantic_ui,BobJavascript/Semantic-UI,dominicwong617/Semantic-UI,rwoll/Semantic-UI,kk9599/Semantic-UI,Pyrotoxin/Semantic-UI,jayphelps/Semantic-UI,maher17/Semantic-UI,edumucelli/Semantic-UI,rockmandew/Semantic-UI,orlaqp/Semantic-UI,codedogfish/Semantic-UI,chrismoulton/Semantic-UI,chlorm-forks/Semantic-UI,ListnPlay/Semantic-UI,ikhakoo/Semantic-UI,champagne-randy/Semantic-UI,zanjs/Semantic-UI,FernandoMueller/Semantic-UI,tamdao/Semantic-UI,JonathanRamier/Semantic-UI,kevinrodbe/Semantic-UI,chlorm-forks/Semantic-UI,FernandoMueller/Semantic-UI,not001praween001/Semantic-UI,bandzoogle/Semantic-UI,guodong/Semantic-UI,anyroadcom/Semantic-UI,wlzc/semantic-ui.src,Dineshs91/Semantic-UI,kushal-likhi/bower-semantic-ui-1.0,anyroadcom/Semantic-UI,orlaqp/Semantic-UI,antyang/Semantic-UI,MrFusion42/Semantic-UI,gangeshwark/Semantic-UI,neomadara/Semantic-UI,youprofit/Semantic-UI,raphaelfruneaux/Semantic-UI,exicon/Semantic-UI,champagne-randy/Semantic-UI,ShanghaitechGeekPie/Semantic-UI,teefresh/Semantic-UI,newsiberian/Semantic-UI,Eynaliyev/Semantic-UI,Acceptd/Semantic-UI,wildKids/Semantic-UI,mnquintana/Semantic-UI,Centiq/semantic-ui,r14r-work/fork_javascript_semantic_ui,tamdao/Semantic-UI,Azzurrio/Semantic-UI,gextech/Semantic-UI,yangyitao/Semantic-UI,codedogfish/Semantic-UI,SungDiYen/Semantic-UI,TagNewk/Semantic-UI,Eynaliyev/Semantic-UI,ordepdev/Semantic-UI,openbizgit/Semantic-UI,leguian/SUI-Less,manukall/Semantic-UI,liangxiaojuan/Semantic-UI,m4tx/egielda-Semantic-UI,dhj2020/Semantic-UI,xiwc/semantic-ui.src,tarvos21/Semantic-UI,SeanOceanHu/Semantic-UI,wang508x102/Semantic-UI,warjiang/Semantic-UI,nik4152/Semantic-UI,eyethereal/archer-Semantic-UI,dieface/Semantic-UI,Pro4People/Semantic-UI,tareq-s/Semantic-UI,warjiang/Semantic-UI,guiquanz/Semantic-UI,listepo/Semantic-UI,larsbo/Semantic-UI,rockmandew/Semantic-UI,Faisalawanisee/Semantic-UI,bradbird1990/Semantic-UI,artemkaint/Semantic-UI,besrabasant/Semantic-UI,Neaox/Semantic-UI,androidesk/Semantic-UI,MathB/Semantic-UI,Sweetymeow/Semantic-UI,ikhakoo/Semantic-UI,martindale/Semantic-UI,ilovezy/Semantic-UI,ryancanhelpyou/Semantic-UI,dominicwong617/Semantic-UI,besrabasant/Semantic-UI,tarvos21/Semantic-UI,gsls1817/Semantic-UI
--- +++ @@ -27,7 +27,7 @@ }, regExp: { - themeRoot: /.*\/themes\/.*?\//mg + themePath: /.*\/themes\/.*?\//mg }, // folder pathsr
63875316d9df4983c477600dac427f1bed899ae2
common/app/Router/redux/add-lang-enhancer.js
common/app/Router/redux/add-lang-enhancer.js
import { langSelector } from './'; // This enhancers sole purpose is to add the lang prop to route actions so that // they do not need to be explicitally added when using a RFR route action. export default function addLangToRouteEnhancer(routesMap) { return createStore => (...args) => { const store = createStore(...args); return { ...store, dispatch(action) { if ( routesMap[action.type] && (action && action.payload && !action.payload.lang) ) { action = { ...action, payload: { ...action.payload, lang: langSelector(store.getState()) || 'en' } }; } return store.dispatch(action); } }; }; }
import { langSelector } from './'; // This enhancers sole purpose is to add the lang prop to route actions so that // they do not need to be explicitly added when using a RFR route action. export default function addLangToRouteEnhancer(routesMap) { return createStore => (...args) => { const store = createStore(...args); return { ...store, dispatch(action) { if ( routesMap[action.type] && (!action.payload || !action.payload.lang) ) { action = { ...action, payload: { ...action.payload, lang: langSelector(store.getState()) || 'en' } }; } return store.dispatch(action); } }; }; }
Add lang to payload if payload doesn't exist
fix(Router): Add lang to payload if payload doesn't exist closes #16134
JavaScript
bsd-3-clause
MiloATH/FreeCodeCamp,HKuz/FreeCodeCamp,Munsterberg/freecodecamp,jonathanihm/freeCodeCamp,FreeCodeCampQuito/FreeCodeCamp,BhaveshSGupta/FreeCodeCamp,no-stack-dub-sack/freeCodeCamp,matthew-t-smith/freeCodeCamp,FreeCodeCamp/FreeCodeCamp,raisedadead/FreeCodeCamp,BerkeleyTrue/FreeCodeCamp,raisedadead/FreeCodeCamp,otavioarc/freeCodeCamp,jonathanihm/freeCodeCamp,HKuz/FreeCodeCamp,systimotic/FreeCodeCamp,BerkeleyTrue/FreeCodeCamp,pahosler/freecodecamp,matthew-t-smith/freeCodeCamp,MiloATH/FreeCodeCamp,FreeCodeCampQuito/FreeCodeCamp,no-stack-dub-sack/freeCodeCamp,Munsterberg/freecodecamp,otavioarc/freeCodeCamp,BhaveshSGupta/FreeCodeCamp,BhaveshSGupta/FreeCodeCamp,systimotic/FreeCodeCamp,pahosler/freecodecamp,FreeCodeCamp/FreeCodeCamp
--- +++ @@ -1,7 +1,7 @@ import { langSelector } from './'; // This enhancers sole purpose is to add the lang prop to route actions so that -// they do not need to be explicitally added when using a RFR route action. +// they do not need to be explicitly added when using a RFR route action. export default function addLangToRouteEnhancer(routesMap) { return createStore => (...args) => { const store = createStore(...args); @@ -11,7 +11,7 @@ dispatch(action) { if ( routesMap[action.type] && - (action && action.payload && !action.payload.lang) + (!action.payload || !action.payload.lang) ) { action = { ...action,
1b36979ac15068f7072fb1cc4d36318fdc805a44
test/view.sendmessage.js
test/view.sendmessage.js
'use strict'; var express = require('express'); var supertest = require('supertest'); var logger = require('log4js').getLogger('Unit-Test'); var nconf = require('nconf'); nconf.argv() .env() .file({ file: 'config.json' }); var request = supertest(app); exports['Check view health'] = function(test){ request.get('/sendmessage').end(function(err,res)){ test.equal(err,null,'It should not had any error!'); test.equal(res,200,'It should return 200!'); test.done(); } } exports['Test send message'] = { 'Test send message success':function(test){ request.post('/sendmessage'), .send({'receiver':'','text':'Hello World'!}) .end(function(err,res)){ test.equal(err,null,'It should not had any error!') test.equal(res,201,'It should return 201!'); } } }
'use strict'; var express = require('express'); var supertest = require('supertest'); var logger = require('log4js').getLogger('Unit-Test'); var nconf = require('nconf'); nconf.argv() .env() .file({ file: 'config.json' }); var request = supertest(app); exports['Check view health'] = function(test){ request.get('/message').end(function(err,res)){ test.equal(err,null,'It should not had any error!'); test.equal(res,200,'It should return 200!'); test.done(); } } exports['Test send message'] = { 'Test send message success':function(test){ request.post('/message'), .send({'receiver':'','text':'Hello World'!}) .end(function(err,res)){ test.equal(err,null,'It should not had any error!') test.equal(res,201,'It should return 201!'); } } }
Fix the url of message
Fix the url of message
JavaScript
apache-2.0
dollars0427/ATMessager,dollars0427/ATMessager
--- +++ @@ -12,7 +12,7 @@ exports['Check view health'] = function(test){ - request.get('/sendmessage').end(function(err,res)){ + request.get('/message').end(function(err,res)){ test.equal(err,null,'It should not had any error!'); @@ -27,7 +27,7 @@ 'Test send message success':function(test){ - request.post('/sendmessage'), + request.post('/message'), .send({'receiver':'','text':'Hello World'!}) .end(function(err,res)){
7ec505fba9972b109a3aea2e70c103f5b8c09286
src/browser-runner/platform-dummy/sagas/server-command-handlers.js
src/browser-runner/platform-dummy/sagas/server-command-handlers.js
/* Copyright 2016 Mozilla Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import { takeEvery } from 'redux-saga/effects'; import opn from 'opn'; import SharedActions from '../../../shared/actions/shared-actions'; function create({ payload: { url } }) { console.log(`Chrome frontend hosted at ${url}`); // eslint-disable-line no-console opn(url); } export default function* () { yield [ takeEvery(SharedActions.commands.fromServer.toRunner.app.window.create, create), ]; }
/* Copyright 2016 Mozilla Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import { takeEvery } from 'redux-saga/effects'; import opn from 'opn'; import logger from '../../logger'; import SharedActions from '../../../shared/actions/shared-actions'; function create({ payload: { url } }) { logger.log(`Chrome frontend hosted at ${url}`); opn(url); } export default function* () { yield [ takeEvery(SharedActions.commands.fromServer.toRunner.app.window.create, create), ]; }
Use logger module instead of console for the dummy browser runner sagas
Use logger module instead of console for the dummy browser runner sagas Signed-off-by: Victor Porof <4f672cb979ca45495d0cccc37abaefc8713fcc24@gmail.com>
JavaScript
apache-2.0
victorporof/tofino,victorporof/tofino
--- +++ @@ -13,10 +13,12 @@ import { takeEvery } from 'redux-saga/effects'; import opn from 'opn'; +import logger from '../../logger'; + import SharedActions from '../../../shared/actions/shared-actions'; function create({ payload: { url } }) { - console.log(`Chrome frontend hosted at ${url}`); // eslint-disable-line no-console + logger.log(`Chrome frontend hosted at ${url}`); opn(url); }
1c4c3c036aa2d88db4d1c078d009eb2d0875b136
packages/babel-preset-expo/index.js
packages/babel-preset-expo/index.js
module.exports = function() { return { presets: ['module:metro-react-native-babel-preset'], plugins: [ [ 'babel-plugin-module-resolver', { alias: { 'react-native-vector-icons': '@expo/vector-icons', }, }, ], ['@babel/plugin-proposal-decorators', { legacy: true }], ], }; };
module.exports = function(api) { const isWeb = api.caller(isTargetWeb); return { presets: ['module:metro-react-native-babel-preset'], plugins: [ [ 'babel-plugin-module-resolver', { alias: { 'react-native-vector-icons': '@expo/vector-icons', }, }, ], ['@babel/plugin-proposal-decorators', { legacy: true }], ], }; }; function isTargetWeb(caller) { return caller && caller.name === 'babel-loader'; }
Update preset to be able to detect if it's run from Webpack's babel-loader
[babel] Update preset to be able to detect if it's run from Webpack's babel-loader
JavaScript
bsd-3-clause
exponentjs/exponent,exponent/exponent,exponentjs/exponent,exponent/exponent,exponentjs/exponent,exponent/exponent,exponent/exponent,exponent/exponent,exponent/exponent,exponentjs/exponent,exponentjs/exponent,exponent/exponent,exponentjs/exponent,exponent/exponent,exponent/exponent,exponentjs/exponent,exponentjs/exponent,exponentjs/exponent
--- +++ @@ -1,4 +1,6 @@ -module.exports = function() { +module.exports = function(api) { + const isWeb = api.caller(isTargetWeb); + return { presets: ['module:metro-react-native-babel-preset'], plugins: [ @@ -14,3 +16,7 @@ ], }; }; + +function isTargetWeb(caller) { + return caller && caller.name === 'babel-loader'; +}
8acde49dee699c4055d930eb4bfb9916e884026f
app/events/model.js
app/events/model.js
var mongoose = require('mongoose'); var schema = require('validate'); var Event = mongoose.model('Event', { name: String, start: Date, end: Date, group: String, notify: Boolean }); var validate = function (event) { var test = schema({ name: { type: 'string', required: true, message: 'You must provide a name for the event.' }, start: { type: 'date', required: true, message: 'You must provide a start time.' }, end: { type: 'date', required: true, message: 'You must provide an end time.' }, group: { type: 'string', required: false }, notify: { type: 'boolean', required: false } }, {typecast: true}); return test.validate(event); }; module.exports = Event; module.exports.validate = validate;
var mongoose = require('mongoose'); var schema = require('validate'); var Event = mongoose.model('Event', { name: String, start: Date, end: Date, group: {type: String, enum: ['attendee', 'staff', 'admin'], default: 'attendee'}, notify: {type: Boolean, default: true} }); var validate = function (event) { var test = schema({ name: { type: 'string', required: true, message: 'You must provide a name for the event.' }, start: { type: 'date', required: true, message: 'You must provide a start time.' }, end: { type: 'date', required: true, message: 'You must provide an end time.' }, group: { type: 'string' }, notify: { type: 'boolean' } }, {typecast: true}); return test.validate(event); }; module.exports = Event; module.exports.validate = validate;
Fix validation issue on events
Fix validation issue on events
JavaScript
mit
hacksu/kenthackenough,hacksu/kenthackenough
--- +++ @@ -5,8 +5,8 @@ name: String, start: Date, end: Date, - group: String, - notify: Boolean + group: {type: String, enum: ['attendee', 'staff', 'admin'], default: 'attendee'}, + notify: {type: Boolean, default: true} }); var validate = function (event) { @@ -27,12 +27,10 @@ message: 'You must provide an end time.' }, group: { - type: 'string', - required: false + type: 'string' }, notify: { - type: 'boolean', - required: false + type: 'boolean' } }, {typecast: true}); return test.validate(event);
db599cb4fdaa27d68a45f0d5198d2e8a6a70201b
server/auth/local/passport.js
server/auth/local/passport.js
'use strict'; import passport from 'passport'; import {Strategy as LocalStrategy} from 'passport-local'; function localAuthenticate(User, email, password, done) { User.findOneAsync({ email: email.toLowerCase() }) .then(user => { if (!user) { return done(null, false, { message: 'This email is not registered.' }); } user.authenticate(password, function(authError, authenticated) { if (authError) { return done(authError); } if (!authenticated) { return done(null, false, { message: 'This password is not correct.' }); } else { return done(null, user); } }); }) .catch(err => done(err)); } export function setup(User, config) { passport.use(new LocalStrategy({ usernameField: 'email', passwordField: 'password' // this is the virtual field on the model }, function(email, password, done) { return localAuthenticate(User, email, password, done); })); }
'use strict'; import passport from 'passport'; import {Strategy as LocalStrategy} from 'passport-local'; function localAuthenticate(User, email, password, done) { User.findOne({ email: email.toLowerCase() }) .then(user => { if (!user) { return done(null, false, { message: 'This email is not registered.' }); } user.authenticate(password, function(authError, authenticated) { if (authError) { return done(authError); } if (!authenticated) { return done(null, false, { message: 'This password is not correct.' }); } else { return done(null, user); } }); }) .catch(err => done(err)); } export function setup(User, config) { passport.use(new LocalStrategy({ usernameField: 'email', passwordField: 'password' // this is the virtual field on the model }, function(email, password, done) { return localAuthenticate(User, email, password, done); })); }
Remove async from mongosoe query
Remove async from mongosoe query
JavaScript
mit
Klemensas/ffempire,Klemensas/ffempire
--- +++ @@ -4,7 +4,7 @@ import {Strategy as LocalStrategy} from 'passport-local'; function localAuthenticate(User, email, password, done) { - User.findOneAsync({ + User.findOne({ email: email.toLowerCase() }) .then(user => {
a6e68f4688fa2f527b118f175d46e1dadba27472
server/publications/groups.js
server/publications/groups.js
Meteor.publish('allGroups', function () { return Groups.find(); });
Meteor.publish('allGroups', function () { // Publish all groups return Groups.find(); }); Meteor.publish('singleGroup', function (groupId) { // Publish only one group, specified as groupId return Groups.find(groupId); });
Add singleGroup publication, clarifying comments
Add singleGroup publication, clarifying comments
JavaScript
agpl-3.0
GeriLife/wellbeing,brylie/juhani-wellbeing,GeriLife/wellbeing,brylie/juhani-wellbeing,GeriLife/wellbeing,brylie/juhani-wellbeing,GeriLife/wellbeing,brylie/juhani-wellbeing
--- +++ @@ -1,3 +1,9 @@ Meteor.publish('allGroups', function () { + // Publish all groups return Groups.find(); }); + +Meteor.publish('singleGroup', function (groupId) { + // Publish only one group, specified as groupId + return Groups.find(groupId); +});
5cd96c419d81f5365121064bfb8a0762c3004984
test/libraries.js
test/libraries.js
var fs = require('fs'), Libraries = require('../lib/libraries'), should = require('should'); describe('Libraries', function() { describe('#bowerLibraries', function() { var readdirSync = fs.readdirSync, statSync = fs.statSync, context = { event: {emit: function() {}} }; before(function() { fs.statSync = function(path) { if (/bar\//.test(path)) { throw new Error(); } }; }); after(function() { fs.readdirSync = readdirSync; fs.statSync = statSync; }); it('should return all modules in bower directory', function() { fs.readdirSync = function(path) { return ['foo', 'bar', 'baz']; }; var library = new Libraries(); library.bowerLibraries(context).should.eql(['bower_components/foo', 'bower_components/baz']); }); it('should not error on fs error', function() { fs.readdirSync = function(path) { throw new Error(); }; var library = new Libraries(); should.not.exist(library.bowerLibraries(context)); }); }); });
var fs = require('fs'), Libraries = require('../lib/libraries'), should = require('should'); describe('Libraries', function() { describe('#bowerLibraries', function() { beforeEach(function() { require('bower').config.directory = 'bower_components'; }); var readdirSync = fs.readdirSync, statSync = fs.statSync, context = { event: {emit: function() {}} }; before(function() { fs.statSync = function(path) { if (/bar\//.test(path)) { throw new Error(); } }; }); after(function() { fs.readdirSync = readdirSync; fs.statSync = statSync; }); it('should return all modules in bower directory', function() { fs.readdirSync = function(path) { return ['foo', 'bar', 'baz']; }; var library = new Libraries(); library.bowerLibraries(context).should.eql(['bower_components/foo', 'bower_components/baz']); }); it('should not error on fs error', function() { fs.readdirSync = function(path) { throw new Error(); }; var library = new Libraries(); should.not.exist(library.bowerLibraries(context)); }); }); });
Fix bower config value for tests
Fix bower config value for tests
JavaScript
mit
walmartlabs/lumbar
--- +++ @@ -4,6 +4,10 @@ describe('Libraries', function() { describe('#bowerLibraries', function() { + beforeEach(function() { + require('bower').config.directory = 'bower_components'; + }); + var readdirSync = fs.readdirSync, statSync = fs.statSync,
30caeb00644a2f7e3740b49b39790f96a796bee5
test/init.js
test/init.js
require('ts-node').register({ fast: true, compilerOptions: { target: 'es2015', } }) require('source-map-support/register') require('jsdom-global/register') require('raf').polyfill(global) const enzyme = require('enzyme') const chai = require('chai') const chaiEnzyme = require('chai-enzyme') const sinonChai = require('sinon-chai') const EnzymeAdapter = require('enzyme-adapter-react-16') const chaiAsPromised = require("chai-as-promised") enzyme.configure({ adapter: new EnzymeAdapter() }) console.error = () => {} chai.use(chaiEnzyme()) chai.use(sinonChai) chai.use(chaiAsPromised)
require('ts-node').register({ fast: true, compilerOptions: { target: 'es2015' } }) require('source-map-support').install({ hookRequire: true }) require('jsdom-global/register') require('raf').polyfill(global) const enzyme = require('enzyme') const chai = require('chai') const chaiEnzyme = require('chai-enzyme') const sinonChai = require('sinon-chai') const EnzymeAdapter = require('enzyme-adapter-react-16') const chaiAsPromised = require("chai-as-promised") enzyme.configure({ adapter: new EnzymeAdapter() }) console.error = () => {} console.warn = () => {} chai.use(chaiEnzyme()) chai.use(sinonChai) chai.use(chaiAsPromised)
Fix testcase source maps and hide console.warn messages
Fix testcase source maps and hide console.warn messages
JavaScript
mit
brightinteractive/bright-js-framework,brightinteractive/bright-js-framework,brightinteractive/bright-js-framework
--- +++ @@ -1,5 +1,5 @@ -require('ts-node').register({ fast: true, compilerOptions: { target: 'es2015', } }) -require('source-map-support/register') +require('ts-node').register({ fast: true, compilerOptions: { target: 'es2015' } }) +require('source-map-support').install({ hookRequire: true }) require('jsdom-global/register') require('raf').polyfill(global) @@ -15,6 +15,7 @@ }) console.error = () => {} +console.warn = () => {} chai.use(chaiEnzyme()) chai.use(sinonChai)
4718270e280fb258aacf942ed6d33cb3e6c39ae3
test/select-test.js
test/select-test.js
var chai = require('chai'), expect = chai.expect, sql = require('../psql'); describe('select', function() { it('should generate a select statement with an asterisk with no arguments', function() { expect(sql.select().from('users').toQuery().text).to.equal('select * from users'); }); it('should generate a select statement with a single column name', function() { expect(sql.select('id').from('users').toQuery().text).to.equal('select id from users'); }) it('should generate a select statement with column names', function() { expect(sql.select('id', 'email').from('users').toQuery().text).to.equal('select id, email from users'); }); });
var chai = require('chai'), expect = chai.expect, sql = require('../psql'); describe('select', function() { it('should generate a select statement with an asterisk with no arguments', function() { expect(sql.select().from('users').toQuery().text).to.equal('select * from users'); }); it('should generate a select statement with a single column name', function() { expect(sql.select('id').from('users').toQuery().text).to.equal('select id from users'); }) it('should generate a select statement with column names', function() { expect(sql.select('id', 'email').from('users').toQuery().text).to.equal('select id, email from users'); }); it('should handle json columns', function() { expect(sql.select('id', "data->>'name' as name").from('users').toQuery().text).to.equal("select id, data->>'name' as name from users") }); //SELECT id, data->'author'->>'first_name' as author_first_name FROM books; it('should handle json column nesting', function() { expect(sql.select('id', "data->'author'->>'first_name' as author_first_name").from('books').toQuery().text) .to.equal("select id, data->'author'->>'first_name' as author_first_name from books") }); });
Add select test for json columns
Add select test for json columns
JavaScript
mit
swlkr/psqljs
--- +++ @@ -14,4 +14,14 @@ it('should generate a select statement with column names', function() { expect(sql.select('id', 'email').from('users').toQuery().text).to.equal('select id, email from users'); }); + + it('should handle json columns', function() { + expect(sql.select('id', "data->>'name' as name").from('users').toQuery().text).to.equal("select id, data->>'name' as name from users") + }); + + //SELECT id, data->'author'->>'first_name' as author_first_name FROM books; + it('should handle json column nesting', function() { + expect(sql.select('id', "data->'author'->>'first_name' as author_first_name").from('books').toQuery().text) + .to.equal("select id, data->'author'->>'first_name' as author_first_name from books") + }); });
0e16b3547b7134e032885053ddac97cb85cb7ee2
tests/karma.conf.js
tests/karma.conf.js
var path = require('path'); var webpack = require('./webpack.config'); process.env.CHROME_BIN = require('puppeteer').executablePath(); module.exports = function (config) { config.set({ basePath: '.', frameworks: ['mocha'], reporters: ['mocha'], client: { captureConsole: true, mocha: { timeout : 10000, // 10 seconds - upped from 2 seconds retries: 3 // Allow for slow server on CI. } }, files: [ {pattern: path.resolve('./build/injector.js'), watched: false}, {pattern: process.env.KARMA_FILE_PATTERN, watched: false} ], preprocessors: { 'build/injector.js': ['webpack'], 'src/*.spec.ts': ['webpack', 'sourcemap'] }, mime: { 'text/x-typescript': ['ts','tsx'] }, webpack: webpack, webpackMiddleware: { noInfo: true, stats: 'errors-only' }, browserNoActivityTimeout: 31000, // 31 seconds - upped from 10 seconds browserDisconnectTimeout: 31000, // 31 seconds - upped from 2 seconds browserDisconnectTolerance: 2, port: 9876, colors: true, singleRun: true, logLevel: config.LOG_INFO }); };
var path = require('path'); var webpack = require('./webpack.config'); process.env.CHROME_BIN = require('puppeteer').executablePath(); module.exports = function (config) { config.set({ basePath: '.', frameworks: ['mocha'], reporters: ['mocha'], client: { captureConsole: true, }, files: [ {pattern: path.resolve('./build/injector.js'), watched: false}, {pattern: process.env.KARMA_FILE_PATTERN, watched: false} ], preprocessors: { 'build/injector.js': ['webpack'], 'src/*.spec.ts': ['webpack', 'sourcemap'] }, mime: { 'text/x-typescript': ['ts','tsx'] }, webpack: webpack, webpackMiddleware: { noInfo: true, stats: 'errors-only' }, port: 9876, colors: true, singleRun: true, logLevel: config.LOG_INFO }); };
Decrease high timeout in ci
Decrease high timeout in ci
JavaScript
bsd-3-clause
jupyter/jupyterlab,jupyter/jupyterlab,jupyter/jupyterlab,jupyter/jupyterlab,jupyter/jupyterlab
--- +++ @@ -10,10 +10,6 @@ reporters: ['mocha'], client: { captureConsole: true, - mocha: { - timeout : 10000, // 10 seconds - upped from 2 seconds - retries: 3 // Allow for slow server on CI. - } }, files: [ {pattern: path.resolve('./build/injector.js'), watched: false}, @@ -31,9 +27,6 @@ noInfo: true, stats: 'errors-only' }, - browserNoActivityTimeout: 31000, // 31 seconds - upped from 10 seconds - browserDisconnectTimeout: 31000, // 31 seconds - upped from 2 seconds - browserDisconnectTolerance: 2, port: 9876, colors: true, singleRun: true,
ce1c01c9c1802296c4ff319f71a60a079b758cbb
examples/dir/counter/index.js
examples/dir/counter/index.js
import { app, html } from "flea" const model = 0 const view = (model, dispatch) => html` <div> <h1>${model}</h1> <button onclick=${_ => dispatch("INCREMENT")}>+</button> <button onclick=${_ => dispatch("DECREMENT")}>-</button> </div>` const update = { INCREMENT: model => model + 2, DECREMENT: model => model - 1 } app(model, view, update)
import { app, html } from "flea" const model = 0 const view = (model, dispatch) => html` <div> <button onclick=${_ => dispatch("INCREMENT")}>+</button> <p>${model}</p> <button onclick=${_ => dispatch("DECREMENT")} disabled=${model <= 0}>-</button> </div>` const update = { INCREMENT: model => model + 1, DECREMENT: model => model - 1 } app(model, view, update)
Increment by one. Show how to use disabled attribute with boolean var.
Increment by one. Show how to use disabled attribute with boolean var.
JavaScript
mit
Mytrill/hyperapp,tzellman/hyperapp,Mytrill/hyperapp
--- +++ @@ -4,13 +4,13 @@ const view = (model, dispatch) => html` <div> - <h1>${model}</h1> <button onclick=${_ => dispatch("INCREMENT")}>+</button> - <button onclick=${_ => dispatch("DECREMENT")}>-</button> + <p>${model}</p> + <button onclick=${_ => dispatch("DECREMENT")} disabled=${model <= 0}>-</button> </div>` const update = { - INCREMENT: model => model + 2, + INCREMENT: model => model + 1, DECREMENT: model => model - 1 }
7d1c8097ef9ead4935f94e7f69dcbe5e8e5f2330
test/spec/json.js
test/spec/json.js
'use strict'; var JsonExtension = require('../../src/json'); var expect = require('chai').expect; describe('JsonExtension', function () { var ext; beforeEach(function() { ext = new JsonExtension(); }); describe('extension applicability', function() { it('should apply when application/json content type', function() { expect(ext.applies({}, { 'content-type': 'application/json' })).to.be.true; }); it('should apply to application/json content type with params', function() { expect(ext.applies({}, { 'content-type': 'application/json; charset=utf-8' }, 200)).to.be.true; }); }); describe('data parser', function() { it('should return the data', function() { var data = ext.dataParser({ name: 'John Doe' }, {}); expect(data).to.eql({ name: 'John Doe' }); }); }); it('should have application/json media types', function() { expect(ext.mediaTypes).to.eql(['application/json']); }); });
'use strict'; var JsonExtension = require('../../src/json'); var expect = require('chai').expect; describe('JsonExtension', function () { var ext; beforeEach(function() { ext = new JsonExtension(); }); describe('extension applicability', function() { it('should apply when application/json content type', function() { expect(ext.applies({}, { 'content-type': 'application/json' })).to.be.true; }); it('should apply to application/json content type with params', function() { expect(ext.applies({}, { 'content-type': 'application/json; charset=utf-8' }, 200)).to.be.true; }); it('should not apply when no content type at all (e.g. 204 response)', function() { expect(ext.applies({}, {}, 204)).to.be.false; }); }); describe('data parser', function() { it('should return the data', function() { var data = ext.dataParser({ name: 'John Doe' }, {}); expect(data).to.eql({ name: 'John Doe' }); }); }); it('should have application/json media types', function() { expect(ext.mediaTypes).to.eql(['application/json']); }); });
Test JSON extension deoes not apply for 204 status responses.
Test JSON extension deoes not apply for 204 status responses.
JavaScript
mit
petejohanson/hy-res
--- +++ @@ -18,6 +18,10 @@ it('should apply to application/json content type with params', function() { expect(ext.applies({}, { 'content-type': 'application/json; charset=utf-8' }, 200)).to.be.true; }); + + it('should not apply when no content type at all (e.g. 204 response)', function() { + expect(ext.applies({}, {}, 204)).to.be.false; + }); }); describe('data parser', function() {
6a25939169dde7cb31093f3ebf7298a658ed0ab4
lib/repl.js
lib/repl.js
const {VM} = require('vm2') const exec = require('child_process').exec module.exports = { js: code => { const vm = new VM() try { return vm.run(code).toString() } catch (e) { return e.toString(); } }, rb: code => { return new Promise((resolve, reject) => { const unsafe = new RegExp(/(`|%x|system|exec|unpack|eval|require|Dir|File|ENV|Process|send|Object)/, 'g') const formattedCode = code.replace(/'/g, '"') if(unsafe.test(formattedCode)){ resolve('Unsafe characters found') } else { exec(`ruby -e 'puts ${formattedCode}'`, (err, stdout, stderr) => { if(err){ reject(err) } resolve(stdout) }) } }) } }
const {VM} = require('vm2') const exec = require('child_process').exec module.exports = { js: code => { const vm = new VM() try { return vm.run(code).toString() } catch (e) { return e.toString(); } }, rb: code => { return new Promise((resolve, reject) => { const unsafe = new RegExp(/(`|%x|system|exec|method|call|unpack|eval|require|Dir|File|ENV|Process|send|Object)/, 'g') const formattedCode = code.replace(/'/g, '"') if(unsafe.test(formattedCode)){ resolve('Unsafe characters found') } else { exec(`ruby -e 'puts ${formattedCode}'`, (err, stdout, stderr) => { if(err){ reject(err) } resolve(stdout) }) } }) } }
Add more keywords to ruby sandbox
Add more keywords to ruby sandbox
JavaScript
mit
josephrexme/sia
--- +++ @@ -12,7 +12,7 @@ }, rb: code => { return new Promise((resolve, reject) => { - const unsafe = new RegExp(/(`|%x|system|exec|unpack|eval|require|Dir|File|ENV|Process|send|Object)/, 'g') + const unsafe = new RegExp(/(`|%x|system|exec|method|call|unpack|eval|require|Dir|File|ENV|Process|send|Object)/, 'g') const formattedCode = code.replace(/'/g, '"') if(unsafe.test(formattedCode)){ resolve('Unsafe characters found')
4b37bc34f49b3cdc59b2960dd97b4083995f72a4
webpack.config.js
webpack.config.js
const HtmlWebPackPlugin = require("html-webpack-plugin") module.exports = { entry: { main: __dirname + "/src/DragRange.jsx", viewer: __dirname + "/src/index.js", }, output: { filename: "[name].js", path: __dirname + "/dist", }, devtool: "source-map", module: { rules: [ { test: /\.jsx?$/, exclude: [/node_modules/], use: { loader: "babel-loader", } }, { test: /\.html$/, use: [ { loader: "html-loader", options: { minimize: true }, } ] }, ], }, plugins: [ new HtmlWebPackPlugin({ template: __dirname + "/src/index.html", filename: __dirname + "/index.html", }) ], }
const HtmlWebPackPlugin = require("html-webpack-plugin") module.exports = { entry: { main: __dirname + "/src/DragRange.jsx", viewer: __dirname + "/src/index.js", }, output: { filename: "[name].js", path: __dirname + "/dist", }, devtool: "source-map", module: { rules: [ { test: /\.jsx?$/, exclude: [/node_modules/], use: { loader: "babel-loader", } }, { test: /\.html$/, use: [ { loader: "html-loader", options: { minimize: true }, } ] }, ], }, plugins: [ new HtmlWebPackPlugin({ template: "./src/index.html", filename: "./index.html", }) ], }
Use relative path for html plugin
Use relative path for html plugin
JavaScript
mit
Radivarig/react-drag-range,Radivarig/react-drag-range
--- +++ @@ -36,8 +36,8 @@ plugins: [ new HtmlWebPackPlugin({ - template: __dirname + "/src/index.html", - filename: __dirname + "/index.html", + template: "./src/index.html", + filename: "./index.html", }) ], }
a49d464a2ba55c3d0c3600f14c85f8c003c785cd
webpack.config.js
webpack.config.js
const path = require("path") const PATHS = { app: path.join(__dirname, 'src/index.tsx'), } module.exports = { entry: { app: PATHS.app, }, output: { path: __dirname + '/dist', filename: 'bundle.js', publicPath: "http://localhost:8080/" }, mode: 'development', module: { rules: [ { test: /\.(js|jsx|tsx)$/, loader: 'babel-loader', exclude: /node_modules/, include: /src/ }, { test: /\.jsx?$/, use: 'react-hot-loader/webpack', include: /node_modules/, } ], }, resolve: { extensions: ['.tsx', '.ts', '.js'], }, devServer: { index: 'index.html', headers: { "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, PATCH, OPTIONS", "Access-Control-Allow-Headers": "X-Requested-With, content-type, Authorization" } }, devtool: 'inline-source-map' }
const path = require("path") const PATHS = { app: path.join(__dirname, 'src/index.tsx'), } module.exports = { entry: { app: PATHS.app, }, output: { path: __dirname + '/dist', filename: 'bundle.js', publicPath: "http://localhost:8080/" }, mode: 'development', module: { rules: [ { test: /\.(js|jsx|ts|tsx)$/, loader: 'babel-loader', exclude: /node_modules/, include: /src/ }, { test: /\.jsx?$/, use: 'react-hot-loader/webpack', include: /node_modules/, } ], }, resolve: { extensions: ['.tsx', '.ts', '.js'], }, devServer: { index: 'index.html', headers: { "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, PATCH, OPTIONS", "Access-Control-Allow-Headers": "X-Requested-With, content-type, Authorization" } }, devtool: 'inline-source-map' }
Add .ts files to loader
Add .ts files to loader
JavaScript
mit
looker-open-source/extension-template-react,looker-open-source/extension-template-react
--- +++ @@ -5,7 +5,7 @@ } module.exports = { - entry: { + entry: { app: PATHS.app, }, output: { @@ -17,7 +17,7 @@ module: { rules: [ { - test: /\.(js|jsx|tsx)$/, + test: /\.(js|jsx|ts|tsx)$/, loader: 'babel-loader', exclude: /node_modules/, include: /src/
f011989558edaea5df62e28155cd904942ed743f
webpack.config.js
webpack.config.js
var path = require('path'); var webpack = require('webpack'); module.exports = { entry: [ path.resolve(__dirname, "src", "r3test.js"), "webpack/hot/dev-server", "webpack-dev-server/client?http://localhost:8081" ], output: { path: path.resolve(__dirname, "scripts"), publicPath: "/scripts/", filename: "r3test.js" }, plugins: [ new webpack.HotModuleReplacementPlugin() ], module: { loaders: [ { test: /\.js$/, loaders: ['react-hot', 'babel'], exclude: /node_modules/, include: path.join(__dirname, 'src') } ] } }
var path = require('path'); var webpack = require('webpack'); module.exports = { entry: [ path.resolve(__dirname, "src", "r3test.js"), "webpack/hot/dev-server", "webpack-dev-server/client?http://localhost:8081" ], output: { path: path.resolve(__dirname, "scripts"), publicPath: "/scripts/", filename: "r3test.js" }, plugins: [ new webpack.HotModuleReplacementPlugin() ], module: { loaders: [ { test: /\.js$/, loader: 'babel', exclude: /node_modules/, include: path.join(__dirname, 'src'), query: { presets: ['es2015', 'stage-2', 'react'], plugins: ['transform-runtime'] } } ] } }
Switch to new babel/react-transform build pipeline
Switch to new babel/react-transform build pipeline
JavaScript
apache-2.0
Izzimach/r3test,Izzimach/r3test
--- +++ @@ -20,9 +20,13 @@ loaders: [ { test: /\.js$/, - loaders: ['react-hot', 'babel'], + loader: 'babel', exclude: /node_modules/, - include: path.join(__dirname, 'src') + include: path.join(__dirname, 'src'), + query: { + presets: ['es2015', 'stage-2', 'react'], + plugins: ['transform-runtime'] + } } ] }
0fb79bc1c55db7e13eb4ce987256b87f751d3d01
src/index.js
src/index.js
require('core-js'); // es2015 polyfill var path = require('path'); var plopBase = require('./modules/plop-base'); var generatorRunner = require('./modules/generator-runner'); /** * Main node-plop module * * @param {string} plopfilePath - The absolute path to the plopfile we are interested in working with * @returns {object} the node-plop API for the plopfile requested */ module.exports = function (plopfilePath) { const plop = plopBase(); const runner = generatorRunner(plop); plopfilePath = path.resolve(plopfilePath); plop.setPlopfilePath(plopfilePath); require(plopfilePath)(plop); ///// // external API for node-plop // return { getGeneratorList: plop.getGeneratorList, getGenerator: function (genName) { const genObject = plop.getGenerator(genName); return Object.assign(genObject, { runActions: (data) => runner.runGeneratorActions(genObject, data), runPrompts: () => runner.runGeneratorPrompts(genObject) }); }, runActions: runner.runGeneratorActions, runPrompts: runner.runGeneratorPrompts }; };
require('core-js'); // es2015 polyfill var path = require('path'); var plopBase = require('./modules/plop-base'); var generatorRunner = require('./modules/generator-runner'); /** * Main node-plop module * * @param {string} plopfilePath - The absolute path to the plopfile we are interested in working with * @returns {object} the node-plop API for the plopfile requested */ module.exports = function (plopfilePath) { const plop = plopBase(); const runner = generatorRunner(plop); if (plopfilePath) { plopfilePath = path.resolve(plopfilePath); plop.setPlopfilePath(plopfilePath); require(plopfilePath)(plop); } ///// // external API for node-plop // return { getGeneratorList: plop.getGeneratorList, getGenerator: function (genName) { const genObject = plop.getGenerator(genName); return Object.assign(genObject, { runActions: (data) => runner.runGeneratorActions(genObject, data), runPrompts: () => runner.runGeneratorPrompts(genObject) }); }, setGenerator: plop.setGenerator, runActions: runner.runGeneratorActions, runPrompts: runner.runGeneratorPrompts }; };
Make plop file optional, and expose plop.setGenerator() function to allow dynamic creation of generator configs.
Make plop file optional, and expose plop.setGenerator() function to allow dynamic creation of generator configs.
JavaScript
mit
amwmedia/node-plop,amwmedia/node-plop,amwmedia/node-plop
--- +++ @@ -14,10 +14,11 @@ const plop = plopBase(); const runner = generatorRunner(plop); - plopfilePath = path.resolve(plopfilePath); - - plop.setPlopfilePath(plopfilePath); - require(plopfilePath)(plop); + if (plopfilePath) { + plopfilePath = path.resolve(plopfilePath); + plop.setPlopfilePath(plopfilePath); + require(plopfilePath)(plop); + } ///// // external API for node-plop @@ -31,6 +32,7 @@ runPrompts: () => runner.runGeneratorPrompts(genObject) }); }, + setGenerator: plop.setGenerator, runActions: runner.runGeneratorActions, runPrompts: runner.runGeneratorPrompts };
ebbffa2dde972b267f70677adc60a21c89c07b8e
src/index.js
src/index.js
import React from 'react' import { render } from 'react-dom' import './index.css' import '../semantic/dist/semantic.min.css'; import Exame from './Exame.js' import Result from './Result.js' import { Route, BrowserRouter } from 'react-router-dom' let TO_ANSWER_GROUPS = require('.//GROUP_DEFINITION.json') render( <BrowserRouter> <div> <Route exact path="/" component={() => <Exame groups={TO_ANSWER_GROUPS}></Exame>}/> <Route path="/result" component={Result}/> </div> </BrowserRouter>, document.getElementById('root') )
import React from 'react' import { render } from 'react-dom' import './index.css' import '../semantic/dist/semantic.min.css'; import Exame from './Exame.js' import Result from './Result.js' import { Route, HashRouter } from 'react-router-dom' let TO_ANSWER_GROUPS = require('.//GROUP_DEFINITION.json') render( <HashRouter> <div> <Route exact path="/" component={() => <Exame groups={TO_ANSWER_GROUPS}></Exame>}/> <Route path="/result" component={Result}/> </div> </HashRouter>, document.getElementById('root') )
Use HashRouter for fix gh-page routing.
Use HashRouter for fix gh-page routing.
JavaScript
mit
wallat/little-test,wallat/little-test
--- +++ @@ -5,16 +5,16 @@ import Exame from './Exame.js' import Result from './Result.js' -import { Route, BrowserRouter } from 'react-router-dom' +import { Route, HashRouter } from 'react-router-dom' let TO_ANSWER_GROUPS = require('.//GROUP_DEFINITION.json') render( - <BrowserRouter> + <HashRouter> <div> <Route exact path="/" component={() => <Exame groups={TO_ANSWER_GROUPS}></Exame>}/> <Route path="/result" component={Result}/> </div> - </BrowserRouter>, + </HashRouter>, document.getElementById('root') )
bc24c5e0a2abc2f89c98f66ea19b632d3248c64b
frontend/app/components/bar-graph.js
frontend/app/components/bar-graph.js
import Ember from 'ember'; export default Ember.Component.extend({ didInsertElement() { Chart.defaults.global.responsive = true; Chart.defaults.global.legend.display =false }, didRender() { let data = this.get('data'); let toGraph = { labels: [], datasets: [{ data: [] }] } data.forEach(item => { toGraph.labels.push(item.get('name')); toGraph.datasets[0].data.push(item.get('value')); }); let options = { type: 'bar', data: toGraph, options: { scales: { yAxes: [ { ticks: {beginAtZero: true} } ] } } } console.log(this.elementId); let ctx = this.$().children(".bar-chart").first();//.getContext('2d'); let statsChart = new Chart(ctx, options); } });
import Ember from 'ember'; export default Ember.Component.extend({ didInsertElement() { Chart.defaults.global.responsive = true; Chart.defaults.global.legend.display =false }, didRender() { let data = this.get('data'); let toGraph = { labels: [], datasets: [{ data: [] }] } data.forEach(item => { toGraph.labels.push(item.get('name')); toGraph.datasets[0].data.push(item.get('value')); }); let options = { type: 'bar', data: toGraph, options: { scales: { yAxes: [ { ticks: {beginAtZero: true} } ] } } } let ctx = this.$().children(".bar-chart").first();//.getContext('2d'); let statsChart = new Chart(ctx, options); } });
Remove console logging from figuring out graphjs.
Remove console logging from figuring out graphjs.
JavaScript
mit
ThreeDRadio/playlists,ThreeDRadio/playlists,ThreeDRadio/playlists
--- +++ @@ -36,7 +36,6 @@ } } } - console.log(this.elementId); let ctx = this.$().children(".bar-chart").first();//.getContext('2d'); let statsChart = new Chart(ctx, options); }
d5e55241a66d37f45b0404be3d4e1d0f85715573
src/store.js
src/store.js
/** @babel */ import { applyMiddleware, createStore } from 'redux' import createLogger from 'redux-logger' import createSagaMiddleware from 'redux-saga' import reducers, { initialState } from './reducers' import rootSaga from './sagas' import { isAtomInDebugMode } from './debug' const saga = createSagaMiddleware() let middlewares = [saga] if (isAtomInDebugMode) { const logger = createLogger({ collapsed: true }) middlewares.push(logger) } export const store = createStore( reducers, applyMiddleware(...middlewares) ) saga.run(rootSaga, initialState)
/** @babel */ import { applyMiddleware, createStore } from 'redux' import createLogger from 'redux-logger' import createSagaMiddleware from 'redux-saga' import reducers, { initialState } from './reducers' import rootSaga from './sagas' import { isAtomInDebugMode } from './debug' const saga = createSagaMiddleware() let middlewares = [saga] if (isAtomInDebugMode()) { const logger = createLogger({ collapsed: true }) middlewares.push(logger) } export const store = createStore( reducers, applyMiddleware(...middlewares) ) saga.run(rootSaga, initialState)
Use loggin on debug mode
Improve(debug): Use loggin on debug mode
JavaScript
mit
sanack/atom-jq
--- +++ @@ -9,7 +9,7 @@ const saga = createSagaMiddleware() let middlewares = [saga] -if (isAtomInDebugMode) { +if (isAtomInDebugMode()) { const logger = createLogger({ collapsed: true }) middlewares.push(logger) }
d8fff58a630c053f4a5706a7022ab2f3589200f6
app/routes.js
app/routes.js
var express = require('express'); var router = express.Router(); var TaxonPresenter = require('./presenters/taxon-presenter.js'); router.get('/', function (req, res) { res.render('index'); }); router.get('/tabbed/:taxonSlug', function (req, res) { var presenter = new TaxonPresenter(req, 'all'); res.render(presenter.viewTemplateName, presenter); }); router.get('/mvp/:taxonSlug', function (req, res) { var presenter = new TaxonPresenter(req, 'all'); res.render(presenter.viewTemplateName, presenter); }); router.get('/tabless/:taxonSlug', function (req, res) { var presenter = new TaxonPresenter(req, 'base'); presenter.curatedContent = presenter.allContent.slice(4); presenter.latestContent = presenter.allContent.slice(-3).reverse(); res.render(presenter.viewTemplateName, presenter); }); module.exports = router;
var express = require('express'); var router = express.Router(); var TaxonPresenter = require('./presenters/taxon-presenter.js'); router.get('/', function (req, res) { res.render('index'); }); router.get('/tabbed/:taxonSlug', function (req, res) { var presenter = new TaxonPresenter(req, 'all'); res.render(presenter.viewTemplateName, presenter); }); router.get('/mvp/:taxonSlug', function (req, res) { var presenter = new TaxonPresenter(req, 'all'); res.render(presenter.viewTemplateName, presenter); }); router.get('/tabless/:taxonSlug', function (req, res) { var presenter = new TaxonPresenter(req, 'base'); presenter.curatedContent = presenter.allContent.slice(0,3); presenter.latestContent = presenter.allContent.slice(-3).reverse(); res.render(presenter.viewTemplateName, presenter); }); module.exports = router;
Fix item list length bug when rendering tabless design
Fix item list length bug when rendering tabless design
JavaScript
mit
alphagov/govuk-navigation-prototype,alphagov/govuk-navigation-prototype,alphagov/govuk-navigation-prototype,alphagov/govuk-navigation-prototype
--- +++ @@ -19,7 +19,7 @@ router.get('/tabless/:taxonSlug', function (req, res) { var presenter = new TaxonPresenter(req, 'base'); - presenter.curatedContent = presenter.allContent.slice(4); + presenter.curatedContent = presenter.allContent.slice(0,3); presenter.latestContent = presenter.allContent.slice(-3).reverse(); res.render(presenter.viewTemplateName, presenter); });
825828d319b65a1027f18b42bac80c7d0a89869f
src/index.js
src/index.js
import React, { Component } from 'react' import PropTypes from 'prop-types' export const getContextualizer = (propTypes, targetProp) => { class ContextProps extends Component { getChildContext () { const props = Object.keys(this.props).reduce((x, key) => { if (key !== 'children') { x[key] = this.props[key] } return x }, {}) return targetProp ? { [targetProp]: props } : props } render () { return <span>{this.props.children}</span> } } ContextProps.displayName = 'ContextProps' ContextProps.childContextTypes = targetProp ? { [targetProp]: PropTypes.shape(propTypes) } : propTypes return ContextProps } export const withPropsFromContext = propList => Target => { class WithPropsFromContext extends Component { render () { const props = { ...propList.reduce((x, prop) => { x[prop] = this.context[prop] return x }, {}), ...this.props } return <Target {...props} /> } } WithPropsFromContext.contextTypes = propList.reduce((x, prop) => { x[prop] = PropTypes.any return x }, {}) WithPropsFromContext.displayName = Target.displayName || Target.name return WithPropsFromContext }
import React, { Component } from 'react' import PropTypes from 'prop-types' export const getContextualizer = (propTypes, targetProp) => { class ContextProps extends Component { getChildContext () { const props = Object.keys(this.props).reduce((x, key) => { if (key !== 'children') { x[key] = this.props[key] } return x }, {}) return targetProp ? { [targetProp]: props } : props } render () { return <span>{this.props.children}</span> } } ContextProps.displayName = 'ContextProps' ContextProps.childContextTypes = targetProp ? { [targetProp]: PropTypes.shape(propTypes) } : propTypes return ContextProps } export const withPropsFromContext = propList => Target => { class WithPropsFromContext extends Component { render () { const props = { ...propList.reduce((x, prop) => { x[prop] = this.context[prop] return x }, {}), ...this.props } return <Target {...props} /> } } WithPropsFromContext.contextTypes = propList.reduce((x, prop) => { x[prop] = PropTypes.any return x }, {}) WithPropsFromContext.displayName = `withPropsFromContext(${Target.displayName || Target.name})` return WithPropsFromContext }
Update displayName of wrapped component to include HoC name
Update displayName of wrapped component to include HoC name
JavaScript
unlicense
xaviervia/react-context-props,xaviervia/react-context-props
--- +++ @@ -49,7 +49,7 @@ return x }, {}) - WithPropsFromContext.displayName = Target.displayName || Target.name + WithPropsFromContext.displayName = `withPropsFromContext(${Target.displayName || Target.name})` return WithPropsFromContext }
987768c4c78761ed5b827131f10b4a9d6e79fc12
src/index.js
src/index.js
const { createLogger, LEVELS: { INFO } } = require('./loggers') const logFunctionConsole = require('./loggers/console') const Cluster = require('./cluster') const createProducer = require('./producer') const createConsumer = require('./consumer') module.exports = class Client { constructor({ brokers, ssl, sasl, clientId, connectionTimeout, retry, logLevel = INFO, logFunction = logFunctionConsole, }) { this.logger = createLogger({ level: logLevel, logFunction }) this.cluster = new Cluster({ logger: this.logger, brokers, ssl, sasl, clientId, connectionTimeout, retry, }) } producer({ createPartitioner, retry } = {}) { return createProducer({ cluster: this.cluster, logger: this.logger, createPartitioner, retry, }) } consumer({ groupId, createPartitionAssigner, sessionTimeout, retry } = {}) { return createConsumer({ cluster: this.cluster, logger: this.logger, groupId, createPartitionAssigner, sessionTimeout, retry, }) } }
const { createLogger, LEVELS: { INFO } } = require('./loggers') const logFunctionConsole = require('./loggers/console') const Cluster = require('./cluster') const createProducer = require('./producer') const createConsumer = require('./consumer') module.exports = class Client { constructor({ brokers, ssl, sasl, clientId, connectionTimeout, retry, logLevel = INFO, logFunction = logFunctionConsole, }) { this.logger = createLogger({ level: logLevel, logFunction }) this.createCluster = () => new Cluster({ logger: this.logger, brokers, ssl, sasl, clientId, connectionTimeout, retry, }) } /** * @public */ producer({ createPartitioner, retry } = {}) { return createProducer({ cluster: this.createCluster(), logger: this.logger, createPartitioner, retry, }) } /** * @public */ consumer({ groupId, createPartitionAssigner, sessionTimeout, retry } = {}) { return createConsumer({ cluster: this.createCluster(), logger: this.logger, groupId, createPartitionAssigner, sessionTimeout, retry, }) } }
Create different instances of the cluster for producers and consumers
Create different instances of the cluster for producers and consumers
JavaScript
mit
tulios/kafkajs,tulios/kafkajs,tulios/kafkajs,tulios/kafkajs
--- +++ @@ -16,29 +16,36 @@ logFunction = logFunctionConsole, }) { this.logger = createLogger({ level: logLevel, logFunction }) - this.cluster = new Cluster({ - logger: this.logger, - brokers, - ssl, - sasl, - clientId, - connectionTimeout, - retry, - }) + this.createCluster = () => + new Cluster({ + logger: this.logger, + brokers, + ssl, + sasl, + clientId, + connectionTimeout, + retry, + }) } + /** + * @public + */ producer({ createPartitioner, retry } = {}) { return createProducer({ - cluster: this.cluster, + cluster: this.createCluster(), logger: this.logger, createPartitioner, retry, }) } + /** + * @public + */ consumer({ groupId, createPartitionAssigner, sessionTimeout, retry } = {}) { return createConsumer({ - cluster: this.cluster, + cluster: this.createCluster(), logger: this.logger, groupId, createPartitionAssigner,
d6a2545ab672c59f66b13570a7d809483cd7e78e
src/index.js
src/index.js
/** * Returns a very important number. * * @returns {number} - The number. */ export default function theDefaultExport() { return 40; } /** * Value that can be incremented. * * @type {number} */ export let value = 0; /** * Increments the value by one. */ export function incrementValue() { value++; } /** * Returns a cool value. * * @returns {string} The cool value. */ export function feature() { return 'cool'; } /** * Returns something. * * @returns {string} - Something. */ export function something() { return 'something'; }
/** * Returns a very important number. * * @returns {number} - The number. */ export default function theDefaultExport() { return 42; } /** * Value that can be incremented. * * @type {number} */ export let value = 0; /** * Increments the value by one. */ export function incrementValue() { value++; } /** * Returns a cool value. * * @returns {string} The cool value. */ export function feature() { return 'cool'; } /** * Returns something. * * @returns {string} - Something. */ export function something() { return 'something'; }
Revert "test: make test fail"
Revert "test: make test fail" This reverts commit 6e23d7e72ae9379a18b756d609985065a840b3d7.
JavaScript
mit
cheminfo-js/test
--- +++ @@ -4,7 +4,7 @@ * @returns {number} - The number. */ export default function theDefaultExport() { - return 40; + return 42; } /**
ab9f0b13f4a8e07d4e255a856fcc2ae2c0e4a456
src/index.js
src/index.js
import React from 'react'; import ReactDOM from 'react-dom'; // Create a new component to produce some html const App = function () { // const means that this is the final value. Here we are making a component. return <div>Hello!</div>; // This is JSX, which gets transpiled to javascript. // Test here: http://babeljs.io/repl } // Put the component HTML into the DOM ReactDOM.render(<App />, document.querySelector('.container')); // To make an instance of the App class, we wrap it in a JSX tag
import React from 'react'; import ReactDOM from 'react-dom'; // Create a new component to produce some html const App = () => { // const means that this is the final value. Here we are making a component. return <div>Hello!</div>; // This is JSX, which gets transpiled to javascript. // Test here: http://babeljs.io/repl } // Put the component HTML into the DOM ReactDOM.render(<App />, document.querySelector('.container')); // To make an instance of the App class, we wrap it in a JSX tag
Use ES6 syntax fat arrow instead of using 'function'
Use ES6 syntax fat arrow instead of using 'function'
JavaScript
mit
phirefly/react-redux-starter,phirefly/react-redux-starter
--- +++ @@ -2,7 +2,7 @@ import ReactDOM from 'react-dom'; // Create a new component to produce some html -const App = function () { // const means that this is the final value. Here we are making a component. +const App = () => { // const means that this is the final value. Here we are making a component. return <div>Hello!</div>; // This is JSX, which gets transpiled to javascript. // Test here: http://babeljs.io/repl }
d86544c4df922080939dc057f7b682298b13a6d6
src/index.js
src/index.js
import h from 'snabbdom/h' import extend from 'extend' const sanitizeProps = (props) => { props = props === null ? {} : props Object.keys(props).map((prop) => { const keysRiver = prop.split('-').reverse() if(keysRiver.length > 1) { let newObject = keysRiver.reduce( (object, key) => ({ [key]: object }), props[prop] ) extend(true, props, newObject) delete props[prop] } else if (!(['class', 'props', 'attrs', 'style', 'on', 'hook', 'key'].indexOf(prop) > -1)) { extend(true, props, {props: { [prop]: props[prop] } }) delete props[prop] } }) return props } const sanitizeChilds = (children) => { return children.length === 1 && typeof children[0] === 'string' ? children[0] : children } export const createElement = (type, props, ...children) => { return h(type, sanitizeProps(props), sanitizeChilds(children)) } export default { createElement }
import h from 'snabbdom/h' import extend from 'extend' const sanitizeProps = (props) => { props = props === null ? {} : props Object.keys(props).map((prop) => { const keysRiver = prop.split('-').reverse() if(keysRiver.length > 1) { let newObject = keysRiver.reduce( (object, key) => ({ [key]: object }), props[prop] ) extend(true, props, newObject) delete props[prop] } else if (!(['class', 'props', 'attrs', 'style', 'on', 'hook', 'key'].indexOf(prop) > -1)) { extend(true, props, {props: { [prop]: props[prop] } }) delete props[prop] } }) return props } const sanitizeChilds = (children) => { return children.length === 1 && typeof children[0] === 'string' ? children[0] : children } export const createElement = (type, props, ...children) => { return (typeof type === 'function') ? type(props, children) : h(type, sanitizeProps(props), sanitizeChilds(children)) } export default { createElement }
Add component as function support
Add component as function support
JavaScript
mit
Swizz/snabbdom-pragma
--- +++ @@ -39,7 +39,10 @@ export const createElement = (type, props, ...children) => { - return h(type, sanitizeProps(props), sanitizeChilds(children)) + + return (typeof type === 'function') ? + type(props, children) : + h(type, sanitizeProps(props), sanitizeChilds(children)) }
069158e6356e3a58a8c41191a5d00f2afeac0bba
src/index.js
src/index.js
import { createFilter } from 'rollup-pluginutils'; import { resolve as resolveSourceMap } from 'source-map-resolve'; import { readFile } from 'fs'; export default function sourcemaps({ include, exclude } = {}) { const filter = createFilter(include, exclude); return { name: 'sourcemaps', load(id) { if (!filter(id)) { return null; } return new Promise(resolve => { readFile(id, 'utf8', (err, code) => { if (err) { // Failed reading file, let the next plugin deal with it resolve(null); } else { resolveSourceMap(code, id, readFile, (err, sourceMap) => { if (err || sourceMap === null) { // Either something went wrong, or there was no source map resolve(code); } else { const { map, sourcesContent } = sourceMap; map.sourcesContent = sourcesContent; resolve({ code, map }); } }); } }); }); }, }; }
import { createFilter } from 'rollup-pluginutils'; import { resolve as resolveSourceMap } from 'source-map-resolve'; import * as fs from 'fs'; export default function sourcemaps({ include, exclude, readFile = fs.readFile } = {}) { const filter = createFilter(include, exclude); return { name: 'sourcemaps', load(id) { if (!filter(id)) { return null; } return new Promise(resolve => { readFile(id, 'utf8', (err, code) => { if (err) { // Failed reading file, let the next plugin deal with it resolve(null); } else { resolveSourceMap(code, id, readFile, (err, sourceMap) => { if (err || sourceMap === null) { // Either something went wrong, or there was no source map resolve(code); } else { const { map, sourcesContent } = sourceMap; map.sourcesContent = sourcesContent; resolve({ code, map }); } }); } }); }); }, }; }
Add the ability to override the readFile function
Add the ability to override the readFile function
JavaScript
mit
maxdavidson/rollup-plugin-sourcemaps,maxdavidson/rollup-plugin-sourcemaps
--- +++ @@ -1,8 +1,8 @@ import { createFilter } from 'rollup-pluginutils'; import { resolve as resolveSourceMap } from 'source-map-resolve'; -import { readFile } from 'fs'; +import * as fs from 'fs'; -export default function sourcemaps({ include, exclude } = {}) { +export default function sourcemaps({ include, exclude, readFile = fs.readFile } = {}) { const filter = createFilter(include, exclude); return {
a6f9255f268d8b17d2820aa0cc32a18cee3f778f
.postcssrc.js
.postcssrc.js
module.exports = { plugins: { '@wearegenki/ui-postcss': {}, }, };
module.exports = { plugins: { '@wearegenki/ui-postcss': {}, }, }; // TODO: Put this in the docs (both ways, depending on array or object type of config): // https://github.com/michael-ciniawsky/postcss-load-config // const { uiPostcssPreset } = require('@wearegenki/ui'); // module.exports = { // plugins: [ // uiPostcssPreset({ // // importPath: ['src'], // mixinsDir: 'src/css/mixins', // // verbose: true, // }), // ], // }; // module.exports = { // plugins: { // '@wearegenki/ui-postcss': { // // importPath: ['src'], // mixinsDir: 'src/css/mixins', // // verbose: true, // }, // }, // };
Add comments about ui-postcss in docs
Add comments about ui-postcss in docs
JavaScript
isc
WeAreGenki/wag-ui
--- +++ @@ -3,3 +3,29 @@ '@wearegenki/ui-postcss': {}, }, }; + +// TODO: Put this in the docs (both ways, depending on array or object type of config): + +// https://github.com/michael-ciniawsky/postcss-load-config + +// const { uiPostcssPreset } = require('@wearegenki/ui'); + +// module.exports = { +// plugins: [ +// uiPostcssPreset({ +// // importPath: ['src'], +// mixinsDir: 'src/css/mixins', +// // verbose: true, +// }), +// ], +// }; + +// module.exports = { +// plugins: { +// '@wearegenki/ui-postcss': { +// // importPath: ['src'], +// mixinsDir: 'src/css/mixins', +// // verbose: true, +// }, +// }, +// };
358d2a9b5d2959031fa685045a9f1a07f2d27c78
client.src/shared/views/gistbook-view/views/text/edit/index.js
client.src/shared/views/gistbook-view/views/text/edit/index.js
// // textEditView // Modify text based on a textarea // import ItemView from 'base/item-view'; export default ItemView.extend({ template: 'editTextView', tagName: 'textarea', className: 'gistbook-textarea', // Get the value of the element value() { return this.el.value; } });
// // textEditView // Modify text based on a textarea // import ItemView from 'base/item-view'; export default ItemView.extend({ template: 'editTextView', tagName: 'textarea', className: 'gistbook-textarea', // Get the value of the element, // stripping line breaks from the // start and end value() { return this.el.value.replace(/^\s+|\s+$/g, ''); } });
Remove new lines from text areas on save.
Remove new lines from text areas on save. Resolves #390
JavaScript
mit
jmeas/gistbook,joshbedo/gistbook
--- +++ @@ -12,8 +12,10 @@ className: 'gistbook-textarea', - // Get the value of the element + // Get the value of the element, + // stripping line breaks from the + // start and end value() { - return this.el.value; + return this.el.value.replace(/^\s+|\s+$/g, ''); } });
5aa339bb60364eb0c43690c907cc391788811a24
src/index.js
src/index.js
/* eslint-disable no-console */ import { createFilter } from 'rollup-pluginutils'; import { resolveSourceMap } from 'source-map-resolve'; import { readFile } from 'fs'; import { promisify } from './utils'; const readFileAsync = promisify(readFile); const resolveSourceMapAsync = promisify(resolveSourceMap); export default function sourcemaps({ include, exclude } = {}) { const filter = createFilter(include, exclude); return { async load(id) { if (!filter(id)) { return null; } let code; try { code = await readFileAsync(id, 'utf8'); } catch (err) { // Failed, let Rollup deal with it return null; } let sourceMap; try { sourceMap = await resolveSourceMapAsync(code, id, readFile); } catch (err) { console.error(`rollup-plugin-sourcemaps: Failed resolving source map from ${id}: ${err}`); return code; } // No source map detected, return code if (sourceMap === null) { return code; } const { map } = sourceMap; return { code, map }; }, }; }
/* eslint-disable no-console */ import { createFilter } from 'rollup-pluginutils'; import { resolve } from 'source-map-resolve'; import { readFile } from 'fs'; import { promisify } from './utils'; const readFileAsync = promisify(readFile); const resolveSourceMapAsync = promisify(resolve); export default function sourcemaps({ include, exclude } = {}) { const filter = createFilter(include, exclude); return { async load(id) { if (!filter(id)) { return null; } let code; try { code = await readFileAsync(id, 'utf8'); } catch (err) { // Failed, let Rollup deal with it return null; } let sourceMap; try { sourceMap = await resolveSourceMapAsync(code, id, readFile); } catch (err) { console.error(`rollup-plugin-sourcemaps: Failed resolving source map from ${id}: ${err}`); return code; } // No source map detected, return code if (sourceMap === null) { return code; } const { map, sourcesContent } = sourceMap; map.sourcesContent = sourcesContent; return { code, map }; }, }; }
Include sourcesContent in source map
Include sourcesContent in source map
JavaScript
mit
maxdavidson/rollup-plugin-sourcemaps,maxdavidson/rollup-plugin-sourcemaps
--- +++ @@ -1,11 +1,11 @@ /* eslint-disable no-console */ import { createFilter } from 'rollup-pluginutils'; -import { resolveSourceMap } from 'source-map-resolve'; +import { resolve } from 'source-map-resolve'; import { readFile } from 'fs'; import { promisify } from './utils'; const readFileAsync = promisify(readFile); -const resolveSourceMapAsync = promisify(resolveSourceMap); +const resolveSourceMapAsync = promisify(resolve); export default function sourcemaps({ include, exclude } = {}) { const filter = createFilter(include, exclude); @@ -37,7 +37,9 @@ return code; } - const { map } = sourceMap; + const { map, sourcesContent } = sourceMap; + + map.sourcesContent = sourcesContent; return { code, map }; },
fbd3bd5365b8dd1b6f4773e22f7b94fe4126acfa
src/index.js
src/index.js
import React from 'react'; import { render } from 'react-dom'; import { Provider } from "react-redux"; import { createStore, applyMiddleware } from "redux"; import thunk from "redux-thunk"; import App from "./containers/App"; import rootReducer from "./reducers"; import { getTodosIfNeeded } from "./actions"; const createStoreWithMiddleware = applyMiddleware(thunk)(createStore); const store = createStoreWithMiddleware(rootReducer) store.dispatch(getTodosIfNeeded()) render( <Provider store={store}> <App /> </Provider>, document.querySelector('#root') );
import React from 'react'; import { render } from 'react-dom'; import { Provider } from "react-redux"; import { createStore, applyMiddleware } from "redux"; import thunk from "redux-thunk"; import injectTapEventPlugin from "react-tap-event-plugin"; import App from "./containers/App"; import rootReducer from "./reducers"; import { getTodosIfNeeded } from "./actions"; const createStoreWithMiddleware = applyMiddleware(thunk)(createStore); const store = createStoreWithMiddleware(rootReducer) store.dispatch(getTodosIfNeeded()) injectTapEventPlugin(); render( <Provider store={store}> <App /> </Provider>, document.querySelector('#root') );
Add react tap event plugin
Add react tap event plugin
JavaScript
mit
alice02/go-todoapi,alice02/go-todoapi,alice02/go-todoapi
--- +++ @@ -3,6 +3,7 @@ import { Provider } from "react-redux"; import { createStore, applyMiddleware } from "redux"; import thunk from "redux-thunk"; +import injectTapEventPlugin from "react-tap-event-plugin"; import App from "./containers/App"; import rootReducer from "./reducers"; import { getTodosIfNeeded } from "./actions"; @@ -11,6 +12,7 @@ const store = createStoreWithMiddleware(rootReducer) store.dispatch(getTodosIfNeeded()) +injectTapEventPlugin(); render( <Provider store={store}>
1481d1905b237c768d45335cc431d567f5676d87
src/index.js
src/index.js
//Get the required shit together const config = require("./config.json"); const Discord = require("discord.js"); const client = new Discord.Client(); const MSS = require("./functions/"); const fs = require("fs"); var command = []; //Login to Discord client.login(config.API.discord); //Include all files in the commands directory fs.readdir("./commands/", function(err, items) { items.forEach(function(item) { var file = item.replace(/['"]+/g, ''); command[file] = require(file); }) }) client.on('ready', function() { console.log("Successfully connected to Discord!"); client.user.setGame(config.MSS.prefix + "help | " + config.MSS.version); }); client.on('message', function(message) { if (!message.content.startsWith(config.MSS.prefix)) return false; let input = message.content.replace (/\n/g, "").split(" "); input[0] = input[0].substring(config.MSS.prefix.length); if (input[0] === "eval" && message.author.id === "190519304972664832") { eval(message.content.substring(config.MSS.prefix.length + input[0].length + 1)); } });
//Get the required shit together const config = require("./config.json"); const Discord = require("discord.js"); const client = new Discord.Client(); const MSS = require("./functions/"); const fs = require("fs"); var command = []; //Login to Discord client.login(config.API.discord); //Include all files in the commands directory fs.readdir("./commands/", function(err, items) { items.forEach(function(item) { var file = item.replace(/['"]+/g, ''); command[file] = require("./commands/" + file); }) }) client.on('ready', function() { console.log("Successfully connected to Discord!"); client.user.setGame(config.MSS.prefix + "help | " + config.MSS.version); }); client.on('message', function(message) { if (!message.content.startsWith(config.MSS.prefix)) return false; let input = message.content.replace (/\n/g, "").split(" "); input[0] = input[0].substring(config.MSS.prefix.length); if (input[0] === "eval" && message.author.id === "190519304972664832") { eval(message.content.substring(config.MSS.prefix.length + input[0].length + 1)); } });
Include from the functions directory
Include from the functions directory
JavaScript
mit
moustacheminer/MSS-Discord,moustacheminer/MSS-Discord,moustacheminer/MSS-Discord
--- +++ @@ -13,7 +13,7 @@ fs.readdir("./commands/", function(err, items) { items.forEach(function(item) { var file = item.replace(/['"]+/g, ''); - command[file] = require(file); + command[file] = require("./commands/" + file); }) })
25e28e9795aee56e9d7acdb09b362c30ee7dad15
src/index.js
src/index.js
define([ "text!src/templates/command.html" ], function(commandTemplate) { var commands = codebox.require("core/commands"); var dialogs = codebox.require("utils/dialogs"); commands.register({ id: "palette.open", title: "Open Command Palette", shortcuts: [ "mod+shift+p" ], run: function() { return dialogs.list(commands, { template: commandTemplate, filter: function(command) { return command.get("palette") !== false && command.isValidContext(); } }) .then(function(command) { return command.run(); }); } }); });
define([ "text!src/templates/command.html" ], function(commandTemplate) { var commands = codebox.require("core/commands"); var dialogs = codebox.require("utils/dialogs"); commands.register({ id: "palette.open", title: "Command Palette: Open", shortcuts: [ "mod+shift+p" ], palette: false, run: function() { return dialogs.list(commands, { template: commandTemplate, filter: function(command) { return command.get("palette") !== false && command.isValidContext(); } }) .then(function(command) { return command.run(); }); } }); });
Change command title and hide from palette
Change command title and hide from palette
JavaScript
apache-2.0
etopian/codebox-package-command-palette,CodeboxIDE/package-command-palette,CodeboxIDE/package-command-palette,etopian/codebox-package-command-palette
--- +++ @@ -6,10 +6,11 @@ commands.register({ id: "palette.open", - title: "Open Command Palette", + title: "Command Palette: Open", shortcuts: [ "mod+shift+p" ], + palette: false, run: function() { return dialogs.list(commands, { template: commandTemplate,
453d61337dda06c15130b9783b39ce0e58979c86
src/index.js
src/index.js
import React from "react"; import { render } from "react-dom"; import Root from "./Root"; render( React.createElement(Root), document.getElementById("root") );
import React from "react"; import { render } from "react-dom"; import "./index.css"; import Root from "./Root"; render( React.createElement(Root), document.getElementById("root") );
Fix missing root css import
Fix missing root css import
JavaScript
apache-2.0
nwsapps/flashcards,nwsapps/flashcards
--- +++ @@ -1,5 +1,6 @@ import React from "react"; import { render } from "react-dom"; +import "./index.css"; import Root from "./Root"; render(
6f8019e821d94975cfab7e62c1557af4254be72e
src/index.js
src/index.js
import React from 'react' import { render } from 'react-dom' import createStore from './createStore' const store = createStore() render( <h1>Hello from React</h1>, document.getElementById('react') )
import React from 'react' import { render } from 'react-dom' import createStore from './createStore' import App from './components/App' const store = createStore() render( <App />, document.getElementById('react') )
Use App component in render
Use App component in render
JavaScript
mit
epicsharp/react-boilerplate,epicsharp/react-boilerplate,RSS-Dev/live-html,RSS-Dev/live-html
--- +++ @@ -1,10 +1,11 @@ import React from 'react' import { render } from 'react-dom' import createStore from './createStore' +import App from './components/App' const store = createStore() render( - <h1>Hello from React</h1>, + <App />, document.getElementById('react') )
61c69d309ad8d80812b3467697ef52ead021249a
src/utils.js
src/utils.js
import pf from 'portfinder'; export function homedir() { return process.env[(process.platform === 'win32') ? 'USERPROFILE' : 'HOME']; } export function wait (time) { return new Promise(resolve => { setTimeout(() => resolve(), time); }); } export function getPort () { return new Promise((resolve, reject) => { pf.getPort((err, port) => { if (err) return reject(err); resolve(port); }); }); }
import fs from 'fs'; import pf from 'portfinder'; export function homedir() { return process.env[(process.platform === 'win32') ? 'USERPROFILE' : 'HOME']; } export function wait (time) { return new Promise(resolve => { setTimeout(() => resolve(), time); }); } export function getPort () { return new Promise((resolve, reject) => { pf.getPort({ host: '127.0.0.1' }, (err, port) => { if (err) return reject(err); resolve(port); }); }); } export function readFile (filename) { return new Promise((resolve, reject) => { fs.readFile(filename, (err, data) => { if (err) return reject(err); resolve(data); }); }); }
Fix getPort and add readFile
Fix getPort and add readFile getPort was considering bind to 0.0.0.0 instead of 127.0.0.1. readFile added to provide a promise-based version of fs.readFile
JavaScript
mit
sqlectron/sqlectron-term
--- +++ @@ -1,3 +1,4 @@ +import fs from 'fs'; import pf from 'portfinder'; @@ -15,9 +16,19 @@ export function getPort () { return new Promise((resolve, reject) => { - pf.getPort((err, port) => { + pf.getPort({ host: '127.0.0.1' }, (err, port) => { if (err) return reject(err); resolve(port); }); }); } + + +export function readFile (filename) { + return new Promise((resolve, reject) => { + fs.readFile(filename, (err, data) => { + if (err) return reject(err); + resolve(data); + }); + }); +}
a2136a83a4c7eeb988da2a2c1833fd16d4828632
extensions/roc-plugin-dredd/src/roc/index.js
extensions/roc-plugin-dredd/src/roc/index.js
import { lazyFunctionRequire } from 'roc'; import config from '../config/roc.config.js'; import meta from '../config/roc.config.meta.js'; const lazyRequire = lazyFunctionRequire(require); export default { config, meta, actions: [ { hook: 'server-started', description: 'Run dredd tests', action: lazyRequire('../actions/dredd'), }, ], commands: { development: { dredd: { command: lazyRequire('../commands/dredd'), description: 'Runs dredd in current project', settings: true, }, }, }, hooks: { 'run-dev-command': { description: 'Used to start dev server used for dredd testing', }, }, };
import { lazyFunctionRequire } from 'roc'; import config from '../config/roc.config.js'; import meta from '../config/roc.config.meta.js'; const lazyRequire = lazyFunctionRequire(require); export default { config, meta, actions: [ { hook: 'server-started', description: 'Run dredd tests', action: lazyRequire('../actions/dredd'), }, ], commands: { development: { dredd: { command: lazyRequire('../commands/dredd'), description: 'Runs dredd in current project', }, }, }, hooks: { 'run-dev-command': { description: 'Used to start dev server used for dredd testing', }, }, };
Remove superflous settings option on dredd command
Remove superflous settings option on dredd command
JavaScript
mit
voldern/roc-plugin-dredd
--- +++ @@ -20,7 +20,6 @@ dredd: { command: lazyRequire('../commands/dredd'), description: 'Runs dredd in current project', - settings: true, }, }, },
83314d1d646ffa3ec5e668ecdc5ae0bbbabfaad8
app/scripts/collections/section.js
app/scripts/collections/section.js
define([ 'underscore', 'backbone', 'models/section', 'config' ], function (_, Backbone, Section, config) { 'use strict'; var SectionCollection = Backbone.Collection.extend({ model: Section, initialize: function(models, options) { if (options) { this.resume = options.resume; } this.fetched = false; this.listenTo(this, 'reset', function() { this.fetched = true }); }, url: function() { if (this.resume) { return config.domain + '/rez/resumes/' + this.resume.id + '/sections'; } else { return config.domain + '/rez/sections'; } }, parse: function(response, options) { return response.sections; } }); return SectionCollection; });
define([ 'underscore', 'backbone', 'models/section', 'config' ], function (_, Backbone, Section, config) { 'use strict'; var SectionCollection = Backbone.Collection.extend({ model: Section, initialize: function(models, options) { if (options) { this.resume = options.resume; } this.fetched = false; this.listenTo(this, 'reset', function() { this.fetched = true }); }, url: function() { return config.domain + '/rez/sections'; }, parse: function(response, options) { return response.sections; } }); return SectionCollection; });
Fix url to be not nested.
Fix url to be not nested.
JavaScript
mit
jmflannery/jackflannery.me,jmflannery/jackflannery.me,jmflannery/rez-backbone,jmflannery/rez-backbone
--- +++ @@ -16,11 +16,7 @@ }, url: function() { - if (this.resume) { - return config.domain + '/rez/resumes/' + this.resume.id + '/sections'; - } else { - return config.domain + '/rez/sections'; - } + return config.domain + '/rez/sections'; }, parse: function(response, options) {
7b3f810e466248d77218a3d59bd674386ff9bd97
src/DB/Mongo.js
src/DB/Mongo.js
var path = require('path'); var fs = require('extfs'); var mongoose = require('mongoose'); import { AbstractDB } from './AbstractDB'; import { Core } from '../Core/Core'; export class Mongo extends AbstractDB { constructor(uri, options) { super(uri, options); } /** * Connect to mongodb * * @return {Promise} */ connect() { this._linkMongoose(); return new Promise((resolve, reject) => { mongoose.connect(this.uri, this.options); this.connection = mongoose.connection; this.connection.on('connected', () => { this.isOpen = true; resolve(this.connection) }); this.connection.on('error', reject); }); } /** * Close connection with mongodb */ close() { this.isOpen = false; return this.connection.close(); } /** * If the app has mongoose installed, replace its mongoose module with the mongoose module of rode * * @private */ _linkMongoose() { var mongoosePath = path.join(__rodeBase, 'node_modules', 'mongoose'); var appMongoosePath = path.join(Core.instance.getPath('node_modules'), 'mongoose'); if (fs.existsSync(appMongoosePath)) { fs.removeSync(appMongoosePath); fs.symlinkSync(mongoosePath, appMongoosePath); } } }
var path = require('path'); var fs = require('extfs'); var mongoose = require('mongoose'); import { AbstractDB } from './AbstractDB'; import { Core } from '../Core/Core'; export class Mongo extends AbstractDB { constructor(uri, options) { super(uri, options); } /** * Connect to mongodb * * @return {Promise} */ connect() { this._linkMongoose(); return new Promise((resolve, reject) => { mongoose.connect(this.uri, this.options); this.connection = mongoose.connection; this.connection.on('connected', () => { this.isOpen = true; resolve(this.connection) }); this.connection.on('error', reject); }); } /** * Close connection with mongodb */ close() { this.isOpen = false; return this.connection.close(); } /** * If the app has mongoose installed, replace its mongoose module with the mongoose module of rode * * @private */ _linkMongoose() { var mongoosePath = path.join(__rodeBase, 'node_modules', 'mongoose'); var appMongoosePath = path.join(Core.instance.getPath('node_modules'), 'mongoose'); if (fs.existsSync(mongoosePath) && fs.existsSync(appMongoosePath)) { fs.removeSync(appMongoosePath); fs.symlinkSync(mongoosePath, appMongoosePath); } } }
Fix a bug if mongoose path does not exist
Fix a bug if mongoose path does not exist
JavaScript
mit
marian2js/rode
--- +++ @@ -44,7 +44,7 @@ _linkMongoose() { var mongoosePath = path.join(__rodeBase, 'node_modules', 'mongoose'); var appMongoosePath = path.join(Core.instance.getPath('node_modules'), 'mongoose'); - if (fs.existsSync(appMongoosePath)) { + if (fs.existsSync(mongoosePath) && fs.existsSync(appMongoosePath)) { fs.removeSync(appMongoosePath); fs.symlinkSync(mongoosePath, appMongoosePath); }
3221f816bc32adee59d03fd9b5549507384f5b08
test/disk.js
test/disk.js
var Disk = require( '../' ) var BlockDevice = require( 'blockdevice' ) var assert = require( 'assert' ) const DISK_IMAGE = __dirname + '/data/bootcamp-osx-win.bin' describe( 'Disk', function( t ) { var device = null var disk = null it( 'init block device', function() { assert.doesNotThrow( function() { device = new BlockDevice({ path: DISK_IMAGE, mode: 'r', blockSize: 512 }) }) }) it( 'init disk with device', function() { assert.doesNotThrow( function() { disk = new Disk( device ) }) }) it( 'disk.open()', function( next ) { disk.open( function( error ) { next( error ) }) }) it( 'repeat disk.open()', function( next ) { disk.open( function( error ) { next( error ) }) }) it( 'disk.close()', function( next ) { disk.close( function( error ) { next( error ) }) }) })
var Disk = require( '../' ) var BlockDevice = require( 'blockdevice' ) var assert = require( 'assert' ) ;[ 'apple-mac-osx-10.10.3.bin', 'bootcamp-osx-win.bin', 'usb-thumb-exfat.bin', 'usb-thumb-fat.bin' ].forEach( function( filename ) { const DISK_IMAGE = __dirname + '/data/' + filename describe( 'Disk ' + filename, function( t ) { var device = null var disk = null it( 'init block device', function() { assert.doesNotThrow( function() { device = new BlockDevice({ path: DISK_IMAGE, mode: 'r', blockSize: 512 }) }) }) it( 'init disk with device', function() { assert.doesNotThrow( function() { disk = new Disk( device ) }) }) it( 'disk.open()', function( next ) { disk.open( function( error ) { next( error ) }) }) it( 'repeat disk.open()', function( next ) { disk.open( function( error ) { next( error ) }) }) it( 'disk.close()', function( next ) { disk.close( function( error ) { next( error ) }) }) }) })
Update test: Run against all test images
Update test: Run against all test images
JavaScript
mit
jhermsmeier/node-disk
--- +++ @@ -2,45 +2,54 @@ var BlockDevice = require( 'blockdevice' ) var assert = require( 'assert' ) -const DISK_IMAGE = __dirname + '/data/bootcamp-osx-win.bin' - -describe( 'Disk', function( t ) { +;[ + 'apple-mac-osx-10.10.3.bin', + 'bootcamp-osx-win.bin', + 'usb-thumb-exfat.bin', + 'usb-thumb-fat.bin' +].forEach( function( filename ) { - var device = null - var disk = null + const DISK_IMAGE = __dirname + '/data/' + filename - it( 'init block device', function() { - assert.doesNotThrow( function() { - device = new BlockDevice({ - path: DISK_IMAGE, - mode: 'r', - blockSize: 512 + describe( 'Disk ' + filename, function( t ) { + + var device = null + var disk = null + + it( 'init block device', function() { + assert.doesNotThrow( function() { + device = new BlockDevice({ + path: DISK_IMAGE, + mode: 'r', + blockSize: 512 + }) }) }) + + it( 'init disk with device', function() { + assert.doesNotThrow( function() { + disk = new Disk( device ) + }) + }) + + it( 'disk.open()', function( next ) { + disk.open( function( error ) { + next( error ) + }) + }) + + it( 'repeat disk.open()', function( next ) { + disk.open( function( error ) { + next( error ) + }) + }) + + it( 'disk.close()', function( next ) { + disk.close( function( error ) { + next( error ) + }) + }) + }) - - it( 'init disk with device', function() { - assert.doesNotThrow( function() { - disk = new Disk( device ) - }) - }) - - it( 'disk.open()', function( next ) { - disk.open( function( error ) { - next( error ) - }) - }) - - it( 'repeat disk.open()', function( next ) { - disk.open( function( error ) { - next( error ) - }) - }) - - it( 'disk.close()', function( next ) { - disk.close( function( error ) { - next( error ) - }) - }) - + })
170248b70dfe6b4eb9eb476919c19fb98a2e88c8
examples/jquery/http-request.js
examples/jquery/http-request.js
// jQuery built with "grunt custom:-ajax/script,-ajax/jsonp,-css,-deprecated,-dimensions,-effects,-event,-event/alias,-offset,-wrap,-ready,-deferred,-exports/amd,-sizzle" // https://github.com/jquery/jquery#how-to-build-your-own-jquery var $ = require("./lib/jquery.min.js"); var MARGIN = 12; var page = tabris.create("Page", { title: "XMLHttpRequest", topLevel: true }); var createLabel = function(labelText) { tabris.create("Label", { text: labelText, markupEnabled: true, layoutData: {left: MARGIN, right: MARGIN, top: [page.children().last() || 0, MARGIN]} }).appendTo(page); }; $.getJSON("http://www.telize.com/geoip", function(json) { createLabel("The IP address is: " + json.ip); createLabel("Latitude: " + json.latitude); createLabel("Longitude: " + json.longitude); }); page.open();
// jQuery built with "grunt custom:-ajax/script,-ajax/jsonp,-css,-deprecated,-dimensions,-effects,-event,-event/alias,-offset,-wrap,-ready,-deferred,-exports/amd,-sizzle" // https://github.com/jquery/jquery#how-to-build-your-own-jquery var $ = require("./lib/jquery.min.js"); var MARGIN = 12; var page = tabris.create("Page", { title: "XMLHttpRequest", topLevel: true }); var createTextView = function(text) { tabris.create("TextView", { text: text, markupEnabled: true, layoutData: {left: MARGIN, right: MARGIN, top: [page.children().last() || 0, MARGIN]} }).appendTo(page); }; $.getJSON("http://www.telize.com/geoip", function(json) { createTextView("The IP address is: " + json.ip); createTextView("Latitude: " + json.latitude); createTextView("Longitude: " + json.longitude); }); page.open();
Rename "Label" to "TextView" in jquery example
Rename "Label" to "TextView" in jquery example Done to reflect eclipsesource/tabris-js@ca0f105e82a2d27067c9674ecf71a93af2c7b7bd Change-Id: I1c267e0130809077c1339ba0395da1a7e1c6b281
JavaScript
bsd-3-clause
moham3d/tabris-js,mkostikov/tabris-js,mkostikov/tabris-js,softnep0531/tabrisjs,softnep0531/tabrisjs,pimaxdev/tabris,pimaxdev/tabris,eclipsesource/tabris-js,moham3d/tabris-js,eclipsesource/tabris-js,eclipsesource/tabris-js
--- +++ @@ -9,18 +9,18 @@ topLevel: true }); -var createLabel = function(labelText) { - tabris.create("Label", { - text: labelText, +var createTextView = function(text) { + tabris.create("TextView", { + text: text, markupEnabled: true, layoutData: {left: MARGIN, right: MARGIN, top: [page.children().last() || 0, MARGIN]} }).appendTo(page); }; $.getJSON("http://www.telize.com/geoip", function(json) { - createLabel("The IP address is: " + json.ip); - createLabel("Latitude: " + json.latitude); - createLabel("Longitude: " + json.longitude); + createTextView("The IP address is: " + json.ip); + createTextView("Latitude: " + json.latitude); + createTextView("Longitude: " + json.longitude); }); page.open();
69914fdba918b1a8c38d9f8b08879d5d3d213132
test/trie.js
test/trie.js
var Trie = require('../app/trie'); describe('Trie', function() { var trie; beforeEach(function() { trie = new Trie(); }); it('should be an object', function() { expect(trie).to.be.ok; }); it('should have a root', function() { expect(trie.root).to.be.ok; }); it('should have add method', function() { expect(trie.add).to.be.an.instanceof(Function); }); it('should have search method', function() { expect(trie.search).to.be.an.instanceof(Function); }); it('should have find method', function() { expect(trie.find).to.be.an.instanceof(Function); }); it('should add string to trie', function() { expect(trie.add('test')).to.be.undefined; }); it('should correctly find an added string', function() { trie.add('test'); expect(trie.find('test')).to.be.true; }); it('should trim leading/trailing spaces when adding a string', function() { trie.add(' test '); expect(trie.find('test')).to.be.true; }); });
var Trie = require('../app/trie'); describe('Trie', function() { var trie; beforeEach(function() { trie = new Trie(); }); it('should be an object', function() { expect(trie).to.be.ok; }); it('should have a root', function() { expect(trie.root).to.be.ok; }); it('should have add method', function() { expect(trie.add).to.be.an.instanceof(Function); }); it('should have search method', function() { expect(trie.search).to.be.an.instanceof(Function); }); it('should have find method', function() { expect(trie.find).to.be.an.instanceof(Function); }); it('should add string without errors', function() { expect(trie.add('test')).to.be.undefined; }); it('should find an added string', function() { trie.add('test'); expect(trie.find('test')).to.be.true; }); it('should trim leading/trailing spaces when adding a string', function() { trie.add(' test '); expect(trie.find('test')).to.be.true; }); });
Reword test for add string and find string
Reword test for add string and find string
JavaScript
mit
mgarbacz/nordrassil,mgarbacz/nordrassil
--- +++ @@ -27,11 +27,11 @@ expect(trie.find).to.be.an.instanceof(Function); }); - it('should add string to trie', function() { + it('should add string without errors', function() { expect(trie.add('test')).to.be.undefined; }); - it('should correctly find an added string', function() { + it('should find an added string', function() { trie.add('test'); expect(trie.find('test')).to.be.true; });
7749879e6c083bd9c5c4d5fc2244399c3cd5e861
releaf-core/app/assets/javascripts/releaf/include/store_settings.js
releaf-core/app/assets/javascripts/releaf/include/store_settings.js
jQuery(function(){ var body = jQuery('body'); var settings_path = body.data('settings-path'); body.on('settingssave', function( event, key_or_settings, value ) { if (!settings_path) { return; } var settings = key_or_settings; if (typeof settings === "string") { settings = {}; settings[key_or_settings] = value; } jQuery.ajax({ url: settings_path, data: { "settings": settings}, headers: { 'X-CSRF-Token': $('meta[name=csrf-token]').attr('content') }, type: 'POST', dataType: 'json' }); }); });
jQuery(function(){ var body = jQuery('body'); var settings_path = body.data('settings-path'); body.on('settingssave', function( event, key_or_settings, value ) { if (!settings_path) { return; } var settings = key_or_settings; if (typeof settings === "string") { settings = {}; settings[key_or_settings] = value; } LiteAjax.ajax({ url: settings_path, method: 'POST', data: { "settings": settings}, json: true }) }); });
Use vanilla-ujs LiteAjax for user settings sending
Use vanilla-ujs LiteAjax for user settings sending
JavaScript
mit
cubesystems/releaf,cubesystems/releaf,graudeejs/releaf,graudeejs/releaf,cubesystems/releaf,graudeejs/releaf
--- +++ @@ -16,15 +16,7 @@ settings[key_or_settings] = value; } - jQuery.ajax({ - url: settings_path, - data: { "settings": settings}, - headers: { - 'X-CSRF-Token': $('meta[name=csrf-token]').attr('content') - }, - type: 'POST', - dataType: 'json' - }); + LiteAjax.ajax({ url: settings_path, method: 'POST', data: { "settings": settings}, json: true }) }); });
0fa905726bc545f6809aac20c7a3c8579dadb647
bin/collider-run.js
bin/collider-run.js
#!/usr/bin/env node 'use strict'; var pkg = require('../package.json') var cli = require('commander'); var fs = require('fs'); var path = require('path'); var spawn = require('child_process').spawn; cli .version( pkg.version ) .parse( process.argv ); var cwd = process.cwd(); var colliderFile = path.join( cwd, 'project', '.collider'); // Check if a Collider-file exists in the current working directory before running Gulp. fs.access( colliderFile, fs.F_OK, function(error) { if(error) { console.log('A Collider-file could not be found in this directory.'); } else { spawn('./node_modules/.bin/gulp', ['default'], { stdio: 'inherit' }); } });
#!/usr/bin/env node 'use strict'; var pkg = require('../package.json') var cli = require('commander'); var createError = require('../lib/createError'); var logErrorExit = require('../lib/logErrorExit'); var fs = require('fs'); var path = require('path'); var spawn = require('child_process').spawn; cli .version( pkg.version ) .parse( process.argv ); var cwd = process.cwd(); var colliderFile = path.join( cwd, 'project', '.collider'); // Check if a Collider-file exists in the current working directory before running Gulp. fs.access( colliderFile, fs.F_OK, function(err) { if(err) { var err = createError("a Collider-file couldn't be found. Is this a Collider project?"); logErrorExit( err, true ); } else { spawn('./node_modules/.bin/gulp', ['default'], { stdio: 'inherit' }); } });
Use creatError and logErrorExit to handle errors
Use creatError and logErrorExit to handle errors
JavaScript
mit
simonsinclair/collider-cli
--- +++ @@ -4,6 +4,9 @@ var pkg = require('../package.json') var cli = require('commander'); + +var createError = require('../lib/createError'); +var logErrorExit = require('../lib/logErrorExit'); var fs = require('fs'); var path = require('path'); @@ -17,9 +20,10 @@ var colliderFile = path.join( cwd, 'project', '.collider'); // Check if a Collider-file exists in the current working directory before running Gulp. -fs.access( colliderFile, fs.F_OK, function(error) { - if(error) { - console.log('A Collider-file could not be found in this directory.'); +fs.access( colliderFile, fs.F_OK, function(err) { + if(err) { + var err = createError("a Collider-file couldn't be found. Is this a Collider project?"); + logErrorExit( err, true ); } else { spawn('./node_modules/.bin/gulp', ['default'], { stdio: 'inherit' }); }
4ccd6bf73b26f9910827bf5bd487bcd30e0b24c0
example/__tests__/example-test.js
example/__tests__/example-test.js
import path from 'path'; import webpack from 'webpack'; import config from '../webpack.config'; describe('example', () => { it('combines loader results into one object', () => new Promise(resolve => { webpack(config, (error, stats) => { const bundlePath = path.resolve( stats.compilation.compiler.outputPath, stats.toJson().assetsByChunkName.main, ); expect(require(bundlePath)).toEqual({ raw: '---\ntitle: Example\n---\n\nSome markdown\n', frontmatter: { title: 'Example' }, content: '<p>Some markdown</p>\n', }); resolve(); }); })); });
import path from 'path'; import webpack from 'webpack'; import config from '../webpack.config'; describe('example', () => { jest.setTimeout(10000); // 10 second timeout it('combines loader results into one object', () => new Promise(resolve => { webpack(config, (error, stats) => { const bundlePath = path.resolve( stats.compilation.compiler.outputPath, stats.toJson().assetsByChunkName.main, ); expect(require(bundlePath)).toEqual({ raw: '---\ntitle: Example\n---\n\nSome markdown\n', frontmatter: { title: 'Example' }, content: '<p>Some markdown</p>\n', }); resolve(); }); })); });
Use a 10-second timeout for the Jest test
Use a 10-second timeout for the Jest test
JavaScript
mit
elliottsj/combine-loader
--- +++ @@ -3,6 +3,7 @@ import config from '../webpack.config'; describe('example', () => { + jest.setTimeout(10000); // 10 second timeout it('combines loader results into one object', () => new Promise(resolve => { webpack(config, (error, stats) => {
42e2cac9631969f51352f1c1d04cde129caa0dee
Resources/public/ol6-compat.js
Resources/public/ol6-compat.js
(function () { "use strict"; if (window.ol && ol.source && !ol.source.VectorEventType) { // HACK: monkey patch event types not present in current OL6 repackage build // @see https://github.com/openlayers/openlayers/blob/main/src/ol/source/VectorEventType.js ol.source.VectorEventType = { ADDFEATURE: 'addfeature', CHANGEFEATURE: 'changefeature', CLEAR: 'clear', REMOVEFEATURE: 'removefeature' }; } if (window.ol && !ol.ObjectEventType) { // HACK: monkey patch event types not present in current OL6 repackage build // @see https://github.com/openlayers/openlayers/blob/main/src/ol/ObjectEventType.js ol.ObjectEventType = { PROPERTYCHANGE: 'propertychange' }; } if (window.ol && ol.interaction && !ol.interaction.ModifyEventType) { // HACK: monkey patch event types not present in current OL6 repackage build // @see https://github.com/openlayers/openlayers/blob/main/src/ol/interaction/Modify.js#L64 ol.interaction.ModifyEventType = { MODIFYSTART: 'modifystart', MODIFYEND: 'modifyend' }; } })();
(function () { "use strict"; if (window.ol && ol.source && !ol.source.VectorEventType) { // HACK: monkey patch event types not present in current OL6 repackage build // @see https://github.com/openlayers/openlayers/blob/main/src/ol/source/VectorEventType.js ol.source.VectorEventType = { ADDFEATURE: 'addfeature', CHANGEFEATURE: 'changefeature', CLEAR: 'clear', REMOVEFEATURE: 'removefeature' }; } if (window.ol && !ol.ObjectEventType) { // HACK: monkey patch event types not present in current OL6 repackage build // @see https://github.com/openlayers/openlayers/blob/main/src/ol/ObjectEventType.js ol.ObjectEventType = { PROPERTYCHANGE: 'propertychange' }; } if (window.ol && ol.interaction && !ol.interaction.ModifyEventType) { // HACK: monkey patch event types not present in current OL6 repackage build // @see https://github.com/openlayers/openlayers/blob/main/src/ol/interaction/Modify.js#L64 ol.interaction.ModifyEventType = { MODIFYSTART: 'modifystart', MODIFYEND: 'modifyend' }; } if (window.ol && ol.interaction && !ol.interaction.TranslateEventType) { // HACK: monkey patch event types not present in current OL6 repackage build // @see https://github.com/openlayers/openlayers/blob/main/src/ol/interaction/Translate.js#L12 ol.interaction.TranslateEventType = { TRANSLATESTART: 'translatestart', TRANSLATING: 'translating', TRANSLATEEND: 'translateend' }; } })();
Fix "moveFeature" tool initialization errors
Fix "moveFeature" tool initialization errors
JavaScript
mit
mapbender/mapbender-digitizer,mapbender/mapbender-digitizer
--- +++ @@ -25,4 +25,13 @@ MODIFYEND: 'modifyend' }; } + if (window.ol && ol.interaction && !ol.interaction.TranslateEventType) { + // HACK: monkey patch event types not present in current OL6 repackage build + // @see https://github.com/openlayers/openlayers/blob/main/src/ol/interaction/Translate.js#L12 + ol.interaction.TranslateEventType = { + TRANSLATESTART: 'translatestart', + TRANSLATING: 'translating', + TRANSLATEEND: 'translateend' + }; + } })();
83c53032c97e74bff2ba97f1a798ab28cad6f31d
shaders/chunks/normal-perturb.glsl.js
shaders/chunks/normal-perturb.glsl.js
module.exports = /* glsl */ ` #if !defined(USE_TANGENTS) && (defined(USE_NORMAL_MAP) || defined(USE_CLEAR_COAT_NORMAL_MAP)) //http://www.thetenthplanet.de/archives/1180 mat3 cotangentFrame(vec3 N, vec3 p, vec2 uv) { // get edge vectors of the pixel triangle vec3 dp1 = dFdx(p); vec3 dp2 = dFdy(p); vec2 duv1 = dFdx(uv); vec2 duv2 = dFdy(uv); // solve the linear system vec3 dp2perp = cross(dp2, N); vec3 dp1perp = cross(N, dp1); vec3 T = dp2perp * duv1.x + dp1perp * duv2.x; vec3 B = dp2perp * duv1.y + dp1perp * duv2.y; // construct a scale-invariant frame float invmax = 1.0 / sqrt(max(dot(T,T), dot(B,B))); return mat3(normalize(T * invmax), normalize(B * invmax), N); } vec3 perturb(vec3 map, vec3 N, vec3 V, vec2 texcoord) { mat3 TBN = cotangentFrame(N, -V, texcoord); return normalize(TBN * map); } #endif `
module.exports = /* glsl */ ` #if !defined(USE_TANGENTS) && (defined(USE_NORMAL_MAP) || defined(USE_CLEAR_COAT_NORMAL_MAP)) //http://www.thetenthplanet.de/archives/1180 mat3 cotangentFrame(vec3 N, vec3 p, vec2 uv) { // get edge vectors of the pixel triangle highp vec3 dp1 = dFdx(p); highp vec3 dp2 = dFdy(p); highp vec2 duv1 = dFdx(uv); highp vec2 duv2 = dFdy(uv); // solve the linear system vec3 dp2perp = cross(dp2, N); vec3 dp1perp = cross(N, dp1); vec3 T = dp2perp * duv1.x + dp1perp * duv2.x; vec3 B = dp2perp * duv1.y + dp1perp * duv2.y; // construct a scale-invariant frame float invmax = 1.0 / sqrt(max(dot(T,T), dot(B,B))); return mat3(normalize(T * invmax), normalize(B * invmax), N); } vec3 perturb(vec3 map, vec3 N, vec3 V, vec2 texcoord) { mat3 TBN = cotangentFrame(N, -V, texcoord); return normalize(TBN * map); } #endif `
Use highp for derivatives calculations in perturb normal
Use highp for derivatives calculations in perturb normal Fixes #258
JavaScript
mit
pex-gl/pex-renderer,pex-gl/pex-renderer
--- +++ @@ -3,10 +3,10 @@ //http://www.thetenthplanet.de/archives/1180 mat3 cotangentFrame(vec3 N, vec3 p, vec2 uv) { // get edge vectors of the pixel triangle - vec3 dp1 = dFdx(p); - vec3 dp2 = dFdy(p); - vec2 duv1 = dFdx(uv); - vec2 duv2 = dFdy(uv); + highp vec3 dp1 = dFdx(p); + highp vec3 dp2 = dFdy(p); + highp vec2 duv1 = dFdx(uv); + highp vec2 duv2 = dFdy(uv); // solve the linear system vec3 dp2perp = cross(dp2, N);
7783b4bc586b8522cfe5f516c90051133e06fe84
feature-detects/css/animations.js
feature-detects/css/animations.js
/*! { "name": "CSS Animations", "property": "cssanimations", "caniuse": "css-animation", "polyfills": ["transformie", "csssandpaper"], "tags": ["css"], "warnings": ["Android < 4 will pass this test, but can only animate a single property at a time"], "notes": [{ "name" : "Article: 'Dispelling the Android CSS animation myths'", "href": "http://goo.gl/CHVJm" }] } !*/ /* DOC Detects wether or not elements can be animated using CSS */ define(['Modernizr', 'testAllProps'], function( Modernizr, testAllProps ) { Modernizr.addTest('cssanimations', testAllProps('animationName', 'a', true)); });
/*! { "name": "CSS Animations", "property": "cssanimations", "caniuse": "css-animation", "polyfills": ["transformie", "csssandpaper"], "tags": ["css"], "warnings": ["Android < 4 will pass this test, but can only animate a single property at a time"], "notes": [{ "name" : "Article: 'Dispelling the Android CSS animation myths'", "href": "http://goo.gl/OGw5Gm" }] } !*/ /* DOC Detects wether or not elements can be animated using CSS */ define(['Modernizr', 'testAllProps'], function( Modernizr, testAllProps ) { Modernizr.addTest('cssanimations', testAllProps('animationName', 'a', true)); });
Fix broken link in comment
Fix broken link in comment
JavaScript
mit
Modernizr/Modernizr,Modernizr/Modernizr
--- +++ @@ -8,7 +8,7 @@ "warnings": ["Android < 4 will pass this test, but can only animate a single property at a time"], "notes": [{ "name" : "Article: 'Dispelling the Android CSS animation myths'", - "href": "http://goo.gl/CHVJm" + "href": "http://goo.gl/OGw5Gm" }] } !*/
a8994cdafba3a7f550ea5507530a06a056313dd2
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. // // Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details // about supported directives. // //= require jquery //= require jquery_ujs //= require foundation //= require turbolinks //= require_tree //= require d3 $(function(){ $(document).foundation(); }); var loader = document.getElementById('loader'); startLoading(); finishedLoading(); function startLoading() { loader.className = ''; } function finishedLoading() { loader.className = 'done'; setTimeout(function() { loader.className = 'hide'; }, 5000); } $('a.close').click(function() { var qqq = $(this).closest('.modal'); $(qqq).removeClass('active'); });
// 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. // // Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details // about supported directives. // //= require jquery //= require jquery_ujs //= require foundation //= require turbolinks //= require_tree //= require d3 $(function(){ $(document).foundation(); }); var loader = document.getElementById('loader'); startLoading(); function startLoading() { loader.className = ''; } function finishedLoading() { loader.className = 'done'; setTimeout(function() { loader.className = 'hide'; }, 5000); }
Remove finishedLoading() call, remove a.close on click method - not using, it was there for trying out items purposes
Remove finishedLoading() call, remove a.close on click method - not using, it was there for trying out items purposes
JavaScript
mit
fma2/nyc-high-school-programs,fma2/nyc-high-school-programs
--- +++ @@ -21,7 +21,6 @@ var loader = document.getElementById('loader'); startLoading(); -finishedLoading(); function startLoading() { loader.className = ''; } @@ -31,9 +30,3 @@ loader.className = 'hide'; }, 5000); } - -$('a.close').click(function() { - var qqq = $(this).closest('.modal'); - $(qqq).removeClass('active'); -}); -
6da644a00f47a7bf6a238ebed701d8b8677316b9
app/assets/javascripts/rating_form.js
app/assets/javascripts/rating_form.js
$(document).ready(function() { $("#progress").on('submit', '.new_rating', function(event) { event.preventDefault(); const $form = $(this), url = $form.attr('action'), method = $form.attr('method'), data = $form.serialize(); $.ajax({ url: url, method: method, data: data, dataType: "json" }) .success(function(response) { $form.closest('.modal')[0].style.display = "none"; // update score $form.closest('.collection-item').find('.current-score').text(response[0].score); // update goal partial $form.closest('.collection-item').find('.rating-partials-container') .prepend('<div class="rating-partial"><p class="confidence_score">Score: ' + response[0].score + '</p><p class="rating_comment">Comment: ' + response[0].comment + '</p></div>'); // update progress bar $('.current-level').text(response[1]); $('.progress-bar').css("width:" + response[2] + "%"); }) .fail(function(error) { console.log(error); }) }); });
$(document).ready(function() { $("#progress").on('submit', '.new_rating', function(event) { event.preventDefault(); const $form = $(this), url = $form.attr('action'), method = $form.attr('method'), data = $form.serialize(); $.ajax({ url: url, method: method, data: data, dataType: "json" }) .success(function(response) { $form.trigger('reset'); $form.closest('.modal')[0].style.display = "none"; // update score $form.closest('.collection-item').find('.current-score').text(response[0].score); // update goal partial $form.closest('.collection-item').find('.rating-partials-container') .prepend('<div class="rating-partial"><p class="confidence_score">Score: ' + response[0].score + '</p><p class="rating_comment">Comment: ' + response[0].comment + '</p></div>'); // update progress bar $('.current-level').text(response[1]); $('.progress-bar').css("width:" + response[2] + "%"); }) .fail(function(error) { console.log(error); }) }); });
Refactor rating jquery to clear rating form on submit
Refactor rating jquery to clear rating form on submit
JavaScript
mit
AliasHendrickson/progress,AliasHendrickson/progress,AliasHendrickson/progress
--- +++ @@ -14,6 +14,7 @@ dataType: "json" }) .success(function(response) { + $form.trigger('reset'); $form.closest('.modal')[0].style.display = "none"; // update score $form.closest('.collection-item').find('.current-score').text(response[0].score);
c6bf12e83cdf792c986b3fc4348a0165fe569e8a
frontend/src/Lists/ListsView.js
frontend/src/Lists/ListsView.js
import React, { Component } from "react"; import styled from "styled-components"; import { Row, RowContent, ColumnContainer } from "../SharedComponents.js"; import Loading from "../loading.js"; import List from "./List.js"; import CreateList from "./CreateList.js"; import Notes from "./Notes.js"; class ListsView extends Component { render() { const { user, lists, loading } = this.props; if (loading) { return <Loading />; } return ( <ColumnContainer> <Row> <RowContent> Du är: {user.nick} </RowContent> </Row> <ListsContainer> {lists.map(list => <List key={list.id} list={list} user={user} />)} <Notes /> {user.isAdmin && <CreateList />} </ListsContainer> </ColumnContainer> ); } } const ListsContainer = styled(Row)` padding-top: 2em; `; export default ListsView;
import React, { Component } from "react"; import styled from "styled-components"; import { Row, RowContent, ColumnContainer } from "../SharedComponents.js"; import Loading from "../loading.js"; import List from "./List.js"; import CreateList from "./CreateList.js"; import Notes from "./Notes.js"; class ListsView extends Component { render() { const { user, lists, loading } = this.props; if (loading) { return <Loading />; } return ( <ColumnContainer> <Row> <RowContent> Du är: {user.nick} </RowContent> </Row> <MainContainer> <ListContainer width={(lists.length - 2) * 20}> {lists.map(list => <List key={list.id} list={list} user={user} />)} </ListContainer> {user.isAdmin && <CreateList />} <Notes /> </MainContainer> </ColumnContainer> ); } } const ListContainer = Row.extend` margin-left: -${props => props.width}em; `; const MainContainer = styled(Row)` padding-top: 2em; `; export default ListsView;
Move lists to the left
Move lists to the left
JavaScript
mit
Tejpbit/talarlista,Tejpbit/talarlista,Tejpbit/talarlista
--- +++ @@ -25,17 +25,23 @@ </RowContent> </Row> - <ListsContainer> - {lists.map(list => <List key={list.id} list={list} user={user} />)} + <MainContainer> + <ListContainer width={(lists.length - 2) * 20}> + {lists.map(list => <List key={list.id} list={list} user={user} />)} + </ListContainer> + {user.isAdmin && <CreateList />} <Notes /> - {user.isAdmin && <CreateList />} - </ListsContainer> + </MainContainer> </ColumnContainer> ); } } -const ListsContainer = styled(Row)` +const ListContainer = Row.extend` + margin-left: -${props => props.width}em; +`; + +const MainContainer = styled(Row)` padding-top: 2em; `;
cf530df7cebd995e5742b4be488fa3c765d267e6
te-append.js
te-append.js
#!/usr/bin/env node 'use strict'; const program = require('commander'); const addLineNumbers = require('add-line-numbers'); const fs = require('fs'); const listAndRun = require('./list-and-run').listAndRun; const path = '/tmp/te'; program.parse(process.argv); const line = '\n' + program.args; fs.appendFileSync(path, line); listAndRun();
#!/usr/bin/env node 'use strict'; const program = require('commander'); const fs = require('fs'); const listAndRun = require('./list-and-run').listAndRun; const path = '/tmp/te'; program.parse(process.argv); const line = program.args; const file = fs.readFileSync(path, 'utf8'); var lines = []; if (file.length) { var lines = file.split('\n'); } lines.push(line); fs.writeFileSync(path, lines.join('\n')); listAndRun();
Make sure append doesn't create an empty line when the first line of code is added
Make sure append doesn't create an empty line when the first line of code is added
JavaScript
mit
gudnm/te
--- +++ @@ -1,14 +1,21 @@ #!/usr/bin/env node 'use strict'; const program = require('commander'); -const addLineNumbers = require('add-line-numbers'); const fs = require('fs'); const listAndRun = require('./list-and-run').listAndRun; const path = '/tmp/te'; program.parse(process.argv); -const line = '\n' + program.args; -fs.appendFileSync(path, line); +const line = program.args; +const file = fs.readFileSync(path, 'utf8'); + +var lines = []; +if (file.length) { + var lines = file.split('\n'); +} +lines.push(line); + +fs.writeFileSync(path, lines.join('\n')); listAndRun();
9c21194c68654e2152d70a28cc9261b13a2035a4
lib/api/middlewares/last-updated-time-layergroup.js
lib/api/middlewares/last-updated-time-layergroup.js
'use strict'; module.exports = function setLastUpdatedTimeToLayergroup () { return function setLastUpdatedTimeToLayergroupMiddleware (req, res, next) { const { mapConfigProvider, analysesResults } = res.locals; const layergroup = res.body; mapConfigProvider.createAffectedTables((err, affectedTables) => { if (err) { return next(err); } if (!affectedTables) { return next(); } var lastUpdateTime = affectedTables.getLastUpdatedAt(); lastUpdateTime = getLastUpdatedTime(analysesResults, lastUpdateTime) || lastUpdateTime; // last update for layergroup cache buster layergroup.layergroupid = layergroup.layergroupid + ':' + lastUpdateTime; layergroup.last_updated = new Date(lastUpdateTime).toISOString(); res.locals.cache_buster = lastUpdateTime; next(); }); }; }; function getLastUpdatedTime (analysesResults, lastUpdateTime) { if (!Array.isArray(analysesResults)) { return lastUpdateTime; } return analysesResults.reduce(function (lastUpdateTime, analysis) { return analysis.getNodes().reduce(function (lastNodeUpdatedAtTime, node) { var nodeUpdatedAtDate = node.getUpdatedAt(); var nodeUpdatedTimeAt = (nodeUpdatedAtDate && nodeUpdatedAtDate.getTime()) || 0; return nodeUpdatedTimeAt > lastNodeUpdatedAtTime ? nodeUpdatedTimeAt : lastNodeUpdatedAtTime; }, lastUpdateTime); }, lastUpdateTime); }
'use strict'; module.exports = function setLastUpdatedTimeToLayergroup () { return function setLastUpdatedTimeToLayergroupMiddleware (req, res, next) { const { mapConfigProvider, analysesResults } = res.locals; const layergroup = res.body; mapConfigProvider.createAffectedTables((err, affectedTables) => { if (err) { return next(err); } if (!affectedTables) { res.locals.cache_buster = 0; layergroup.layergroupid = `${layergroup.layergroupid}:${res.locals.cache_buster}`; layergroup.last_updated = new Date(res.locals.cache_buster).toISOString(); return next(); } var lastUpdateTime = affectedTables.getLastUpdatedAt(); lastUpdateTime = getLastUpdatedTime(analysesResults, lastUpdateTime) || lastUpdateTime; // last update for layergroup cache buster layergroup.layergroupid = layergroup.layergroupid + ':' + lastUpdateTime; layergroup.last_updated = new Date(lastUpdateTime).toISOString(); res.locals.cache_buster = lastUpdateTime; next(); }); }; }; function getLastUpdatedTime (analysesResults, lastUpdateTime) { if (!Array.isArray(analysesResults)) { return lastUpdateTime; } return analysesResults.reduce(function (lastUpdateTime, analysis) { return analysis.getNodes().reduce(function (lastNodeUpdatedAtTime, node) { var nodeUpdatedAtDate = node.getUpdatedAt(); var nodeUpdatedTimeAt = (nodeUpdatedAtDate && nodeUpdatedAtDate.getTime()) || 0; return nodeUpdatedTimeAt > lastNodeUpdatedAtTime ? nodeUpdatedTimeAt : lastNodeUpdatedAtTime; }, lastUpdateTime); }, lastUpdateTime); }
Set cache buster equal to 0 when there is no affected tables in the mapconfig
Set cache buster equal to 0 when there is no affected tables in the mapconfig
JavaScript
bsd-3-clause
CartoDB/Windshaft-cartodb,CartoDB/Windshaft-cartodb,CartoDB/Windshaft-cartodb,CartoDB/Windshaft-cartodb
--- +++ @@ -11,6 +11,10 @@ } if (!affectedTables) { + res.locals.cache_buster = 0; + layergroup.layergroupid = `${layergroup.layergroupid}:${res.locals.cache_buster}`; + layergroup.last_updated = new Date(res.locals.cache_buster).toISOString(); + return next(); }
79f3d9a6a7ca614dce7fb0444d3799d9d55f198c
assets/js/theme/global/mobile-menu.js
assets/js/theme/global/mobile-menu.js
import $ from 'jquery'; export default function() { const $mobileMenuTrigger = $('[data-mobilemenu]'); const $header = $('.header'); const headerHeight = $('.header').outerHeight(); const $mobileMenu = $('#mobile-menu'); function mobileMenu() { $mobileMenuTrigger.on('click', toggleMobileMenu); } function toggleMobileMenu(e) { e.preventDefault(); calculateMobileMenuOffset(); targetMenuItemID = $mobileMenuTrigger.data('mobilemenu'); $mobileMenuTrigger.toggleClass('is-open').attr('aria-expanded', (i, attr) => { return attr === 'true' ? 'false' : 'true'; }); $mobileMenu.toggleClass('is-open').attr('aria-hidden', (i, attr) => { return attr === 'true' ? 'false' : 'true'; }); } function calculateMobileMenuOffset() { $mobileMenu.attr('style', (i, attr) => { return attr !== `top:${headerHeight}px` ? `top:${headerHeight}px` : 'top:auto'; }); $header.attr('style', (i, attr) => { return attr === 'height:100%' ? 'height:auto' : 'height:100%'; }); } if ($mobileMenuTrigger.length) { mobileMenu(); } }
import $ from 'jquery'; export default function() { const $mobileMenuTrigger = $('[data-mobilemenu]'); const $header = $('.header'); const headerHeight = $('.header').outerHeight(); const $mobileMenu = $('#mobile-menu'); function mobileMenu() { $mobileMenuTrigger.on('click', toggleMobileMenu); } function toggleMobileMenu(e) { e.preventDefault(); calculateMobileMenuOffset(); $mobileMenuTrigger.toggleClass('is-open').attr('aria-expanded', (i, attr) => { return attr === 'true' ? 'false' : 'true'; }); $mobileMenu.toggleClass('is-open').attr('aria-hidden', (i, attr) => { return attr === 'true' ? 'false' : 'true'; }); } function calculateMobileMenuOffset() { $mobileMenu.attr('style', (i, attr) => { return attr !== `top:${headerHeight}px` ? `top:${headerHeight}px` : 'top:auto'; }); $header.attr('style', (i, attr) => { return attr === 'height:100%' ? 'height:auto' : 'height:100%'; }); } if ($mobileMenuTrigger.length) { mobileMenu(); } }
Fix mobile hamburger menu contents not appearing
Fix mobile hamburger menu contents not appearing
JavaScript
mit
aaronrodier84/flukerfarms,juancho1/bauhaus,PascalZajac/cornerstone,bigcommerce/stencil,PeteyRev/ud-revamp,aaronrodier84/rouxbrands,bigcommerce/stencil,mcampa/cornerstone,rho1140/cornerstone,ovsokolov/dashconnect-bc,mcampa/cornerstone,PeteyRev/ud-revamp,juancho1/bauhaus,bc-annavu/stencil,aaronrodier84/rouxbrands,mcampa/cornerstone,ovsokolov/dashconnect-bc,bc-annavu/stencil,aaronrodier84/flukerfarms,aaronrodier84/rouxbrands,rho1140/cornerstone,caras-ey/BST,rho1140/cornerstone,caras-ey/BST,bigcommerce/stencil,juancho1/bauhaus,PascalZajac/cornerstone,PeteyRev/ud-revamp,bc-annavu/stencil,caras-ey/BST,aaronrodier84/flukerfarms,ovsokolov/dashconnect-bc,PascalZajac/cornerstone
--- +++ @@ -14,7 +14,6 @@ e.preventDefault(); calculateMobileMenuOffset(); - targetMenuItemID = $mobileMenuTrigger.data('mobilemenu'); $mobileMenuTrigger.toggleClass('is-open').attr('aria-expanded', (i, attr) => { return attr === 'true' ? 'false' : 'true';
9557e87a24a1b6d33cef2bce1231f9d9b2a35602
app/components/Auth/Auth.js
app/components/Auth/Auth.js
import React, { Component } from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import jwtDecode from 'jwt-decode'; import styles from './styles.scss'; import Login from './Login'; import Signup from './Signup'; import Info from './Info'; import { addUser } from '../../actions/user'; const mapDispatchToProps = dispatch => ({ addUserFromToken: token => dispatch(addUser(jwtDecode(token))), }); class Auth extends Component { state = { isNewUser: false } toggleNewUser = () => { this.setState({ isNewUser: !this.state.isNewUser }); } render() { const { addUserFromToken } = this.props; const { isNewUser } = this.state; return ( <div className={styles.Auth}> <div className={[styles.AuthBox, isNewUser ? '' : styles.OldUser].join(' ')}> { isNewUser ? <Signup switchForm={this.toggleNewUser} addUser={addUserFromToken} /> : <Login switchForm={this.toggleNewUser} addUser={addUserFromToken} /> } <Info message={isNewUser ? 'Take a part in creating better video games!' : 'Welcome back!'} isNewUser={isNewUser} /> </div> </div> ); } } Auth.propTypes = { addUserFromToken: PropTypes.func.isRequired }; export default connect(null, mapDispatchToProps)(Auth);
import React, { Component } from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import jwtDecode from 'jwt-decode'; import styles from './styles.scss'; import Login from './Login'; import Signup from './Signup'; import Info from './Info'; import Controls from '../Controls'; import { addUser } from '../../actions/user'; const mapDispatchToProps = dispatch => ({ addUserFromToken: token => dispatch(addUser(jwtDecode(token))), }); class Auth extends Component { state = { isNewUser: false } toggleNewUser = () => { this.setState({ isNewUser: !this.state.isNewUser }); } render() { const { addUserFromToken } = this.props; const { isNewUser } = this.state; return ( <div className={styles.Auth}> <Controls /> <div className={[styles.AuthBox, isNewUser ? '' : styles.OldUser].join(' ')}> { isNewUser ? <Signup switchForm={this.toggleNewUser} addUser={addUserFromToken} /> : <Login switchForm={this.toggleNewUser} addUser={addUserFromToken} /> } <Info message={isNewUser ? 'Take a part in creating better video games!' : 'Welcome back!'} isNewUser={isNewUser} /> </div> </div> ); } } Auth.propTypes = { addUserFromToken: PropTypes.func.isRequired }; export default connect(null, mapDispatchToProps)(Auth);
Add control buttons to auth
Add control buttons to auth
JavaScript
mit
cdiezmoran/AlphaStage-2.0,cdiezmoran/AlphaStage-2.0
--- +++ @@ -7,6 +7,7 @@ import Login from './Login'; import Signup from './Signup'; import Info from './Info'; +import Controls from '../Controls'; import { addUser } from '../../actions/user'; @@ -28,6 +29,7 @@ const { isNewUser } = this.state; return ( <div className={styles.Auth}> + <Controls /> <div className={[styles.AuthBox, isNewUser ? '' : styles.OldUser].join(' ')}> { isNewUser
1e1e1e351b3d0a9f4f824e5392de8afea93d5ffe
src/components/posts_index.js
src/components/posts_index.js
import _ from 'lodash'; import React from 'react'; import { connect } from 'react-redux'; import { Link } from 'react-router-dom'; import { fetchPosts } from '../actions'; class PostsIndex extends React.Component { componentDidMount() { this.props.fetchPosts(); } renderPosts() { return _.map(this.props.posts, (post) => { return ( <li className="list-group-item" key={post.id}> {post.title} </li> ); }); } render() { return ( <div className='posts-index'> <div className='text-xs-right'> <Link className='btn btn-primary' to='/posts/new'> Add a Post </Link> </div> <h3>Posts</h3> <ul className="list-group"> { this.renderPosts() } </ul> </div> ) } } function mapStateToProps(state) { return { posts: state.posts }; } export default connect(mapStateToProps, { fetchPosts: fetchPosts })(PostsIndex);
import _ from 'lodash'; import React from 'react'; import { connect } from 'react-redux'; import { Link } from 'react-router-dom'; import { fetchPosts } from '../actions'; class PostsIndex extends React.Component { componentDidMount() { this.props.fetchPosts(); } renderPosts() { return _.map(this.props.posts, (post) => { return ( <li className="list-group-item" key={post.id}> <Link to={`/posts/${post.id}`}> {post.title} </Link> </li> ); }); } render() { return ( <div className='posts-index'> <div className='text-xs-right'> <Link className='btn btn-primary' to='/posts/new'> Add a Post </Link> </div> <h3>Posts</h3> <ul className="list-group"> { this.renderPosts() } </ul> </div> ) } } function mapStateToProps(state) { return { posts: state.posts }; } export default connect(mapStateToProps, { fetchPosts: fetchPosts })(PostsIndex);
Add link to link to each page
Add link to link to each page
JavaScript
mit
monsteronfire/redux-learning-blog,monsteronfire/redux-learning-blog
--- +++ @@ -14,7 +14,9 @@ return _.map(this.props.posts, (post) => { return ( <li className="list-group-item" key={post.id}> - {post.title} + <Link to={`/posts/${post.id}`}> + {post.title} + </Link> </li> ); });
a081e1554614ac92aebe31b0dd514a12484d4ece
app/lib/collections/posts.js
app/lib/collections/posts.js
Posts = new Mongo.Collection('posts'); Posts.allow({ insert: function(userId, doc) { // only allow posting if you are logged in return !! userId; } });
Posts = new Mongo.Collection('posts'); Meteor.methods({ postInsert: function(postAttributes) { check(Meteor.userId(), String); check(postAttributes, { title: String, url: String }); var user = Meteor.user(); var post = _.extend(postAttributes, { userId: user._id, author: user.username, submitted: new Date() }); var postId = Posts.insert(post); return { _id: postId }; } });
Use Meteor.methods to set up post (including user)
Use Meteor.methods to set up post (including user)
JavaScript
mit
drainpip/music-management-system,drainpip/music-management-system
--- +++ @@ -1,8 +1,21 @@ Posts = new Mongo.Collection('posts'); -Posts.allow({ - insert: function(userId, doc) { - // only allow posting if you are logged in - return !! userId; +Meteor.methods({ + postInsert: function(postAttributes) { + check(Meteor.userId(), String); + check(postAttributes, { + title: String, + url: String + }); + var user = Meteor.user(); + var post = _.extend(postAttributes, { + userId: user._id, + author: user.username, + submitted: new Date() + }); + var postId = Posts.insert(post); + return { + _id: postId + }; } });
fbae2755bb25ef803cd3508448cb1646868a6618
test/mqtt.js
test/mqtt.js
/** * Testing includes */ var should = require('should'); /** * Unit under test */ var mqtt = require('../lib/mqtt'); describe('mqtt', function() { describe('#createClient', function() { it('should return an MqttClient', function() { var c = mqtt.createClient(); c.should.be.instanceOf(mqtt.MqttClient); }); }); describe('#createSecureClient', function() { it('should return an MqttClient', function() { var c = mqtt.createClient(); c.should.be.instanceOf(mqtt.MqttClient); }); it('should throw on incorrect args'); }); describe('#createServer', function() { it('should return an MqttServer', function() { var s = mqtt.createServer(); s.should.be.instanceOf(mqtt.MqttServer); }); }); describe('#createSecureServer', function() { it('should return an MqttSecureServer', function() { var s = mqtt.createSecureServer( __dirname + '/helpers/private-key.pem', __dirname + '/helpers/public-cert.pem' ); s.should.be.instanceOf(mqtt.MqttSecureServer); }); }); });
/** * Testing includes */ var should = require('should'); /** * Unit under test */ var mqtt = require('../lib/mqtt'); describe('mqtt', function() { describe('#createClient', function() { it('should return an MqttClient', function() { var c = mqtt.createClient(); c.should.be.instanceOf(mqtt.MqttClient); }); }); describe('#createSecureClient', function() { it('should return an MqttClient', function() { var c = mqtt.createClient(); c.should.be.instanceOf(mqtt.MqttClient); }); it('should throw on incorrect args'); }); describe('#createServer', function() { it('should return an MqttServer', function() { var s = mqtt.createServer(); s.should.be.instanceOf(mqtt.MqttServer); }); }); describe('#createSecureServer', function() { it('should return an MqttSecureServer', function() { var s = mqtt.createSecureServer( __dirname + '/helpers/private-key.pem', __dirname + '/helpers/public-cert.pem' ); s.should.be.instanceOf(mqtt.MqttSecureServer); }); }); describe('#createConnection', function() { it('should return an MqttConnection', function() { var c = mqtt.createConnection(); c.should.be.instanceOf(mqtt.MqttConnection); }); }); });
Add test for MqttConnection creation
Add test for MqttConnection creation
JavaScript
mit
itavy/MQTT.js,bqevin/MQTT.js,AdySan/MQTT.js,mcanthony/MQTT.js,yunba/MQTT.js,jaambee/MQTT.js,daliworks/MQTT.js,jdiamond/MQTT.js,wesley1001/MQTT.js,authere/MQTT.js,RangerMauve/MQTT.js,1248/MQTT.js
--- +++ @@ -45,4 +45,12 @@ s.should.be.instanceOf(mqtt.MqttSecureServer); }); }); + + describe('#createConnection', function() { + it('should return an MqttConnection', function() { + var c = mqtt.createConnection(); + + c.should.be.instanceOf(mqtt.MqttConnection); + }); + }); });
41db6cf165dd083d3b284c961c128db609fcad81
src/extend/getConnectivityMatrix.js
src/extend/getConnectivityMatrix.js
'use strict'; var OCL = require('openchemlib'); module.exports = function getConnectivityMatrix(options={}) { var { sdt, mass } = options; this.ensureHelperArrays(OCL.Molecule.cHelperNeighbours); var nbAtoms=this.getAllAtoms(); var result=new Array(nbAtoms); for (var i=0; i<nbAtoms; i++) { result[i]=new Array(nbAtoms).fill(0); result[i][i]=(mass) ? OCL.Molecule.cRoundedMass[this.getAtomicNo(i)] : 1; } for (var i=0; i<nbAtoms; i++) { for (var j=0; j<this.getAllConnAtoms(i); j++) { result[i][this.getConnAtom(i,j)]=(sdt) ? this.getConnBondOrder(i,j) : 1; } } return result; }
'use strict'; var OCL = require('openchemlib'); module.exports = function getConnectivityMatrix(options) { var options = options || {}; var sdt=options.sdt; var mass=options.mass; this.ensureHelperArrays(OCL.Molecule.cHelperNeighbours); var nbAtoms=this.getAllAtoms(); var result=new Array(nbAtoms); for (var i=0; i<nbAtoms; i++) { result[i]=new Array(nbAtoms).fill(0); result[i][i]=(mass) ? OCL.Molecule.cRoundedMass[this.getAtomicNo(i)] : 1; } for (var i=0; i<nbAtoms; i++) { for (var j=0; j<this.getAllConnAtoms(i); j++) { result[i][this.getConnAtom(i,j)]=(sdt) ? this.getConnBondOrder(i,j) : 1; } } return result; }
Make it compatible with node 4.0
Make it compatible with node 4.0
JavaScript
bsd-3-clause
cheminfo-js/openchemlib-extended
--- +++ @@ -2,11 +2,10 @@ var OCL = require('openchemlib'); -module.exports = function getConnectivityMatrix(options={}) { - var { - sdt, - mass - } = options; +module.exports = function getConnectivityMatrix(options) { + var options = options || {}; + var sdt=options.sdt; + var mass=options.mass; this.ensureHelperArrays(OCL.Molecule.cHelperNeighbours); var nbAtoms=this.getAllAtoms();
94bc6236e23440d4f3958e601d0ab880b17d09de
public/js/book-app/components/book-app.component.js
public/js/book-app/components/book-app.component.js
;(function() { "use strict"; angular. module("bookApp"). component("bookApp", { template: ` <div class="nav"><a href="new-book">Add new book</a></div> <div class="book-container" ng-repeat="book in $ctrl.books"> <h3>{{book.title}}</h3> <img ng-src="http://theproactiveprogrammer.com/wp-content/uploads/2014/09/js_good_parts.png" alt="" /> <p>{{book.rate}}</p> <p>{{book.author}}</p> <p>{{book.descroption}}</p> </div> `, controller: BookAppController }); BookAppController.$inject = ["$scope"]; function BookAppController($scope) { let vm = this, bookRef = firebase.database().ref("Books"); vm.books = []; bookRef.on("value", function(snapshot) { // vm.users.push(snapshot.val()); snapshot.forEach(function(subSnap) { vm.books.push(subSnap.val()); }); if(!$scope.$$phase) $scope.$apply(); }); } })();
;(function() { "use strict"; angular. module("bookApp"). component("bookApp", { template: ` <div class="nav"><a href="new-book" class="nav-click">Add new book</a></div> <div class="book-container" ng-repeat="book in $ctrl.books"> <h3>{{book.title}}</h3> <img ng-src="http://theproactiveprogrammer.com/wp-content/uploads/2014/09/js_good_parts.png" alt="" /> <p>{{book.rate}}</p> <p>{{book.author}}</p> <p>{{book.descroption}}</p> </div> `, controller: BookAppController }); BookAppController.$inject = ["$scope"]; function BookAppController($scope) { let vm = this, bookRef = firebase.database().ref("Books"); vm.books = []; bookRef.on("value", function(snapshot) { // vm.users.push(snapshot.val()); snapshot.forEach(function(subSnap) { vm.books.push(subSnap.val()); }); if(!$scope.$$phase) $scope.$apply(); }); } })();
Add New Class To Link
Add New Class To Link
JavaScript
mit
fejs-levelup/angular-bookshelf,fejs-levelup/angular-bookshelf
--- +++ @@ -5,7 +5,7 @@ module("bookApp"). component("bookApp", { template: ` - <div class="nav"><a href="new-book">Add new book</a></div> + <div class="nav"><a href="new-book" class="nav-click">Add new book</a></div> <div class="book-container" ng-repeat="book in $ctrl.books"> <h3>{{book.title}}</h3>
c8b6d8adb8ae1dea1148416acfdfb99502ce281c
app/assets/javascripts/init.js
app/assets/javascripts/init.js
window.atthemovies = { init: function() { var body = document.querySelectorAll("body")[0]; var jsController = body.getAttribute("data-js-controller"); var jsAction = body.getAttribute("data-js-action"); this.pageJS("atthemovies." + jsController + ".init", window); this.pageJS("atthemovies." + jsController + ".init" + jsAction, window); }, pageJS: function(functionName, context) { var namespaces = functionName.split("."); var func = namespaces.pop(); for (var i = 0; i < namespaces.length; i++) { if(context[namespaces[i]]) { context = context[namespaces[i]]; } else { return null; } } if(typeof context[func] === "function") { return context[func].apply(context, null); } else { return null; } } }
window.atthemovies = { init: function() { var body = document.querySelectorAll("body")[0]; var jsController = body.getAttribute("data-js-controller"); var jsAction = body.getAttribute("data-js-action"); this.pageJS("atthemovies." + jsController + ".init", window); this.pageJS("atthemovies." + jsController + ".init" + jsAction, window); }, // pass a string to call a namespaced function that may not exist pageJS: function(functionString, context) { var namespaces = functionString.split("."); var functionName = namespaces.pop(); // recursively loop into existing namespaces, else return harmlessly for (var i = 0; i < namespaces.length; i++) { if(context[namespaces[i]]) { context = context[namespaces[i]]; } else { return null; } } // call the function if it exists in this context, else return harmlessly if(typeof context[functionName] === "function") { return context[functionName].apply(context, null); } else { return null; } } }
Tidy up JS, add commentary
Tidy up JS, add commentary
JavaScript
agpl-3.0
andycroll/atthemovies,andycroll/atthemovies,andycroll/atthemovies,andycroll/atthemovies
--- +++ @@ -8,10 +8,12 @@ this.pageJS("atthemovies." + jsController + ".init" + jsAction, window); }, - pageJS: function(functionName, context) { - var namespaces = functionName.split("."); - var func = namespaces.pop(); + // pass a string to call a namespaced function that may not exist + pageJS: function(functionString, context) { + var namespaces = functionString.split("."); + var functionName = namespaces.pop(); + // recursively loop into existing namespaces, else return harmlessly for (var i = 0; i < namespaces.length; i++) { if(context[namespaces[i]]) { context = context[namespaces[i]]; @@ -19,8 +21,10 @@ return null; } } - if(typeof context[func] === "function") { - return context[func].apply(context, null); + + // call the function if it exists in this context, else return harmlessly + if(typeof context[functionName] === "function") { + return context[functionName].apply(context, null); } else { return null; }
d3017cbcd542cc5c310d23c0bd478eae10ceef32
src/modules/ajax/retryAjax.js
src/modules/ajax/retryAjax.js
function doAjax(options, retries, dfr) { $.ajax(options).pipe(function(data) {dfr.resolve(data);}, function(jqXhr) { if (retries > 0) { setTimeout(doAjax, 100, options, retries - 1, dfr); } else { dfr.reject(jqXhr); } }); } export default function retryAjax(options) { var dfr = $.Deferred(); doAjax(options, 10, dfr); return dfr; }
function doAjax(options, retries, dfr) { $.ajax(options).pipe(function(data, textStatus, jqXHR) { dfr.resolve(data, textStatus, jqXHR); }, function(jqXhr, textStatus, errorThrown) { if (retries > 0) { setTimeout(doAjax, 100, options, retries - 1, dfr); } else { dfr.reject(jqXhr, textStatus, errorThrown); } }); } export default function retryAjax(options) { var dfr = $.Deferred(); doAjax(options, 10, dfr); return dfr; }
Return all arguments from AJAX
Return all arguments from AJAX
JavaScript
mit
fallenswordhelper/fallenswordhelper,fallenswordhelper/fallenswordhelper
--- +++ @@ -1,10 +1,12 @@ function doAjax(options, retries, dfr) { - $.ajax(options).pipe(function(data) {dfr.resolve(data);}, function(jqXhr) { + $.ajax(options).pipe(function(data, textStatus, jqXHR) { + dfr.resolve(data, textStatus, jqXHR); + }, function(jqXhr, textStatus, errorThrown) { if (retries > 0) { setTimeout(doAjax, 100, options, retries - 1, dfr); } else { - dfr.reject(jqXhr); + dfr.reject(jqXhr, textStatus, errorThrown); } }); }