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
7f292e1e1c3a7147331a462e2ded5e3a01cdfe7f
server/public/scripts/controllers/home.controller.js
server/public/scripts/controllers/home.controller.js
app.controller('HomeController', ['$http', 'AuthFactory', function($http, AuthFactory) { console.log('HomeController running'); var self = this; self.userStatus = AuthFactory.userStatus; self.dataArray = [{ src: '../assets/images/carousel/genome-sm.jpg' }, { src: '../assets/images/carousel/falkirk-wheel-sm.jpg' }, { src: '../assets/images/carousel/iss-sm.jpg' }, { src: '../assets/images/carousel/shark-sm.jpg' }, { src: '../assets/images/carousel/snowflake-sm.jpg' }, { src: '../assets/images/carousel/virus-sm.jpg' }, { src: '../assets/images/carousel/rock-formation-sm.jpg' }, { src: '../assets/images/carousel/circuit-board-sm.jpg' } ]; }]);
app.controller('HomeController', ['$http', 'AuthFactory', function($http, AuthFactory) { console.log('HomeController running'); var self = this; self.userStatus = AuthFactory.userStatus; self.dataArray = [ { src: '../assets/images/carousel/genome-sm.jpg' }, { src: '../assets/images/carousel/falkirk-wheel-sm.jpg' }, { src: '../assets/images/carousel/iss-sm.jpg' }, { src: '../assets/images/carousel/shark-sm.jpg' }, { src: '../assets/images/carousel/snowflake-sm.jpg' }, { src: '../assets/images/carousel/virus-sm.jpg' }, { src: '../assets/images/carousel/rock-formation-sm.jpg' }, { src: '../assets/images/carousel/circuit-board-sm.jpg' } ]; }]);
Refactor carousel image references for better readability
Refactor carousel image references for better readability
JavaScript
mit
STEMentor/STEMentor,STEMentor/STEMentor
--- +++ @@ -3,29 +3,14 @@ var self = this; self.userStatus = AuthFactory.userStatus; - self.dataArray = [{ - src: '../assets/images/carousel/genome-sm.jpg' - }, - { - src: '../assets/images/carousel/falkirk-wheel-sm.jpg' - }, - { - src: '../assets/images/carousel/iss-sm.jpg' - }, - { - src: '../assets/images/carousel/shark-sm.jpg' - }, - { - src: '../assets/images/carousel/snowflake-sm.jpg' - }, - { - src: '../assets/images/carousel/virus-sm.jpg' - }, - { - src: '../assets/images/carousel/rock-formation-sm.jpg' - }, - { - src: '../assets/images/carousel/circuit-board-sm.jpg' - } + self.dataArray = [ + { src: '../assets/images/carousel/genome-sm.jpg' }, + { src: '../assets/images/carousel/falkirk-wheel-sm.jpg' }, + { src: '../assets/images/carousel/iss-sm.jpg' }, + { src: '../assets/images/carousel/shark-sm.jpg' }, + { src: '../assets/images/carousel/snowflake-sm.jpg' }, + { src: '../assets/images/carousel/virus-sm.jpg' }, + { src: '../assets/images/carousel/rock-formation-sm.jpg' }, + { src: '../assets/images/carousel/circuit-board-sm.jpg' } ]; }]);
f3c4fc88e6e2bb7cb28bd491812226805f321994
lib/helpers.js
lib/helpers.js
'use babel' import minimatch from 'minimatch' export function showError(e) { atom.notifications.addError(`[Linter] ${e.message}`, { detail: e.stack, dismissable: true }) } export function shouldTriggerLinter(linter, wasTriggeredOnChange, scopes) { if (wasTriggeredOnChange && !linter.lintOnFly) { return false } return scopes.some(function (scope) { return linter.grammarScopes.indexOf(scope) !== -1 }) } export function requestUpdateFrame(callback) { setTimeout(callback, 100) } export function debounce(callback, delay) { let timeout = null return function(arg) { clearTimeout(timeout) timeout = setTimeout(() => { callback.call(this, arg) }, delay) } } export function isPathIgnored(filePath, ignoredGlob) { const projectPaths = atom.project.getPaths() const projectPathsLength = projectPaths.length let repository = null for (let i = 0; i < projectPathsLength; ++i) { const projectPath = projectPaths[i] if (filePath.indexOf(projectPath) === 0) { repository = atom.project.getRepositories()[i] break } } if (repository !== null && repository.isProjectAtRoot() && repository.isPathIgnored(filePath)) { return true } return minimatch(filePath, ignoredGlob) }
'use babel' import minimatch from 'minimatch' export function showError(e) { atom.notifications.addError(`[Linter] ${e.message}`, { detail: e.stack, dismissable: true }) } export function shouldTriggerLinter(linter, wasTriggeredOnChange, scopes) { if (wasTriggeredOnChange && !linter.lintOnFly) { return false } return scopes.some(function (scope) { return linter.grammarScopes.indexOf(scope) !== -1 }) } export function isPathIgnored(filePath, ignoredGlob) { const projectPaths = atom.project.getPaths() const projectPathsLength = projectPaths.length let repository = null for (let i = 0; i < projectPathsLength; ++i) { const projectPath = projectPaths[i] if (filePath.indexOf(projectPath) === 0) { repository = atom.project.getRepositories()[i] break } } if (repository !== null && repository.isProjectAtRoot() && repository.isPathIgnored(filePath)) { return true } return minimatch(filePath, ignoredGlob) } export function messageKey(message) { return (message.text || message.html) + '$' + message.class + '$' + message.name + '$' + ( message.range ? (message.range.start.column + ':' + message.range.start.row + message.range.end.column + ':' + message.range.end.row) : '' ) }
Add a message key helper; also cleanup unused
:new: Add a message key helper; also cleanup unused
JavaScript
mit
AtomLinter/Linter,atom-community/linter,steelbrain/linter
--- +++ @@ -18,20 +18,6 @@ }) } -export function requestUpdateFrame(callback) { - setTimeout(callback, 100) -} - -export function debounce(callback, delay) { - let timeout = null - return function(arg) { - clearTimeout(timeout) - timeout = setTimeout(() => { - callback.call(this, arg) - }, delay) - } -} - export function isPathIgnored(filePath, ignoredGlob) { const projectPaths = atom.project.getPaths() const projectPathsLength = projectPaths.length @@ -48,3 +34,9 @@ } return minimatch(filePath, ignoredGlob) } + +export function messageKey(message) { + return (message.text || message.html) + '$' + message.class + '$' + message.name + '$' + ( + message.range ? (message.range.start.column + ':' + message.range.start.row + message.range.end.column + ':' + message.range.end.row) : '' + ) +}
1b37e313bc95d878a2774590bdad9e7682d4b829
lib/html2js.js
lib/html2js.js
'use babel' import Html2JsView from './html2js-view' import html2js from './html-2-js' import { CompositeDisposable } from 'atom' export default { html2JsView: null, modalPanel: null, subscriptions: null, activate (state) { this.subscriptions = new CompositeDisposable() this.html2JsView = new Html2JsView(state.html2JsViewState) this.html2JsView.onSubmit((text) => { atom.workspace.open().then((textEditor) => { let htmlJs = html2js(text, {}) textEditor.setText(htmlJs) }) }) this.subscriptions.add(atom.commands.add('atom-workspace', { 'html2js:toggle': () => this.html2JsView.toggle() })) }, deactivate () { this.subscriptions.dispose() this.subscriptions = null this.html2JsView.destroy() this.html2JsView = null }, serialize () { return { html2JsViewState: this.html2JsView.serialize() } } }
'use babel' import Html2JsView from './html2js-view' import html2js from './html-2-js' import { CompositeDisposable } from 'atom' export default { html2JsView: null, modalPanel: null, subscriptions: null, activate (state) { this.subscriptions = new CompositeDisposable() this.html2JsView = new Html2JsView(state.html2JsViewState) this.html2JsView.onSubmit((text) => { atom.workspace.open().then((textEditor) => { let htmlJs = html2js(text, {}) textEditor.setText(htmlJs) textEditor.setGrammar(atom.grammars.grammarForScopeName('source.js')) }) }) this.subscriptions.add(atom.commands.add('atom-workspace', { 'html2js:toggle': () => this.html2JsView.toggle() })) }, deactivate () { this.subscriptions.dispose() this.subscriptions = null this.html2JsView.destroy() this.html2JsView = null }, serialize () { return { html2JsViewState: this.html2JsView.serialize() } } }
Set JS grammar to newly created pane texteditor
Set JS grammar to newly created pane texteditor
JavaScript
mit
jerone/atom-html2js,jerone/atom-html2js
--- +++ @@ -18,6 +18,7 @@ atom.workspace.open().then((textEditor) => { let htmlJs = html2js(text, {}) textEditor.setText(htmlJs) + textEditor.setGrammar(atom.grammars.grammarForScopeName('source.js')) }) })
bac10e88a8732cf5d4914635bb93ff91c8c68e81
.grunt-tasks/postcss.js
.grunt-tasks/postcss.js
module.exports = { options: { map: true, processors: [ require("pixrem")(), // add fallbacks for rem units for IE8+ require("autoprefixer")({ browsers: "> 1%, last 2 versions, ie >= 8" }), // add vendor prefixes ] }, default: { src: "dist/stylesheets/*.css" } };
module.exports = { options: { map: true, processors: [ require("pixrem")({ html: false, atrules: true }), // add fallbacks for rem units for IE8+ require("autoprefixer")({ browsers: "> 1%, last 2 versions, ie >= 8" }), // add vendor prefixes ] }, default: { src: "dist/stylesheets/*.css" } };
Update post css task to add rem fallbacks properly for IE8
Update post css task to add rem fallbacks properly for IE8
JavaScript
mit
nhsevidence/NICE-Experience,nhsevidence/NICE-Experience
--- +++ @@ -2,7 +2,7 @@ options: { map: true, processors: [ - require("pixrem")(), // add fallbacks for rem units for IE8+ + require("pixrem")({ html: false, atrules: true }), // add fallbacks for rem units for IE8+ require("autoprefixer")({ browsers: "> 1%, last 2 versions, ie >= 8" }), // add vendor prefixes ] },
a8cddb0a5b2e026ce0733a66aa4aaa77de1ec506
bin/cli.js
bin/cli.js
#!/usr/bin/env node 'use strict'; const dependencyTree = require('../'); const program = require('commander'); program .version(require('../package.json').version) .usage('[options] <filename>') .option('-d, --directory <path>', 'location of files of supported filetypes') .option('-c, --require-config <path>', 'path to a requirejs config') .option('-w, --webpack-config <path>', 'path to a webpack config') .option('--list-form', 'output the list form of the tree (one element per line)') .parse(process.argv); let tree; const options = { filename: program.args[0], root: program.directory, config: program.requireConfig, webpackConfig: program.webpackConfig }; if (program.listForm) { tree = dependencyTree.toList(options); tree.forEach(function(node) { console.log(node); }); } else { tree = dependencyTree(options); console.log(JSON.stringify(tree)); }
#!/usr/bin/env node 'use strict'; const dependencyTree = require('../'); const program = require('commander'); program .version(require('../package.json').version) .usage('[options] <filename>') .option('-d, --directory <path>', 'location of files of supported filetypes') .option('-c, --require-config <path>', 'path to a requirejs config') .option('-w, --webpack-config <path>', 'path to a webpack config') .option('-t, --ts-config <path>', 'path to a typescript config') .option('--list-form', 'output the list form of the tree (one element per line)') .parse(process.argv); let tree; const options = { filename: program.args[0], root: program.directory, config: program.requireConfig, webpackConfig: program.webpackConfig, tsConfig: program.tsConfig }; if (program.listForm) { tree = dependencyTree.toList(options); tree.forEach(function(node) { console.log(node); }); } else { tree = dependencyTree(options); console.log(JSON.stringify(tree)); }
Add --tsconfig CLI option to specify a TypeScript config file
Add --tsconfig CLI option to specify a TypeScript config file
JavaScript
mit
dependents/node-dependency-tree,dependents/node-dependency-tree
--- +++ @@ -11,6 +11,7 @@ .option('-d, --directory <path>', 'location of files of supported filetypes') .option('-c, --require-config <path>', 'path to a requirejs config') .option('-w, --webpack-config <path>', 'path to a webpack config') + .option('-t, --ts-config <path>', 'path to a typescript config') .option('--list-form', 'output the list form of the tree (one element per line)') .parse(process.argv); @@ -20,7 +21,8 @@ filename: program.args[0], root: program.directory, config: program.requireConfig, - webpackConfig: program.webpackConfig + webpackConfig: program.webpackConfig, + tsConfig: program.tsConfig }; if (program.listForm) {
408567081d82c28b1ff0041c10c57f879acf1187
dawn/js/components/peripherals/NameEdit.js
dawn/js/components/peripherals/NameEdit.js
import React from 'react'; import InlineEdit from 'react-edit-inline'; import Ansible from '../../utils/Ansible'; var NameEdit = React.createClass({ propTypes: { name: React.PropTypes.string, id: React.PropTypes.string }, dataChange(data) { Ansible.sendMessage('custom_names', { id: this.props.id, name: data.name }); }, render() { return ( <div> <InlineEdit className="static" activeClassName="editing" text={this.props.name} change={this.dataChange} paramName="name" style = {{ backgroundColor: 'white', minWidth: 150, display: 'inline-block', margin: 0, padding: 0, fontSize:15 }} /> </div> ); } }); export default NameEdit;
import React from 'react'; import InlineEdit from 'react-edit-inline'; import Ansible from '../../utils/Ansible'; var NameEdit = React.createClass({ propTypes: { name: React.PropTypes.string, id: React.PropTypes.string }, dataChange(data) { var x = new RegExp("^[A-Za-z][A-Za-z0-9]+$"); if (x.test(data.name)) { Ansible.sendMessage('custom_names', { id: this.props.id, name: data.name }); } }, render() { return ( <div> <InlineEdit className="static" activeClassName="editing" text={this.props.name} change={this.dataChange} paramName="name" style = {{ backgroundColor: 'white', minWidth: 150, display: 'inline-block', margin: 0, padding: 0, fontSize:15 }} /> </div> ); } }); export default NameEdit;
Check new peripheral names against regex
Check new peripheral names against regex
JavaScript
apache-2.0
pioneers/PieCentral,pioneers/PieCentral,pioneers/PieCentral,pioneers/PieCentral,pioneers/PieCentral,pioneers/PieCentral,pioneers/PieCentral
--- +++ @@ -8,10 +8,13 @@ id: React.PropTypes.string }, dataChange(data) { - Ansible.sendMessage('custom_names', { - id: this.props.id, - name: data.name - }); + var x = new RegExp("^[A-Za-z][A-Za-z0-9]+$"); + if (x.test(data.name)) { + Ansible.sendMessage('custom_names', { + id: this.props.id, + name: data.name + }); + } }, render() { return (
ee678fe9f72422507e138ffa9fb45485c7fb0449
src/views/Main/Container.js
src/views/Main/Container.js
import React from 'react'; import Map, {GoogleApiWrapper} from 'google-maps-react'; import { searchNearby } from 'utils/googleApiHelpers'; export class Container extends React.Component { onReady(mapProps, map) { // when map is ready and const { google } = this.props; const opts = { location: map.center, radius: '500', types: ['cafe'] } searchNearby(google, map, opts) .then((results, pagination) => { // we got some results and a pagination object }).catch((status, result) => { // there was an error }) } render() { return ( <div> <Map onReady={this.onReady.bind(this)} google={this.props.google} /> </div> ) } } export default GoogleApiWrapper({ apiKey: __GAPI_KEY__ })(Container);
import React from 'react'; import Map, {GoogleApiWrapper} from 'google-maps-react'; import { searchNearby } from 'utils/googleApiHelpers'; export class Container extends React.Component { constructor(props) { // super initializes this super(props); this.state = { places: [], pagination: null } } onReady(mapProps, map) { // when map is ready const { google } = this.props; const opts = { location: map.center, radius: '500', types: ['cafe'] } searchNearby(google, map, opts) .then((results, pagination) => { // we got some results and a pagination object this.setState({ places: results, pagination }) }).catch((status, result) => { // there was an error }) } render() { return ( <div> <Map onReady={this.onReady.bind(this)} google={this.props.google} visible={false} > {this.state.places.map(place => { return (<div key={place.id}>{place.name}</div>) })} </Map> </div> ) } } export default GoogleApiWrapper({ apiKey: __GAPI_KEY__ })(Container);
Set Main container to be stateful
Set Main container to be stateful
JavaScript
mit
Kgiberson/welp
--- +++ @@ -4,8 +4,17 @@ import { searchNearby } from 'utils/googleApiHelpers'; export class Container extends React.Component { + constructor(props) { + // super initializes this + super(props); + + this.state = { + places: [], + pagination: null + } + } onReady(mapProps, map) { - // when map is ready and + // when map is ready const { google } = this.props; const opts = { location: map.center, @@ -15,6 +24,10 @@ searchNearby(google, map, opts) .then((results, pagination) => { // we got some results and a pagination object + this.setState({ + places: results, + pagination + }) }).catch((status, result) => { // there was an error }) @@ -24,7 +37,14 @@ <div> <Map onReady={this.onReady.bind(this)} - google={this.props.google} /> + google={this.props.google} + visible={false} > + + {this.state.places.map(place => { + return (<div key={place.id}>{place.name}</div>) + })} + + </Map> </div> ) }
7da241808bb335551bd4a822c6970561b859ab76
src/models/apikey.js
src/models/apikey.js
import stampit from 'stampit'; import {Meta, Model} from './base'; const ApiKeyMeta = Meta({ name: 'apiKey', pluralName: 'apiKeys', endpoints: { 'detail': { 'methods': ['delete', 'get'], 'path': '/v1/instances/{instanceName}/api_keys/{id}/' }, 'list': { 'methods': ['post', 'get'], 'path': '/v1/instances/{instanceName}/api_keys/' } } }); const ApiKey = stampit() .compose(Model) .setMeta(ApiKeyMeta); export default ApiKey;
import stampit from 'stampit'; import {Meta, Model} from './base'; const ApiKeyMeta = Meta({ name: 'apiKey', pluralName: 'apiKeys', endpoints: { 'detail': { 'methods': ['delete', 'patch', 'put', 'get'], 'path': '/v1/instances/{instanceName}/api_keys/{id}/' }, 'list': { 'methods': ['post', 'get'], 'path': '/v1/instances/{instanceName}/api_keys/' } } }); const ApiKey = stampit() .compose(Model) .setMeta(ApiKeyMeta); export default ApiKey;
Add methods to api key's detail endpoint
[LIB-386] Add methods to api key's detail endpoint
JavaScript
mit
Syncano/syncano-server-js
--- +++ @@ -6,7 +6,7 @@ pluralName: 'apiKeys', endpoints: { 'detail': { - 'methods': ['delete', 'get'], + 'methods': ['delete', 'patch', 'put', 'get'], 'path': '/v1/instances/{instanceName}/api_keys/{id}/' }, 'list': {
35cbf16ff15966ecddc02abd040f8c46fe824a0d
src/components/posts/PostsAsGrid.js
src/components/posts/PostsAsGrid.js
import React from 'react' import { parsePost } from '../parsers/PostParser' class PostsAsGrid extends React.Component { static propTypes = { posts: React.PropTypes.object, json: React.PropTypes.object, currentUser: React.PropTypes.object, gridColumnCount: React.PropTypes.number, } renderColumn(posts) { const { json, currentUser } = this.props return ( <div className="Column"> {posts.map((post) => { return ( <article ref={`postGrid_${post.id}`} key={post.id} className="Post PostGrid"> {parsePost(post, json, currentUser)} </article> ) })} </div> ) } render() { const { posts, gridColumnCount } = this.props if (!gridColumnCount) { return null } const columns = [] for (let i = 0; i < gridColumnCount; i++) { columns.push([]) } for (const index in posts.data) { if (posts.data[index]) { columns[index % gridColumnCount].push(posts.data[index]) } } return ( <div className="Posts asGrid"> {columns.map((column) => { return this.renderColumn(column) })} </div> ) } } export default PostsAsGrid
import React from 'react' import { parsePost } from '../parsers/PostParser' class PostsAsGrid extends React.Component { static propTypes = { posts: React.PropTypes.object, json: React.PropTypes.object, currentUser: React.PropTypes.object, gridColumnCount: React.PropTypes.number, } renderColumn(posts, index) { const { json, currentUser } = this.props return ( <div className="Column" key={`column_${index}`}> {posts.map((post) => { return ( <article ref={`postGrid_${post.id}`} key={post.id} className="Post PostGrid"> {parsePost(post, json, currentUser)} </article> ) })} </div> ) } render() { const { posts, gridColumnCount } = this.props if (!gridColumnCount) { return null } const columns = [] for (let i = 0; i < gridColumnCount; i++) { columns.push([]) } for (const index in posts.data) { if (posts.data[index]) { columns[index % gridColumnCount].push(posts.data[index]) } } return ( <div className="Posts asGrid"> {columns.map((column, index) => { return this.renderColumn(column, index) })} </div> ) } } export default PostsAsGrid
Fix an issue with grid post rendering.
Fix an issue with grid post rendering.
JavaScript
mit
ello/webapp,ello/webapp,ello/webapp
--- +++ @@ -9,10 +9,10 @@ gridColumnCount: React.PropTypes.number, } - renderColumn(posts) { + renderColumn(posts, index) { const { json, currentUser } = this.props return ( - <div className="Column"> + <div className="Column" key={`column_${index}`}> {posts.map((post) => { return ( <article ref={`postGrid_${post.id}`} key={post.id} className="Post PostGrid"> @@ -38,8 +38,8 @@ } return ( <div className="Posts asGrid"> - {columns.map((column) => { - return this.renderColumn(column) + {columns.map((column, index) => { + return this.renderColumn(column, index) })} </div> )
74b87cbca5fc7bd065ecd129463856dffc8b4b7e
app/routes/fellows.server.routes.js
app/routes/fellows.server.routes.js
'use strict'; var users = require('../../app/controllers/users'); var fellows = require('../../app/controllers/fellows'); module.exports = function(app) { // Setting up the bootcamp api app.route('/camps') <<<<<<< HEAD .get(fellows.list_camp) // login and authorization required ======= .get(fellows.list_camp); // login and authorization required >>>>>>> d27202af5ed201b57b4a5a78a95f3bdc88556d1a // .post(fellows.create_camp); //by admin app.route('/camps/:campId') .get(fellows.read_camp) // login and authorization required .put(fellows.update_camp) // login and authorization required .delete(fellows.delete_camp); // login and authorization required app.route('/camps/:campId/fellows'); //.get(fellows.list_applicant) // login and authorization required // .post(fellows.create_applicant); //by admin app.route('/camps/:campId/fellows/:fellowId') .get(fellows.read_applicant) // login and authorization required .delete(fellows.delete_applicant); // login and authorization required by admin // Finish by binding the fellow middleware app.param('fellowId', fellows.fellowByID); };
'use strict'; var users = require('../../app/controllers/users'); var fellows = require('../../app/controllers/fellows'); module.exports = function(app) { // Setting up the bootcamp api app.route('/camps') .get(fellows.list_camp); // login and authorization required // .post(fellows.create_camp); //by admin app.route('/camps/:campId') .get(fellows.read_camp) // login and authorization required .put(fellows.update_camp) // login and authorization required .delete(fellows.delete_camp); // login and authorization required app.route('/camps/:campId/fellows'); //.get(fellows.list_applicant) // login and authorization required // .post(fellows.create_applicant); //by admin app.route('/camps/:campId/fellows/:fellowId') .get(fellows.read_applicant) // login and authorization required .delete(fellows.delete_applicant); // login and authorization required by admin // Finish by binding the fellow middleware app.param('fellowId', fellows.fellowByID); };
Reset fellow server js file
Reset fellow server js file
JavaScript
mit
andela-ogaruba/AndelaAPI
--- +++ @@ -6,11 +6,7 @@ module.exports = function(app) { // Setting up the bootcamp api app.route('/camps') -<<<<<<< HEAD - .get(fellows.list_camp) // login and authorization required -======= .get(fellows.list_camp); // login and authorization required ->>>>>>> d27202af5ed201b57b4a5a78a95f3bdc88556d1a // .post(fellows.create_camp); //by admin app.route('/camps/:campId')
36ffbef010db6d60a4dbc9b6c4eab9ad4ebbcf7b
src/components/views/elements/Field.js
src/components/views/elements/Field.js
/* Copyright 2019 New Vector Ltd 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 React from 'react'; import PropTypes from 'prop-types'; export default class Field extends React.PureComponent { static propTypes = { // The field's id, which binds the input and label together. id: PropTypes.string.isRequired, // The field's <input> type. Defaults to "text". type: PropTypes.string, // The field's label string. label: PropTypes.string, // The field's placeholder string. placeholder: PropTypes.string, // All other props pass through to the <input>. } render() { const extraProps = Object.assign({}, this.props); // Remove explicit props delete extraProps.id; delete extraProps.type; delete extraProps.placeholder; delete extraProps.label; return <div className="mx_Field"> <input id={this.props.id} type={this.props.type || "text"} placeholder={this.props.placeholder} {...extraProps} /> <label htmlFor={this.props.id}>{this.props.label}</label> </div>; } }
/* Copyright 2019 New Vector Ltd 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 React from 'react'; import PropTypes from 'prop-types'; export default class Field extends React.PureComponent { static propTypes = { // The field's ID, which binds the input and label together. id: PropTypes.string.isRequired, // The field's <input> type. Defaults to "text". type: PropTypes.string, // The field's label string. label: PropTypes.string, // The field's placeholder string. placeholder: PropTypes.string, // All other props pass through to the <input>. } render() { const extraProps = Object.assign({}, this.props); // Remove explicit props delete extraProps.id; delete extraProps.type; delete extraProps.placeholder; delete extraProps.label; return <div className="mx_Field"> <input id={this.props.id} type={this.props.type || "text"} placeholder={this.props.placeholder} {...extraProps} /> <label htmlFor={this.props.id}>{this.props.label}</label> </div>; } }
Tweak comment about field ID
Tweak comment about field ID Co-Authored-By: jryans <91e4c98f79b38ce04c052c188926e2d9ae2a3b28@gmail.com>
JavaScript
apache-2.0
matrix-org/matrix-react-sdk,matrix-org/matrix-react-sdk,matrix-org/matrix-react-sdk,matrix-org/matrix-react-sdk,matrix-org/matrix-react-sdk,matrix-org/matrix-react-sdk
--- +++ @@ -19,7 +19,7 @@ export default class Field extends React.PureComponent { static propTypes = { - // The field's id, which binds the input and label together. + // The field's ID, which binds the input and label together. id: PropTypes.string.isRequired, // The field's <input> type. Defaults to "text". type: PropTypes.string,
49cb1ee49686ea320689ae97ce94c5d593cccdbb
ws-connect.js
ws-connect.js
var WebSocket = require('ws'); var reHttpSignalhost = /^http(.*)$/; var reTrailingSlash = /\/$/; function connect(signalhost) { // if we have a http/https signalhost then do some replacement magic to push across // to ws implementation (also add the /primus endpoint) if (reHttpSignalhost.test(signalhost)) { signalhost = signalhost .replace(reHttpSignalhost, 'ws$1') .replace(reTrailingSlash, '') + '/primus'; } return new WebSocket(signalhost); } module.exports = function(signalhost, opts, callback) { var ws = connect(signalhost); ws.once('open', function() { // close the test socket ws.close(); callback(null, { connect: connect }); }); };
var WebSocket = require('ws'); var reHttpSignalhost = /^http(.*)$/; var reTrailingSlash = /\/$/; var pingers = []; var PINGHEADER = 'primus::ping::'; var PONGHEADER = 'primus::pong::'; function connect(signalhost) { var socket; // if we have a http/https signalhost then do some replacement magic to push across // to ws implementation (also add the /primus endpoint) if (reHttpSignalhost.test(signalhost)) { signalhost = signalhost .replace(reHttpSignalhost, 'ws$1') .replace(reTrailingSlash, '') + '/primus'; } socket = new WebSocket(signalhost); socket.on('message', function(data) { if (data.slice(0, PONGHEADER.length) === PONGHEADER) { queuePing(socket); } }); queuePing(socket); return socket; } function queuePing(socket) { pingers.push(socket); } setInterval(function() { pingers.splice(0).forEach(function(socket) { if (socket.readyState === 1) { socket.send(PINGHEADER + Date.now(), function(err) { if (err) { console.log('could not send ping: ', err); } }); } }); }, 10e3); module.exports = function(signalhost, opts, callback) { var ws = connect(signalhost); ws.once('open', function() { // close the test socket ws.close(); callback(null, { connect: connect }); }); };
Improve node socket connection to ping as per what a primus server expects
Improve node socket connection to ping as per what a primus server expects
JavaScript
apache-2.0
eightyeight/rtc-signaller,rtc-io/rtc-signaller
--- +++ @@ -1,8 +1,13 @@ var WebSocket = require('ws'); var reHttpSignalhost = /^http(.*)$/; var reTrailingSlash = /\/$/; +var pingers = []; +var PINGHEADER = 'primus::ping::'; +var PONGHEADER = 'primus::pong::'; function connect(signalhost) { + var socket; + // if we have a http/https signalhost then do some replacement magic to push across // to ws implementation (also add the /primus endpoint) if (reHttpSignalhost.test(signalhost)) { @@ -11,8 +16,33 @@ .replace(reTrailingSlash, '') + '/primus'; } - return new WebSocket(signalhost); + socket = new WebSocket(signalhost); + + socket.on('message', function(data) { + if (data.slice(0, PONGHEADER.length) === PONGHEADER) { + queuePing(socket); + } + }); + + queuePing(socket); + return socket; } + +function queuePing(socket) { + pingers.push(socket); +} + +setInterval(function() { + pingers.splice(0).forEach(function(socket) { + if (socket.readyState === 1) { + socket.send(PINGHEADER + Date.now(), function(err) { + if (err) { + console.log('could not send ping: ', err); + } + }); + } + }); +}, 10e3); module.exports = function(signalhost, opts, callback) { var ws = connect(signalhost);
a6972191cf167266225ddcedc1c12ce94297ef1c
lib/reporters/lcov-reporter.js
lib/reporters/lcov-reporter.js
var Reporter = require('../reporter'); var lcovRecord = function(data) { var str = "", lineHandled = 0, lineFound = 0, fileName = data.fileName; if(this.options.lcovOptions && this.options.lcovOptions.renamer){ fileName = this.options.lcovOptions.renamer(fileName); } str += 'SF:' + fileName + '\n'; data.lines.forEach(function(value, num) { if (value !== null) { str += 'DA:' + num + ',' + value + '\n'; lineFound += 1; if (value > 0) { lineHandled += 1; } } }); str += 'LF:' + lineFound + '\n'; str += 'LH:' + lineHandled + '\n'; str += 'end_of_record'; return str; }; /** * LCOVReporter outputs lcov formatted coverage data * from the test run * * @class LCOVReporter * @param {Object} options hash of options interpreted by reporter */ module.exports = Reporter.extend({ name: 'lcov', defaultOutput: 'lcov.dat', transform: function(coverageData) { var data = coverageData.fileData.map(lcovRecord, this); return data.join('\n'); } });
var Reporter = require('../reporter'); var lcovRecord = function(data) { var str = '', lineHandled = 0, lineFound = 0, fileName = data.fileName; if (this.options.cliOptions && this.options.cliOptions.lcovOptions && this.options.cliOptions.lcovOptions.renamer){ fileName = this.options.cliOptions.lcovOptions.renamer(fileName); } str += 'SF:' + fileName + '\n'; data.lines.forEach(function(value, num) { if (value !== null) { str += 'DA:' + num + ',' + value + '\n'; lineFound += 1; if (value > 0) { lineHandled += 1; } } }); str += 'LF:' + lineFound + '\n'; str += 'LH:' + lineHandled + '\n'; str += 'end_of_record'; return str; }; /** * LCOVReporter outputs lcov formatted coverage data * from the test run * * @class LCOVReporter * @param {Object} options hash of options interpreted by reporter */ module.exports = Reporter.extend({ name: 'lcov', defaultOutput: 'lcov.dat', transform: function(coverageData) { var data = coverageData.fileData.map(lcovRecord, this); return data.join('\n'); } });
Fix renamer, lcov check was not accessing the proper object
Fix renamer, lcov check was not accessing the proper object
JavaScript
mit
yagni/ember-cli-blanket,elwayman02/ember-cli-blanket,jschilli/ember-cli-blanket,calderas/ember-cli-blanket,dwickern/ember-cli-blanket,yagni/ember-cli-blanket,calderas/ember-cli-blanket,notmessenger/ember-cli-blanket,jschilli/ember-cli-blanket,elwayman02/ember-cli-blanket,mike-north/ember-cli-blanket,sglanzer/ember-cli-blanket,mike-north/ember-cli-blanket,sglanzer/ember-cli-blanket,dwickern/ember-cli-blanket,notmessenger/ember-cli-blanket
--- +++ @@ -1,13 +1,13 @@ var Reporter = require('../reporter'); var lcovRecord = function(data) { - var str = "", + var str = '', lineHandled = 0, lineFound = 0, fileName = data.fileName; - if(this.options.lcovOptions && this.options.lcovOptions.renamer){ - fileName = this.options.lcovOptions.renamer(fileName); + if (this.options.cliOptions && this.options.cliOptions.lcovOptions && this.options.cliOptions.lcovOptions.renamer){ + fileName = this.options.cliOptions.lcovOptions.renamer(fileName); } str += 'SF:' + fileName + '\n';
24e687564a18b651d57f7f49ae5c79ff935fb95a
lib/ui/widgets/basewidget.js
lib/ui/widgets/basewidget.js
var schema = require('signalk-schema'); function BaseWidget(id, options, streamBundle, instrumentPanel) { this.instrumentPanel = instrumentPanel; } BaseWidget.prototype.setActive = function(value) { this.options.active = value; this.instrumentPanel.onWidgetChange(this); } BaseWidget.prototype.getLabelForPath = function(path) { var i18nElement = schema.i18n.en[path]; return i18nElement ? i18nElement.shortName || i18nElement.longName || "??" : path } BaseWidget.prototype.getUnitForPath = function(path) { var i18nElement = schema.i18n.en[path]; return i18nElement ? i18nElement.unit : undefined; } module.exports = BaseWidget;
var schema = require('signalk-schema'); function BaseWidget(id, options, streamBundle, instrumentPanel) { this.instrumentPanel = instrumentPanel; } BaseWidget.prototype.setActive = function(value) { this.options.active = value; this.instrumentPanel.onWidgetChange(this); } BaseWidget.prototype.getLabelForPath = function(path) { var i18nElement = schema.i18n.en[path]; return i18nElement ? i18nElement.shortName || i18nElement.longName || "??" : path } BaseWidget.prototype.getUnitForPath = function(path) { var i18nElement = schema.i18n.en[path]; return i18nElement ? i18nElement.unit : undefined; } BaseWidget.prototype.displayValue = function(value) { if(typeof value === 'number') { var v = Math.abs(value); if(v >= 50) { return value.toFixed(0); } else if(v >= 10) { return value.toFixed(1); } else { return value.toFixed(2); } } return value; } module.exports = BaseWidget;
Add shared function for range sensitive rounding
Add shared function for range sensitive rounding
JavaScript
apache-2.0
SignalK/instrumentpanel,SignalK/instrumentpanel
--- +++ @@ -21,4 +21,18 @@ return i18nElement ? i18nElement.unit : undefined; } +BaseWidget.prototype.displayValue = function(value) { + if(typeof value === 'number') { + var v = Math.abs(value); + if(v >= 50) { + return value.toFixed(0); + } else if(v >= 10) { + return value.toFixed(1); + } else { + return value.toFixed(2); + } + } + return value; +} + module.exports = BaseWidget;
e17572851a8351fdf7210db5aed7c6c9784c2497
test/stack-test.js
test/stack-test.js
/*global describe, it*/ /* * mochify.js * * Copyright (c) 2014 Maximilian Antoni <mail@maxantoni.de> * * @license MIT */ 'use strict'; var assert = require('assert'); var run = require('./fixture/run'); describe('stack', function () { this.timeout(3000); it('does not screw up xunit', function (done) { run('passes', ['-R', 'xunit'], function (code, stdout) { var lines = stdout.split('\n'); assert.equal(lines[1].substring(0, lines[1].length - 3), '<testcase classname="test" name="passes" time="0'); assert.equal(lines[2], '</testsuite>'); assert.equal(code, 0); done(); }); }); });
/*global describe, it*/ /* * mochify.js * * Copyright (c) 2014 Maximilian Antoni <mail@maxantoni.de> * * @license MIT */ 'use strict'; var assert = require('assert'); var run = require('./fixture/run'); describe('stack', function () { this.timeout(3000); it('does not screw up xunit', function (done) { run('passes', ['-R', 'xunit'], function (code, stdout) { var lines = stdout.split('\n'); var expect = '<testcase classname="test" name="passes" time="0'; assert.equal(lines[1].substring(0, expect.length), expect); assert.equal(lines[2], '</testsuite>'); assert.equal(code, 0); done(); }); }); });
Fix test case to not fail due to varying timing (again)
Fix test case to not fail due to varying timing (again)
JavaScript
mit
mantoni/mochify.js,jhytonen/mochify.js,mantoni/mochify.js,mantoni/mochify.js,jhytonen/mochify.js,Heng-xiu/mochify.js,Swaagie/mochify.js,Swaagie/mochify.js,boneskull/mochify.js,boneskull/mochify.js,Heng-xiu/mochify.js
--- +++ @@ -18,8 +18,8 @@ it('does not screw up xunit', function (done) { run('passes', ['-R', 'xunit'], function (code, stdout) { var lines = stdout.split('\n'); - assert.equal(lines[1].substring(0, lines[1].length - 3), - '<testcase classname="test" name="passes" time="0'); + var expect = '<testcase classname="test" name="passes" time="0'; + assert.equal(lines[1].substring(0, expect.length), expect); assert.equal(lines[2], '</testsuite>'); assert.equal(code, 0); done();
e178e5a5213b07650fa4c9ce1fc32c25c3d7af12
main/plugins/settings/index.js
main/plugins/settings/index.js
import React from 'react'; import Settings from './Settings'; /** * Plugin to show app settings in results list * @param {String} term */ const settingsPlugin = (term, callback) => { if (!term.match(/^(show\s+)?(settings|preferences)\s*/i)) return; callback([{ icon: '/Applications/Cerebro.app', title: 'Cerebro settings', id: `settings`, getPreview: () => <Settings /> }]); }; export default { name: 'Cerebro settings', icon: '/Applications/Cerebro.app', keyword: 'Settings', fn: settingsPlugin };
import React from 'react'; import search from 'lib/search'; import Settings from './Settings'; // Settings plugin name const NAME = 'Cerebro Settings'; // Phrases that used to find settings plugins const KEYWORDS = [ NAME, 'Cerebro Preferences' ]; /** * Plugin to show app settings in results list * @param {String} term */ const settingsPlugin = (term, callback) => { const found = search(KEYWORDS, term).length > 0; if (found) { const results = [{ icon: '/Applications/Cerebro.app', title: NAME, term: NAME, id: 'settings', getPreview: () => <Settings /> }]; callback(results); } } export default { name: NAME, fn: settingsPlugin };
Improve search if settings plugin Now available by settings and preferences words
Improve search if settings plugin Now available by settings and preferences words
JavaScript
mit
KELiON/cerebro,KELiON/cerebro
--- +++ @@ -1,23 +1,35 @@ import React from 'react'; +import search from 'lib/search'; import Settings from './Settings'; + +// Settings plugin name +const NAME = 'Cerebro Settings'; + +// Phrases that used to find settings plugins +const KEYWORDS = [ + NAME, + 'Cerebro Preferences' +]; /** * Plugin to show app settings in results list * @param {String} term */ const settingsPlugin = (term, callback) => { - if (!term.match(/^(show\s+)?(settings|preferences)\s*/i)) return; - callback([{ - icon: '/Applications/Cerebro.app', - title: 'Cerebro settings', - id: `settings`, - getPreview: () => <Settings /> - }]); -}; + const found = search(KEYWORDS, term).length > 0; + if (found) { + const results = [{ + icon: '/Applications/Cerebro.app', + title: NAME, + term: NAME, + id: 'settings', + getPreview: () => <Settings /> + }]; + callback(results); + } +} export default { - name: 'Cerebro settings', - icon: '/Applications/Cerebro.app', - keyword: 'Settings', + name: NAME, fn: settingsPlugin };
3af7d2e005748a871efe4d2dd278d11dfc82950f
next.config.js
next.config.js
const withOffline = require("next-offline"); const nextConfig = { target: "serverless", future: { webpack5: true, }, workboxOpts: { swDest: "static/service-worker.js", runtimeCaching: [ { urlPattern: /^https?.*/, handler: "NetworkFirst", options: { cacheName: "https-calls", networkTimeoutSeconds: 15, expiration: { maxEntries: 150, maxAgeSeconds: 30 * 24 * 60 * 60 }, cacheableResponse: { statuses: [0, 200] } } } ] } }; module.exports = withOffline(nextConfig);
const withOffline = require("next-offline"); const nextConfig = { target: "serverless", workboxOpts: { runtimeCaching: [ { urlPattern: /^https?.*/, handler: "NetworkFirst", options: { cacheName: "offlineCache", expiration: { maxEntries: 200 } } } ] } }; module.exports = withOffline(nextConfig);
Swap back to webpack 4, adjust next-offline
Swap back to webpack 4, adjust next-offline
JavaScript
bsd-2-clause
overshard/isaacbythewood.com,overshard/isaacbythewood.com
--- +++ @@ -2,24 +2,15 @@ const nextConfig = { target: "serverless", - future: { - webpack5: true, - }, workboxOpts: { - swDest: "static/service-worker.js", runtimeCaching: [ { urlPattern: /^https?.*/, handler: "NetworkFirst", options: { - cacheName: "https-calls", - networkTimeoutSeconds: 15, + cacheName: "offlineCache", expiration: { - maxEntries: 150, - maxAgeSeconds: 30 * 24 * 60 * 60 - }, - cacheableResponse: { - statuses: [0, 200] + maxEntries: 200 } } }
06cac5f7a677bf7d9bc4f92811203d52dc3c6313
cookie-bg-picker/background_scripts/background.js
cookie-bg-picker/background_scripts/background.js
/* Retrieve any previously set cookie and send to content script */ browser.tabs.onUpdated.addListener(cookieUpdate); function getActiveTab() { return browser.tabs.query({active: true, currentWindow: true}); } function cookieUpdate(tabId, changeInfo, tab) { getActiveTab().then((tabs) => { // get any previously set cookie for the current tab var gettingCookies = browser.cookies.get({ url: tabs[0].url, name: "bgpicker" }); gettingCookies.then((cookie) => { if (cookie) { var cookieVal = JSON.parse(cookie.value); browser.tabs.sendMessage(tabs[0].id, {image: cookieVal.image}); browser.tabs.sendMessage(tabs[0].id, {color: cookieVal.color}); } }); }); }
/* Retrieve any previously set cookie and send to content script */ function getActiveTab() { return browser.tabs.query({active: true, currentWindow: true}); } function cookieUpdate() { getActiveTab().then((tabs) => { // get any previously set cookie for the current tab var gettingCookies = browser.cookies.get({ url: tabs[0].url, name: "bgpicker" }); gettingCookies.then((cookie) => { if (cookie) { var cookieVal = JSON.parse(cookie.value); browser.tabs.sendMessage(tabs[0].id, {image: cookieVal.image}); browser.tabs.sendMessage(tabs[0].id, {color: cookieVal.color}); } }); }); } // update when the tab is updated browser.tabs.onUpdated.addListener(cookieUpdate); // update when the tab is activated browser.tabs.onActivated.addListener(cookieUpdate);
Update on tab activate as well as update
Update on tab activate as well as update
JavaScript
mpl-2.0
mdn/webextensions-examples,mdn/webextensions-examples,mdn/webextensions-examples
--- +++ @@ -1,12 +1,10 @@ /* Retrieve any previously set cookie and send to content script */ - -browser.tabs.onUpdated.addListener(cookieUpdate); function getActiveTab() { return browser.tabs.query({active: true, currentWindow: true}); } -function cookieUpdate(tabId, changeInfo, tab) { +function cookieUpdate() { getActiveTab().then((tabs) => { // get any previously set cookie for the current tab var gettingCookies = browser.cookies.get({ @@ -22,3 +20,8 @@ }); }); } + +// update when the tab is updated +browser.tabs.onUpdated.addListener(cookieUpdate); +// update when the tab is activated +browser.tabs.onActivated.addListener(cookieUpdate);
5b20639101d8da9031641fa9565970bcdc67b441
app/assets/javascripts/books.js
app/assets/javascripts/books.js
var ready = function() { $('#FontSize a').click(function() { $('.content').css("font-size", this.dataset.size); }); $('#FontFamily a').click(function(){ $('.content').css("font-family", this.innerHTML); }); $('#Leading a').click(function(){ $('.content').css("line-height", this.dataset.spacing); }); $('#Background a').click(function() { $('body').css("background-color", $(this).css('background-color')); }); }; $(document).ready(ready); $(document).on('page:load', ready);
// http://www.quirksmode.org/js/cookies.html function createCookie(name, value, days) { var expires; if (days) { var date = new Date(); date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000)); expires = "; expires=" + date.toGMTString(); } else { expires = ""; } document.cookie = encodeURIComponent(name) + "=" + encodeURIComponent(value) + expires + "; path=/"; } function readCookie(name) { var nameEQ = encodeURIComponent(name) + "="; var ca = document.cookie.split(';'); for (var i = 0; i < ca.length; i++) { var c = ca[i]; while (c.charAt(0) === ' ') c = c.substring(1, c.length); if (c.indexOf(nameEQ) === 0) return decodeURIComponent(c.substring(nameEQ.length, c.length)); } return null; } var ready = function() { var size = readCookie('font-size'); var family = readCookie('font-family'); var height = readCookie('line-height'); var background = readCookie('background'); if (size) $('.content').css("font-size", size); if (family) $('.content').css("font-family", family); if (height) $('.content').css("line-height", height); if (background) $('body').css("background-color", background); $('#FontSize a').click(function() { $('.content').css("font-size", this.dataset.size); createCookie('font-size', this.dataset.size); }); $('#FontFamily a').click(function(){ $('.content').css("font-family", this.innerHTML); createCookie('font-family', this.innerHTML); }); $('#Leading a').click(function(){ $('.content').css("line-height", this.dataset.spacing); createCookie('line-height', this.dataset.spacing); }); $('#Background a').click(function() { $('body').css("background-color", $(this).css('background-color')); createCookie('background', $(this).css('background-color')); }); }; $(document).ready(ready); $(document).on('page:load', ready);
Use cookies to persist formatting options
Use cookies to persist formatting options
JavaScript
mit
mk12/great-reads,mk12/great-reads,mk12/great-reads
--- +++ @@ -1,18 +1,57 @@ +// http://www.quirksmode.org/js/cookies.html +function createCookie(name, value, days) { + var expires; + + if (days) { + var date = new Date(); + date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000)); + expires = "; expires=" + date.toGMTString(); + } else { + expires = ""; + } + document.cookie = encodeURIComponent(name) + "=" + encodeURIComponent(value) + expires + "; path=/"; +} + +function readCookie(name) { + var nameEQ = encodeURIComponent(name) + "="; + var ca = document.cookie.split(';'); + for (var i = 0; i < ca.length; i++) { + var c = ca[i]; + while (c.charAt(0) === ' ') c = c.substring(1, c.length); + if (c.indexOf(nameEQ) === 0) return decodeURIComponent(c.substring(nameEQ.length, c.length)); + } + return null; +} + var ready = function() { + var size = readCookie('font-size'); + var family = readCookie('font-family'); + var height = readCookie('line-height'); + var background = readCookie('background'); + + if (size) $('.content').css("font-size", size); + if (family) $('.content').css("font-family", family); + if (height) $('.content').css("line-height", height); + if (background) $('body').css("background-color", background); + $('#FontSize a').click(function() { $('.content').css("font-size", this.dataset.size); + createCookie('font-size', this.dataset.size); }); $('#FontFamily a').click(function(){ $('.content').css("font-family", this.innerHTML); + createCookie('font-family', this.innerHTML); }); $('#Leading a').click(function(){ $('.content').css("line-height", this.dataset.spacing); + createCookie('line-height', this.dataset.spacing); }); $('#Background a').click(function() { $('body').css("background-color", $(this).css('background-color')); + createCookie('background', $(this).css('background-color')); }); };
39b78875d513f19cd5ba3b6eeeafe244d6980953
app/assets/javascripts/forms.js
app/assets/javascripts/forms.js
$(function() { if ($('small.error').length > 0) { $('html, body').animate({ scrollTop: ($('small.error').first().offset().top) },500); } });
$(function() { if ($('small.error').length > 0) { $('html, body').animate({ scrollTop: ($('small.error').first().offset().top-100) },500); } });
Improve scrolling to error feature
Improve scrolling to error feature
JavaScript
mit
airslie/renalware-core,airslie/renalware-core,airslie/renalware-core,airslie/renalware-core
--- +++ @@ -1,7 +1,7 @@ $(function() { if ($('small.error').length > 0) { $('html, body').animate({ - scrollTop: ($('small.error').first().offset().top) + scrollTop: ($('small.error').first().offset().top-100) },500); } });
add6c9550f0968e0efe196747997887ed8921c33
app/controllers/observations.js
app/controllers/observations.js
var config = require('../../config/config.js'); var express = require('express'); var router = express.Router(); var mongoose = require('mongoose'); var Observation = mongoose.model('Observation'); var realtime = require('../realtime/realtime.js'); module.exports = function (app) { app.use('/observations', router); }; router.post('/', function (req, res, next) { var newObservation = new Observation(req.body); newObservation.save(function (err, doc, n) { if (err) { console.log(err); if (err.name === "ValidationError") { return next({ status: 422, message: "Invalid observation data" }); } else { return next(err); } } //realtime.notifyObservation(req.body); return res.status(201).location('/observations/' + newObservation._id).end(); }); });
var config = require('../../config/config.js'); var express = require('express'); var router = express.Router(); var mongoose = require('mongoose'); var Observation = mongoose.model('Observation'); var realtime = require('../realtime/realtime.js'); module.exports = function (app) { app.use('/observations', router); }; router.post('/', function (req, res, next) { var newObservation = new Observation(req.body); newObservation.save(function (err, doc, n) { if (err) { console.log(err); if (err.name === "ValidationError") { return next({ status: 422, message: "Invalid observation data" }); } else { return next(err); } } realtime.notifyObservation(req.body); return res.status(201).location('/observations/' + newObservation._id).end(); }); });
Fix bug by restoring calls to socket.io service
Fix bug by restoring calls to socket.io service
JavaScript
mit
MichaelRohrer/OpenAudit,IoBirds/iob-server,MichaelRohrer/OpenAudit,IoBirds/iob-server
--- +++ @@ -20,7 +20,7 @@ return next(err); } } - //realtime.notifyObservation(req.body); + realtime.notifyObservation(req.body); return res.status(201).location('/observations/' + newObservation._id).end(); }); });
a5b130aaeb84c5dc2b26fddba87805c4d9a8915d
xmlToJson/index.js
xmlToJson/index.js
var fs = require('fs'); module.exports = function (context, xmlZipBlob) { context.log('Node.js blob trigger function processed blob:', xmlZipBlob); context.log(`typeof xmlZipBlob:`, typeof xmlZipBlob); fs.writeFile('xmlZip.txt', "Hello World", 'utf8', (err) => { if (err) { throw err; } context.log('saved blob to loal file called xmlZip.zip'); context.done(); }); };
var fs = require('fs'); var path = rqeuire('path'); module.exports = function (context, xmlZipBlob) { context.log('Node.js blob trigger function processed blob:', xmlZipBlob); context.log(`typeof xmlZipBlob:`, typeof xmlZipBlob); var tempDirectory = process.env["TMP"]; var tempFileName = "xmlZip.zip"; var fileDestination = path.join(tempDirectory, tempFileName); context.log('Writing blob file to: ', fileDestination); fs.writeFile(fileDestination, xmlZipBlob, function (error, result) { if (error) { throw error; } context.log('saved blob to loal file called: ', tempFileName); context.done(); }); };
Update xmlBlob function to write to temp directory
Update xmlBlob function to write to temp directory
JavaScript
mit
mattmazzola/sc2iq-azure-functions
--- +++ @@ -1,15 +1,22 @@ var fs = require('fs'); +var path = rqeuire('path'); module.exports = function (context, xmlZipBlob) { context.log('Node.js blob trigger function processed blob:', xmlZipBlob); context.log(`typeof xmlZipBlob:`, typeof xmlZipBlob); - fs.writeFile('xmlZip.txt', "Hello World", 'utf8', (err) => { - if (err) { - throw err; + var tempDirectory = process.env["TMP"]; + var tempFileName = "xmlZip.zip"; + var fileDestination = path.join(tempDirectory, tempFileName); + + context.log('Writing blob file to: ', fileDestination); + + fs.writeFile(fileDestination, xmlZipBlob, function (error, result) { + if (error) { + throw error; } - context.log('saved blob to loal file called xmlZip.zip'); + context.log('saved blob to loal file called: ', tempFileName); context.done(); }); };
6916f08a1d587d64db47aa9068c0389d08aa5e1c
app/scripts/filters/timecode.js
app/scripts/filters/timecode.js
(function() { function timecode() { return function(seconds) { var seconds = Number.parseFloat(seconds); if (Number.isNaN(seconds)) { return '-:--'; } var wholeSeconds = Math.floor(seconds); var minutes = Math.floor(wholeSeconds / 60); var remainingSeconds = wholeSeconds % 60; var output = minutes + ':'; if (remainingSeconds < 10) { output += '0'; } output += remainingSeconds; return output; }; } angular .module('blocJams') .filter('timecode', timecode); })();
(function() { function timecode() { return function(seconds) { /** var seconds = Number.parseFloat(seconds); if (Number.isNaN(seconds)) { return '-:--'; } var wholeSeconds = Math.floor(seconds); var minutes = Math.floor(wholeSeconds / 60); var remainingSeconds = wholeSeconds % 60; var output = minutes + ':'; if (remainingSeconds < 10) { output += '0'; } output += remainingSeconds; return output; */ var output = buzz.toTimer(seconds); return output; }; } angular .module('blocJams') .filter('timecode', timecode); })();
Use buzz.toTimer() method for time filter
Use buzz.toTimer() method for time filter
JavaScript
apache-2.0
orlando21/ng-bloc-jams,orlando21/ng-bloc-jams
--- +++ @@ -1,6 +1,8 @@ (function() { function timecode() { return function(seconds) { + + /** var seconds = Number.parseFloat(seconds); if (Number.isNaN(seconds)) { @@ -17,7 +19,11 @@ } output += remainingSeconds; - + + return output; + */ + + var output = buzz.toTimer(seconds); return output; }; }
f6c1c6a4bf04d64c97c06fd57cc14f584fc530f5
static/js/components/callcount_test.js
static/js/components/callcount_test.js
const html = require('choo/html'); const callcount = require('./callcount.js'); const chai = require('chai'); const expect = chai.expect; // Skip a test if the browser does not support locale-based number formatting function ifLocaleSupportedIt (test) { if (window.Intl && window.Intl.NumberFormat) { it(test); } else { it.skip(test); } } describe('callcount component', () => { ifLocaleSupportedIt('should properly format call total >=1000 with commas', () => { let state = {totalCalls: '123456789'}; let result = callcount(state); expect(result.textContent).to.contain('123,456,789'); }); ifLocaleSupportedIt('should properly format call total < 1000 without commas', () => { const totals = '123'; let state = {totalCalls: totals}; let result = callcount(state); expect(result.textContent).to.contain(totals); expect(result.textContent).to.not.contain(','); }); ifLocaleSupportedIt('should not format zero call total', () => { const totals = '0'; let state = {totalCalls: totals}; let result = callcount(state); expect(result.textContent).to.contain(totals); expect(result.textContent).to.not.contain(','); }); });
const html = require('choo/html'); const callcount = require('./callcount.js'); const chai = require('chai'); const expect = chai.expect; // Skip a test if the browser does not support locale-based number formatting function ifLocaleSupportedIt (name, test) { if (window.Intl && window.Intl.NumberFormat) { it(name, test); } else { it.skip(name, test); } } describe('callcount component', () => { ifLocaleSupportedIt('should properly format call total >=1000 with commas', () => { let state = {totalCalls: '123456789'}; let result = callcount(state); expect(result.textContent).to.contain('123,456,789'); }); ifLocaleSupportedIt('should properly format call total < 1000 without commas', () => { const totals = '123'; let state = {totalCalls: totals}; let result = callcount(state); expect(result.textContent).to.contain(totals); expect(result.textContent).to.not.contain(','); }); ifLocaleSupportedIt('should not format zero call total', () => { const totals = '0'; let state = {totalCalls: totals}; let result = callcount(state); expect(result.textContent).to.contain(totals); expect(result.textContent).to.not.contain(','); }); });
Fix support check that skips tests on ALL browsers
Fix support check that skips tests on ALL browsers Mistake and poor checking on my part.
JavaScript
mit
5calls/5calls,5calls/5calls,5calls/5calls,5calls/5calls
--- +++ @@ -4,12 +4,12 @@ const expect = chai.expect; // Skip a test if the browser does not support locale-based number formatting -function ifLocaleSupportedIt (test) { +function ifLocaleSupportedIt (name, test) { if (window.Intl && window.Intl.NumberFormat) { - it(test); + it(name, test); } else { - it.skip(test); + it.skip(name, test); } }
d08cf84a589a20686ed431e8c8134697ee3c004c
js/home.js
js/home.js
function startTime() { var today=new Date(); var h=checkTime(today.getHours()); var m=checkTime(today.getMinutes()); var s=checkTime(today.getSeconds()); var timeString = s%2===0 ? h + ":" + m + ":" + s : h + ":" + m + " " + s; document.getElementById("time").innerHTML = timeString; var twentyFour = 10.625; var sixty = 4.25; var c1 = Math.round(twentyFour*h).toString(16); var c2 = Math.round(sixty*m).toString(16); var c3 = Math.round(sixty*s).toString(16); [c1, c2, c3].forEach(function (c) { c = c.length === 2 ? c : "0"+c; }); document.getElementById("center-container").style.backgroundColor = "#" + c1 + c2 + c3; var t = setTimeout(function(){ startTime(); },500); } function checkTime(i) { if (i<10) {i = "0" + i;} // add zero in front of numbers < 10 return i; } startTime();
function startTime() { var today=new Date(); var h=checkTime(today.getHours()); var m=checkTime(today.getMinutes()); var s=checkTime(today.getSeconds()); var timeString = s%2===0 ? h + ":" + m + ":" + s : h + ":" + m + " " + s; document.getElementById("time").innerHTML = timeString; var twentyFour = 10.625; var sixty = 4.25; var backgroundColor = "#"; [ Math.round(twentyFour*h).toString(16), Math.round(sixty*m).toString(16), Math.round(sixty*s).toString(16) ].forEach(function (c) { backgroundColor += c.length === 2 ? c : "0" + c; }); document.getElementById("center-container").style.backgroundColor = backgroundColor; var t = setTimeout(function(){ startTime(); },500); } function checkTime(i) { if (i<10) {i = "0" + i;} // add zero in front of numbers < 10 return i; } startTime();
Fix bug in background color
Fix bug in background color
JavaScript
mit
SalomonSmeke/old-site,SalomonSmeke/old-site,SalomonSmeke/old-site
--- +++ @@ -7,13 +7,15 @@ document.getElementById("time").innerHTML = timeString; var twentyFour = 10.625; var sixty = 4.25; - var c1 = Math.round(twentyFour*h).toString(16); - var c2 = Math.round(sixty*m).toString(16); - var c3 = Math.round(sixty*s).toString(16); - [c1, c2, c3].forEach(function (c) { - c = c.length === 2 ? c : "0"+c; + var backgroundColor = "#"; + [ + Math.round(twentyFour*h).toString(16), + Math.round(sixty*m).toString(16), + Math.round(sixty*s).toString(16) + ].forEach(function (c) { + backgroundColor += c.length === 2 ? c : "0" + c; }); - document.getElementById("center-container").style.backgroundColor = "#" + c1 + c2 + c3; + document.getElementById("center-container").style.backgroundColor = backgroundColor; var t = setTimeout(function(){ startTime(); },500); }
11bab5733e1f0292ff06b0accc1fc6cc25cd29b6
share/spice/maps/maps/maps_maps.js
share/spice/maps/maps/maps_maps.js
DDG.require('maps',function(){ ddg_spice_maps_maps = function(response) { if (!response || !response.length) { return Spice.failed('maps'); } // OSM sends back a bunch of places, just want the first one for now response = [response[0]]; if (!DDG.isRelevant(response[0].display_name.toLowerCase())) { return Spice.failed('maps'); } Spice.add({ data: response, id: "maps", name: "maps", model: "Place" }); }; });
DDG.require('maps',function(){ ddg_spice_maps_maps = function(response) { if (!response) { return Spice.failed('maps'); } // OSM sends back a bunch of places, just want the first one for now response = response.features[0]; Spice.add({ data: response, id: "maps", name: "maps", model: "Place" }); }; });
Handle mapbox geocoder response data
Handle mapbox geocoder response data
JavaScript
apache-2.0
whalenrp/zeroclickinfo-spice,MoriTanosuke/zeroclickinfo-spice,MoriTanosuke/zeroclickinfo-spice,sagarhani/zeroclickinfo-spice,lernae/zeroclickinfo-spice,Retrobottega/zeroclickinfo-spice,xaviervalarino/zeroclickinfo-spice,GrandpaCardigan/zeroclickinfo-spice,MoriTanosuke/zeroclickinfo-spice,shyamalschandra/zeroclickinfo-spice,Kakkoroid/zeroclickinfo-spice,bibliotechy/zeroclickinfo-spice,bigcurl/zeroclickinfo-spice,sagarhani/zeroclickinfo-spice,Retrobottega/zeroclickinfo-spice,marianosimone/zeroclickinfo-spice,imwally/zeroclickinfo-spice,kevintab95/zeroclickinfo-spice,ScreapDK/zeroclickinfo-spice,marianosimone/zeroclickinfo-spice,dogomedia/zeroclickinfo-spice,Kakkoroid/zeroclickinfo-spice,brianrisk/zeroclickinfo-spice,bibliotechy/zeroclickinfo-spice,levaly/zeroclickinfo-spice,imwally/zeroclickinfo-spice,Retrobottega/zeroclickinfo-spice,ScreapDK/zeroclickinfo-spice,ScreapDK/zeroclickinfo-spice,xaviervalarino/zeroclickinfo-spice,sagarhani/zeroclickinfo-spice,lernae/zeroclickinfo-spice,andrey-p/zeroclickinfo-spice,andrey-p/zeroclickinfo-spice,bibliotechy/zeroclickinfo-spice,GrandpaCardigan/zeroclickinfo-spice,sagarhani/zeroclickinfo-spice,mr-karan/zeroclickinfo-spice,deserted/zeroclickinfo-spice,lernae/zeroclickinfo-spice,soleo/zeroclickinfo-spice,samskeller/zeroclickinfo-spice,dogomedia/zeroclickinfo-spice,tagawa/zeroclickinfo-spice,xaviervalarino/zeroclickinfo-spice,andrey-p/zeroclickinfo-spice,P71/zeroclickinfo-spice,lerna/zeroclickinfo-spice,iambibhas/zeroclickinfo-spice,marianosimone/zeroclickinfo-spice,mr-karan/zeroclickinfo-spice,levaly/zeroclickinfo-spice,TomBebbington/zeroclickinfo-spice,shyamalschandra/zeroclickinfo-spice,iambibhas/zeroclickinfo-spice,dogomedia/zeroclickinfo-spice,kevintab95/zeroclickinfo-spice,Kr1tya3/zeroclickinfo-spice,kevintab95/zeroclickinfo-spice,cylgom/zeroclickinfo-spice,rmad17/zeroclickinfo-spice,iambibhas/zeroclickinfo-spice,lerna/zeroclickinfo-spice,tagawa/zeroclickinfo-spice,deserted/zeroclickinfo-spice,tagawa/zeroclickinfo-spice,kevintab95/zeroclickinfo-spice,soleo/zeroclickinfo-spice,iambibhas/zeroclickinfo-spice,Kakkoroid/zeroclickinfo-spice,xaviervalarino/zeroclickinfo-spice,P71/zeroclickinfo-spice,Retrobottega/zeroclickinfo-spice,sagarhani/zeroclickinfo-spice,soleo/zeroclickinfo-spice,marianosimone/zeroclickinfo-spice,mr-karan/zeroclickinfo-spice,levaly/zeroclickinfo-spice,cylgom/zeroclickinfo-spice,lerna/zeroclickinfo-spice,marianosimone/zeroclickinfo-spice,MoriTanosuke/zeroclickinfo-spice,iambibhas/zeroclickinfo-spice,whalenrp/zeroclickinfo-spice,samskeller/zeroclickinfo-spice,brianrisk/zeroclickinfo-spice,P71/zeroclickinfo-spice,kevintab95/zeroclickinfo-spice,cylgom/zeroclickinfo-spice,bibliotechy/zeroclickinfo-spice,soleo/zeroclickinfo-spice,rmad17/zeroclickinfo-spice,whalenrp/zeroclickinfo-spice,cylgom/zeroclickinfo-spice,brianrisk/zeroclickinfo-spice,bigcurl/zeroclickinfo-spice,whalenrp/zeroclickinfo-spice,rmad17/zeroclickinfo-spice,samskeller/zeroclickinfo-spice,shyamalschandra/zeroclickinfo-spice,cylgom/zeroclickinfo-spice,samskeller/zeroclickinfo-spice,mr-karan/zeroclickinfo-spice,tagawa/zeroclickinfo-spice,GrandpaCardigan/zeroclickinfo-spice,GrandpaCardigan/zeroclickinfo-spice,levaly/zeroclickinfo-spice,lernae/zeroclickinfo-spice,whalenrp/zeroclickinfo-spice,shyamalschandra/zeroclickinfo-spice,Kakkoroid/zeroclickinfo-spice,deserted/zeroclickinfo-spice,xaviervalarino/zeroclickinfo-spice,Retrobottega/zeroclickinfo-spice,deserted/zeroclickinfo-spice,lernae/zeroclickinfo-spice,dogomedia/zeroclickinfo-spice,imwally/zeroclickinfo-spice,imwally/zeroclickinfo-spice,xaviervalarino/zeroclickinfo-spice,tagawa/zeroclickinfo-spice,levaly/zeroclickinfo-spice,imwally/zeroclickinfo-spice,andrey-p/zeroclickinfo-spice,whalenrp/zeroclickinfo-spice,rmad17/zeroclickinfo-spice,soleo/zeroclickinfo-spice,TomBebbington/zeroclickinfo-spice,Kakkoroid/zeroclickinfo-spice,P71/zeroclickinfo-spice,andrey-p/zeroclickinfo-spice,rmad17/zeroclickinfo-spice,marianosimone/zeroclickinfo-spice,soleo/zeroclickinfo-spice,MoriTanosuke/zeroclickinfo-spice,Kr1tya3/zeroclickinfo-spice,kevintab95/zeroclickinfo-spice,Kr1tya3/zeroclickinfo-spice,TomBebbington/zeroclickinfo-spice,Kr1tya3/zeroclickinfo-spice,bigcurl/zeroclickinfo-spice,Kr1tya3/zeroclickinfo-spice,brianrisk/zeroclickinfo-spice,TomBebbington/zeroclickinfo-spice,levaly/zeroclickinfo-spice,mr-karan/zeroclickinfo-spice,lernae/zeroclickinfo-spice,dogomedia/zeroclickinfo-spice,GrandpaCardigan/zeroclickinfo-spice,shyamalschandra/zeroclickinfo-spice,brianrisk/zeroclickinfo-spice,bigcurl/zeroclickinfo-spice,ScreapDK/zeroclickinfo-spice,bigcurl/zeroclickinfo-spice,ScreapDK/zeroclickinfo-spice,deserted/zeroclickinfo-spice,lerna/zeroclickinfo-spice,iambibhas/zeroclickinfo-spice,lerna/zeroclickinfo-spice,deserted/zeroclickinfo-spice,bigcurl/zeroclickinfo-spice,cylgom/zeroclickinfo-spice
--- +++ @@ -1,14 +1,10 @@ DDG.require('maps',function(){ ddg_spice_maps_maps = function(response) { - if (!response || !response.length) { return Spice.failed('maps'); } + if (!response) { return Spice.failed('maps'); } // OSM sends back a bunch of places, just want the first one for now - response = [response[0]]; - - if (!DDG.isRelevant(response[0].display_name.toLowerCase())) { - return Spice.failed('maps'); - } + response = response.features[0]; Spice.add({ data: response,
d1b9a635f976403db95e86b7cbbdbd03daadc44a
addon/components/bs4/bs-navbar.js
addon/components/bs4/bs-navbar.js
import { computed } from '@ember/object'; import Navbar from 'ember-bootstrap/components/base/bs-navbar'; export default Navbar.extend({ classNameBindings: ['breakpointClass', 'backgroundClass'], type: 'light', /** * Defines the responsive toggle breakpoint size. Options are the standard * two character Bootstrap size abbreviations. Used to set the `navbar-expand-*` * class. * * @property toggleBreakpoint * @type String * @default 'md' * @public */ toggleBreakpoint: 'lg', /** * Sets the background color for the navbar. Can be any color * in the set that composes the `bg-*` classes. * * @property backgroundColor * @type String * @default 'light' * @public */ backgroundColor: 'light', breakpointClass: computed('toggleBreakpoint', function() { let toggleBreakpoint = this.get('toggleBreakpoint'); return `navbar-expand-${toggleBreakpoint}`; }), backgroundClass: computed('backgroundColor', function() { let backgroundColor = this.get('backgroundColor'); return `bg-${backgroundColor}`; }), _validPositions: ['fixed-top', 'fixed-bottom', 'sticky-top'], _positionPrefix: '' });
import { computed } from '@ember/object'; import Navbar from 'ember-bootstrap/components/base/bs-navbar'; export default Navbar.extend({ classNameBindings: ['breakpointClass', 'backgroundClass'], type: computed('appliedType', { get() { return this.get('appliedType'); }, set(key, value) { // eslint-disable-line no-unused let newValue = (!value || value === 'default') ? 'light' : value; this.set('appliedType', newValue); return newValue; } }), appliedType: 'light', /** * Defines the responsive toggle breakpoint size. Options are the standard * two character Bootstrap size abbreviations. Used to set the `navbar-expand-*` * class. * * @property toggleBreakpoint * @type String * @default 'md' * @public */ toggleBreakpoint: 'lg', /** * Sets the background color for the navbar. Can be any color * in the set that composes the `bg-*` classes. * * @property backgroundColor * @type String * @default 'light' * @public */ backgroundColor: 'light', breakpointClass: computed('toggleBreakpoint', function() { let toggleBreakpoint = this.get('toggleBreakpoint'); return `navbar-expand-${toggleBreakpoint}`; }), backgroundClass: computed('backgroundColor', function() { let backgroundColor = this.get('backgroundColor'); return `bg-${backgroundColor}`; }), _validPositions: ['fixed-top', 'fixed-bottom', 'sticky-top'], _positionPrefix: '' });
Enforce compatibility of the `undefined` and `default` setting for navbar color scheme. This makes the demo work for the default, but the inverse still doesn't work because of different scheme names.
Enforce compatibility of the `undefined` and `default` setting for navbar color scheme. This makes the demo work for the default, but the inverse still doesn't work because of different scheme names.
JavaScript
mit
jelhan/ember-bootstrap,jelhan/ember-bootstrap,kaliber5/ember-bootstrap,kaliber5/ember-bootstrap
--- +++ @@ -4,7 +4,19 @@ export default Navbar.extend({ classNameBindings: ['breakpointClass', 'backgroundClass'], - type: 'light', + type: computed('appliedType', { + get() { + return this.get('appliedType'); + }, + + set(key, value) { // eslint-disable-line no-unused + let newValue = (!value || value === 'default') ? 'light' : value; + this.set('appliedType', newValue); + return newValue; + } + }), + + appliedType: 'light', /** * Defines the responsive toggle breakpoint size. Options are the standard
d0d1e2f8beee81818d0905c9e86c1d0f59ee2e31
html/introduction-to-html/the-html-head/script.js
html/introduction-to-html/the-html-head/script.js
var list = document.createElement('ul'); var info = document.createElement('p'); var html = document.querySelector('html'); info.textContent = 'Below is a dynamic list. Click anywhere outside the list to add a new list item. Click an existing list item to change its text to something else.'; document.body.appendChild(info); document.body.appendChild(list); html.onclick = function() { var listItem = document.createElement('li'); var listContent = prompt('What content do you want the list item to have?'); listItem.textContent = listContent; list.appendChild(listItem); listItem.onclick = function(e) { e.stopPropagation(); var listContent = prompt('Enter new content for your list item'); this.textContent = listContent; } }
const list = document.createElement('ul'); const info = document.createElement('p'); const html = document.querySelector('html'); info.textContent = 'Below is a dynamic list. Click anywhere outside the list to add a new list item. Click an existing list item to change its text to something else.'; document.body.appendChild(info); document.body.appendChild(list); html.onclick = function() { const listItem = document.createElement('li'); const listContent = prompt('What content do you want the list item to have?'); listItem.textContent = listContent; list.appendChild(listItem); listItem.onclick = function(e) { e.stopPropagation(); const listContent = prompt('Enter new content for your list item'); this.textContent = listContent; } }
Use const instead of var as according to best practices
Use const instead of var as according to best practices
JavaScript
cc0-1.0
mdn/learning-area,mdn/learning-area,mdn/learning-area,mdn/learning-area
--- +++ @@ -1,6 +1,6 @@ -var list = document.createElement('ul'); -var info = document.createElement('p'); -var html = document.querySelector('html'); +const list = document.createElement('ul'); +const info = document.createElement('p'); +const html = document.querySelector('html'); info.textContent = 'Below is a dynamic list. Click anywhere outside the list to add a new list item. Click an existing list item to change its text to something else.'; @@ -8,14 +8,14 @@ document.body.appendChild(list); html.onclick = function() { - var listItem = document.createElement('li'); - var listContent = prompt('What content do you want the list item to have?'); + const listItem = document.createElement('li'); + const listContent = prompt('What content do you want the list item to have?'); listItem.textContent = listContent; list.appendChild(listItem); listItem.onclick = function(e) { e.stopPropagation(); - var listContent = prompt('Enter new content for your list item'); + const listContent = prompt('Enter new content for your list item'); this.textContent = listContent; } }
78204ce46e10970b9911f956615709d4e68dcd6f
config/supportedLanguages.js
config/supportedLanguages.js
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ // The list below should be kept in sync with: // https://raw.githubusercontent.com/mozilla/fxa-content-server/master/server/config/production-locales.json module.exports = [ 'ar', 'az', 'bg', 'cs', 'cy', 'da', 'de', 'dsb', 'en', 'en-GB', 'es', 'es-AR', 'es-CL', 'et', 'fa', 'ff', 'fi', 'fr', 'fy', 'he', 'hi-IN', 'hsb', 'hu', 'it', 'ja', 'kk', 'ko', 'lt', 'nl', 'pa', 'pl', 'pt', 'pt-BR', 'pt-PT', 'ro', 'rm', 'ru', 'sk', 'sl', 'sq', 'sr', 'sr-LATN', 'sv', 'sv-SE', 'tr', 'uk', 'zh-CN', 'zh-TW' ]
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ // The list below should be kept in sync with: // https://raw.githubusercontent.com/mozilla/fxa-content-server/master/server/config/production-locales.json module.exports = [ 'az', 'bg', 'cs', 'cy', 'da', 'de', 'dsb', 'en', 'en-GB', 'es', 'es-AR', 'es-CL', 'et', 'fa', 'ff', 'fi', 'fr', 'fy', 'he', 'hi-IN', 'hsb', 'hu', 'it', 'ja', 'kk', 'ko', 'lt', 'nl', 'pa', 'pl', 'pt', 'pt-BR', 'pt-PT', 'ro', 'rm', 'ru', 'sk', 'sl', 'sq', 'sr', 'sr-LATN', 'sv', 'sv-SE', 'tr', 'uk', 'zh-CN', 'zh-TW' ]
Revert "feat(locale): add Arabic locale support"
Revert "feat(locale): add Arabic locale support" This reverts commit a13e32a8f0426a0890c813cefbe3987750b12802.
JavaScript
mpl-2.0
mozilla/fxa-auth-server,mozilla/fxa-auth-server,mozilla/fxa-auth-server,mozilla/fxa-auth-server
--- +++ @@ -6,7 +6,6 @@ // https://raw.githubusercontent.com/mozilla/fxa-content-server/master/server/config/production-locales.json module.exports = [ - 'ar', 'az', 'bg', 'cs',
e2276933cf61b229ed63e6fe69010586468af649
src/graphql/dataLoaders/articleCategoriesByCategoryIdLoaderFactory.js
src/graphql/dataLoaders/articleCategoriesByCategoryIdLoaderFactory.js
import DataLoader from 'dataloader'; import client from 'util/client'; export default () => new DataLoader(async categoryQueries => { const body = []; categoryQueries.forEach(({ id, first, before, after }) => { // TODO error independently? if (before && after) { throw new Error('Use of before & after is prohibited.'); } body.push({ index: 'articles', type: 'doc' }); body.push({ query: { nested: { path: 'articleCategories', query: { term: { 'articleCategories.categoryId': id, }, }, }, }, size: first ? first : 10, sort: before ? [{ updatedAt: 'desc' }] : [{ updatedAt: 'asc' }], search_after: before || after ? before || after : undefined, }); }); return (await client.msearch({ body, })).responses.map(({ hits }, idx) => { if (!hits || !hits.hits) return []; const categoryId = categoryQueries[idx].id; return hits.hits.map(({ _id, _source: { articleCategories } }) => { // Find corresponding articleCategory and insert articleId // const articleCategory = articleCategories.find( articleCategory => articleCategory.categoryId === categoryId ); articleCategory.articleId = _id; return articleCategory; }); }); });
import DataLoader from 'dataloader'; import client from 'util/client'; export default () => new DataLoader( async categoryQueries => { const body = []; categoryQueries.forEach(({ id, first, before, after }) => { // TODO error independently? if (before && after) { throw new Error('Use of before & after is prohibited.'); } body.push({ index: 'articles', type: 'doc' }); body.push({ query: { nested: { path: 'articleCategories', query: { term: { 'articleCategories.categoryId': id, }, }, }, }, size: first ? first : 10, sort: before ? [{ updatedAt: 'desc' }] : [{ updatedAt: 'asc' }], search_after: before || after ? before || after : undefined, }); }); return (await client.msearch({ body, })).responses.map(({ hits }, idx) => { if (!hits || !hits.hits) return []; const categoryId = categoryQueries[idx].id; return hits.hits.map(({ _id, _source: { articleCategories } }) => { // Find corresponding articleCategory and insert articleId // const articleCategory = articleCategories.find( articleCategory => articleCategory.categoryId === categoryId ); articleCategory.articleId = _id; return articleCategory; }); }); }, { cacheKeyFn: ({ id, first, before, after }) => `/${id}/${first}/${before}/${after}`, } );
Implement cacheKeyFn and fix lint
Implement cacheKeyFn and fix lint
JavaScript
mit
MrOrz/rumors-api,MrOrz/rumors-api,cofacts/rumors-api
--- +++ @@ -2,48 +2,54 @@ import client from 'util/client'; export default () => - new DataLoader(async categoryQueries => { - const body = []; + new DataLoader( + async categoryQueries => { + const body = []; - categoryQueries.forEach(({ id, first, before, after }) => { - // TODO error independently? - if (before && after) { - throw new Error('Use of before & after is prohibited.'); - } + categoryQueries.forEach(({ id, first, before, after }) => { + // TODO error independently? + if (before && after) { + throw new Error('Use of before & after is prohibited.'); + } - body.push({ index: 'articles', type: 'doc' }); + body.push({ index: 'articles', type: 'doc' }); - body.push({ - query: { - nested: { - path: 'articleCategories', - query: { - term: { - 'articleCategories.categoryId': id, + body.push({ + query: { + nested: { + path: 'articleCategories', + query: { + term: { + 'articleCategories.categoryId': id, + }, }, }, }, - }, - size: first ? first : 10, - sort: before ? [{ updatedAt: 'desc' }] : [{ updatedAt: 'asc' }], - search_after: before || after ? before || after : undefined, + size: first ? first : 10, + sort: before ? [{ updatedAt: 'desc' }] : [{ updatedAt: 'asc' }], + search_after: before || after ? before || after : undefined, + }); }); - }); - return (await client.msearch({ - body, - })).responses.map(({ hits }, idx) => { - if (!hits || !hits.hits) return []; + return (await client.msearch({ + body, + })).responses.map(({ hits }, idx) => { + if (!hits || !hits.hits) return []; - const categoryId = categoryQueries[idx].id; - return hits.hits.map(({ _id, _source: { articleCategories } }) => { - // Find corresponding articleCategory and insert articleId - // - const articleCategory = articleCategories.find( - articleCategory => articleCategory.categoryId === categoryId - ); - articleCategory.articleId = _id; - return articleCategory; + const categoryId = categoryQueries[idx].id; + return hits.hits.map(({ _id, _source: { articleCategories } }) => { + // Find corresponding articleCategory and insert articleId + // + const articleCategory = articleCategories.find( + articleCategory => articleCategory.categoryId === categoryId + ); + articleCategory.articleId = _id; + return articleCategory; + }); }); - }); - }); + }, + { + cacheKeyFn: ({ id, first, before, after }) => + `/${id}/${first}/${before}/${after}`, + } + );
62af16add5c5e9456b543787a136226c892ea229
app/mixins/inventory-selection.js
app/mixins/inventory-selection.js
import Ember from "ember"; export default Ember.Mixin.create({ /** * For use with the inventory-type ahead. When an inventory item is selected, resolve the selected * inventory item into an actual model object and set is as inventoryItem. */ inventoryItemChanged: function() { var selectedInventoryItem = this.get('selectedInventoryItem'); if (!Ember.isEmpty(selectedInventoryItem)) { selectedInventoryItem.id = selectedInventoryItem._id.substr(10); this.store.find('inventory', selectedInventoryItem._id.substr(10)).then(function(item) { this.set('inventoryItem', item); Ember.run.once(this, function(){ this.get('model').validate(); }); }.bind(this)); } }.observes('selectedInventoryItem'), });
import Ember from "ember"; export default Ember.Mixin.create({ /** * For use with the inventory-type ahead. When an inventory item is selected, resolve the selected * inventory item into an actual model object and set is as inventoryItem. */ inventoryItemChanged: function() { var selectedInventoryItem = this.get('selectedInventoryItem'); if (!Ember.isEmpty(selectedInventoryItem)) { selectedInventoryItem.id = selectedInventoryItem._id.substr(10); this.store.find('inventory', selectedInventoryItem._id.substr(10)).then(function(item) { item.reload().then(function() { this.set('inventoryItem', item); Ember.run.once(this, function(){ this.get('model').validate(); }); }.bind(this), function(err) { console.log("ERROR reloading inventory item", err); }); }.bind(this)); } }.observes('selectedInventoryItem'), });
Make sure inventory item is completely loaded
Make sure inventory item is completely loaded
JavaScript
mit
HospitalRun/hospitalrun-frontend,HospitalRun/hospitalrun-frontend,HospitalRun/hospitalrun-frontend,HospitalRun/hospitalrun-frontend
--- +++ @@ -9,9 +9,13 @@ if (!Ember.isEmpty(selectedInventoryItem)) { selectedInventoryItem.id = selectedInventoryItem._id.substr(10); this.store.find('inventory', selectedInventoryItem._id.substr(10)).then(function(item) { - this.set('inventoryItem', item); - Ember.run.once(this, function(){ - this.get('model').validate(); + item.reload().then(function() { + this.set('inventoryItem', item); + Ember.run.once(this, function(){ + this.get('model').validate(); + }); + }.bind(this), function(err) { + console.log("ERROR reloading inventory item", err); }); }.bind(this)); }
584bdf23880938277f952bb8e59b33c697bd5974
Resources/lib/events.js
Resources/lib/events.js
var listeners = {}; exports.addEventListener = function(name, func) { if (!listeners[name]) { listeners[name] = []; } listeners[name].push(func); return exports; }; exports.hasEventListeners = function(name) { return !!listeners[name]; }; exports.clearEventListeners = function() { listeners = {}; return exports; }; exports.fireEvent = function(name, data) { if (listeners[name]) { for (var l in listeners[name]) { listeners[name][l](data); } } return exports; }; exports.curryFireEvent = function(name, data) { return function() { return exports.fireEvent(name, data); } }; exports.removeEventListener = function(name, func) { if (listeners[name]) { for (var l in listeners[name]) { if (listeners[name][l] === func) { listeners[name].splice(l, 1); break; } } } return exports; };
var listeners = {}; exports.addEventListener = function(name, func) { if (!listeners[name]) { listeners[name] = []; } listeners[name].push(func); return exports; }; exports.hasEventListeners = function(name) { return !!listeners[name]; }; exports.clearEventListeners = function() { listeners = {}; return exports; }; exports.fireEvent = function(name, data) { if (listeners[name]) { var args = Array.prototype.slice.call(arguments, 1); for (var l in listeners[name]) { listeners[name][l].apply(this, args); } } return exports; }; exports.curryFireEvent = function(name, data) { var args = arguments; return function() { return exports.fireEvent.apply(this, args); }; }; exports.removeEventListener = function(name, func) { if (listeners[name]) { for (var l in listeners[name]) { if (listeners[name][l] === func) { listeners[name].splice(l, 1); break; } } } return exports; };
Allow Multiple Arguments to Events
Allow Multiple Arguments to Events
JavaScript
apache-2.0
appcelerator-titans/abcsWriter
--- +++ @@ -19,17 +19,19 @@ exports.fireEvent = function(name, data) { if (listeners[name]) { + var args = Array.prototype.slice.call(arguments, 1); for (var l in listeners[name]) { - listeners[name][l](data); + listeners[name][l].apply(this, args); } } return exports; }; exports.curryFireEvent = function(name, data) { + var args = arguments; return function() { - return exports.fireEvent(name, data); - } + return exports.fireEvent.apply(this, args); + }; }; exports.removeEventListener = function(name, func) {
ee492f36b4d945945bb88a6dcbc64c5b6ef602d1
.prettierrc.js
.prettierrc.js
module.exports = { semi: false, tabWidth: 2, singleQuote: true, proseWrap: 'always', }
module.exports = { semi: false, tabWidth: 2, singleQuote: true, proseWrap: 'always', overrides: [ { files: 'src/**/*.mdx', options: { parser: 'mdx', }, }, ], }
Configure prettier to format mdx
Configure prettier to format mdx
JavaScript
mit
dtjv/dtjv.github.io
--- +++ @@ -3,4 +3,12 @@ tabWidth: 2, singleQuote: true, proseWrap: 'always', + overrides: [ + { + files: 'src/**/*.mdx', + options: { + parser: 'mdx', + }, + }, + ], }
c5ad27b894412c2cf32a723b1bfad1cce62360bf
app/scripts/reducers/userStatus.js
app/scripts/reducers/userStatus.js
import update from 'immutability-helper' import ActionTypes from '../actionTypes' const initialState = { isLoading: false, lastRequestAt: undefined, latestActivities: [], unreadMessagesCount: 0, } export default (state = initialState, action) => { switch (action.type) { case ActionTypes.AUTH_TOKEN_EXPIRED_OR_INVALID: case ActionTypes.AUTH_LOGOUT: return update(state, { lastRequestAt: { $set: undefined }, latestActivities: [], unreadMessagesCount: 0, }) case ActionTypes.USER_STATUS_REQUEST: return update(state, { isLoading: { $set: true }, }) case ActionTypes.USER_STATUS_SUCCESS: return update(state, { isLoading: { $set: false }, lastRequestAt: { $set: Date.now() }, latestActivities: { $set: action.payload.latestActivities }, unreadMessagesCount: { $set: action.payload.unreadMessagesCount }, }) case ActionTypes.USER_STATUS_FAILURE: return update(state, { isLoading: { $set: false }, }) default: return state } }
import update from 'immutability-helper' import ActionTypes from '../actionTypes' const initialState = { isLoading: false, lastRequestAt: undefined, latestActivities: [], unreadMessagesCount: 0, } export default (state = initialState, action) => { switch (action.type) { case ActionTypes.AUTH_TOKEN_EXPIRED_OR_INVALID: case ActionTypes.AUTH_LOGOUT: return initialState case ActionTypes.USER_STATUS_REQUEST: return update(state, { isLoading: { $set: true }, }) case ActionTypes.USER_STATUS_SUCCESS: return update(state, { isLoading: { $set: false }, lastRequestAt: { $set: Date.now() }, latestActivities: { $set: action.payload.latestActivities }, unreadMessagesCount: { $set: action.payload.unreadMessagesCount }, }) case ActionTypes.USER_STATUS_FAILURE: return update(state, { isLoading: { $set: false }, }) default: return state } }
Fix wrong usage of update
Fix wrong usage of update
JavaScript
agpl-3.0
adzialocha/hoffnung3000,adzialocha/hoffnung3000
--- +++ @@ -13,11 +13,7 @@ switch (action.type) { case ActionTypes.AUTH_TOKEN_EXPIRED_OR_INVALID: case ActionTypes.AUTH_LOGOUT: - return update(state, { - lastRequestAt: { $set: undefined }, - latestActivities: [], - unreadMessagesCount: 0, - }) + return initialState case ActionTypes.USER_STATUS_REQUEST: return update(state, { isLoading: { $set: true },
15cdaec26ef23fac04c6055dc93398dd55cb65d4
app/scripts/directives/sidebar.js
app/scripts/directives/sidebar.js
'use strict'; (function() { angular.module('ncsaas') .directive('sidebar', ['$state', sidebar]); function sidebar($state, $uibModal) { return { restrict: 'E', scope: { items: '=', context: '=' }, templateUrl: 'views/directives/sidebar.html', link: function(scope) { scope.$state = $state; } }; } angular.module('ncsaas') .directive('workspaceSelectToggle', ['$uibModal', workspaceSelectToggle]); function workspaceSelectToggle($uibModal) { return { restrict: 'E', template: '<button class="btn btn-primary dim minimalize-styl-2" ng-click="selectWorkspace()">'+ '<i class="fa fa-bars"></i> Select workspace</button>', link: function(scope) { scope.selectWorkspace = function() { $uibModal.open({ templateUrl: 'views/directives/select-workspace.html', controller: 'SelectWorkspaceController', controllerAs: 'Ctrl', bindToController: true, size: 'lg' }) } } } } })();
'use strict'; (function() { angular.module('ncsaas') .directive('sidebar', ['$state', sidebar]); function sidebar($state, $uibModal) { return { restrict: 'E', scope: { items: '=', context: '=' }, templateUrl: 'views/directives/sidebar.html', link: function(scope) { scope.$state = $state; } }; } angular.module('ncsaas') .directive('workspaceSelectToggle', ['$uibModal', workspaceSelectToggle]); function workspaceSelectToggle($uibModal) { return { restrict: 'E', template: '<button class="btn btn-primary minimalize-styl-2" ng-click="selectWorkspace()">'+ '<i class="fa fa-bars"></i> Select workspace</button>', link: function(scope) { scope.selectWorkspace = function() { $uibModal.open({ templateUrl: 'views/directives/select-workspace.html', controller: 'SelectWorkspaceController', controllerAs: 'Ctrl', bindToController: true, size: 'lg' }) } } } } })();
Use normal button for select workspace button (SAAS-1389)
Use normal button for select workspace button (SAAS-1389)
JavaScript
mit
opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport
--- +++ @@ -25,7 +25,7 @@ function workspaceSelectToggle($uibModal) { return { restrict: 'E', - template: '<button class="btn btn-primary dim minimalize-styl-2" ng-click="selectWorkspace()">'+ + template: '<button class="btn btn-primary minimalize-styl-2" ng-click="selectWorkspace()">'+ '<i class="fa fa-bars"></i> Select workspace</button>', link: function(scope) { scope.selectWorkspace = function() {
243f8dc177fbcf33c2fa67c0df2f177e3d53e6ad
app/scripts/modules/auth/index.js
app/scripts/modules/auth/index.js
import { connect } from 'react-redux'; import { Component } from 'react'; import PropTypes from 'prop-types'; import { setConfig } from 'widget-editor'; import { browserHistory } from 'react-router'; import actions from './auth-actions'; import initialState from './auth-reducer-initial-state'; import * as reducers from './auth-reducer'; const mapStateToProps = state => ({ session: state.auth.session }); class AuthContainer extends Component { componentWillMount() { const { location } = this.props; const { token } = location; if (token) { this.handleAuthenticationAction(); localStorage.setItem('token', token); } else { browserHistory.push('/'); } // We update the widget editor's config setConfig({ userToken: token || null }); } handleAuthenticationAction() { const { logInSuccess } = this.props; logInSuccess(true); } render() { return false; } } AuthContainer.propTypes = { location: PropTypes.object.isRequired, logInSuccess: PropTypes.func.isRequired }; export { actions, reducers, initialState }; export default connect(mapStateToProps, actions)(AuthContainer);
import { connect } from 'react-redux'; import { Component } from 'react'; import PropTypes from 'prop-types'; import { setConfig } from 'widget-editor'; import { browserHistory } from 'react-router'; import actions from './auth-actions'; import initialState from './auth-reducer-initial-state'; import * as reducers from './auth-reducer'; const mapStateToProps = state => ({ session: state.auth.session }); class AuthContainer extends Component { componentWillMount() { const { location } = this.props; const { query } = location; const { token } = query; if (token) { this.handleAuthenticationAction(); localStorage.setItem('token', token); } else { browserHistory.push('/'); } // We update the widget editor's config setConfig({ userToken: token || null }); } handleAuthenticationAction() { const { logInSuccess } = this.props; logInSuccess(true); } render() { return false; } } AuthContainer.propTypes = { location: PropTypes.object.isRequired, logInSuccess: PropTypes.func.isRequired }; export { actions, reducers, initialState }; export default connect(mapStateToProps, actions)(AuthContainer);
Fix a bug where the user wouldn't be able to log in
Fix a bug where the user wouldn't be able to log in
JavaScript
mit
resource-watch/prep-app,resource-watch/prep-app
--- +++ @@ -13,7 +13,8 @@ class AuthContainer extends Component { componentWillMount() { const { location } = this.props; - const { token } = location; + const { query } = location; + const { token } = query; if (token) { this.handleAuthenticationAction();
ed9b3e12309fa37080541f96f11e4c1ab2fb8cf1
lib/cartodb/models/mapconfig_overviews_adapter.js
lib/cartodb/models/mapconfig_overviews_adapter.js
var queue = require('queue-async'); var _ = require('underscore'); function MapConfigNamedLayersAdapter(overviewsApi) { this.overviewsApi = overviewsApi; } module.exports = MapConfigNamedLayersAdapter; MapConfigNamedLayersAdapter.prototype.getLayers = function(username, layers, callback) { var self = this; if (!layers) { return callback(null); } var augmentLayersQueue = queue(layers.length); function augmentLayer(layer, done) { self.overviewsApi.getOverviewsMetadata(username, layer.options.sql, function(err, metadata){ if (err) { done(err, layer); } else { if ( !_.isEmpty(metadata) ) { // layer = _.extend({}, layer, { overviews: metadata }); } done(null, layer); } }); } function layersAugmentQueueFinish(err, layers) { if (err) { return callback(err); } if (!layers || layers.length === 0) { return callback(new Error('Missing layers array from layergroup config')); } return callback(null, layers); } layers.forEach(function(layer) { augmentLayersQueue.defer(augmentLayer, layer); }); augmentLayersQueue.awaitAll(layersAugmentQueueFinish); };
var queue = require('queue-async'); var _ = require('underscore'); function MapConfigNamedLayersAdapter(overviewsApi) { this.overviewsApi = overviewsApi; } module.exports = MapConfigNamedLayersAdapter; MapConfigNamedLayersAdapter.prototype.getLayers = function(username, layers, callback) { var self = this; if (!layers) { return callback(null); } var augmentLayersQueue = queue(layers.length); function augmentLayer(layer, done) { self.overviewsApi.getOverviewsMetadata(username, layer.options.sql, function(err, metadata){ if (err) { done(err, layer); } else { if ( !_.isEmpty(metadata) ) { layer = _.extend({}, layer, { overviews: metadata }); } done(null, layer); } }); } function layersAugmentQueueFinish(err, layers) { if (err) { return callback(err); } if (!layers || layers.length === 0) { return callback(new Error('Missing layers array from layergroup config')); } return callback(null, layers); } layers.forEach(function(layer) { augmentLayersQueue.defer(augmentLayer, layer); }); augmentLayersQueue.awaitAll(layersAugmentQueueFinish); };
Bring in code commented out for tests
Bring in code commented out for tests
JavaScript
bsd-3-clause
CartoDB/Windshaft-cartodb,CartoDB/Windshaft-cartodb,CartoDB/Windshaft-cartodb,CartoDB/Windshaft-cartodb
--- +++ @@ -22,7 +22,7 @@ done(err, layer); } else { if ( !_.isEmpty(metadata) ) { - // layer = _.extend({}, layer, { overviews: metadata }); + layer = _.extend({}, layer, { overviews: metadata }); } done(null, layer); }
2ae9e370b6b3c4ef87275471f50f1db007dbfb23
test/channel-mapping.test.js
test/channel-mapping.test.js
import chai from 'chai'; import irc from 'irc'; import discord from 'discord.js'; import Bot from '../lib/bot'; import config from './fixtures/single-test-config.json'; import caseConfig from './fixtures/case-sensitivity-config.json'; import DiscordStub from './stubs/discord-stub'; import ClientStub from './stubs/irc-client-stub'; import { validateChannelMapping } from '../lib/validators'; chai.should(); describe('Channel Mapping', () => { before(() => { irc.Client = ClientStub; discord.Client = DiscordStub; }); it('should fail when not given proper JSON', () => { const wrongMapping = 'not json'; function wrap() { validateChannelMapping(wrongMapping); } (wrap).should.throw('Invalid channel mapping given'); }); it('should not fail if given a proper channel list as JSON', () => { const correctMapping = { '#channel': '#otherchannel' }; function wrap() { validateChannelMapping(correctMapping); } (wrap).should.not.throw(); }); it('should clear channel keys from the mapping', () => { const bot = new Bot(config); bot.channelMapping['#discord'].should.equal('#irc'); bot.invertedMapping['#irc'].should.equal('#discord'); bot.channels[0].should.equal('#irc channelKey'); }); it('should lowercase IRC channel names', () => { const bot = new Bot(caseConfig); bot.channelMapping['#discord'].should.equal('#irc'); bot.channelMapping['#otherDiscord'].should.equal('#otherirc'); }); });
import chai from 'chai'; import irc from 'irc'; import discord from 'discord.js'; import Bot from '../lib/bot'; import config from './fixtures/single-test-config.json'; import caseConfig from './fixtures/case-sensitivity-config.json'; import DiscordStub from './stubs/discord-stub'; import ClientStub from './stubs/irc-client-stub'; import { validateChannelMapping } from '../lib/validators'; chai.should(); describe('Channel Mapping', () => { before(() => { irc.Client = ClientStub; discord.Client = DiscordStub; }); it('should fail when not given proper JSON', () => { const wrongMapping = 'not json'; function wrap() { validateChannelMapping(wrongMapping); } (wrap).should.throw('Invalid channel mapping given'); }); it('should not fail if given a proper channel list as JSON', () => { const correctMapping = { '#channel': '#otherchannel' }; function wrap() { validateChannelMapping(correctMapping); } (wrap).should.not.throw(); }); it('should clear channel keys from the mapping', () => { const bot = new Bot(config); bot.channelMapping['#discord'].should.equal('#irc'); bot.invertedMapping['#irc'].should.equal('#discord'); bot.channels.should.contain('#irc channelKey'); }); it('should lowercase IRC channel names', () => { const bot = new Bot(caseConfig); bot.channelMapping['#discord'].should.equal('#irc'); bot.channelMapping['#otherDiscord'].should.equal('#otherirc'); }); });
Update check to look for presence, not equality (order unnecessary)
Update check to look for presence, not equality (order unnecessary)
JavaScript
mit
reactiflux/discord-irc
--- +++ @@ -38,7 +38,7 @@ const bot = new Bot(config); bot.channelMapping['#discord'].should.equal('#irc'); bot.invertedMapping['#irc'].should.equal('#discord'); - bot.channels[0].should.equal('#irc channelKey'); + bot.channels.should.contain('#irc channelKey'); }); it('should lowercase IRC channel names', () => {
23ff386f7989dd6a1aaf63d6c1108c5b0b5d2583
blueprints/ember-table/index.js
blueprints/ember-table/index.js
module.exports = { normalizeEntityName: function() {}, afterInstall: function(options) { // We assume that handlebars, ember, and jquery already exist return this.addBowerPackagesToProject([ { // Antiscroll seems to be abandoned by its original authors. We need // two things: (1) a version in package.json, and (2) the name of the // package must be "antiscroll" to satisfy ember-cli. 'name': 'git://github.com/azirbel/antiscroll.git#90391fb371c7be769bc32e7287c5271981428356' }, { 'name': 'jquery-mousewheel', 'target': '~3.1.4' }, { 'name': 'jquery-ui', 'target': '~1.11.4' } ]); } };
module.exports = { normalizeEntityName: function() {}, afterInstall: function(options) { // We assume that handlebars, ember, and jquery already exist return this.addBowerPackagesToProject([ { // Antiscroll seems to be abandoned by its original authors. We need // two things: (1) a version in package.json, and (2) the name of the // package must be "antiscroll" to satisfy ember-cli. 'name': 'git://github.com/Addepar/antiscroll.git#e0d1538cf4f3fd61c5bedd6168df86d651f125da' }, { 'name': 'jquery-mousewheel', 'target': '~3.1.4' }, { 'name': 'jquery-ui', 'target': '~1.11.4' } ]); } };
Use correct version of antiscroll in blueprint
Use correct version of antiscroll in blueprint
JavaScript
bsd-3-clause
hedgeserv/ember-table,Gaurav0/ember-table,phoebusliang/ember-table,phoebusliang/ember-table,Gaurav0/ember-table,hedgeserv/ember-table
--- +++ @@ -8,7 +8,7 @@ // Antiscroll seems to be abandoned by its original authors. We need // two things: (1) a version in package.json, and (2) the name of the // package must be "antiscroll" to satisfy ember-cli. - 'name': 'git://github.com/azirbel/antiscroll.git#90391fb371c7be769bc32e7287c5271981428356' + 'name': 'git://github.com/Addepar/antiscroll.git#e0d1538cf4f3fd61c5bedd6168df86d651f125da' }, { 'name': 'jquery-mousewheel',
d2b7ee755b6d51c93d5f6f1d24a65b34f2d1f90d
app/soc/content/js/tips-081027.js
app/soc/content/js/tips-081027.js
$(function() { $('tr[title]').bt(); });
$(function() { // Change 'title' to something else first $('tr[title]').each(function() { $(this).attr('xtitle', $(this).attr('title')).removeAttr('title'); }) .children().children(':input') // Set up event handlers .bt({trigger: ['helperon', 'helperoff'], titleSelector: "parent().parent().attr('xtitle')", killTitle: false, fill: 'rgba(135, 206, 250, .9)', positions: ['bottom', 'top', 'right'], }) .bind('focus', function() { $(this).trigger('helperon'); }) .bind('blur', function() { $(this).trigger('helperoff'); }) .parent() .bind('mouseover', function() { $(this).children(':input').trigger('helperon'); }) .bind('mouseleave', function() { $(this).children(':input').trigger('helperoff'); }); });
Make tooltips work when tabbing
Make tooltips work when tabbing Fixed the tooltips on IE, and changed the background colour to be nicer on Firefox. Patch by: Haoyu Bai <baihaoyu@gmail.com> --HG-- extra : convert_revision : svn%3A32761e7d-7263-4528-b7be-7235b26367ec/trunk%401624
JavaScript
apache-2.0
rhyolight/nupic.son,rhyolight/nupic.son,rhyolight/nupic.son
--- +++ @@ -1,3 +1,28 @@ $(function() { - $('tr[title]').bt(); + // Change 'title' to something else first + $('tr[title]').each(function() { + $(this).attr('xtitle', $(this).attr('title')).removeAttr('title'); + }) + .children().children(':input') + // Set up event handlers + .bt({trigger: ['helperon', 'helperoff'], + titleSelector: "parent().parent().attr('xtitle')", + killTitle: false, + fill: 'rgba(135, 206, 250, .9)', + positions: ['bottom', 'top', 'right'], + }) + .bind('focus', function() { + $(this).trigger('helperon'); + }) + .bind('blur', function() { + $(this).trigger('helperoff'); + }) + .parent() + .bind('mouseover', function() { + $(this).children(':input').trigger('helperon'); + }) + .bind('mouseleave', function() { + $(this).children(':input').trigger('helperoff'); + }); }); +
0202747e5620276e90c907bfbd14905891f744a5
public/javascripts/youtube-test.js
public/javascripts/youtube-test.js
var tag = document.createElement('script'); tag.src = "https://www.youtube.com/iframe_api"; var firstScriptTag = document.getElementsByTagName('script')[0]; firstScriptTag.parentNode.insertBefore(tag, firstScriptTag); var player; function onYouTubeIframeAPIReady() { player = new YT.Player('player', { height: '390', width: '640', videoId: 'GxfwZMdSt4w', events: { 'onReady': onPlayerReady } }); } function onPlayerReady(event) { event.target.playVideo(); player.setVolume(30); }
var tag = document.createElement('script'); tag.src = "https://www.youtube.com/iframe_api"; var firstScriptTag = document.getElementsByTagName('script')[0]; firstScriptTag.parentNode.insertBefore(tag, firstScriptTag); var player; function onYouTubeIframeAPIReady() { player = new YT.Player('player', { height: '390', width: '640', videoId: 'c24En0r-lXg', events: { 'onReady': onPlayerReady } }); } function onPlayerReady(event) { event.target.playVideo(); player.setVolume(30); }
Change video ID (see extended log)
Change video ID (see extended log) - Demonstrate that HTTP referrer overriding is not necessary. This is mostly for my own research and for eventual changes I will make to Toby my YouTube player so that I no longer require a patch to libchromiumcontent allowing the overriding of the HTTP referrer.
JavaScript
mit
frankhale/electron-with-express
--- +++ @@ -8,7 +8,7 @@ player = new YT.Player('player', { height: '390', width: '640', - videoId: 'GxfwZMdSt4w', + videoId: 'c24En0r-lXg', events: { 'onReady': onPlayerReady }
5c0ff1bf885ac5a40dddd67b9e9733ee120e4361
project/src/js/main.js
project/src/js/main.js
/* application entry point */ // require mithril globally for convenience window.m = require('mithril'); // cordova plugins polyfills for browser if (!window.cordova) require('./cordovaPolyfills.js'); var utils = require('./utils'); var session = require('./session'); var i18n = require('./i18n'); var home = require('./ui/home'); var login = require('./ui/login'); var play = require('./ui/play'); var seek = require('./ui/seek'); function main() { m.route(document.body, '/', { '/': home, '/login': login, '/seek/:id': seek, '/play/:id': play }); if (utils.hasNetwork()) session.refresh(true); window.cordova.plugins.Keyboard.disableScroll(true); if (window.gaId) window.analytics.startTrackerWithId(window.gaId); setTimeout(function() { window.navigator.splashscreen.hide(); }, 500); } document.addEventListener('deviceready', // i18n must be loaded before any rendering happens utils.ƒ(i18n.loadPreferredLanguage, main), false );
/* application entry point */ // require mithril globally for convenience window.m = require('mithril'); // cordova plugins polyfills for browser if (!window.cordova) require('./cordovaPolyfills.js'); var utils = require('./utils'); var session = require('./session'); var i18n = require('./i18n'); var home = require('./ui/home'); var login = require('./ui/login'); var play = require('./ui/play'); var seek = require('./ui/seek'); function onResume() { session.refresh(true); } function main() { m.route(document.body, '/', { '/': home, '/login': login, '/seek/:id': seek, '/play/:id': play }); // refresh data once and on app resume if (utils.hasNetwork()) session.refresh(true); document.addEventListener('resume', onResume, false); // iOs keyboard hack // TODO we may want to remove this and call only on purpose window.cordova.plugins.Keyboard.disableScroll(true); if (window.gaId) window.analytics.startTrackerWithId(window.gaId); setTimeout(function() { window.navigator.splashscreen.hide(); }, 500); } document.addEventListener('deviceready', // i18n must be loaded before any rendering happens utils.ƒ(i18n.loadPreferredLanguage, main), false );
Refresh data on app going foreground
Refresh data on app going foreground
JavaScript
mit
btrent/lichobile,btrent/lichobile,garawaa/lichobile,garawaa/lichobile,btrent/lichobile,garawaa/lichobile,btrent/lichobile
--- +++ @@ -15,6 +15,10 @@ var play = require('./ui/play'); var seek = require('./ui/seek'); +function onResume() { + session.refresh(true); +} + function main() { m.route(document.body, '/', { @@ -24,8 +28,12 @@ '/play/:id': play }); + // refresh data once and on app resume if (utils.hasNetwork()) session.refresh(true); + document.addEventListener('resume', onResume, false); + // iOs keyboard hack + // TODO we may want to remove this and call only on purpose window.cordova.plugins.Keyboard.disableScroll(true); if (window.gaId) window.analytics.startTrackerWithId(window.gaId);
96f88d87967b29d338f5baf984691ba7f7e9110d
Web/api/models/Questions.js
Web/api/models/Questions.js
/** * Questions.js * * @description :: TODO: You might write a short summary of how this model works and what it represents here. * @docs :: http://sailsjs.org/#!documentation/models */ module.exports = { attributes: { text: 'string', type: { type: 'string', enum: ['email', 'range', 'freetext'] }, } };
/** * Questions.js * * @description :: TODO: You might write a short summary of how this model works and what it represents here. * @docs :: http://sailsjs.org/#!documentation/models */ module.exports = { attributes: { text: 'string', type: { type: 'string', enum: ['string', 'text', 'range'] }, } };
Modify question type to allow the following type: string, text or range
Modify question type to allow the following type: string, text or range
JavaScript
mit
Xignal/Backend
--- +++ @@ -11,7 +11,7 @@ text: 'string', type: { type: 'string', - enum: ['email', 'range', 'freetext'] + enum: ['string', 'text', 'range'] }, } };
5bd0512b74cb30edd82b8aa4d2c8ea55f8944a56
viewsource/js/static/ast.js
viewsource/js/static/ast.js
// This just dumps out an ast for your viewing pleasure. include("dumpast.js"); function process_js(ast) { dump_ast(ast); }
include("beautify.js"); function process_js(ast) { _print('// process_js'); _print(js_beautify(uneval(ast)) .replace(/op: (\d+),/g, function (hit, group1) { return 'op: ' + decode_op(group1) + '(' + group1 + '),' }) .replace(/type: (\d+),/g, function (hit, group1) { return 'type: ' + decode_type(group1) + '(' + group1 + '),' }) .replace(/{/g, '<span>{') .replace(/}/g, '}</span>')); } var global = this; var optable = null, toktable; function decode_op(opcode) { if (!optable) { optable = []; for (let key in global) { if (key.indexOf("JSOP_") == 0) { optable[global[key]] = key; } } } if (opcode in optable) return optable[opcode]; return opcode; } function decode_type(opcode) { if (!toktable) { toktable = []; for (let key in global) { if (key.indexOf("TOK_") == 0) { toktable[global[key]] = key; } } } if (opcode in toktable) return toktable[opcode]; return opcode; }
Make jshydra output match dehydra's.
[ViewSource] Make jshydra output match dehydra's.
JavaScript
mit
srenatus/dxr,jonasfj/dxr,pelmers/dxr,jay-z007/dxr,jay-z007/dxr,jbradberry/dxr,jbradberry/dxr,pelmers/dxr,kleintom/dxr,jonasfj/dxr,erikrose/dxr,pombredanne/dxr,nrc/dxr,gartung/dxr,pombredanne/dxr,pelmers/dxr,nrc/dxr,jay-z007/dxr,KiemVM/Mozilla--dxr,gartung/dxr,erikrose/dxr,jay-z007/dxr,KiemVM/Mozilla--dxr,jbradberry/dxr,KiemVM/Mozilla--dxr,jay-z007/dxr,pelmers/dxr,jay-z007/dxr,nrc/dxr,bozzmob/dxr,nrc/dxr,jonasfj/dxr,jbradberry/dxr,pombredanne/dxr,gartung/dxr,srenatus/dxr,bozzmob/dxr,srenatus/dxr,pombredanne/dxr,srenatus/dxr,jonasfj/dxr,kleintom/dxr,erikrose/dxr,nrc/dxr,erikrose/dxr,pelmers/dxr,nrc/dxr,srenatus/dxr,bozzmob/dxr,gartung/dxr,jonasfj/dxr,pelmers/dxr,jbradberry/dxr,jbradberry/dxr,jbradberry/dxr,jay-z007/dxr,kleintom/dxr,gartung/dxr,kleintom/dxr,pombredanne/dxr,gartung/dxr,srenatus/dxr,bozzmob/dxr,kleintom/dxr,kleintom/dxr,gartung/dxr,KiemVM/Mozilla--dxr,bozzmob/dxr,KiemVM/Mozilla--dxr,jonasfj/dxr,bozzmob/dxr,pombredanne/dxr,bozzmob/dxr,pelmers/dxr,kleintom/dxr,KiemVM/Mozilla--dxr,erikrose/dxr,pombredanne/dxr
--- +++ @@ -1,7 +1,46 @@ -// This just dumps out an ast for your viewing pleasure. - -include("dumpast.js"); +include("beautify.js"); function process_js(ast) { - dump_ast(ast); + _print('// process_js'); + _print(js_beautify(uneval(ast)) + .replace(/op: (\d+),/g, + function (hit, group1) { + return 'op: ' + decode_op(group1) + '(' + group1 + '),' + }) + .replace(/type: (\d+),/g, + function (hit, group1) { + return 'type: ' + decode_type(group1) + '(' + group1 + '),' + }) + .replace(/{/g, '<span>{') + .replace(/}/g, '}</span>')); } + +var global = this; +var optable = null, toktable; +function decode_op(opcode) { + if (!optable) { + optable = []; + for (let key in global) { + if (key.indexOf("JSOP_") == 0) { + optable[global[key]] = key; + } + } + } + if (opcode in optable) + return optable[opcode]; + return opcode; +} + +function decode_type(opcode) { + if (!toktable) { + toktable = []; + for (let key in global) { + if (key.indexOf("TOK_") == 0) { + toktable[global[key]] = key; + } + } + } + if (opcode in toktable) + return toktable[opcode]; + return opcode; +}
67f62b161eb997b77e21a2c1bedd6748baa97908
app/components/quotes.js
app/components/quotes.js
import React, { PropTypes } from 'react'; const Quote = ({quote}) => ( <div> <p>{quote.value}</p> <p>{quote.author}</p> </div> ) Quote.propTypes = { quote: PropTypes.object.isRequired } export default Quote;
import React, { PropTypes } from 'react'; const Quote = ({quote}) => ( <div className='quote_comp'> <p className='quote_comp__text'>{quote.value}</p> <p className='quote_comp__author'>- {quote.author}</p> </div> ) Quote.propTypes = { quote: PropTypes.object.isRequired } export default Quote;
Add classes to quote component
Add classes to quote component
JavaScript
mit
subramaniashiva/quotes-pwa,subramaniashiva/quotes-pwa
--- +++ @@ -1,9 +1,9 @@ import React, { PropTypes } from 'react'; const Quote = ({quote}) => ( - <div> - <p>{quote.value}</p> - <p>{quote.author}</p> + <div className='quote_comp'> + <p className='quote_comp__text'>{quote.value}</p> + <p className='quote_comp__author'>- {quote.author}</p> </div> )
c82e4c18c64c3f86e3865484b4b1a01de6f026a5
lib/app.js
lib/app.js
#!/usr/bin/env node /*eslint-disable no-var */ var path = require('path'); var spawner = require('child_process'); exports.getFullPath = function(script){ return path.join(__dirname, script); }; // Respawn ensuring proper command switches exports.respawn = function respawn(script, requiredArgs, hostProcess) { if (!requiredArgs || requiredArgs.length === 0) { requiredArgs = ['--harmony']; } var args = hostProcess.execArgv.slice(); for (var i = 0; i < requiredArgs.length; i += 1) { if (args.indexOf(requiredArgs[i]) < 0) { args.push(requiredArgs[i]); } } var execScript = exports.getFullPath(script); spawner.spawn(hostProcess.execPath, args.concat(execScript, hostProcess.argv.slice(2)), { cwd: hostProcess.cwd(), stdio: 'inherit' }); }; /* istanbul ignore if */ if (require.main === module) { var argv = require('yargs') .usage('Usage: $0 [options] <cfgFile>') .demand(1, 1, 'A valid configuration file must be provided') .describe({ checkCfg: 'Check the validity of the configuration file without starting the bot' }) .argv; //respawn, ensuring required command switches exports.respawn('cli', ['--harmony', '--harmony_arrow_functions'], process); } /*eslint-enable no-var */
#!/usr/bin/env node /*eslint-disable no-var */ var path = require('path'); var spawner = require('child_process'); exports.getFullPath = function(script){ return path.join(__dirname, script); }; // Respawn ensuring proper command switches exports.respawn = function respawn(script, requiredArgs, hostProcess) { if (!requiredArgs || requiredArgs.length === 0) { requiredArgs = ['--harmony']; } var args = hostProcess.execArgv.slice(); for (var i = 0; i < requiredArgs.length; i += 1) { if (args.indexOf(requiredArgs[i]) < 0) { args.push(requiredArgs[i]); } } var execScript = exports.getFullPath(script); spawner.spawn(hostProcess.execPath, args.concat(execScript, hostProcess.argv.slice(2)), { cwd: hostProcess.cwd(), stdio: 'inherit' }); }; /* istanbul ignore if */ if (require.main === module) { var argv = require('yargs') .usage('Usage: $0 <cfgFile> [options]') .demand(1, 1, 'A valid configuration file must be provided') .describe({ checkCfg: 'Check the validity of the configuration file without starting the bot' }) .argv; //respawn, ensuring required command switches exports.respawn('cli', ['--harmony', '--harmony_arrow_functions'], process); } /*eslint-enable no-var */
Fix ordering on command line
Fix ordering on command line
JavaScript
mit
SockDrawer/SockBot
--- +++ @@ -29,7 +29,7 @@ /* istanbul ignore if */ if (require.main === module) { var argv = require('yargs') - .usage('Usage: $0 [options] <cfgFile>') + .usage('Usage: $0 <cfgFile> [options]') .demand(1, 1, 'A valid configuration file must be provided') .describe({ checkCfg: 'Check the validity of the configuration file without starting the bot'
f9ea5ab178f8326b79c177889a5266a2bd4af91b
client/app/scripts/services/api.js
client/app/scripts/services/api.js
angular .module('app') .factory('apiService', [ '$http', function($http) { return { client: $http.get('/api/bower'), server: $http.get('/api/package') }; } ]) ;
angular .module('app') .factory('apiService', [ '$http', function($http) { return { client: $http.get('../bower.json'), server: $http.get('../package.json') }; } ]) ;
Use relative paths for bower/package.json
Use relative paths for bower/package.json
JavaScript
mit
ericclemmons/ericclemmons.github.io,ericclemmons/ericclemmons.github.io
--- +++ @@ -4,8 +4,8 @@ '$http', function($http) { return { - client: $http.get('/api/bower'), - server: $http.get('/api/package') + client: $http.get('../bower.json'), + server: $http.get('../package.json') }; } ])
92b0f90d0962114f54ec58babcc6017018a1263b
client/helpers/validations/book.js
client/helpers/validations/book.js
const validate = (values) => { const errors = {}; if (!values.title || values.title.trim() === '') { errors.title = 'Book title is required'; } if (!values.author || values.author.trim() === '') { errors.author = 'Book author is required'; } if (!values.description || values.description.trim() === '') { errors.description = 'Book description is required'; } if (!values.subject) { errors.subject = 'Book subject is required'; } if (!values.description || values.description.trim() === '') { errors.description = 'Book description is required'; } if (!values.imageURL || values.imageURL.trim() === '') { errors.imageURL = 'ImageURL is required'; } if (!values.quantity || values.quantity.trim() === '') { errors.quantity = 'quantity is required'; } if (values.quantity && values.quantity <= 0) { errors.quantity = 'quantity must be greater than 0'; } return errors; }; export default validate;
const validate = (values) => { const errors = {}; if (!values.title || values.title.trim() === '') { errors.title = 'Book title is required'; } if (!values.author || values.author.trim() === '') { errors.author = 'Book author is required'; } if (!values.description || values.description.trim() === '') { errors.description = 'Book description is required'; } if (!values.subject) { errors.subject = 'Book subject is required'; } if (!values.description || values.description.trim() === '') { errors.description = 'Book description is required'; } if (!values.imageURL || values.imageURL.trim() === '') { errors.imageURL = 'ImageURL is required'; } if (!values.quantity) { errors.quantity = 'quantity is required'; } if (values.quantity && values.quantity <= 0) { errors.quantity = 'quantity must be greater than 0'; } return errors; }; export default validate;
Fix bug in validation method
Fix bug in validation method
JavaScript
mit
amarachukwu-agbo/hello-books,amarachukwu-agbo/hello-books
--- +++ @@ -18,7 +18,7 @@ if (!values.imageURL || values.imageURL.trim() === '') { errors.imageURL = 'ImageURL is required'; } - if (!values.quantity || values.quantity.trim() === '') { + if (!values.quantity) { errors.quantity = 'quantity is required'; } if (values.quantity && values.quantity <= 0) {
8070c9f13209b80b1881fc83de027b3895656046
test/unescape-css.js
test/unescape-css.js
var test = require('ava'); var unescapeCss = require('../lib/unescape-css'); test('should unescape plain chars', function (t) { t.is(unescapeCss('Romeo \\+ Juliette'), 'Romeo + Juliette'); }); test('should unescape ASCII chars', function (t) { t.is(unescapeCss('\\34\\32'), '42'); }); test('should unescape Unicode chars', function (t) { t.is(unescapeCss('I \\2665 NY'), 'I ♥ NY'); });
var test = require('ava'); var unescapeCss = require('../lib/unescape-css'); test('unescapes plain chars', function (t) { t.is(unescapeCss('Romeo \\+ Juliette'), 'Romeo + Juliette'); }); test('unescapes ASCII chars', function (t) { t.is(unescapeCss('\\34\\32'), '42'); }); test('unescapes Unicode chars', function (t) { t.is(unescapeCss('I \\2665 NY'), 'I ♥ NY'); });
Remove word "should" from test descriptions
Remove word "should" from test descriptions
JavaScript
mit
assetsjs/postcss-assets,borodean/postcss-assets
--- +++ @@ -1,14 +1,14 @@ var test = require('ava'); var unescapeCss = require('../lib/unescape-css'); -test('should unescape plain chars', function (t) { +test('unescapes plain chars', function (t) { t.is(unescapeCss('Romeo \\+ Juliette'), 'Romeo + Juliette'); }); -test('should unescape ASCII chars', function (t) { +test('unescapes ASCII chars', function (t) { t.is(unescapeCss('\\34\\32'), '42'); }); -test('should unescape Unicode chars', function (t) { +test('unescapes Unicode chars', function (t) { t.is(unescapeCss('I \\2665 NY'), 'I ♥ NY'); });
7c8a1b33bad96e772921a24ced0343d756dcae34
jquery.dragster.js
jquery.dragster.js
(function ($) { $.fn.dragster = function (options) { var settings = $.extend({ enter: $.noop, leave: $.noop }, options); return this.each(function () { var first = false, second = false, $this = $(this); $this.on({ dragenter: function () { if (first) { return second = true; } else { first = true; $this.trigger('dragster:enter'); } }, dragleave: function () { if (second) { second = false; } else if (first) { first = false; } if (!first && !second) { $this.trigger('dragster:leave'); } }, 'dragster:enter': settings.enter, 'dragster:leave': settings.leave }); }); }; }(jQuery));
(function ($) { $.fn.dragster = function (options) { var settings = $.extend({ enter: $.noop, leave: $.noop, over: $.noop }, options); return this.each(function () { var first = false, second = false, $this = $(this); $this.on({ dragenter: function (event) { if (first) { return second = true; } else { first = true; $this.trigger('dragster:enter', event); } event.preventDefault(); }, dragleave: function (event) { if (second) { second = false; } else if (first) { first = false; } if (!first && !second) { $this.trigger('dragster:leave', event); } event.preventDefault(); }, dragover: function (event) { event.preventDefault(); }, 'dragster:enter': settings.enter, 'dragster:leave': settings.leave, 'dragster:over': settings.over }); }); }; }(jQuery));
Fix drop event with preventDefault
Fix drop event with preventDefault If preventDefault is not triggered, we can't use drop event. I fix it and added an over function to disable it by default.
JavaScript
mit
catmanjan/jquery-dragster
--- +++ @@ -3,7 +3,8 @@ $.fn.dragster = function (options) { var settings = $.extend({ enter: $.noop, - leave: $.noop + leave: $.noop, + over: $.noop }, options); return this.each(function () { @@ -12,26 +13,32 @@ $this = $(this); $this.on({ - dragenter: function () { + dragenter: function (event) { if (first) { return second = true; } else { first = true; - $this.trigger('dragster:enter'); + $this.trigger('dragster:enter', event); } - }, - dragleave: function () { + event.preventDefault(); + }, + dragleave: function (event) { if (second) { second = false; } else if (first) { first = false; } if (!first && !second) { - $this.trigger('dragster:leave'); + $this.trigger('dragster:leave', event); } + event.preventDefault(); + }, + dragover: function (event) { + event.preventDefault(); }, 'dragster:enter': settings.enter, - 'dragster:leave': settings.leave + 'dragster:leave': settings.leave, + 'dragster:over': settings.over }); }); };
439cfd0b85a8a2416aeac40607bfddad86ef9773
app/controllers/form.js
app/controllers/form.js
var args = arguments[0] || {}; if (args.hasOwnProperty('itemIndex')) { // Edit mode var myModel = Alloy.Collections.tasks.at(args.itemIndex); $.text.value = myModel.get('text'); } else { // Add mode var myModel = Alloy.createModel('tasks'); myModel.set("status", "pending"); } // Focus on 1st input function windowOpened() { $.text.focus(); } function saveBtnClicked() { myModel.set("text", $.text.value); myModel.set("lastModifiedDate", Alloy.Globals.moment().toISOString()); // insert if add, update if edit myModel.save(); // Refresh home screen args.refreshCollection(); Alloy.Globals.pageStack.back(); }
var args = arguments[0] || {}; if (args.hasOwnProperty('itemIndex')) { // Edit mode var myModel = Alloy.Collections.tasks.at(args.itemIndex); $.text.value = myModel.get('text'); } else { // Add mode var myModel = Alloy.createModel('tasks'); myModel.set("status", "pending"); } // Focus on 1st input function windowOpened() { $.text.focus(); } function saveBtnClicked() { if ($.text.value.length === 0) { var alertDialog = Ti.UI.createAlertDialog({ title: 'Error', message: 'Enter task title at least', buttons: ['OK'] }); alertDialog.addEventListener('click', function() { $.text.focus(); }); alertDialog.show(); return false; } myModel.set("text", $.text.value); myModel.set("lastModifiedDate", Alloy.Globals.moment().toISOString()); // insert if add, update if edit myModel.save(); // Refresh home screen args.refreshCollection(); Alloy.Globals.pageStack.back(); }
Validate the only 1 field we have right now
Validate the only 1 field we have right now
JavaScript
mit
HazemKhaled/TiTODOs,HazemKhaled/TiTODOs
--- +++ @@ -16,6 +16,21 @@ } function saveBtnClicked() { + + if ($.text.value.length === 0) { + var alertDialog = Ti.UI.createAlertDialog({ + title: 'Error', + message: 'Enter task title at least', + buttons: ['OK'] + }); + alertDialog.addEventListener('click', function() { + $.text.focus(); + }); + alertDialog.show(); + + return false; + } + myModel.set("text", $.text.value); myModel.set("lastModifiedDate", Alloy.Globals.moment().toISOString());
350209bd9bebca2d9365e531d87ecdf53758026d
assets/javascripts/js.js
assets/javascripts/js.js
$(document).ready(function() { $('.side-nav-container').hover(function() { $(this).addClass('is-showed'); $('.kudo').addClass('hide'); }, function() { $(this).removeClass('is-showed'); $('.kudo').removeClass('hide'); }); $(window).scroll(function () { var logotype = $('.logotype'); var buttonNav = $('.side-nav__button'); if ($(window).scrollTop() > 150) { logotype.addClass('is-showed'); buttonNav.addClass('no-opacity'); } else { logotype.removeClass('is-showed'); buttonNav.removeClass('no-opacity') } }); });
$(document).ready(function () { $('.side-nav-container').hover(function () { $(this).addClass('is-showed'); $('.kudo').addClass('hide'); }, function() { $(this).removeClass('is-showed'); $('.kudo').removeClass('hide'); }); $(window).scroll(function () { var logotype = $('.logotype'), buttonNav = $('.side-nav__button'), scrollTop = $(window).scrollTop(), windowHeight = $(window).outerHeight(), kudoSide = $('.kudo'); kudoBottom = $('.instapaper'); // $('.kudo-bottom') kudoBottomPosition = kudoBottom.offset().top; // instapaper for now while adding kudo-bottom elem if ( scrollTop > 150) { logotype.addClass('is-showed'); buttonNav.addClass('no-opacity'); } else { logotype.removeClass('is-showed'); buttonNav.removeClass('no-opacity') } if ( scrollTop + windowHeight > kudoBottomPosition) { kudoSide.addClass('hide'); } else { kudoSide.removeClass('hide'); } }); });
Add animation for kudo-side when kudo-bottom is showed
Add animation for kudo-side when kudo-bottom is showed
JavaScript
cc0-1.0
cybertk/cybertk.github.io,margaritis/svbtle-jekyll,orlando/svbtle-jekyll,margaritis/margaritis.github.io,orlando/svbtle-jekyll,margaritis/margaritis.github.io,margaritis/margaritis.github.io,cybertk/cybertk.github.io,margaritis/svbtle-jekyll
--- +++ @@ -1,24 +1,34 @@ -$(document).ready(function() { - - $('.side-nav-container').hover(function() { - $(this).addClass('is-showed'); - $('.kudo').addClass('hide'); - }, function() { - $(this).removeClass('is-showed'); - $('.kudo').removeClass('hide'); - }); +$(document).ready(function () { - $(window).scroll(function () { - var logotype = $('.logotype'); - var buttonNav = $('.side-nav__button'); + $('.side-nav-container').hover(function () { + $(this).addClass('is-showed'); + $('.kudo').addClass('hide'); + }, function() { + $(this).removeClass('is-showed'); + $('.kudo').removeClass('hide'); + }); - if ($(window).scrollTop() > 150) { - logotype.addClass('is-showed'); - buttonNav.addClass('no-opacity'); - } else { - logotype.removeClass('is-showed'); - buttonNav.removeClass('no-opacity') - } - }); + $(window).scroll(function () { + var logotype = $('.logotype'), + buttonNav = $('.side-nav__button'), + scrollTop = $(window).scrollTop(), + windowHeight = $(window).outerHeight(), + kudoSide = $('.kudo'); + kudoBottom = $('.instapaper'); // $('.kudo-bottom') + kudoBottomPosition = kudoBottom.offset().top; // instapaper for now while adding kudo-bottom elem + if ( scrollTop > 150) { + logotype.addClass('is-showed'); + buttonNav.addClass('no-opacity'); + } else { + logotype.removeClass('is-showed'); + buttonNav.removeClass('no-opacity') + } + + if ( scrollTop + windowHeight > kudoBottomPosition) { + kudoSide.addClass('hide'); + } else { + kudoSide.removeClass('hide'); + } + }); });
67efb8bde264e3ea0823e40558d29dd89120c0c9
src/components/views/messages/MessageTimestamp.js
src/components/views/messages/MessageTimestamp.js
/* Copyright 2015, 2016 OpenMarket Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ 'use strict'; var React = require('react'); var DateUtils = require('matrix-react-sdk/lib/DateUtils'); module.exports = React.createClass({ displayName: 'MessageTimestamp', render: function() { var date = new Date(this.props.ts); return ( <span className="mx_MessageTimestamp"> { DateUtils.formatTime(date) } </span> ); }, });
/* Copyright 2015, 2016 OpenMarket Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ 'use strict'; var React = require('react'); var DateUtils = require('matrix-react-sdk/lib/DateUtils'); module.exports = React.createClass({ displayName: 'MessageTimestamp', render: function() { var date = new Date(this.props.ts); return ( <span className="mx_MessageTimestamp" title={ DateUtils.formatDate(date) }> { DateUtils.formatTime(date) } </span> ); }, });
Add date tooltip to timestamps
Add date tooltip to timestamps
JavaScript
apache-2.0
vector-im/riot-web,vector-im/riot-web,vector-im/vector-web,vector-im/vector-web,vector-im/vector-web,martindale/vector,vector-im/vector-web,vector-im/riot-web,vector-im/riot-web,vector-im/vector-web,vector-im/riot-web,vector-im/riot-web,martindale/vector
--- +++ @@ -25,7 +25,7 @@ render: function() { var date = new Date(this.props.ts); return ( - <span className="mx_MessageTimestamp"> + <span className="mx_MessageTimestamp" title={ DateUtils.formatDate(date) }> { DateUtils.formatTime(date) } </span> );
50a084e7894ae1b3586709cf488bd2260cbeb615
packages/eslint-config-eventbrite/rules/style.js
packages/eslint-config-eventbrite/rules/style.js
// The rules ultimately override any rules defined in legacy/rules/style.js module.exports = { rules: { // Enforce function expressions // http://eslint.org/docs/rules/func-style 'func-style': ['error', 'expression'], // enforce that `let` & `const` declarations are declared together // http://eslint.org/docs/rules/one-var 'one-var': ['error', 'never'] } };
// The rules ultimately override any rules defined in legacy/rules/style.js module.exports = { rules: { // Enforce function expressions // http://eslint.org/docs/rules/func-style 'func-style': ['error', 'expression'], // enforce that `let` & `const` declarations are declared together // http://eslint.org/docs/rules/one-var 'one-var': ['error', 'never'], // enforce spacing around infix operators // http://eslint.org/docs/rules/space-infix-ops 'space-infix-ops': 'error' } };
Add new rule for spacing around infix operators
Add new rule for spacing around infix operators
JavaScript
mit
eventbrite/javascript
--- +++ @@ -7,6 +7,10 @@ // enforce that `let` & `const` declarations are declared together // http://eslint.org/docs/rules/one-var - 'one-var': ['error', 'never'] + 'one-var': ['error', 'never'], + + // enforce spacing around infix operators + // http://eslint.org/docs/rules/space-infix-ops + 'space-infix-ops': 'error' } };
f683c19b98c6f2a87ea4c97e55854f871fae5763
app/reducers/network.js
app/reducers/network.js
import { ActionConstants as actions } from '../actions' import { NETWORK_MAIN, NETWORK_TEST } from '../actions/network' export default function network(state = {}, action) { switch (action.type) { case actions.network.SWITCH: { return { ...state, net: action.network } } case actions.network.SET_BLOCK_HEIGHT: { const newBlockHeight = { ...state.blockHeight, [state.net]: action.blockHeight } return { ...state, blockHeight: newBlockHeight } } case actions.network.TOGGLE: { return { ...state, net: state.net === NETWORK_MAIN ? NETWORK_TEST : NETWORK_MAIN } } default: return state } }
import { ActionConstants as actions } from '../actions' import { NETWORK_MAIN, NETWORK_TEST } from '../actions/network' export default function network(state = {}, action) { switch (action.type) { case actions.network.SWITCH: { return { ...state, net: action.network } } case actions.network.SET_BLOCK_HEIGHT: { const newBlockHeight = { ...state.blockHeight, [state.net]: action.blockHeight } return { ...state, blockHeight: newBlockHeight } } case actions.network.TOGGLE: { return { ...state, net: state.net === NETWORK_MAIN ? NETWORK_TEST : NETWORK_MAIN } } case actions.wallet.RESET_STATE: return { ...state, blockHeight: { TestNet: 0, MainNet: 0 } } default: return state } }
Fix updating of balance after a logout followed by a quick login
Fix updating of balance after a logout followed by a quick login
JavaScript
mit
ixje/neon-wallet-react-native,ixje/neon-wallet-react-native,ixje/neon-wallet-react-native
--- +++ @@ -25,6 +25,14 @@ net: state.net === NETWORK_MAIN ? NETWORK_TEST : NETWORK_MAIN } } + case actions.wallet.RESET_STATE: + return { + ...state, + blockHeight: { + TestNet: 0, + MainNet: 0 + } + } default: return state }
0c009ce0f6c647b3e514f1e4efeefb30c929120e
client/angular/src/app/controllers/movies.controller.spec.js
client/angular/src/app/controllers/movies.controller.spec.js
'use strict'; describe('controllers', function() { var httpBackend, scope, createController; beforeEach(module('polyflix')); beforeEach(inject(function($rootScope, $httpBackend, $controller) { httpBackend = $httpBackend; scope = $rootScope.$new(); httpBackend.whenGET(mocks.configUrl).respond( JSON.stringify(mocks.configResults) ); httpBackend.whenGET(mocks.allMoviesUrl).respond( JSON.stringify(mocks.allMoviesResults) ); createController = function() { return $controller('MoviesCtrl', { '$scope': scope }); }; })); describe('controller', function() { it('should exist', function() { var controller = createController(); expect(controller).toBeDefined(); }); }); });
'use strict'; describe('controllers', function() { var httpBackend, scope, createController; beforeEach(module('polyflix')); beforeEach(inject(function($rootScope, $httpBackend, $controller) { httpBackend = $httpBackend; scope = $rootScope.$new(); httpBackend.whenGET(mocks.configUrl).respond( JSON.stringify(mocks.configResults) ); httpBackend.whenGET(mocks.allMoviesUrl).respond( JSON.stringify(mocks.allMoviesResults) ); httpBackend.whenDELETE(mocks.deleteUrl).respond( JSON.stringify(mocks.deleteResults) ); createController = function() { return $controller('MoviesCtrl', { '$scope': scope }); }; })); describe('controller', function() { it('should exist', function() { var controller = createController(); httpBackend.flush(); expect(controller).toBeDefined(); }); }); });
Add mocks to movies controller tests
Add mocks to movies controller tests
JavaScript
mit
ryanbradynd05/polyflix,ryanbradynd05/polyflix,ryanbradynd05/polyflix,ryanbradynd05/polyflix,ryanbradynd05/polyflix
--- +++ @@ -13,6 +13,9 @@ httpBackend.whenGET(mocks.allMoviesUrl).respond( JSON.stringify(mocks.allMoviesResults) ); + httpBackend.whenDELETE(mocks.deleteUrl).respond( + JSON.stringify(mocks.deleteResults) + ); createController = function() { return $controller('MoviesCtrl', { @@ -24,6 +27,7 @@ describe('controller', function() { it('should exist', function() { var controller = createController(); + httpBackend.flush(); expect(controller).toBeDefined(); }); });
75cb05b23b6267665a59e1cc3d53ac6abdd2e11d
adventofcode/day10.js
adventofcode/day10.js
/* * Run in: http://adventofcode.com/day/10 */ ;(function () { let input = document.querySelector('.puzzle-input').textContent console.log( 'Day09/first:', first(input) ) console.log( 'Day09/second:', second(input) ) function first (input) { return Array(40).fill().reduce(lookAndSay, input).length } function second (input) { return Array(50).fill().reduce(lookAndSay, input).length } function lookAndSay (input) { let ex = /(\d)\1*/g return input.match(ex).map(el => el.length + el[0]).join('') } }())
/* * Run in: http://adventofcode.com/day/10 */ ;(function () { let input = document.querySelector('.puzzle-input').textContent console.log( 'Day10/first:', first(input) ) console.log( 'Day10/second:', second(input) ) function first (input) { return Array(40).fill().reduce(lookAndSay, input).length } function second (input) { return Array(50).fill().reduce(lookAndSay, input).length } function lookAndSay (input) { let ex = /(\d)\1*/g return input.match(ex).map(el => el.length + el[0]).join('') } }())
Fix typo on console message
Fix typo on console message
JavaScript
mit
stefanmaric/scripts,stefanmaric/scripts
--- +++ @@ -6,12 +6,12 @@ let input = document.querySelector('.puzzle-input').textContent console.log( - 'Day09/first:', + 'Day10/first:', first(input) ) console.log( - 'Day09/second:', + 'Day10/second:', second(input) )
3f425c1e15751fd8ea7d857b417a2932208b4366
client/app/modules/sandbox/controllers/sandbox.forms.ctrl.js
client/app/modules/sandbox/controllers/sandbox.forms.ctrl.js
'use strict'; angular.module('com.module.sandbox') .controller('SandboxFormsCtrl', function ($scope, CoreService) { var now = new Date(); $scope.formOptions = {}; $scope.formData = { name: null, description: null, startDate: now, startTime: now, endDate: now, endTime: now }; $scope.formFields = [{ key: 'name', type: 'input', templateOptions: { label: 'Name' } }, { key: 'description', type: 'textarea', templateOptions: { label: 'Description' } }, { key: 'startDate', type: 'datepicker', templateOptions: { label: 'Start Date' } }, { key: 'startTime', type: 'timepicker', templateOptions: { label: 'Start Time' } }, { key: 'endDate', type: 'datepicker', templateOptions: { label: 'End Date' } }, { key: 'endTime', type: 'timepicker', templateOptions: { label: 'End Time' } }]; $scope.formOptions = {}; $scope.onSubmit = function (data) { CoreService.alertSuccess('Good job!', JSON.stringify(data, null, 2)); }; });
'use strict'; angular.module('com.module.sandbox') .controller('SandboxFormsCtrl', function ($scope, CoreService) { var now = new Date(); $scope.formOptions = {}; $scope.formData = { name: null, description: null, startDate: now, startTime: now, endDate: now, endTime: now }; $scope.formFields = [{ key: 'name', type: 'input', templateOptions: { label: 'Name' } }, { key: 'description', type: 'textarea', templateOptions: { label: 'Description' } }, { key: 'startDate', type: 'datepicker', templateOptions: { label: 'Start Date' } }, { key: 'startTime', type: 'timepicker', templateOptions: { label: 'Start Time' } }, { key: 'endDate', type: 'datepicker', templateOptions: { label: 'End Date' } }, { key: 'endTime', type: 'timepicker', templateOptions: { label: 'End Time' } }]; $scope.onSubmit = function (data) { CoreService.alertSuccess('Good job!', JSON.stringify(data, null, 2)); }; });
Remove obsolete object from scope
Remove obsolete object from scope
JavaScript
mit
TNick/loopback-angular-admin,igormusic/referenceData,gxr1028/loopback-angular-admin,shalkam/loopback-angular-admin,igormusic/referenceData,colmena/colmena,jingood2/loopbackadmin,Jeff-Lewis/loopback-angular-admin,colmena/colmena-cms,telemed-duth/eclinpro,senorcris/loopback-angular-admin,colmena/colmena-cms,shalkam/loopback-angular-admin,ktersius/loopback-angular-admin,colmena/colmena-cms,dawao/loopback-angular-admin,edagarli/loopback-angular-admin,petergi/loopback-angular-admin,senorcris/loopback-angular-admin,colmena/colmena,telemed-duth/eclinpro,petergi/loopback-angular-admin,movibe/loopback-angular-admin,gxr1028/loopback-angular-admin,movibe/loopback-angular-admin,telemed-duth/eclinpro,edagarli/loopback-angular-admin,jingood2/loopbackadmin,Jeff-Lewis/loopback-angular-admin,beeman/loopback-angular-admin,beeman/loopback-angular-admin,silverbux/loopback-angular-admin,silverbux/loopback-angular-admin,colmena/colmena,TNick/loopback-angular-admin,burstsms/loopback-angular-admin,burstsms/loopback-angular-admin,dawao/loopback-angular-admin,beeman/loopback-angular-admin,ktersius/loopback-angular-admin
--- +++ @@ -53,8 +53,6 @@ } }]; - $scope.formOptions = {}; - $scope.onSubmit = function (data) { CoreService.alertSuccess('Good job!', JSON.stringify(data, null, 2)); };
f05b9ad8b3c8f7bb201fccbbb0267c01e7eabbbf
lib/game-engine.js
lib/game-engine.js
'use strict'; const Game = require('./game'); // todo: this class got refactored away to almost nothing. does it still have value? // hmm, yes, since we are decorating it class GameEngine { constructor(repositorySet, commandHandlers) { this._repositorySet = repositorySet; this._handlers = commandHandlers; } createGame() { return new Game(this._repositorySet, this._handlers); } } module.exports = GameEngine;
'use strict'; const Game = require('./game-state'); // todo: this class got refactored away to almost nothing. does it still have value? // hmm, yes, since we are decorating it class GameEngine { constructor(repositorySet, commandHandlers) { this._repositorySet = repositorySet; this._handlers = commandHandlers; } createGame() { return new Game(this._repositorySet, this._handlers); } } module.exports = GameEngine;
Fix module name in require after rename
Fix module name in require after rename
JavaScript
mit
dshaneg/text-adventure,dshaneg/text-adventure
--- +++ @@ -1,6 +1,6 @@ 'use strict'; -const Game = require('./game'); +const Game = require('./game-state'); // todo: this class got refactored away to almost nothing. does it still have value? // hmm, yes, since we are decorating it
5240db9f7366808a612e6ad722b16e63ba23baa6
package.js
package.js
Package.describe({ name: '255kb:cordova-disable-select', version: '1.0.2', summary: 'Disables user selection and iOS magnifying glass / longpress menu in Cordova applications.', git: 'https://github.com/255kb/cordova-disable-select', documentation: 'README.md' }); Package.onUse(function(api) { api.versionsFrom('1.2'); Cordova.depends({ 'cordova-plugin-ios-longpress-fix': '1.1.0' }); api.addFiles(['client/cordova-disable-select.css'], 'client'); });
Package.describe({ name: '255kb:cordova-disable-select', version: '1.0.2', summary: 'Disables user selection and iOS magnifying glass / longpress menu in Cordova applications.', git: 'https://github.com/255kb/cordova-disable-select', documentation: 'README.md' }); Package.onUse(function(api) { api.versionsFrom('1.2'); Cordova.depends({ 'cordova-plugin-ios-longpress-fix': '1.1.0' }); api.addFiles(['client/cordova-disable-select.css'], 'web.cordova'); });
Add css file as 'web.cordova' is more accurate.
Add css file as 'web.cordova' is more accurate. If application is browser and cordova in the same time, it will have impact on browser.
JavaScript
mit
255kb/cordova-disable-select
--- +++ @@ -13,5 +13,5 @@ 'cordova-plugin-ios-longpress-fix': '1.1.0' }); - api.addFiles(['client/cordova-disable-select.css'], 'client'); + api.addFiles(['client/cordova-disable-select.css'], 'web.cordova'); });
775ca23e5d251e27012b9ddb43843840958deae2
distributionviewer/core/static/js/app/components/views/logout-button.js
distributionviewer/core/static/js/app/components/views/logout-button.js
import React from 'react'; export default function LogoutButton(props) { return ( <div className="sign-out-wrapper"> <span>{props.email}</span> <span className="button" onClick={props.signOut}>Sign Out</span> </div> ); } LogoutButton.propTypes = { email: React.PropTypes.string.isRequired, signOut: React.PropTypes.string.isRequired, };
import React from 'react'; export default function LogoutButton(props) { return ( <div className="sign-out-wrapper"> <span>{props.email}</span> <span className="button" onClick={props.signOut}>Sign Out</span> </div> ); } LogoutButton.propTypes = { email: React.PropTypes.string.isRequired, signOut: React.PropTypes.func.isRequired, };
Fix logout button prop type warning
Fix logout button prop type warning
JavaScript
mpl-2.0
openjck/distribution-viewer,openjck/distribution-viewer,openjck/distribution-viewer,openjck/distribution-viewer
--- +++ @@ -12,5 +12,5 @@ LogoutButton.propTypes = { email: React.PropTypes.string.isRequired, - signOut: React.PropTypes.string.isRequired, + signOut: React.PropTypes.func.isRequired, };
088438040d865c219cd602cc59bfb66d2b6f2486
scripts/pre-publish.js
scripts/pre-publish.js
const { join } = require('path') const { writeFile } = require('fs').promises const { default: players } = require('../lib/players') const generateSinglePlayers = async () => { for (const { key, name } of players) { const file = ` const { createReactPlayer } = require('./lib/ReactPlayer') const Player = require('./lib/players/${name}').default module.exports = createReactPlayer([Player]) ` await writeFile(join('.', `${key}.js`), file) } } generateSinglePlayers()
const { join } = require('path') const { writeFile } = require('fs').promises const { default: players } = require('../lib/players') const generateSinglePlayers = async () => { for (const { key, name } of players) { const file = ` const createReactPlayer = require('./lib/ReactPlayer').createReactPlayer const Player = require('./lib/players/${name}').default module.exports = createReactPlayer([Player]) ` await writeFile(join('.', `${key}.js`), file) } } generateSinglePlayers()
Fix single player imports on IE11
Fix single player imports on IE11 Fixes https://github.com/CookPete/react-player/issues/954
JavaScript
mit
CookPete/react-player,CookPete/react-player
--- +++ @@ -5,7 +5,7 @@ const generateSinglePlayers = async () => { for (const { key, name } of players) { const file = ` - const { createReactPlayer } = require('./lib/ReactPlayer') + const createReactPlayer = require('./lib/ReactPlayer').createReactPlayer const Player = require('./lib/players/${name}').default module.exports = createReactPlayer([Player]) `
af31fac9ce0fcc39d6d8e079cc9c534261c2d455
wherehows-web/tests/integration/components/datasets/containers/dataset-acl-access-test.js
wherehows-web/tests/integration/components/datasets/containers/dataset-acl-access-test.js
import { moduleForComponent, skip } from 'ember-qunit'; import hbs from 'htmlbars-inline-precompile'; import notificationsStub from 'wherehows-web/tests/stubs/services/notifications'; import userStub from 'wherehows-web/tests/stubs/services/current-user'; import sinon from 'sinon'; moduleForComponent( 'datasets/containers/dataset-acl-access', 'Integration | Component | datasets/containers/dataset acl access', { integration: true, beforeEach() { this.register('service:current-user', userStub); this.register('service:notifications', notificationsStub); this.inject.service('current-user'); this.inject.service('notifications'); this.server = sinon.createFakeServer(); this.server.respondImmediately = true; }, afterEach() { this.server.restore(); } } ); // Skipping, due to investigate test failure in future PR skip('it renders', function(assert) { this.server.respondWith('GET', /\/api\/v2\/datasets.*/, [ 200, { 'Content-Type': 'application/json' }, JSON.stringify({}) ]); this.render(hbs`{{datasets/containers/dataset-acl-access}}`); assert.equal( this.$() .text() .trim(), 'JIT ACL is not currently available for this dataset platform' ); });
import { moduleForComponent, test } from 'ember-qunit'; import hbs from 'htmlbars-inline-precompile'; import notificationsStub from 'wherehows-web/tests/stubs/services/notifications'; import userStub from 'wherehows-web/tests/stubs/services/current-user'; import sinon from 'sinon'; moduleForComponent( 'datasets/containers/dataset-acl-access', 'Integration | Component | datasets/containers/dataset acl access', { integration: true, beforeEach() { this.register('service:current-user', userStub); this.register('service:notifications', notificationsStub); this.inject.service('current-user'); this.inject.service('notifications'); this.server = sinon.createFakeServer(); this.server.respondImmediately = true; }, afterEach() { this.server.restore(); } } ); test('it renders', function(assert) { this.server.respondWith('GET', /\/api\/v2\/datasets.*/, [ 200, { 'Content-Type': 'application/json' }, JSON.stringify({}) ]); this.render(hbs`{{datasets/containers/dataset-acl-access}}`); assert.equal( this.$() .text() .trim(), 'JIT ACL is not currently available for this dataset platform' ); });
Undo skip test after fix
Undo skip test after fix
JavaScript
apache-2.0
mars-lan/WhereHows,linkedin/WhereHows,linkedin/WhereHows,camelliazhang/WhereHows,mars-lan/WhereHows,camelliazhang/WhereHows,camelliazhang/WhereHows,camelliazhang/WhereHows,alyiwang/WhereHows,theseyi/WhereHows,linkedin/WhereHows,mars-lan/WhereHows,theseyi/WhereHows,alyiwang/WhereHows,theseyi/WhereHows,camelliazhang/WhereHows,linkedin/WhereHows,linkedin/WhereHows,linkedin/WhereHows,alyiwang/WhereHows,theseyi/WhereHows,mars-lan/WhereHows,theseyi/WhereHows,alyiwang/WhereHows,alyiwang/WhereHows,theseyi/WhereHows,mars-lan/WhereHows,alyiwang/WhereHows,camelliazhang/WhereHows,mars-lan/WhereHows
--- +++ @@ -1,4 +1,4 @@ -import { moduleForComponent, skip } from 'ember-qunit'; +import { moduleForComponent, test } from 'ember-qunit'; import hbs from 'htmlbars-inline-precompile'; import notificationsStub from 'wherehows-web/tests/stubs/services/notifications'; import userStub from 'wherehows-web/tests/stubs/services/current-user'; @@ -26,8 +26,8 @@ } } ); -// Skipping, due to investigate test failure in future PR -skip('it renders', function(assert) { + +test('it renders', function(assert) { this.server.respondWith('GET', /\/api\/v2\/datasets.*/, [ 200, { 'Content-Type': 'application/json' },
b463c1709faf3da73b907dc842d83aa2709a1e77
app/services/redux.js
app/services/redux.js
import Ember from 'ember'; import redux from 'npm:redux'; import reducers from '../reducers/index'; import enhancers from '../enhancers/index'; import optional from '../reducers/optional'; import middlewareConfig from '../middleware/index'; const { assert, isArray } = Ember; // Util for handling the case where no setup thunk was created in middleware const noOp = () => {}; // Handle "classic" middleware exports (i.e. an array), as well as the hash option const extractMiddlewareConfig = (mc) => { assert( 'Middleware must either be an array, or a hash containing a `middleware` property', isArray(mc) || mc.middleware ); return isArray(mc) ? { middleware: mc } : mc; } // Destructure the middleware array and the setup thunk into two different variables const { middleware, setup = noOp } = extractMiddlewareConfig(middlewareConfig); var { createStore, applyMiddleware, combineReducers, compose } = redux; var createStoreWithMiddleware = compose(applyMiddleware(...middleware), enhancers)(createStore); export default Ember.Service.extend({ init() { this.store = createStoreWithMiddleware(optional(combineReducers(reducers))); setup(this.store); this._super(...arguments); }, getState() { return this.store.getState(); }, dispatch(action) { return this.store.dispatch(action); }, subscribe(func) { return this.store.subscribe(func); } });
import Ember from 'ember'; import redux from 'npm:redux'; import reducers from '../reducers/index'; import enhancers from '../enhancers/index'; import optional from '../reducers/optional'; import middlewareConfig from '../middleware/index'; const { assert, isArray, K } = Ember; // Handle "classic" middleware exports (i.e. an array), as well as the hash option const extractMiddlewareConfig = (mc) => { assert( 'Middleware must either be an array, or a hash containing a `middleware` property', isArray(mc) || mc.middleware ); return isArray(mc) ? { middleware: mc } : mc; } // Destructure the middleware array and the setup thunk into two different variables const { middleware, setup = K } = extractMiddlewareConfig(middlewareConfig); var { createStore, applyMiddleware, combineReducers, compose } = redux; var createStoreWithMiddleware = compose(applyMiddleware(...middleware), enhancers)(createStore); export default Ember.Service.extend({ init() { this.store = createStoreWithMiddleware(optional(combineReducers(reducers))); setup(this.store); this._super(...arguments); }, getState() { return this.store.getState(); }, dispatch(action) { return this.store.dispatch(action); }, subscribe(func) { return this.store.subscribe(func); } });
Use Ember.K instead of noOp
Use Ember.K instead of noOp
JavaScript
mit
ember-redux/ember-redux,dustinfarris/ember-redux,dustinfarris/ember-redux,toranb/ember-redux,toranb/ember-redux,ember-redux/ember-redux
--- +++ @@ -5,10 +5,7 @@ import optional from '../reducers/optional'; import middlewareConfig from '../middleware/index'; -const { assert, isArray } = Ember; - -// Util for handling the case where no setup thunk was created in middleware -const noOp = () => {}; +const { assert, isArray, K } = Ember; // Handle "classic" middleware exports (i.e. an array), as well as the hash option const extractMiddlewareConfig = (mc) => { @@ -20,7 +17,7 @@ } // Destructure the middleware array and the setup thunk into two different variables -const { middleware, setup = noOp } = extractMiddlewareConfig(middlewareConfig); +const { middleware, setup = K } = extractMiddlewareConfig(middlewareConfig); var { createStore, applyMiddleware, combineReducers, compose } = redux; var createStoreWithMiddleware = compose(applyMiddleware(...middleware), enhancers)(createStore);
78e163a1867cc996a47213fcef248b288793c3cd
src/music-collection/groupSongsIntoCategories.js
src/music-collection/groupSongsIntoCategories.js
import _ from 'lodash' const grouping = [ { title: 'Custom Song', criteria: song => song.custom }, { title: 'Tutorial', criteria: song => song.tutorial }, { title: 'Unreleased', criteria: song => song.unreleased }, { title: 'New Songs', criteria: song => song.added && Date.now() - Date.parse(song.added) < 14 * 86400000, sort: song => song.added, reverse: true }, { title: '☆', criteria: () => true } ] export function groupSongsIntoCategories (songs) { let groups = grouping.map(group => ({ input: group, output: { title: group.title, songs: [] } })) for (let song of songs) { for (let { input, output } of groups) { if (input.criteria(song)) { output.songs.push(song) break } } } for (let { input, output } of groups) { if (input.sort) output.songs = _.sortBy(output.songs, input.sort) if (input.reverse) output.songs.reverse() } return _(groups) .map('output') .filter(group => group.songs.length > 0) .value() } export default groupSongsIntoCategories
import _ from 'lodash' const grouping = [ { title: 'Custom Song', criteria: song => song.custom }, { title: 'Tutorial', criteria: song => song.tutorial }, { title: 'Unreleased', criteria: song => song.unreleased }, { title: 'New Songs', criteria: song => song.added && Date.now() - Date.parse(song.added) < 60 * 86400000, sort: song => song.added, reverse: true }, { title: '☆', criteria: () => true } ] export function groupSongsIntoCategories (songs) { let groups = grouping.map(group => ({ input: group, output: { title: group.title, songs: [] } })) for (let song of songs) { for (let { input, output } of groups) { if (input.criteria(song)) { output.songs.push(song) break } } } for (let { input, output } of groups) { if (input.sort) output.songs = _.sortBy(output.songs, input.sort) if (input.reverse) output.songs.reverse() } return _(groups) .map('output') .filter(group => group.songs.length > 0) .value() } export default groupSongsIntoCategories
Put songs as new for 2 months
:wrench: Put songs as new for 2 months
JavaScript
agpl-3.0
bemusic/bemuse,bemusic/bemuse,bemusic/bemuse,bemusic/bemuse,bemusic/bemuse
--- +++ @@ -7,7 +7,7 @@ { title: 'New Songs', criteria: song => - song.added && Date.now() - Date.parse(song.added) < 14 * 86400000, + song.added && Date.now() - Date.parse(song.added) < 60 * 86400000, sort: song => song.added, reverse: true },
bc19de3950abae46adf992dfa77ee890e8ed6aa9
src/DELETE/sanitizeArguments/index.js
src/DELETE/sanitizeArguments/index.js
const is = require('is'); const url = require('url'); /** * Returns an object containing the required properties to make an * http request. * @module DELETE/sanitizeArguments * @param {array} a - Arguments * @return {object} args - "Sanitized" arguments */ module.exports = function sanitizeArguments(a = []) { const args = {}; // The first argument can either be an url string or an options object if (is.string(a[0])) args.url = a[0]; else if (is.object(a[0])) args.options = a[0]; // Lets always use an request options object if (!args.options) args.options = {}; if (args.url) { const urlObj = url.parse(args.url); args.options.hostname = urlObj.hostname; args.options.port = urlObj.port; args.options.path = urlObj.path; args.options.method = 'DELETE'; if (args.url.indexOf('https') !== -1) args.options.protocol = 'https:'; else args.options.protocol = 'http:'; } // Is there a callback? if (is.function(a[1])) args.cb = a[1]; return args; };
const is = require('is'); const url = require('url'); /** * Returns an object containing the required properties to make an * http request. * @module DELETE/sanitizeArguments * @param {array} a - Arguments * @return {object} args - "Sanitized" arguments */ module.exports = function sanitizeArguments(a = []) { const args = {}; // The first argument can either be an url string or an options object if (is.string(a[0])) args.url = a[0]; else if (is.object(a[0])) args.options = a[0]; // Lets always use an request options object if (!args.options) args.options = {}; // Fill request object with data from url (if set) if (args.url) { const urlObj = url.parse(args.url); args.options.hostname = urlObj.hostname; args.options.port = urlObj.port; args.options.path = urlObj.path; args.options.method = 'DELETE'; if (args.url.indexOf('https') !== -1) args.options.protocol = 'https:'; else args.options.protocol = 'http:'; } // Is there a callback? if (is.function(a[1])) args.cb = a[1]; return args; };
DELETE correct options object + protocol handling
DELETE correct options object + protocol handling
JavaScript
mit
opensoars/ezreq
--- +++ @@ -16,6 +16,8 @@ // Lets always use an request options object if (!args.options) args.options = {}; + + // Fill request object with data from url (if set) if (args.url) { const urlObj = url.parse(args.url); args.options.hostname = urlObj.hostname;
93fa682de8cd2ed950432c64c32c352579cfa7cd
views/board.js
views/board.js
import React from 'react'; import Invocation from './invocation'; import StatusLine from './status_line'; export default React.createClass({ getInitialState() { return {vcsData: { isRepository: true, branch: 'name', status: 'clean' }}; }, componentWillMount() { this.props.terminal .on('invocation', this.forceUpdate.bind(this)) .on('vcs-data', (data) => { this.setState({vcsData: data}) }); }, handleKeyDown(event) { // Ctrl+l if (event.ctrlKey && event.keyCode === 76) { this.props.terminal.clearInvocations(); event.stopPropagation(); event.preventDefault(); } }, render() { var invocations = this.props.terminal.invocations.map((invocation) => { return ( <Invocation key={invocation.id} invocation={invocation}/> ) }); return ( <div id="board" onKeyDown={this.handleKeyDown}> <div id="invocations"> {invocations} </div> <StatusLine currentWorkingDirectory={this.props.terminal.currentDirectory} vcsData={this.state.vcsData}/> </div> ); } });
import React from 'react'; import Invocation from './invocation'; import StatusLine from './status_line'; export default React.createClass({ getInitialState() { return {vcsData: { isRepository: true, branch: 'name', status: 'clean' }}; }, componentWillMount() { this.props.terminal .on('invocation', this.forceUpdate.bind(this)) .on('vcs-data', (data) => { this.setState({vcsData: data}) }); }, handleKeyDown(event) { // Ctrl+L. if (event.ctrlKey && event.keyCode === 76) { this.props.terminal.clearInvocations(); event.stopPropagation(); event.preventDefault(); } // Cmd+D. if (event.metaKey && event.keyCode === 68) { window.DEBUG = !window.DEBUG; event.stopPropagation(); event.preventDefault(); this.forceUpdate(); console.log(`Debugging mode has been ${window.DEBUG ? 'enabled' : 'disabled'}.`); } }, render() { var invocations = this.props.terminal.invocations.map((invocation) => { return ( <Invocation key={invocation.id} invocation={invocation}/> ) }); return ( <div id="board" onKeyDown={this.handleKeyDown}> <div id="invocations"> {invocations} </div> <StatusLine currentWorkingDirectory={this.props.terminal.currentDirectory} vcsData={this.state.vcsData}/> </div> ); } });
Add a shortcut to toggle debug mode.
Add a shortcut to toggle debug mode.
JavaScript
mit
Young55555/black-screen,rocky-jaiswal/black-screen,over300laughs/black-screen,rocky-jaiswal/black-screen,smaty1/black-screen,drew-gross/black-screen,noikiy/black-screen,toxic88/black-screen,AnalogRez/black-screen,RyanTech/black-screen,alessandrostone/black-screen,mzgnr/black-screen,jbhannah/black-screen,jassyboy/black-screen,jbhannah/black-screen,N00D13/black-screen,shockone/black-screen,Thundabrow/black-screen,Ribeiro/black-screen,gastrodia/black-screen,rob3ns/black-screen,smaty1/black-screen,gastrodia/black-screen,RyanTech/black-screen,gabrielbellamy/black-screen,jonadev95/black-screen,AnalogRez/black-screen,Cavitt/black-screen,habibmasuro/black-screen,bestwpw/black-screen,Thundabrow/black-screen,JimLiu/black-screen,AnalogRez/black-screen,skomski/black-screen,kustomzone/black-screen,littlecodeshop/black-screen,rakesh-mohanta/black-screen,Thundabrow/black-screen,habibmasuro/black-screen,toxic88/black-screen,Cavitt/black-screen,bodiam/black-screen,jacobmarshall/black-screen,w9jds/black-screen,rob3ns/black-screen,genecyber/black-screen,railsware/upterm,alice-gh/black-screen-1,bodiam/black-screen,noikiy/black-screen,taraszerebecki/black-screen,kingland/black-screen,vshatskyi/black-screen,genecyber/black-screen,over300laughs/black-screen,Serg09/black-screen,w9jds/black-screen,stefohnee/black-screen,bodiam/black-screen,Dangku/black-screen,over300laughs/black-screen,kaze13/black-screen,Serg09/black-screen,littlecodeshop/black-screen,jassyboy/black-screen,bestwpw/black-screen,jqk6/black-screen,Suninus/black-screen,adamliesko/black-screen,kingland/black-screen,smaty1/black-screen,alessandrostone/black-screen,vshatskyi/black-screen,gabrielbellamy/black-screen,vshatskyi/black-screen,Dangku/black-screen,stefohnee/black-screen,geksilla/black-screen,ammaroff/black-screen,black-screen/black-screen,kingland/black-screen,geksilla/black-screen,geksilla/black-screen,jacobmarshall/black-screen,Serg09/black-screen,Dangku/black-screen,jonadev95/black-screen,kustomzone/black-screen,kustomzone/black-screen,adamliesko/black-screen,toxic88/black-screen,j-allard/black-screen,Young55555/black-screen,noikiy/black-screen,kaze13/black-screen,williara/black-screen,alessandrostone/black-screen,jonadev95/black-screen,ammaroff/black-screen,skomski/black-screen,jqk6/black-screen,stefohnee/black-screen,drew-gross/black-screen,N00D13/black-screen,drew-gross/black-screen,williara/black-screen,rakesh-mohanta/black-screen,drew-gross/black-screen,genecyber/black-screen,gastrodia/black-screen,cyrixhero/black-screen,railsware/upterm,alice-gh/black-screen-1,Young55555/black-screen,jqk6/black-screen,jacobmarshall/black-screen,bestwpw/black-screen,rocky-jaiswal/black-screen,shockone/black-screen,ammaroff/black-screen,w9jds/black-screen,williara/black-screen,rob3ns/black-screen,mzgnr/black-screen,habibmasuro/black-screen,Cavitt/black-screen,Suninus/black-screen,jbhannah/black-screen,JimLiu/black-screen,cyrixhero/black-screen,cyrixhero/black-screen,rakesh-mohanta/black-screen,taraszerebecki/black-screen,Suninus/black-screen,black-screen/black-screen,RyanTech/black-screen,jassyboy/black-screen,Ribeiro/black-screen,black-screen/black-screen,JimLiu/black-screen,vshatskyi/black-screen,N00D13/black-screen,gabrielbellamy/black-screen,taraszerebecki/black-screen,adamliesko/black-screen,littlecodeshop/black-screen,alice-gh/black-screen-1,skomski/black-screen,kaze13/black-screen,Ribeiro/black-screen,j-allard/black-screen,j-allard/black-screen,mzgnr/black-screen
--- +++ @@ -16,12 +16,22 @@ .on('vcs-data', (data) => { this.setState({vcsData: data}) }); }, handleKeyDown(event) { - // Ctrl+l + // Ctrl+L. if (event.ctrlKey && event.keyCode === 76) { this.props.terminal.clearInvocations(); event.stopPropagation(); event.preventDefault(); + } + + // Cmd+D. + if (event.metaKey && event.keyCode === 68) { + window.DEBUG = !window.DEBUG; + + event.stopPropagation(); + event.preventDefault(); + this.forceUpdate(); + console.log(`Debugging mode has been ${window.DEBUG ? 'enabled' : 'disabled'}.`); } }, render() {
74eed05c7175e7fe96d54286f7feaaf68fcc3085
addon/services/ember-ambitious-forms.js
addon/services/ember-ambitious-forms.js
import Ember from 'ember' import AFField, { DEFAULT_CONFIG as FIELD_DEFAULT_CONFIG } from '../components/af-field' import i18n from '../mixins/i18n' import loc from '../mixins/loc' import restless from '../mixins/restless' import validations from '../mixins/validations' const AF_FIELD_MIXINS = { i18n, loc, restless, validations } export default Ember.Service.extend({ config: Object.assign({}, FIELD_DEFAULT_CONFIG, { prompt: 'Select', fieldPlugins: [] }), configure (arg) { if (typeof arg === 'function') { arg(this.config) } else { Ember.$.extend(true, this.config, arg) } // TODO: localize plugin logic instead of tossing them onto the base class this.config.fieldPlugins.forEach((plugin) => { if (plugin instanceof Ember.Mixin) { AFField.reopen(plugin) } else if (AF_FIELD_MIXINS[plugin]) { AFField.reopen(AF_FIELD_MIXINS[plugin]) } else { Ember.warn(`Not a valid plugin: ${plugin}`) } }) return this } })
import Ember from 'ember' import { DEFAULT_CONFIG as FIELD_DEFAULT_CONFIG } from '../components/af-field' import i18n from '../mixins/i18n' import loc from '../mixins/loc' import restless from '../mixins/restless' import validations from '../mixins/validations' const AF_FIELD_MIXINS = { i18n, loc, restless, validations } export default Ember.Service.extend({ config: Object.assign({}, FIELD_DEFAULT_CONFIG, { prompt: 'Select', fieldPlugins: [] }), configure (arg) { if (typeof arg === 'function') { arg(this.config) } else { Ember.$.extend(true, this.config, arg) } let afFieldClass = Ember.getOwner(this).resolveRegistration('component:af-field') this.config.fieldPlugins.forEach((plugin) => { if (plugin instanceof Ember.Mixin) { afFieldClass.reopen(plugin) } else if (AF_FIELD_MIXINS[plugin]) { afFieldClass.reopen(AF_FIELD_MIXINS[plugin]) } else { Ember.warn(`Not a valid plugin: ${plugin}`) } }) return this } })
Load addons into resolver AFField instead of global AFField
Load addons into resolver AFField instead of global AFField
JavaScript
mit
dough-com/ember-ambitious-forms,dough-com/ember-ambitious-forms
--- +++ @@ -1,6 +1,6 @@ import Ember from 'ember' -import AFField, { DEFAULT_CONFIG as FIELD_DEFAULT_CONFIG } from '../components/af-field' +import { DEFAULT_CONFIG as FIELD_DEFAULT_CONFIG } from '../components/af-field' import i18n from '../mixins/i18n' import loc from '../mixins/loc' @@ -21,12 +21,12 @@ Ember.$.extend(true, this.config, arg) } - // TODO: localize plugin logic instead of tossing them onto the base class + let afFieldClass = Ember.getOwner(this).resolveRegistration('component:af-field') this.config.fieldPlugins.forEach((plugin) => { if (plugin instanceof Ember.Mixin) { - AFField.reopen(plugin) + afFieldClass.reopen(plugin) } else if (AF_FIELD_MIXINS[plugin]) { - AFField.reopen(AF_FIELD_MIXINS[plugin]) + afFieldClass.reopen(AF_FIELD_MIXINS[plugin]) } else { Ember.warn(`Not a valid plugin: ${plugin}`) }
11c687b1d5bb1eb5a09c7efb6086ee6d3f536d0e
tests/test-files/preserve-simple-binary-expressions/input.js
tests/test-files/preserve-simple-binary-expressions/input.js
a * b; 10*5; 10 * 5; 10e5*5; 10 * (5 + 10); 10*(5 + 10);
a * b; a*b; 10*5; 10 * 5; 10e5*5; 10 * (5 + 10); 10*(5 + 10);
Add test for two variables being multiplied who lack a space in between.
Add test for two variables being multiplied who lack a space in between.
JavaScript
mit
Mark-Simulacrum/attractifier,Mark-Simulacrum/pretty-generator
--- +++ @@ -1,4 +1,5 @@ a * b; +a*b; 10*5; 10 * 5; 10e5*5;
29de57f99e6946e6db7257d650b860eaf2f58a7d
app/assets/javascripts/carnival/advanced_search.js
app/assets/javascripts/carnival/advanced_search.js
$(document).ready(function(){ $("#advanced_search_toggler").click(function(e){ $('body').append('<div class="as-form-overlay">') $("#advanced_search_toggler").toggleClass('is-opened') $("#advanced_search_form").toggle(); $(".as-form-overlay").click(function(e){ $(".as-form-overlay").remove(); $("#advanced_search_form").hide(); $(".select2-drop").hide(); return false; }); return false; }); $("#search_button").click(function(e){ e.preventDefault(); var queryParams = []; Carnival.submitIndexForm(); }); $("#clear_button").click(function(e){ e.preventDefault(); $($(this).parent().parent().parent()).trigger("reset") $("#advanced_search_form input").each(function(){ var inputValue = $(this).val(); $(this).val(''); }); $("#advanced_search_form select").each(function(){ var inputValue = $(this).val(); $(this).val(''); }); Carnival.submitIndexForm(); }); });
$(document).ready(function(){ $("#advanced_search_toggler").click(function(e){ $('body').append('<div class="as-form-overlay">') $("#advanced_search_toggler").toggleClass('is-opened') $("#advanced_search_form").toggle(); $('#advanced_search_form').find('input').focus(); $(".as-form-overlay").click(function(e){ $(".as-form-overlay").remove(); $("#advanced_search_form").hide(); $(".select2-drop").hide(); return false; }); return false; }); $("#search_button").click(function(e){ e.preventDefault(); var queryParams = []; Carnival.submitIndexForm(); }); $("#clear_button").click(function(e){ e.preventDefault(); $($(this).parent().parent().parent()).trigger("reset") $("#advanced_search_form input").each(function(){ var inputValue = $(this).val(); $(this).val(''); }); $("#advanced_search_form select").each(function(){ var inputValue = $(this).val(); $(this).val(''); }); Carnival.submitIndexForm(); }); });
Set focus on the first advanced search field
Set focus on the first advanced search field
JavaScript
mit
cartolari/carnival,dsakuma/carnival,dsakuma/carnival,Vizir/carnival,dsakuma/carnival,cartolari/carnival,dsakuma/carnival,Vizir/carnival,cartolari/carnival,Vizir/carnival,cartolari/carnival,Vizir/carnival,cartolari/carnival,Vizir/carnival,dsakuma/carnival
--- +++ @@ -3,6 +3,8 @@ $('body').append('<div class="as-form-overlay">') $("#advanced_search_toggler").toggleClass('is-opened') $("#advanced_search_form").toggle(); + $('#advanced_search_form').find('input').focus(); + $(".as-form-overlay").click(function(e){ $(".as-form-overlay").remove(); $("#advanced_search_form").hide();
bebd287f6a3552fcd0eabfa28afd522da32a6478
etc/protractorConfSauce.js
etc/protractorConfSauce.js
var pr = process.env.TRAVIS_PULL_REQUEST; var souceUser = process.env.SAUCE_USERNAME || "liqd"; var sauceKey = process.env.SAUCE_ACCESS_KEY; var name = ((pr === "false") ? "" : "#" + pr + " ") + process.env.TRAVIS_COMMIT; var common = require("./protractorCommon.js"); var local = { sauceUser: souceUser, sauceKey: sauceKey, capabilities: { "browserName": "chrome", "tunnel-identifier": process.env.TRAVIS_JOB_NUMBER, "build": process.env.TRAVIS_BUILD_NUMBER, "name": name }, allScriptsTimeout: 21000, getPageTimeout: 20000, jasmineNodeOpts: { showColors: true, defaultTimeoutInterval: 120000, isVerbose: true, includeStackTrace: true } }; exports.config = Object.assign({}, common.config, local);
var pr = process.env.TRAVIS_PULL_REQUEST; var souceUser = process.env.SAUCE_USERNAME || "liqd"; var sauceKey = process.env.SAUCE_ACCESS_KEY; var name = ((pr === "false") ? "" : "#" + pr + " ") + process.env.TRAVIS_COMMIT; var common = require("./protractorCommon.js"); var local = { sauceUser: souceUser, sauceKey: sauceKey, directConnect: false, capabilities: { "browserName": "chrome", "tunnel-identifier": process.env.TRAVIS_JOB_NUMBER, "build": process.env.TRAVIS_BUILD_NUMBER, "name": name }, allScriptsTimeout: 21000, getPageTimeout: 20000, jasmineNodeOpts: { showColors: true, defaultTimeoutInterval: 120000, isVerbose: true, includeStackTrace: true } }; exports.config = Object.assign({}, common.config, local);
Disable direct connect for sauce labs
Disable direct connect for sauce labs
JavaScript
agpl-3.0
liqd/adhocracy3.mercator,liqd/adhocracy3.mercator,liqd/adhocracy3.mercator,liqd/adhocracy3.mercator,liqd/adhocracy3.mercator,liqd/adhocracy3.mercator,liqd/adhocracy3.mercator
--- +++ @@ -8,6 +8,7 @@ var local = { sauceUser: souceUser, sauceKey: sauceKey, + directConnect: false, capabilities: { "browserName": "chrome",
d718fa64b1b3ab4fc0aa9c678faf15477a205dce
app/assets/javascripts/views/components/Editor/fields/virtualKeyboard.js
app/assets/javascripts/views/components/Editor/fields/virtualKeyboard.js
import React, {Component, PropTypes} from 'react'; import t from 'tcomb-form'; function renderInput(locals) { const onChange = function (event) { locals.onChange(event.target.value); }; const triggerRealInputChange = function (event) { locals.onChange(document.getElementById('virtual-keyboard-helper-' + locals.attrs.name).value); }; return <div> <input type="text" label={locals.label} name={locals.attrs.name} value={locals.value} onChange={onChange} style={{display: 'none'}} /> <input type="text" id={'virtual-keyboard-helper-' + locals.attrs.name} className="form-control" label={locals.label} onBlur={triggerRealInputChange} /> </div>; } const textboxTemplate = t.form.Form.templates.textbox.clone({ renderInput }) export default class VirtualKeyboardFactory extends t.form.Textbox { getTemplate() { return textboxTemplate } }
import React, {Component, PropTypes} from 'react'; import t from 'tcomb-form'; function renderInput(locals) { const onChange = function (event) { locals.onChange(event.target.value); }; const triggerRealInputChange = function (event) { locals.onChange(document.getElementById('virtual-keyboard-helper-' + locals.attrs.name).value); }; return <div> <input type="text" label={locals.label} name={locals.attrs.name} value={locals.value} onChange={onChange} style={{display: 'none'}} /> <input type="text" id={'virtual-keyboard-helper-' + locals.attrs.name} value={locals.value} className="form-control" label={locals.label} onBlur={triggerRealInputChange} /> </div>; } const textboxTemplate = t.form.Form.templates.textbox.clone({ renderInput }) export default class VirtualKeyboardFactory extends t.form.Textbox { getTemplate() { return textboxTemplate } }
Fix bug with moving up and down
Fix bug with moving up and down
JavaScript
apache-2.0
First-Peoples-Cultural-Council/fv-web-ui,First-Peoples-Cultural-Council/fv-web-ui,First-Peoples-Cultural-Council/fv-web-ui,First-Peoples-Cultural-Council/fv-web-ui,First-Peoples-Cultural-Council/fv-web-ui
--- +++ @@ -13,7 +13,7 @@ return <div> <input type="text" label={locals.label} name={locals.attrs.name} value={locals.value} onChange={onChange} style={{display: 'none'}} /> - <input type="text" id={'virtual-keyboard-helper-' + locals.attrs.name} className="form-control" label={locals.label} onBlur={triggerRealInputChange} /> + <input type="text" id={'virtual-keyboard-helper-' + locals.attrs.name} value={locals.value} className="form-control" label={locals.label} onBlur={triggerRealInputChange} /> </div>; }
49500617b9ffe668dd4883c9190cac4c1ca15781
indico/htdocs/js/utils/i18n.js
indico/htdocs/js/utils/i18n.js
(function(global) { "use strict"; var default_i18n = new Jed({ locale_data: TRANSLATIONS, domain: "indico" }); global.i18n = default_i18n; global.$T = _.bind(default_i18n.gettext, default_i18n); ['gettext', 'ngettext', 'pgettext', 'npgettext', 'translate'].forEach(function(method_name) { global.$T[method_name] = _.bind(default_i18n[method_name], default_i18n); }); global.$T.domain = _.memoize(function(domain) { return new Jed({ locale_data: TRANSLATIONS, domain: domain }); }); }(window));
(function(global) { "use strict"; var default_i18n = new Jed({ locale_data: global.TRANSLATIONS, domain: "indico" }); global.i18n = default_i18n; global.$T = _.bind(default_i18n.gettext, default_i18n); ['gettext', 'ngettext', 'pgettext', 'npgettext', 'translate'].forEach(function(method_name) { global.$T[method_name] = _.bind(default_i18n[method_name], default_i18n); }); global.$T.domain = _.memoize(function(domain) { return new Jed({ locale_data: global.TRANSLATIONS, domain: domain }); }); }(window));
Make it more obvious that TRANSLATIONS is global
Make it more obvious that TRANSLATIONS is global
JavaScript
mit
ThiefMaster/indico,OmeGak/indico,mvidalgarcia/indico,indico/indico,ThiefMaster/indico,DirkHoffmann/indico,pferreir/indico,DirkHoffmann/indico,mvidalgarcia/indico,ThiefMaster/indico,pferreir/indico,indico/indico,mic4ael/indico,pferreir/indico,mic4ael/indico,mic4ael/indico,DirkHoffmann/indico,OmeGak/indico,mvidalgarcia/indico,pferreir/indico,mic4ael/indico,mvidalgarcia/indico,DirkHoffmann/indico,indico/indico,OmeGak/indico,indico/indico,ThiefMaster/indico,OmeGak/indico
--- +++ @@ -2,7 +2,7 @@ "use strict"; var default_i18n = new Jed({ - locale_data: TRANSLATIONS, + locale_data: global.TRANSLATIONS, domain: "indico" }); @@ -15,7 +15,7 @@ global.$T.domain = _.memoize(function(domain) { return new Jed({ - locale_data: TRANSLATIONS, + locale_data: global.TRANSLATIONS, domain: domain }); });
0939f9e32aa620132b444799f864056a097ead2d
test/e2e/main.js
test/e2e/main.js
'use strict'; describe('Sign up page', function () { var watchButton; beforeEach(function () { watchButton = element('.btn-primary'); }); it('should have Watch/Unwatch disabled by default', function() { expect(watchButton.attr('disabled')).toBeTruthy(); }); it('should enable Watch/Unwatch button', function() { input('#email').enter('banan@fluga.com'); expect(watchButton.attr('disabled')).toBeTruthy(); input('#url').enter('http://github.com'); expect(watchButton.attr('disabled')).toBeFalsy(); }); });
'use strict'; describe('Sign up page', function () { var watchButton; beforeEach(function () { watchButton = element('.btn-primary'); }); it('should have Watch enabled by default', function() { expect(watchButton.attr('disabled')).toBeFalsy(); }); it('should enable Watch/Unwatch button', function() { input('#email').enter('banan@fluga.com'); expect(watchButton.attr('disabled')).toBeTruthy(); input('#url').enter('http://github.com'); expect(watchButton.attr('disabled')).toBeFalsy(); }); });
Update default behavior of Watch button
Update default behavior of Watch button
JavaScript
mit
seriema/npmalerts-web,seriema/npmalerts-web
--- +++ @@ -8,8 +8,8 @@ watchButton = element('.btn-primary'); }); - it('should have Watch/Unwatch disabled by default', function() { - expect(watchButton.attr('disabled')).toBeTruthy(); + it('should have Watch enabled by default', function() { + expect(watchButton.attr('disabled')).toBeFalsy(); }); it('should enable Watch/Unwatch button', function() {
59745c5117613e7822056fe75ceb502ef702853d
example/user/controller.js
example/user/controller.js
var users = require('./user-dump'), Promise = require('bluebird') module.exports = { get : Get, add : Add }; function Get(request,reply) { setTimeout(function() { reply.data = users; reply.continue(); },500); } function Add(request,reply) { setTimeout(function() { users.push({name : request.payload.name,id : (users.length + 1)}); reply.continue(); },500); }
var users = require('./stub'), Promise = require('bluebird') module.exports = { get : Get, add : Add }; function Get(request,reply) { setTimeout(function() { reply.data = users; reply.continue(); },500); } function Add(request,reply) { setTimeout(function() { users.push({name : request.payload.name,id : (users.length + 1)}); reply.continue(); },500); }
Use correct file name for db stub
Use correct file name for db stub
JavaScript
mit
Pranay92/hapi-next
--- +++ @@ -1,4 +1,4 @@ -var users = require('./user-dump'), +var users = require('./stub'), Promise = require('bluebird') module.exports = {
7a7a6905f01aa99f5ff2c75cee165cf691dde8eb
ui/src/shared/components/FancyScrollbar.js
ui/src/shared/components/FancyScrollbar.js
import React, {Component, PropTypes} from 'react' import classnames from 'classnames' import {Scrollbars} from 'react-custom-scrollbars' class FancyScrollbar extends Component { constructor(props) { super(props) } static defaultProps = { autoHide: true, autoHeight: false, } render() { const {autoHide, autoHeight, children, className, maxHeight} = this.props return ( <Scrollbars className={classnames('fancy-scroll--container', { [className]: className, })} autoHide={autoHide} autoHideTimeout={1000} autoHideDuration={250} autoHeight={autoHeight} autoHeightMax={maxHeight} renderTrackHorizontal={props => <div {...props} className="fancy-scroll--track-h" />} renderTrackVertical={props => <div {...props} className="fancy-scroll--track-v" />} renderThumbHorizontal={props => <div {...props} className="fancy-scroll--thumb-h" />} renderThumbVertical={props => <div {...props} className="fancy-scroll--thumb-v" />} renderView={props => <div {...props} className="fancy-scroll--view" />} > {children} </Scrollbars> ) } } const {bool, node, number, string} = PropTypes FancyScrollbar.propTypes = { children: node.isRequired, className: string, autoHide: bool, autoHeight: bool, maxHeight: number, } export default FancyScrollbar
import React, {Component, PropTypes} from 'react' import classnames from 'classnames' import {Scrollbars} from 'react-custom-scrollbars' class FancyScrollbar extends Component { constructor(props) { super(props) } static defaultProps = { autoHide: true, autoHeight: false, } handleMakeDiv = className => props => { return <div {...props} className={`fancy-scroll--${className}`} /> } render() { const {autoHide, autoHeight, children, className, maxHeight} = this.props return ( <Scrollbars className={classnames('fancy-scroll--container', { [className]: className, })} autoHide={autoHide} autoHideTimeout={1000} autoHideDuration={250} autoHeight={autoHeight} autoHeightMax={maxHeight} renderTrackHorizontal={this.handleMakeDiv('track-h')} renderTrackVertical={this.handleMakeDiv('track-v')} renderThumbHorizontal={this.handleMakeDiv('thumb-h')} renderThumbVertical={this.handleMakeDiv('thumb-v')} renderView={this.handleMakeDiv('view')} > {children} </Scrollbars> ) } } const {bool, node, number, string} = PropTypes FancyScrollbar.propTypes = { children: node.isRequired, className: string, autoHide: bool, autoHeight: bool, maxHeight: number, } export default FancyScrollbar
Update FancyScrollBar to use arrow properties
Update FancyScrollBar to use arrow properties
JavaScript
mit
mark-rushakoff/influxdb,nooproblem/influxdb,influxdb/influxdb,influxdb/influxdb,mark-rushakoff/influxdb,influxdata/influxdb,nooproblem/influxdb,mark-rushakoff/influxdb,mark-rushakoff/influxdb,influxdb/influxdb,mark-rushakoff/influxdb,li-ang/influxdb,nooproblem/influxdb,li-ang/influxdb,mark-rushakoff/influxdb,nooproblem/influxdb,influxdb/influxdb,nooproblem/influxdb,influxdb/influxdb,influxdb/influxdb,influxdata/influxdb
--- +++ @@ -10,6 +10,10 @@ static defaultProps = { autoHide: true, autoHeight: false, + } + + handleMakeDiv = className => props => { + return <div {...props} className={`fancy-scroll--${className}`} /> } render() { @@ -25,15 +29,11 @@ autoHideDuration={250} autoHeight={autoHeight} autoHeightMax={maxHeight} - renderTrackHorizontal={props => - <div {...props} className="fancy-scroll--track-h" />} - renderTrackVertical={props => - <div {...props} className="fancy-scroll--track-v" />} - renderThumbHorizontal={props => - <div {...props} className="fancy-scroll--thumb-h" />} - renderThumbVertical={props => - <div {...props} className="fancy-scroll--thumb-v" />} - renderView={props => <div {...props} className="fancy-scroll--view" />} + renderTrackHorizontal={this.handleMakeDiv('track-h')} + renderTrackVertical={this.handleMakeDiv('track-v')} + renderThumbHorizontal={this.handleMakeDiv('thumb-h')} + renderThumbVertical={this.handleMakeDiv('thumb-v')} + renderView={this.handleMakeDiv('view')} > {children} </Scrollbars>
eca69d314c990f7523742277cd104ef5371a49d2
test/dummy/app/assets/javascripts/application.js
test/dummy/app/assets/javascripts/application.js
// This is a manifest file that'll be compiled into including all the files listed below. // Add new JavaScript/Coffee code in separate files in this directory and they'll automatically // be included in the compiled file accessible from http://example.com/assets/application.js // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // the compiled file. // //= require jquery //= require jquery_ujs //= require_tree .
// This is a manifest file that'll be compiled into including all the files listed below. // Add new JavaScript/Coffee code in separate files in this directory and they'll automatically // be included in the compiled file accessible from http://example.com/assets/application.js // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // the compiled file. // //= require_tree .
Remove jQuery from the assets
Remove jQuery from the assets
JavaScript
mit
Soluciones/kpi,Soluciones/kpi,Soluciones/kpi
--- +++ @@ -4,6 +4,4 @@ // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // the compiled file. // -//= require jquery -//= require jquery_ujs //= require_tree .
1c84ae2c3ebe985ed1e5348cd4ee2cdb4aee1be3
test/mriTests.js
test/mriTests.js
"use strict" const mocha = require('mocha'); const expect = require('chai').expect; const fs = require('fs'); const mri = require('../src/mri'); describe("Detect CSharp functions", function(){ it("should detect functions", function(){ const expected = ["DiscoverTestsToExecute", "GetTestsThatCall", "GetTestsThatCall", "GetCallsInMethod", "GetTestMethodsInAssembly"]; const code = fs.readFileSync('test/testRepo/aFile.cs').toString(); const result = mri.getCSharpFunctionNamesFrom(code); expect(result).to.have.ordered.deep.members(expected); }); });
"use strict" const mocha = require('mocha'); const expect = require('chai').expect; const fs = require('fs'); const mri = require('../src/mri'); describe("Detect CSharp functions", function(){ it("should detect functions", function(){ this.timeout(5000); const expected = ["DiscoverTestsToExecute", "GetTestsThatCall", "GetTestsThatCall", "GetCallsInMethod", "GetTestMethodsInAssembly"]; const code = fs.readFileSync('test/testRepo/aFile.cs').toString(); const result = mri.getCSharpFunctionNamesFrom(code); expect(result).to.have.ordered.deep.members(expected); }); });
Add timeout to mri tests
Add timeout to mri tests
JavaScript
mit
vgaltes/CrystalGazer,vgaltes/CrystalGazer
--- +++ @@ -7,6 +7,8 @@ describe("Detect CSharp functions", function(){ it("should detect functions", function(){ + this.timeout(5000); + const expected = ["DiscoverTestsToExecute", "GetTestsThatCall", "GetTestsThatCall", "GetCallsInMethod", "GetTestMethodsInAssembly"]; const code = fs.readFileSync('test/testRepo/aFile.cs').toString();
ad3279b9d7642dbe53e951ea7d7131e637c4e589
tests/lib/rules/no-const-outside-module-scope.js
tests/lib/rules/no-const-outside-module-scope.js
'use strict'; //------------------------------------------------------------------------------ // Requirements //------------------------------------------------------------------------------ var rule = require('../../../lib/rules/no-const-outside-module-scope'); var RuleTester = require('eslint').RuleTester; //------------------------------------------------------------------------------ // Tests //------------------------------------------------------------------------------ var ruleTester = new RuleTester({ parserOptions: { ecmaVersion: 6, sourceType: 'module' } }); ruleTester.run('no-const-outside-module-scope', rule, { valid: [ 'const FOOBAR = 5;', 'export const FOOBAR = 5;' ], invalid: [{ code: '{ const FOOBAR = 5; }', errors: [{ message: '`const` should only be used in module scope (not inside functions/blocks).' }] }, { code: 'function foobar() { const FOOBAR = 5; return FOOBAR; }', errors: [{ message: '`const` should only be used in module scope (not inside functions/blocks).' }] }] });
'use strict'; //------------------------------------------------------------------------------ // Requirements //------------------------------------------------------------------------------ var rule = require('../../../lib/rules/no-const-outside-module-scope'); var RuleTester = require('eslint').RuleTester; //------------------------------------------------------------------------------ // Tests //------------------------------------------------------------------------------ var ruleTester = new RuleTester({ parserOptions: { ecmaVersion: 6, sourceType: 'module' } }); ruleTester.run('no-const-outside-module-scope', rule, { valid: [ 'const FOOBAR = 5;', 'export const FOOBAR = 5;' ], invalid: [{ code: '{ const FOOBAR = 5; }', output: '{ let FOOBAR = 5; }', errors: [{ message: '`const` should only be used in module scope (not inside functions/blocks).' }] }, { code: 'function foobar() { const FOOBAR = 5; return FOOBAR; }', output: 'function foobar() { let FOOBAR = 5; return FOOBAR; }', errors: [{ message: '`const` should only be used in module scope (not inside functions/blocks).' }] }] });
Add output returned by the fixer
Test: Add output returned by the fixer
JavaScript
mit
Turbo87/eslint-plugin-ember-internal
--- +++ @@ -27,9 +27,11 @@ invalid: [{ code: '{ const FOOBAR = 5; }', + output: '{ let FOOBAR = 5; }', errors: [{ message: '`const` should only be used in module scope (not inside functions/blocks).' }] }, { code: 'function foobar() { const FOOBAR = 5; return FOOBAR; }', + output: 'function foobar() { let FOOBAR = 5; return FOOBAR; }', errors: [{ message: '`const` should only be used in module scope (not inside functions/blocks).' }] }] });
fa126551f8dafa5171aca253e6add5ecc7b928b5
src/docs/components/SpinningDoc.js
src/docs/components/SpinningDoc.js
// (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP import React, { Component } from 'react'; import Spinning from 'grommet/components/icons/Spinning'; import DocsArticle from '../../components/DocsArticle'; import Code from '../../components/Code'; export default class SpinningDoc extends Component { render () { return ( <DocsArticle title='Spinning'> <section> <p>An indeterminate spinning/busy icon. This should be used sparingly. If at all possible, use Meter with % to indicate progress. For content loading situations, Meter, Chart, and Distribution already have visuals for when the data has not arrived yet. In general, there should not be more than one Spinning icon on the screen at a time.</p> <Spinning /> </section> <section> <h2>Usage</h2> <Code preamble={ `import Spinning from 'grommet/components/Spinning';`}> <Spinning /> </Code> </section> </DocsArticle> ); } };
// (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP import React, { Component } from 'react'; import Spinning from 'grommet/components/icons/Spinning'; import DocsArticle from '../../components/DocsArticle'; import Code from '../../components/Code'; export default class SpinningDoc extends Component { render () { return ( <DocsArticle title='Spinning'> <section> <p>An indeterminate spinning/busy icon. This should be used sparingly. If at all possible, use Meter with % to indicate progress. For content loading situations, Meter, Chart, and Distribution already have visuals for when the data has not arrived yet. In general, there should not be more than one Spinning icon on the screen at a time.</p> <Spinning /> </section> <section> <h2>Usage</h2> <Code preamble={ `import Spinning from 'grommet/components/icons/Spinning';`}> <Spinning /> </Code> </section> </DocsArticle> ); } };
Fix import path of Spinning usage
Fix import path of Spinning usage
JavaScript
apache-2.0
grommet/grommet-docs,grommet/grommet-docs
--- +++ @@ -25,7 +25,7 @@ <section> <h2>Usage</h2> <Code preamble={ - `import Spinning from 'grommet/components/Spinning';`}> + `import Spinning from 'grommet/components/icons/Spinning';`}> <Spinning /> </Code> </section>
b2403270ce82fdae09db5e07b07ea6f92bb955d6
core-plugins/shared/1/as/webapps/project-viewer/html/js/config/config.js
core-plugins/shared/1/as/webapps/project-viewer/html/js/config/config.js
/** * This is the default (fallback) configuration file for the web application. */ // Create empty CONFIG object as fallback if it does not exist. var CONFIG = CONFIG || {}; // Default configuration. var DEFAULT_CONFIG = {};
/** * This is the default (fallback) configuration file for the web application. */ // Default configuration. var DEFAULT_CONFIG = {};
Remove duplicate declaration of CONFIG.
Remove duplicate declaration of CONFIG.
JavaScript
apache-2.0
aarpon/obit_shared_core_technology,aarpon/obit_shared_core_technology,aarpon/obit_shared_core_technology
--- +++ @@ -2,8 +2,5 @@ * This is the default (fallback) configuration file for the web application. */ -// Create empty CONFIG object as fallback if it does not exist. -var CONFIG = CONFIG || {}; - // Default configuration. var DEFAULT_CONFIG = {};
02f49e650e067a9dac49998bf2ddfdcf38b23eb8
Resources/lib/Como/Models.js
Resources/lib/Como/Models.js
module.exports = function (Como) { var models = {}, // include underscore utility-belt _ = require('/lib/Underscore/underscore.min'); _.each(Como.config.models, function (m) { var _m = require('/app/models/' + m.name), mName = m.name.toLowerCase(); models[mName] = new _m(Como); if (m.truncate) { models[mName].truncate(); } }); return models; };
module.exports = function (Como) { var models = {}, // include underscore utility-belt _ = require('/lib/Underscore/underscore.min'); _.each(Como.config.models, function (m) { var _m = require('/app/models/' + m.name), mName = m.name.toLowerCase(); models[mName] = new _m(Como); //if (m.truncate) { models[mName].truncate(); } }); return models; };
Truncate during app start causing error, disable it for now.
Truncate during app start causing error, disable it for now.
JavaScript
apache-2.0
geekzy/tiapp-como
--- +++ @@ -8,7 +8,7 @@ mName = m.name.toLowerCase(); models[mName] = new _m(Como); - if (m.truncate) { models[mName].truncate(); } + //if (m.truncate) { models[mName].truncate(); } }); return models;
ce7365ee16191777ad76d4009e2e0d21cde204fe
app/initializers/session.js
app/initializers/session.js
export default { name: 'app.session', initialize(container, application) { application.inject('controller', 'session', 'service:session'); application.inject('route', 'session', 'service:session'); } };
export default { name: 'app.session', initialize(application) { application.inject('controller', 'session', 'service:session'); application.inject('route', 'session', 'service:session'); } };
Fix a deprecation warning about `initialize` arguments
Fix a deprecation warning about `initialize` arguments This shows up in the browser console. Fixed as suggested at: http://emberjs.com/deprecations/v2.x/#toc_initializer-arity
JavaScript
apache-2.0
Susurrus/crates.io,achanda/crates.io,achanda/crates.io,steveklabnik/crates.io,achanda/crates.io,rust-lang/crates.io,steveklabnik/crates.io,Susurrus/crates.io,steveklabnik/crates.io,rust-lang/crates.io,rust-lang/crates.io,achanda/crates.io,steveklabnik/crates.io,Susurrus/crates.io,rust-lang/crates.io,Susurrus/crates.io
--- +++ @@ -1,7 +1,7 @@ export default { name: 'app.session', - initialize(container, application) { + initialize(application) { application.inject('controller', 'session', 'service:session'); application.inject('route', 'session', 'service:session'); }
41abdbad1fc8af309a852770478a0a517c0a6395
DebugGlobals.js
DebugGlobals.js
/** * Globals we expose on the window object for manual debugging with the Chrome * console. * * TODO: Consider disabling this for release builds. * * @flow */ import * as actions from './actions' import store from './store' import parseExpression from './parseExpression' /** * Parse the given expression text and place the expression on the screen. */ const makeExpression = (exprString: string) => { const userExpr = parseExpression(exprString); const screenExpr = { expr: userExpr, x: 100, y: 100, }; store.dispatch(actions.addExpression(screenExpr)); }; window.DebugGlobals = { store, actions, makeExpression, };
/** * Globals we expose on the window object for manual debugging with the Chrome * console. * * @flow */ import {NativeModules} from 'react-native' import * as actions from './actions' import store from './store' import parseExpression from './parseExpression' /** * Parse the given expression text and place the expression on the screen. */ const makeExpression = (exprString: string) => { const userExpr = parseExpression(exprString); const screenExpr = { expr: userExpr, x: 100, y: 100, }; store.dispatch(actions.addExpression(screenExpr)); refreshNative(); }; // Only run when we're running in Chrome. We detect this by checking if we're in // the debuggerWorker.js web worker, which defines a messageHandlers global. if (__DEV__ && window.messageHandlers !== undefined) { window.DebugGlobals = { store, actions, makeExpression, }; // Set a callback to be run regularly. This ensures that pending calls to // native code are flushed in a relatively timely manner, so we can run // things like redux actions from the Chrome console and have them take // effect immediately. setInterval(() => {}, 100); console.log( 'Created debug globals. Access them on the DebugGlobals object.'); }
Update debug globals code to allow modifications from the Chrome console
Update debug globals code to allow modifications from the Chrome console Previously, refreshes wouldn't happen until the next call from native code. Now, we run a setInterval that runs all the time to force any Chrome-triggered events to get flushed.
JavaScript
mit
alangpierce/LambdaCalculusPlayground,alangpierce/LambdaCalculusPlayground,alangpierce/LambdaCalculusPlayground
--- +++ @@ -2,10 +2,10 @@ * Globals we expose on the window object for manual debugging with the Chrome * console. * - * TODO: Consider disabling this for release builds. - * * @flow */ + +import {NativeModules} from 'react-native' import * as actions from './actions' import store from './store' @@ -22,10 +22,24 @@ y: 100, }; store.dispatch(actions.addExpression(screenExpr)); + refreshNative(); }; -window.DebugGlobals = { - store, - actions, - makeExpression, -}; +// Only run when we're running in Chrome. We detect this by checking if we're in +// the debuggerWorker.js web worker, which defines a messageHandlers global. +if (__DEV__ && window.messageHandlers !== undefined) { + window.DebugGlobals = { + store, + actions, + makeExpression, + }; + + // Set a callback to be run regularly. This ensures that pending calls to + // native code are flushed in a relatively timely manner, so we can run + // things like redux actions from the Chrome console and have them take + // effect immediately. + setInterval(() => {}, 100); + + console.log( + 'Created debug globals. Access them on the DebugGlobals object.'); +}
0e91b9b2a063a22bf1033777452c8c87cb399829
src/app/index.route.js
src/app/index.route.js
function routerConfig ($stateProvider, $urlRouterProvider) { 'ngInject'; $stateProvider // Holding page .state('holding-page', { url: '/', views: { 'content': { templateUrl: 'app/holding-page/holding-page.html' } } }) // Home page .state('home', { url: '/home', views: { 'content': { templateUrl: 'app/home/home.html', controller: 'HomeController', controllerAs: 'home' } } }) // Projects .state('ambr', { url: '/ambr', views: { 'content': { templateUrl: 'app/projects/ambr/ambr.html' } } }) .state('layla-moran', { url: '/layla-moran', views: { 'content': { templateUrl: 'app/projects/layla/layla.html' } } }); $urlRouterProvider.otherwise('/'); } export default routerConfig;
function routerConfig ($stateProvider, $urlRouterProvider) { 'ngInject'; $stateProvider // Holding page .state('holding-page', { url: '/', views: { 'content': { templateUrl: 'app/holding-page/holding-page.html' } } }) // Home page .state('home', { url: '/home', views: { 'content': { templateUrl: 'app/home/home.html', controller: 'HomeController', controllerAs: 'home' } } }) // Projects .state('eufn', { url: '/eufn', views: { 'content': { templateUrl: 'app/projects/eufn/eufn.html' } } }) .state('lancastrians', { url: '/lancastrians', views: { 'content': { templateUrl: 'app/projects/lancastrians/lancastrians.html' } } }) .state('layla-moran', { url: '/layla-moran', views: { 'content': { templateUrl: 'app/projects/layla/layla.html' } } }) .state('ambr', { url: '/ambr', views: { 'content': { templateUrl: 'app/projects/ambr/ambr.html' } } }); $urlRouterProvider.otherwise('/'); } export default routerConfig;
Add routing for EUFN and Lancastrians projects
Add routing for EUFN and Lancastrians projects
JavaScript
mit
RobEasthope/lazarus,RobEasthope/lazarus
--- +++ @@ -24,11 +24,19 @@ }) // Projects - .state('ambr', { - url: '/ambr', + .state('eufn', { + url: '/eufn', views: { 'content': { - templateUrl: 'app/projects/ambr/ambr.html' + templateUrl: 'app/projects/eufn/eufn.html' + } + } + }) + .state('lancastrians', { + url: '/lancastrians', + views: { + 'content': { + templateUrl: 'app/projects/lancastrians/lancastrians.html' } } }) @@ -39,6 +47,14 @@ templateUrl: 'app/projects/layla/layla.html' } } + }) + .state('ambr', { + url: '/ambr', + views: { + 'content': { + templateUrl: 'app/projects/ambr/ambr.html' + } + } }); $urlRouterProvider.otherwise('/');
657ea31a8373be43b33d80cfe58915e294ec21ea
index.js
index.js
var persist = require('./lib/persist'); module.exports = persist;
var persist = require('./lib/persist'); /** * @param String db MongoDB connection string * @param Array data * @return promise * This module makes use of the node-promise API. * Operate on the singular result argument passed to a `then` callback, as follows: * * persist(db, data).then(function (result) { * // Operate on the mongodb documents * }, function (error) { * // Handle errors * }) */ module.exports = persist;
Add a more useful comment
Add a more useful comment
JavaScript
mit
imgges/persist
--- +++ @@ -1,3 +1,16 @@ var persist = require('./lib/persist'); +/** + * @param String db MongoDB connection string + * @param Array data + * @return promise + * This module makes use of the node-promise API. + * Operate on the singular result argument passed to a `then` callback, as follows: + * + * persist(db, data).then(function (result) { + * // Operate on the mongodb documents + * }, function (error) { + * // Handle errors + * }) + */ module.exports = persist;
0e3db15aa1c142c5028a0da35f0da42a237aa306
index.js
index.js
'use strict'; module.exports = function(prompts) { // This method will only show prompts that haven't been supplied as options. This makes the generator more composable. const filteredPrompts = []; const props = new Map(); prompts.forEach(function prompts(prompt) { this.option(prompt.name); const option = this.options[prompt.name]; if (option === undefined) { // No option supplied, user will be prompted filteredPrompts.push(prompt); } else { // Options supplied, add to props props[prompt.name] = option; } }, this); if (filteredPrompts.length) { return this.prompt(filteredPrompts).then(function mergeProps(mergeProps) { // Merge mergeProps into props/ Object.assign(props, mergeProps); return props; }); } // No prompting required call the callback right away. return Promise.resolve(props); };
'use strict'; module.exports = function(prompts) { // This method will only show prompts that haven't been supplied as options. This makes the generator more composable. const filteredPrompts = []; const props = new Map(); prompts.forEach(function prompts(prompt) { const option = this.options[prompt.name]; if (option === undefined) { // No option supplied, user will be prompted filteredPrompts.push(prompt); } else { // Options supplied, add to props props[prompt.name] = option; } }, this); if (filteredPrompts.length) { return this.prompt(filteredPrompts).then(function mergeProps(mergeProps) { // Merge mergeProps into props/ Object.assign(props, mergeProps); return props; }); } // No prompting required call the callback right away. return Promise.resolve(props); };
Fix to allow non boolean options
Fix to allow non boolean options
JavaScript
mit
artefact-group/yeoman-option-or-prompt
--- +++ @@ -6,7 +6,6 @@ const props = new Map(); prompts.forEach(function prompts(prompt) { - this.option(prompt.name); const option = this.options[prompt.name]; if (option === undefined) {
c631ca483da85d04ef13afcf9e9c0f78a74cfc61
index.js
index.js
exports.register = function(plugin, options, next) { // Wait 10 seconds for existing connections to close then exit. var stop = function() { plugin.servers[0].stop({ timeout: 10 * 1000 }, function() { process.exit(); }); }; process.on('SIGTERM', stop); process.on('SIGINT', stop); next(); }; exports.register.attributes = { pkg: require('./package.json') };
exports.register = function(server, options, next) { // Wait 10 seconds for existing connections to close then exit. var stop = function() { server.connections[0].stop({ timeout: 10 * 1000 }, function() { process.exit(); }); }; process.on('SIGTERM', stop); process.on('SIGINT', stop); next(); }; exports.register.attributes = { pkg: require('./package.json') };
Upgrade for compatability with Hapi 8
Upgrade for compatability with Hapi 8
JavaScript
mit
KyleAMathews/hapi-death
--- +++ @@ -1,8 +1,8 @@ -exports.register = function(plugin, options, next) { +exports.register = function(server, options, next) { // Wait 10 seconds for existing connections to close then exit. var stop = function() { - plugin.servers[0].stop({ + server.connections[0].stop({ timeout: 10 * 1000 }, function() { process.exit();
8044a284695bb16567d50c4bb58a965f7d181bfe
index.js
index.js
var path = require('path'); module.exports = function (source) { if (this.cacheable) { this.cacheable(); } var filename = path.basename(this.resourcePath), matches = 0, processedSource; processedSource = source.replace(/React\.createClass\s*\(\s*\{/g, function (match) { matches++; return '__hotUpdateAPI.createClass({'; }); if (!matches) { return source; } return [ 'var __hotUpdateAPI = (function () {', ' var React = require("react");', ' var getHotUpdateAPI = require(' + JSON.stringify(require.resolve('./getHotUpdateAPI')) + ');', ' return getHotUpdateAPI(React, ' + JSON.stringify(filename) + ', module.id);', '})();', processedSource, 'if (module.hot) {', ' module.hot.accept(function (err) {', ' if (err) {', ' console.error("Cannot not apply hot update to " + ' + JSON.stringify(filename) + ' + ": " + err.message);', ' }', ' });', ' module.hot.dispose(function () {', ' var nextTick = require(' + JSON.stringify(require.resolve('next-tick')) + ');', ' nextTick(__hotUpdateAPI.updateMountedInstances);', ' });', '}' ].join('\n'); };
var path = require('path'); module.exports = function (source) { if (this.cacheable) { this.cacheable(); } var filename = path.basename(this.resourcePath), matches = 0, processedSource; processedSource = source.replace(/[Rr]eact\.createClass\s*\(/g, function (match) { matches++; return '__hotUpdateAPI.createClass('; }); if (!matches) { return source; } return [ 'var __hotUpdateAPI = (function () {', ' var React = require("react");', ' var getHotUpdateAPI = require(' + JSON.stringify(require.resolve('./getHotUpdateAPI')) + ');', ' return getHotUpdateAPI(React, ' + JSON.stringify(filename) + ', module.id);', '})();', processedSource, 'if (module.hot) {', ' module.hot.accept(function (err) {', ' if (err) {', ' console.error("Cannot not apply hot update to " + ' + JSON.stringify(filename) + ' + ": " + err.message);', ' }', ' });', ' module.hot.dispose(function () {', ' var nextTick = require(' + JSON.stringify(require.resolve('next-tick')) + ');', ' nextTick(__hotUpdateAPI.updateMountedInstances);', ' });', '}' ].join('\n'); };
Allow lowercase React import and using an object reference
Allow lowercase React import and using an object reference
JavaScript
mit
gaearon/react-hot-loader,gaearon/react-hot-loader
--- +++ @@ -9,9 +9,9 @@ matches = 0, processedSource; - processedSource = source.replace(/React\.createClass\s*\(\s*\{/g, function (match) { + processedSource = source.replace(/[Rr]eact\.createClass\s*\(/g, function (match) { matches++; - return '__hotUpdateAPI.createClass({'; + return '__hotUpdateAPI.createClass('; }); if (!matches) {
f2bbd2ed9f3a7cac8075d1ddb1b294c5069b0589
prototype.spawn.js
prototype.spawn.js
module.exports = function () { StructureSpawn.prototype.createCustomCreep = function(energy, roleName) { var numberOfParts = Math.floor(energy / 350); var body = []; for (let i = 0; i < numberOfParts; i++) { body.push(WORK); } for (let i = 0; i < numberOfParts; i++) { body.push(WORK); } for (let i = 0; i < numberOfParts; i++) { body.push(CARRY); } for (let i = 0; i < numberOfParts; i++) { body.push(MOVE); } for (let i = 0; i < numberOfParts; i++) { body.push(MOVE); } for (let i = 0; i < numberOfParts; i++) { body.push(MOVE); } return this.createCreep(body, undefined, {role: roleName, working: false }); }; };
module.exports = function () { StructureSpawn.prototype.createCustomCreep = function(energy, roleName) { var numberOfParts = Math.floor(energy / 350); var body = []; for (let i = 0; i < numberOfParts; i++) { body.push(WORK); } for (let i = 0; i < numberOfParts; i++) { body.push(WORK); } for (let i = 0; i < numberOfParts; i++) { body.push(CARRY); } for (let i = 0; i < numberOfParts; i++) { body.push(CARRY); } for (let i = 0; i < numberOfParts; i++) { body.push(MOVE); } for (let i = 0; i < numberOfParts; i++) { body.push(MOVE); } for (let i = 0; i < numberOfParts; i++) { body.push(MOVE); } return this.createCreep(body, undefined, {role: roleName, working: false }); }; };
WORK WORK CARRY CARRY MOVE MOVE MOVE
WORK WORK CARRY CARRY MOVE MOVE MOVE
JavaScript
mit
Raltrwx/Ralt-Screeps
--- +++ @@ -8,6 +8,9 @@ } for (let i = 0; i < numberOfParts; i++) { body.push(WORK); + } + for (let i = 0; i < numberOfParts; i++) { + body.push(CARRY); } for (let i = 0; i < numberOfParts; i++) { body.push(CARRY);
7c3bcda4f834cfab2fdd4caa32b59ea6c8082176
release.js
release.js
var shell = require('shelljs') if (exec('git status --porcelain').stdout) { console.error('Git working directory not clean. Please commit all chances to release a new package to npm.') process.exit(2) } var versionIncrement = process.argv[process.argv.length - 1] var versionIncrements = ['major', 'minor', 'patch'] if (versionIncrements.indexOf(versionIncrement) < 0) { console.error('Usage: node release.js major|minor|patch') process.exit(1) } exec('npm test') var geotag = execOptional('npm run geotag') if (geotag.code == 0) { exec('git commit -m "Geotag package for release" package.json') } exec('npm version ' + versionIncrement) exec('git push') exec('git push --tags') exec('npm publish') function exec (cmd) { var ret = shell.exec(cmd, { silent: true }) if (ret.code !== 0) { console.error(ret.stdout) process.exit(1) } return ret } function execOptional (cmd) { var ret = shell.exec(cmd, { silent: true }) if (ret.code !== 0) { console.log(ret.stdout) } return ret }
var shell = require('shelljs') if (exec('git status --porcelain').stdout) { console.error('Git working directory not clean. Please commit all chances to release a new package to npm.') process.exit(2) } var versionIncrement = process.argv[process.argv.length - 1] var versionIncrements = ['major', 'minor', 'patch'] if (versionIncrements.indexOf(versionIncrement) < 0) { console.error('Usage: node release.js major|minor|patch') process.exit(1) } exec('npm test') var geotag = execOptional('npm run geotag') if (geotag.code === 0) { exec('git commit -m "Geotag package for release" package.json') } exec('npm version ' + versionIncrement) exec('git push') exec('git push --tags') exec('npm publish') function exec (cmd) { var ret = shell.exec(cmd, { silent: true }) if (ret.code !== 0) { console.error(ret.stdout) process.exit(1) } return ret } function execOptional (cmd) { var ret = shell.exec(cmd, { silent: true }) if (ret.code !== 0) { console.log(ret.stdout) } return ret }
Use === instead of == to please the standard
Use === instead of == to please the standard
JavaScript
mit
mafintosh/mongojs
--- +++ @@ -17,7 +17,7 @@ var geotag = execOptional('npm run geotag') -if (geotag.code == 0) { +if (geotag.code === 0) { exec('git commit -m "Geotag package for release" package.json') }
29aae66080fcdff0fe62486d445c6a3a9aeff406
app/assets/javascripts/forest/admin/partials/forest_tables.js
app/assets/javascripts/forest/admin/partials/forest_tables.js
// Forest tables $(document).on('mouseenter', '.forest-table tbody tr', function() { var $row = $(this); $row.addClass('active'); $(document).one('turbolinks:before-cache.forestTables', function() { $row.removeClass('active'); }); }); $(document).on('mouseleave', '.forest-table tbody tr', function() { var $row = $(this); $row.removeClass('active'); }); $(document).on('click', '.forest-table tbody tr', function(e) { var $row = $(this); if ( !$(e.target).closest('a').length ) { var $button = $row.find('a.forest-table__link:first'); if ( !$button.length ) { $button = $row.find('a.btn-primary:first'); } var url = $button.attr('href'); if ( url ) { Turbolinks.visit(url); } } });
// Forest tables $(document).on('mouseenter', '.forest-table tbody tr', function() { var $row = $(this); $row.addClass('active'); $(document).one('turbolinks:before-cache.forestTables', function() { $row.removeClass('active'); }); }); $(document).on('mouseleave', '.forest-table tbody tr', function() { var $row = $(this); $row.removeClass('active'); }); $(document).on('click', '.forest-table tbody tr', function(e) { var $row = $(this); if ( !$(e.target).closest('a').length ) { var $button = $row.find('a.forest-table__link:first'); if ( !$button.length ) { $button = $row.find('a.btn-primary:first'); } var url = $button.attr('href'); if ( url ) { if ( e.metaKey || e.ctrlKey ) { window.open( url, '_blank' ); } else if ( e.shiftKey ) { window.open( url, '_blank' ); window.focus(); } else { Turbolinks.visit(url); } } } });
Allow modifier key press when opening table rows
Allow modifier key press when opening table rows
JavaScript
mit
dylanfisher/forest,dylanfisher/forest,dylanfisher/forest
--- +++ @@ -29,7 +29,14 @@ var url = $button.attr('href'); if ( url ) { - Turbolinks.visit(url); + if ( e.metaKey || e.ctrlKey ) { + window.open( url, '_blank' ); + } else if ( e.shiftKey ) { + window.open( url, '_blank' ); + window.focus(); + } else { + Turbolinks.visit(url); + } } } });
1d46cc1e616d64cdae5b29e9f777c309b3ea08f7
SPAWithAngularJS/module3/directives/controllersInsideDirective/js/app.shoppingListDirective.js
SPAWithAngularJS/module3/directives/controllersInsideDirective/js/app.shoppingListDirective.js
// app.shoppingListDirective.js (function() { "use strict"; angular.module("ShoppingListDirectiveApp") .directive("shoppingList", ShoppingList); function ShoppingList() { const templateUrl = "../templates/shoppingList.view.html"; const ddo = { restrict: "E", templateUrl, scope: { list: "<", title: "@" }, controller: "ShoppingListDirectiveController as l", bindToController: true }; return ddo; } })();
// app.shoppingListDirective.js (function() { "use strict"; angular.module("ShoppingListDirectiveApp") .directive("shoppingList", ShoppingList); function ShoppingList() { const templateUrl = "../templates/shoppingList.view.html"; const ddo = { restrict: "E", templateUrl, scope: { list: "<", title: "@" }, controller: "ShoppingListDirectiveController as ShoppingListDirectiveCtrl", bindToController: true }; return ddo; } })();
Edit controllerAs label for ShoppingListDirectiveController
Edit controllerAs label for ShoppingListDirectiveController
JavaScript
mit
var-bin/angularjs-training,var-bin/angularjs-training,var-bin/angularjs-training,var-bin/angularjs-training
--- +++ @@ -15,7 +15,7 @@ list: "<", title: "@" }, - controller: "ShoppingListDirectiveController as l", + controller: "ShoppingListDirectiveController as ShoppingListDirectiveCtrl", bindToController: true };
446503cb5c27964f693b0d931b52ff18f862b159
assets/js/external-links.js
assets/js/external-links.js
//// External Links // Open external links in a new tab. $(function () { $('a').each(function () { if ( $(this).href.indexOf(window.location.host) == -1 ) { $(this).attr('target', '_blank'); } }); });
//// External Links // Open external links in a new tab. $(function () { $('a').each(function () { if ( $(this).href.indexOf(window.location.host) === -1 ) { $(this).attr('target', '_blank'); } }); });
Fix "Expected '===' and instead saw '=='."
Fix "Expected '===' and instead saw '=='."
JavaScript
mit
eustasy/puff-core,eustasy/puff-core,eustasy/puff-core
--- +++ @@ -2,7 +2,7 @@ // Open external links in a new tab. $(function () { $('a').each(function () { - if ( $(this).href.indexOf(window.location.host) == -1 ) { + if ( $(this).href.indexOf(window.location.host) === -1 ) { $(this).attr('target', '_blank'); } });
5b7eda2be2c50e4aab45b862c2f9cde0d31c2dfe
gulpfile.js
gulpfile.js
var gulp = require('gulp'); var clean = require('gulp-clean'); var zip = require('gulp-zip'); var bases = { root: 'dist/' }; var paths = [ 'core/actions/*', 'core/common/**', 'admin/**', '!admin/config/*', 'boxoffice/**', '!boxoffice/config/*', 'customer/**', '!customer/config/*', 'scanner/**', '!scanner/config/*', 'printer/**', '!printer/config/*', 'core/model/*', 'core/services/*', 'vendor/**', 'composer.lock', 'core/dependencies.php' ]; gulp.task('clean', function() { return gulp.src(bases.root) .pipe(clean({})); }); gulp.task('collect', function() { return gulp.src(paths, { base: './', dot: true }) .pipe(gulp.dest(bases.root)); }); gulp.task('zip', function() { return gulp.src(bases.root + '**') .pipe(zip('ticketbox-server-php.zip')) .pipe(gulp.dest(bases.root)); }); gulp.task('default', gulp.series('clean', 'collect', 'zip'));
var gulp = require('gulp'); var clean = require('gulp-clean'); var zip = require('gulp-zip'); var bases = { root: 'dist/' }; var paths = [ 'core/actions/*', 'core/common/**', 'admin/**', '!admin/config/*', 'boxoffice/**', '!boxoffice/config/*', 'customer/**', '!customer/config/*', 'scanner/**', '!scanner/config/*', 'printer/**', '!printer/config/*', 'core/model/*', 'core/services/*', 'vendor/**', 'composer.lock', 'core/dependencies.php', 'core/.htaccess' ]; gulp.task('clean', function() { return gulp.src(bases.root) .pipe(clean({})); }); gulp.task('collect', function() { return gulp.src(paths, { base: './', dot: true }) .pipe(gulp.dest(bases.root)); }); gulp.task('zip', function() { return gulp.src(bases.root + '**') .pipe(zip('ticketbox-server-php.zip')) .pipe(gulp.dest(bases.root)); }); gulp.task('default', gulp.series('clean', 'collect', 'zip'));
Copy core .htaccess file to dist
Copy core .htaccess file to dist
JavaScript
mit
ssigg/ticketbox-server-php,ssigg/ticketbox-server-php,ssigg/ticketbox-server-php
--- +++ @@ -24,7 +24,8 @@ 'core/services/*', 'vendor/**', 'composer.lock', - 'core/dependencies.php' + 'core/dependencies.php', + 'core/.htaccess' ]; gulp.task('clean', function() {
77726d201de27f48485de497ff706ccea11becc2
src/config/config.default.js
src/config/config.default.js
// TODO Just add fallbacks to config.js var path = require('path') module.exports = { port: 8080, address: '127.0.0.1', session_secret: 'asdf', database: { host: 'mongodb://127.0.0.1/', // MongoDB host name: 'vegosvar', // MongoDB database name }, facebook: { app_id: '', app_secret: '', callback: 'http://local.vegosvar.se:8080/auth/facebook/callback' }, root: path.join(__dirname, '..'), uploads: path.join(__dirname, '../uploads') }
// TODO Just add fallbacks to config.js var path = require('path') module.exports = { port: 8080, address: '127.0.0.1', session_secret: 'asdf', database: { host: 'mongodb://127.0.0.1/', // MongoDB host name: 'vegosvar', // MongoDB database name }, facebook: { app_id: '', app_secret: '', callback: 'http://local.vegosvar.se:8080/auth/facebook/callback' }, instagram: { client_id: '', client_secret: '', callback: 'http://local.vegosvar.se/admin/auth/instagram/callback', scope: 'public_content ' }, root: path.join(__dirname, '..'), uploads: path.join(__dirname, '../uploads') }
Add config for instagram authentication
Add config for instagram authentication
JavaScript
unlicense
Vegosvar/Vegosvar,Vegosvar/Vegosvar,Vegosvar/Vegosvar
--- +++ @@ -18,6 +18,13 @@ callback: 'http://local.vegosvar.se:8080/auth/facebook/callback' }, + instagram: { + client_id: '', + client_secret: '', + callback: 'http://local.vegosvar.se/admin/auth/instagram/callback', + scope: 'public_content ' + }, + root: path.join(__dirname, '..'), uploads: path.join(__dirname, '../uploads') }
e4e9561be08162dc7d00ce5cf38f55b52cad5863
src/models/interact.js
src/models/interact.js
var _ = require("lodash"); var Bacon = require("baconjs"); var Interact = module.exports; Interact.ask = function (question) { var readline = require("readline").createInterface({ input: process.stdin, output: process.stdout }); return Bacon.fromCallback(_.partial(readline.question.bind(readline), question)).doAction(readline.close.bind(readline)); }; Interact.confirm = function(question, rejectionMessage) { return Interact.ask(question).flatMapLatest(function(answer) { if(_.includes(["yes", "y"], answer)) { return true; } else { return new Bacon.Error(rejectionMessage); } }); };
var _ = require("lodash"); var Bacon = require("baconjs"); var Interact = module.exports; Interact.ask = function (question) { var readline = require("readline").createInterface({ input: process.stdin, output: process.stdout }); return Bacon.fromCallback(_.partial(readline.question.bind(readline), question)).doAction(readline.close.bind(readline)); }; Interact.confirm = function(question, rejectionMessage, answers) { var defaultAnswers = ["yes", "y"]; var expectedAnswers = typeof answers === "undefined" ? defaultAnswers : answers; return Interact.ask(question).flatMapLatest(function(answer) { if(_.includes(expectedAnswers, answer)) { return true; } else { return new Bacon.Error(rejectionMessage); } }); };
Make Interact.confirm use configurable acceptance strings
Make Interact.confirm use configurable acceptance strings
JavaScript
apache-2.0
CleverCloud/clever-tools,CleverCloud/clever-tools,CleverCloud/clever-tools
--- +++ @@ -12,9 +12,11 @@ return Bacon.fromCallback(_.partial(readline.question.bind(readline), question)).doAction(readline.close.bind(readline)); }; -Interact.confirm = function(question, rejectionMessage) { +Interact.confirm = function(question, rejectionMessage, answers) { + var defaultAnswers = ["yes", "y"]; + var expectedAnswers = typeof answers === "undefined" ? defaultAnswers : answers; return Interact.ask(question).flatMapLatest(function(answer) { - if(_.includes(["yes", "y"], answer)) { + if(_.includes(expectedAnswers, answer)) { return true; } else { return new Bacon.Error(rejectionMessage);
8695e857ae870b1e991cd511ffd70101969876cc
api/feed/pending/matchExec.js
api/feed/pending/matchExec.js
(function () { var cogClass = function () {}; cogClass.prototype.exec = function (params, request, response) { var oops = this.sys.apiError; var sys = this.sys; var userID = params.id; var userKey = params.key; var pages = sys.pages; pages.reset(); var delay = 30; if (sys.output_style === 'demo') { delay = 0; } var sql = 'SELECT eventID FROM events WHERE (strftime("%s","now")-strftime("%s",touchDate,"unixepoch"))/60>? AND NOT published=1 and status=0 ORDER BY pageDate DESC;'; sys.db.all(sql,[delay],function(err,rows){ if (err) {return oops(response,err,'pending(1)')}; sys.runEvents(rows,response,processData); function processData (data) { var page = pages.composeFeed(data,null) page = page.replace(/@@USER_ID@@/g,userID) .replace(/@@USER_KEY@@/g,userKey); response.writeHead(200, {'Content-Type': 'application/atom+xml'}); response.end(page) } }); } exports.cogClass = cogClass; })();
(function () { var cogClass = function () {}; cogClass.prototype.exec = function (params, request, response) { var oops = this.sys.apiError; var sys = this.sys; var userID = params.id; var userKey = params.key; var pages = sys.pages; pages.reset(); var delay = 30; if (sys.output_style === 'demo') { delay = 0; } delay = 3; var sql = 'SELECT eventID FROM events WHERE (strftime("%s","now")-strftime("%s",touchDate,"unixepoch"))/60>? AND NOT published=1 and status=0 ORDER BY pageDate DESC;'; sys.db.all(sql,[delay],function(err,rows){ if (err) {return oops(response,err,'pending(1)')}; sys.runEvents(rows,response,processData); function processData (data) { var page = pages.composeFeed(data,null) page = page.replace(/@@USER_ID@@/g,userID) .replace(/@@USER_KEY@@/g,userKey); response.writeHead(200, {'Content-Type': 'application/atom+xml'}); response.end(page) } }); } exports.cogClass = cogClass; })();
Set short delay for demo
Set short delay for demo
JavaScript
unlicense
fbennett/newswriter
--- +++ @@ -13,6 +13,8 @@ if (sys.output_style === 'demo') { delay = 0; } + + delay = 3; var sql = 'SELECT eventID FROM events WHERE (strftime("%s","now")-strftime("%s",touchDate,"unixepoch"))/60>? AND NOT published=1 and status=0 ORDER BY pageDate DESC;'; sys.db.all(sql,[delay],function(err,rows){
7cf8e87de3aac94d6371799c1bc23c117df06b8d
ti_mocha_tests/modules/commonjs/commonjs.legacy.index_json/1.0.0/commonjs.legacy.index_json.js
ti_mocha_tests/modules/commonjs/commonjs.legacy.index_json/1.0.0/commonjs.legacy.index_json.js
module.exports = { name: 'commonjs.legacy.index_json/commonjs.legacy.index_js.js' };
module.exports = { name: 'commonjs.legacy.index_json/commonjs.legacy.index_json.js' };
Fix test input file with incorrect contets
Fix test input file with incorrect contets
JavaScript
apache-2.0
mano-mykingdom/titanium_mobile,ashcoding/titanium_mobile,cheekiatng/titanium_mobile,mano-mykingdom/titanium_mobile,mano-mykingdom/titanium_mobile,cheekiatng/titanium_mobile,ashcoding/titanium_mobile,cheekiatng/titanium_mobile,cheekiatng/titanium_mobile,ashcoding/titanium_mobile,ashcoding/titanium_mobile,ashcoding/titanium_mobile,cheekiatng/titanium_mobile,ashcoding/titanium_mobile,mano-mykingdom/titanium_mobile,cheekiatng/titanium_mobile,mano-mykingdom/titanium_mobile,ashcoding/titanium_mobile,ashcoding/titanium_mobile,mano-mykingdom/titanium_mobile,mano-mykingdom/titanium_mobile,cheekiatng/titanium_mobile,cheekiatng/titanium_mobile,mano-mykingdom/titanium_mobile
--- +++ @@ -1,3 +1,3 @@ module.exports = { - name: 'commonjs.legacy.index_json/commonjs.legacy.index_js.js' + name: 'commonjs.legacy.index_json/commonjs.legacy.index_json.js' };
dda231347aeba1e692ddbf31d10897d6499cd44b
src/fn/fn-buckets-quantiles.js
src/fn/fn-buckets-quantiles.js
'use strict'; require('es6-promise').polyfill(); var debug = require('../helper/debug')('fn-quantiles'); var LazyFiltersResult = require('../model/lazy-filters-result'); var fnBuckets = require('./fn-buckets'); module.exports = function (datasource) { return function fn$quantiles (numBuckets) { debug('fn$quantiles(%j)', arguments); debug('Using "%s" datasource to calculate quantiles', datasource.getName()); return new Promise(function (resolve) { return resolve(new LazyFiltersResult(function (column, strategy) { return fnBuckets(datasource)(column, 'quantiles', numBuckets).then(function (filters) { filters.strategy = strategy || '>'; return new Promise(function (resolve) { return resolve(filters); }); }); })); }); }; }; module.exports.fnName = 'quantiles';
'use strict'; var createBucketsFn = require('./fn-buckets').createBucketsFn; var FN_NAME = 'quantiles'; module.exports = function (datasource) { return createBucketsFn(datasource, FN_NAME, '>'); }; module.exports.fnName = FN_NAME;
Migrate quantiles to buckets creation
Migrate quantiles to buckets creation
JavaScript
bsd-3-clause
CartoDB/turbo-cartocss
--- +++ @@ -1,26 +1,11 @@ 'use strict'; -require('es6-promise').polyfill(); +var createBucketsFn = require('./fn-buckets').createBucketsFn; -var debug = require('../helper/debug')('fn-quantiles'); -var LazyFiltersResult = require('../model/lazy-filters-result'); -var fnBuckets = require('./fn-buckets'); +var FN_NAME = 'quantiles'; module.exports = function (datasource) { - return function fn$quantiles (numBuckets) { - debug('fn$quantiles(%j)', arguments); - debug('Using "%s" datasource to calculate quantiles', datasource.getName()); - return new Promise(function (resolve) { - return resolve(new LazyFiltersResult(function (column, strategy) { - return fnBuckets(datasource)(column, 'quantiles', numBuckets).then(function (filters) { - filters.strategy = strategy || '>'; - return new Promise(function (resolve) { - return resolve(filters); - }); - }); - })); - }); - }; + return createBucketsFn(datasource, FN_NAME, '>'); }; -module.exports.fnName = 'quantiles'; +module.exports.fnName = FN_NAME;