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
721faf4dd71bef6ee170e3b029dc52ac8f9055a1
src/sprites/object/PineCone/place.js
src/sprites/object/PineCone/place.js
import { treeGrow as growChance } from '../../../game-data/chances'; import { tryChance } from '../../../utils'; import { fastMap } from '../../../world'; import objectPool from '../../../object-pool'; import Phaser from 'phaser'; import Tree from '../Tree'; export default function place() { this.placed = true; this.changeType('planted-pine-cone'); this.game.time.events.add(Phaser.Timer.SECOND * 5, function() { if (this.destroyed) return; const playerTile = this.game.state.states.Game.player.tile; const thisTile = this.tile; if ( (playerTile.x !== thisTile.x || playerTile.y !== thisTile.y) && fastMap[thisTile.x + ',' + thisTile.y].length === 1 && // this pine cone should be only thing on tile tryChance(growChance) ) { objectPool.new('tree', Tree, { game: this.game, x: this.x, y: this.y, }); this.destroy(); } else { place.call(this); } }, this); }
import { treeGrow as growChance } from '../../../game-data/chances'; import { tryChance } from '../../../utils'; import { fastMap } from '../../../world'; import objectPool from '../../../object-pool'; import Phaser from 'phaser'; import Tree from '../Tree'; export default function place() { this.placed = true; this.changeType('planted-pine-cone'); this.game.time.events.add(Phaser.Timer.SECOND * 5, function() { if (this.destroyed) return; const playerTile = this.game.state.states.Game.player.tile; const thisTile = this.tile; if ( (playerTile.x !== thisTile.x || playerTile.y !== thisTile.y) && fastMap[thisTile.y][thisTile.x].length === 1 && // this pine cone should be only thing on tile tryChance(growChance) ) { objectPool.new('tree', Tree, { game: this.game, x: this.x, y: this.y, }); this.destroy(); } else { place.call(this); } }, this); }
Fix using old map format
Fix using old map format
JavaScript
mit
ThomasMays/incremental-forest,ThomasMays/incremental-forest
--- +++ @@ -19,7 +19,7 @@ if ( (playerTile.x !== thisTile.x || playerTile.y !== thisTile.y) && - fastMap[thisTile.x + ',' + thisTile.y].length === 1 && // this pine cone should be only thing on tile + fastMap[thisTile.y][thisTile.x].length === 1 && // this pine cone should be only thing on tile tryChance(growChance) ) { objectPool.new('tree', Tree, {
1d42cae605889f5bab9f7b773561f9a493c32a6a
src/js/helpers/SecretsUtil.js
src/js/helpers/SecretsUtil.js
var SecretsUtil = { /** * This function checks if the environment value is a reference to a secret * and if yes, it cross-references the secret with the `secrets` property * in `allFields` and it returns the secret reference name. * * @param {Object|String} value - The environment variable value * @param {Object} allFields - The full object definition or all form fields * @returns {String} Returns the string for the environment value */ getSecretReferenceOfEnvValue: function (value, allFields) { if (typeof value !== "object") { return value; } let placeholder; const {secret} = value; const secretSource = allFields[`secrets.${secret}.source`] || (allFields.secrets && allFields.secrets[secret] && allFields.secrets[secret].source); if (!secretSource) { placeholder = 'Invalid Secret Reference'; if (!secret) { placeholder = 'Invalid Value'; } } else { placeholder = `Secret "${secretSource}"`; } return placeholder; } }; export default SecretsUtil;
var SecretsUtil = { /** * This function checks if the environment value is a reference to a secret * and if yes, it cross-references the secret with the `secrets` property * in `allFields` and it returns the secret reference name. * * @param {Object|String} value - The environment variable value * @param {Object} allFields - The full object definition or all form fields * @returns {String} Returns the string for the environment value */ getSecretReferenceOfEnvValue: function (value, allFields) { if (typeof value !== "object") { return value; } let placeholder; const {secret} = value; const secretSource = allFields[`secrets.${secret}.source`] || (allFields.secrets && allFields.secrets[secret] && allFields.secrets[secret].source); if (!secretSource) { placeholder = "Invalid Secret Reference"; if (!secret) { placeholder = "Invalid Value"; } } else { placeholder = `Secret "${secretSource}"`; } return placeholder; } }; export default SecretsUtil;
Replace single with double quotes
Replace single with double quotes
JavaScript
apache-2.0
mesosphere/marathon-ui,mesosphere/marathon-ui
--- +++ @@ -20,9 +20,9 @@ allFields.secrets[secret].source); if (!secretSource) { - placeholder = 'Invalid Secret Reference'; + placeholder = "Invalid Secret Reference"; if (!secret) { - placeholder = 'Invalid Value'; + placeholder = "Invalid Value"; } } else { placeholder = `Secret "${secretSource}"`;
ff58f96f6579d583f8f44db8e9c91260cf2ae5a7
ocw-ui/frontend-new/test/spec/filters/isodatetomiddleendian.js
ocw-ui/frontend-new/test/spec/filters/isodatetomiddleendian.js
'use strict'; describe('Filter: ISODateToMiddleEndian', function () { // load the filter's module beforeEach(module('ocwUiApp')); // initialize a new instance of the filter before each test var ISODateToMiddleEndian; beforeEach(inject(function ($filter) { ISODateToMiddleEndian = $filter('ISODateToMiddleEndian'); })); it('should return the input prefixed with "ISODateToMiddleEndian filter:"', function () { var text = 'angularjs'; expect(ISODateToMiddleEndian(text)).toBe('ISODateToMiddleEndian filter: ' + text); }); });
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http: *www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ 'use strict'; describe('Filter: ISODateToMiddleEndian', function () { // load the filter's module beforeEach(module('ocwUiApp')); // initialize a new instance of the filter before each test var ISODateToMiddleEndian; beforeEach(inject(function ($filter) { ISODateToMiddleEndian = $filter('ISODateToMiddleEndian'); })); it('should return the input prefixed with "ISODateToMiddleEndian filter:"', function () { var text = 'angularjs'; expect(ISODateToMiddleEndian(text)).toBe('ISODateToMiddleEndian filter: ' + text); }); });
Add ASF license headers to filter tests
Add ASF license headers to filter tests
JavaScript
apache-2.0
kwhitehall/climate,pwcberry/climate,MJJoyce/climate,jarifibrahim/climate,riverma/climate,lewismc/climate,apache/climate,apache/climate,huikyole/climate,MJJoyce/climate,agoodm/climate,agoodm/climate,jarifibrahim/climate,MBoustani/climate,lewismc/climate,Omkar20895/climate,MJJoyce/climate,agoodm/climate,lewismc/climate,jarifibrahim/climate,pwcberry/climate,agoodm/climate,riverma/climate,MBoustani/climate,lewismc/climate,Omkar20895/climate,lewismc/climate,pwcberry/climate,apache/climate,kwhitehall/climate,riverma/climate,Omkar20895/climate,agoodm/climate,kwhitehall/climate,MJJoyce/climate,pwcberry/climate,MBoustani/climate,huikyole/climate,Omkar20895/climate,huikyole/climate,kwhitehall/climate,riverma/climate,riverma/climate,MBoustani/climate,MBoustani/climate,pwcberry/climate,apache/climate,huikyole/climate,Omkar20895/climate,jarifibrahim/climate,MJJoyce/climate,jarifibrahim/climate,huikyole/climate,apache/climate
--- +++ @@ -1,3 +1,22 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http: *www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + 'use strict'; describe('Filter: ISODateToMiddleEndian', function () {
7b8c50c247a6ea4b382fb59f83c0c2a7473b9fbc
src/Input/TouchInput.js
src/Input/TouchInput.js
function TouchInput(inputController) { this.inputController = inputController; } TouchInput.prototype.listen = function() { document.addEventListener('touchstart', this.startTouch.bind(this)); document.addEventListener('touchmove', this.detectSwipe.bind(this)); }; TouchInput.prototype.startTouch = function(event) { this.xStart = event.touches[0].clientX; this.yStart = event.touches[0].clientY; }; TouchInput.prototype.detectSwipe = function(event) { if( this.xStart === null || this.yStart === null) { return; } var xEnd = event.touches[0].clientX; var yEnd = event.touches[0].clientY; var deltaX = xEnd - this.xStart; var deltaY = yEnd - this.yStart; var isHorizontalSwipe = Math.abs(deltaX) > Math.abs(deltaY); if(isHorizontalSwipe) { deltaX < 0 ? this.inputController.left(): this.inputController.right(); } else if(deltaY > 0) { this.inputController.down(); } this.xStart = null; this.yStart = null; };
function TouchInput(inputController, element) { this.inputController = inputController; this.element = typeof element !== 'undefined' ? element : document; } TouchInput.prototype.listen = function() { this.element.addEventListener('touchstart', this.startTouch.bind(this)); this.element.addEventListener('touchmove', this.detectSwipe.bind(this)); }; TouchInput.prototype.startTouch = function(event) { this.xStart = event.touches[0].clientX; this.yStart = event.touches[0].clientY; }; TouchInput.prototype.detectSwipe = function(event) { if( this.xStart === null || this.yStart === null) { return; } var xEnd = event.touches[0].clientX; var yEnd = event.touches[0].clientY; var deltaX = xEnd - this.xStart; var deltaY = yEnd - this.yStart; var isHorizontalSwipe = Math.abs(deltaX) > Math.abs(deltaY); if(isHorizontalSwipe) { deltaX < 0 ? this.inputController.left(): this.inputController.right(); } else if(deltaY > 0) { this.inputController.down(); } this.xStart = null; this.yStart = null; };
Add element binding to touch input
Add element binding to touch input
JavaScript
mit
mnito/factors-game,mnito/factors-game
--- +++ @@ -1,10 +1,11 @@ -function TouchInput(inputController) { +function TouchInput(inputController, element) { this.inputController = inputController; + this.element = typeof element !== 'undefined' ? element : document; } TouchInput.prototype.listen = function() { - document.addEventListener('touchstart', this.startTouch.bind(this)); - document.addEventListener('touchmove', this.detectSwipe.bind(this)); + this.element.addEventListener('touchstart', this.startTouch.bind(this)); + this.element.addEventListener('touchmove', this.detectSwipe.bind(this)); }; TouchInput.prototype.startTouch = function(event) {
e3f9fd07b08f30067d055dcbb1ce2558c776f81e
src/controllers/SpotifyController.js
src/controllers/SpotifyController.js
if (!!document.querySelector('#app-player')) { // Old Player controller = new BasicController({ supports: { playpause: true, next: true, previous: true }, useLazyObserving: true, frameSelector: '#app-player', playStateSelector: '#play-pause', playStateClass: 'playing', playPauseSelector: '#play-pause', nextSelector: '#next', previousSelector: '#previous', titleSelector: '#track-name', artistSelector: '#track-artist' }); controller.override('getAlbumArt', function() { return document.querySelector(this.frameSelector).contentDocument.querySelector('#cover-art .sp-image-img').style.backgroundImage.slice(4, -1); }); } else { // New Player controller = new BasicController({ supports: { playpause: true, next: true, previous: true }, useLazyObserving: true, frameSelector: '#main', playStateSelector: '#play', playStateClass: 'playing', playPauseSelector: '#play', nextSelector: '#next', previousSelector: '#previous', titleSelector: '.caption .track', artistSelector: '.caption .artist' }); controller.override('getAlbumArt', function() { return document.querySelector(this.frameSelector).contentDocument.querySelector('#large-cover-image').style.backgroundImage.slice(4, -1); }); }
var config = { supports: { playpause: true, next: true, previous: true }, useLazyObserving: true, playStateClass: 'playing', nextSelector: '#next', previousSelector: '#previous' } if (document.querySelector('#app-player')) { // Old Player config.artworkImageSelector = '#cover-art .sp-image-img'; config.frameSelector = '#app-player'; config.playStateSelector = '#play-pause'; config.playPauseSelector = '#play-pause'; config.titleSelector = '#track-name'; config.artistSelector = '#track-artist'; } else { // New Player config.artworkImageSelector = '#large-cover-image'; config.frameSelector = '#main'; config.playStateSelector = '#play'; config.playPauseSelector = '#pause'; config.titleSelector = '.caption .track'; config.artistSelector = '.caption .artist'; } controller = new BasicController(config); controller.override('getAlbumArt', function() { var img = this.doc().querySelector(this.artworkImageSelector); return img && img.style.backgroundImage.slice(5, -2); });
Fix album art retrieved from Spotify
Fix album art retrieved from Spotify Remove double quotes around image URL retrieved from Spotify by slicing one character more from left and one character more from right. Also, remove redundant code and null errors to console when element is not found. Signed-off-by: Tomas Slusny <71c4488fd0941e24cd13e3ad13ef1eb0a5fe5168@gmail.com>
JavaScript
agpl-3.0
msfeldstein/chrome-media-keys,PeterMinin/chrome-media-keys,PeterMinin/chrome-media-keys
--- +++ @@ -1,43 +1,33 @@ -if (!!document.querySelector('#app-player')) { // Old Player - controller = new BasicController({ - supports: { +var config = { + supports: { playpause: true, next: true, previous: true - }, - useLazyObserving: true, - frameSelector: '#app-player', - playStateSelector: '#play-pause', - playStateClass: 'playing', - playPauseSelector: '#play-pause', - nextSelector: '#next', - previousSelector: '#previous', - titleSelector: '#track-name', - artistSelector: '#track-artist' - }); + }, + useLazyObserving: true, + playStateClass: 'playing', + nextSelector: '#next', + previousSelector: '#previous' +} - controller.override('getAlbumArt', function() { - return document.querySelector(this.frameSelector).contentDocument.querySelector('#cover-art .sp-image-img').style.backgroundImage.slice(4, -1); - }); +if (document.querySelector('#app-player')) { // Old Player + config.artworkImageSelector = '#cover-art .sp-image-img'; + config.frameSelector = '#app-player'; + config.playStateSelector = '#play-pause'; + config.playPauseSelector = '#play-pause'; + config.titleSelector = '#track-name'; + config.artistSelector = '#track-artist'; } else { // New Player - controller = new BasicController({ - supports: { - playpause: true, - next: true, - previous: true - }, - useLazyObserving: true, - frameSelector: '#main', - playStateSelector: '#play', - playStateClass: 'playing', - playPauseSelector: '#play', - nextSelector: '#next', - previousSelector: '#previous', - titleSelector: '.caption .track', - artistSelector: '.caption .artist' - }); + config.artworkImageSelector = '#large-cover-image'; + config.frameSelector = '#main'; + config.playStateSelector = '#play'; + config.playPauseSelector = '#pause'; + config.titleSelector = '.caption .track'; + config.artistSelector = '.caption .artist'; +} - controller.override('getAlbumArt', function() { - return document.querySelector(this.frameSelector).contentDocument.querySelector('#large-cover-image').style.backgroundImage.slice(4, -1); - }); -} +controller = new BasicController(config); +controller.override('getAlbumArt', function() { + var img = this.doc().querySelector(this.artworkImageSelector); + return img && img.style.backgroundImage.slice(5, -2); +});
9bec9dd156f97a1d00bf57a5badedebece295844
packages/@sanity/form-builder/src/inputs/BlockEditor-slate/toolbar/LinkButton.js
packages/@sanity/form-builder/src/inputs/BlockEditor-slate/toolbar/LinkButton.js
import React, {PropTypes} from 'react' import ToggleButton from 'part:@sanity/components/toggles/button' import LinkIcon from 'part:@sanity/base/sanity-logo-icon' import styles from './styles/LinkButton.css' export default class LinkButton extends React.Component { static propTypes = { onClick: PropTypes.func, activeLink: PropTypes.bool } handleToggleButtonClick = () => { this.props.onClick(this.props.activeLink) } render() { return ( <div style={{position: 'relative'}}> <ToggleButton onClick={this.handleToggleButtonClick} title={'Link'} className={styles.button} > <div className={styles.iconContainer}> <LinkIcon /> </div> </ToggleButton> </div> ) } }
import React, {PropTypes} from 'react' import ToggleButton from 'part:@sanity/components/toggles/button' import LinkIcon from 'part:@sanity/base/link-icon' import styles from './styles/LinkButton.css' export default class LinkButton extends React.Component { static propTypes = { onClick: PropTypes.func, activeLink: PropTypes.bool } handleToggleButtonClick = () => { this.props.onClick(this.props.activeLink) } render() { const {activeLink} = this.props return ( <div style={{position: 'relative'}}> <ToggleButton onClick={this.handleToggleButtonClick} title={'Link'} selected={activeLink} className={styles.button} > <div className={styles.iconContainer}> <LinkIcon /> </div> </ToggleButton> </div> ) } }
Use link icon for link button
[form-builder] Use link icon for link button
JavaScript
mit
sanity-io/sanity,sanity-io/sanity,sanity-io/sanity,sanity-io/sanity
--- +++ @@ -1,7 +1,7 @@ import React, {PropTypes} from 'react' import ToggleButton from 'part:@sanity/components/toggles/button' -import LinkIcon from 'part:@sanity/base/sanity-logo-icon' +import LinkIcon from 'part:@sanity/base/link-icon' import styles from './styles/LinkButton.css' export default class LinkButton extends React.Component { @@ -16,11 +16,13 @@ } render() { + const {activeLink} = this.props return ( <div style={{position: 'relative'}}> <ToggleButton onClick={this.handleToggleButtonClick} title={'Link'} + selected={activeLink} className={styles.button} > <div className={styles.iconContainer}>
1aa3c6485e5c6d04480332e64ee848930fcbba70
configurations/react.js
configurations/react.js
module.exports = { "extends": "justinlocsei/configurations/es6", "ecmaFeatures": { "jsx": true }, "env": { "browser": true }, "plugins": [ "react" ], "rules": { "jsx-quotes": [2, "prefer-double"], "react/jsx-boolean-value": [2, "always"], "react/jsx-curly-spacing": [2, "never"], "react/jsx-handler-names": 2, "react/jsx-no-bind": 2, "react/jsx-no-duplicate-props": [2, {"ignoreCase": true}], "react/jsx-no-undef": 2, "react/jsx-pascal-case": 2, "react/jsx-uses-vars": 2, "react/no-did-mount-set-state": 2, "react/no-did-update-set-state": 2, "react/no-direct-mutation-state": 2, "react/no-multi-comp": 2, "react/no-unknown-property": 2, "react/prop-types": 2, "react/self-closing-comp": 2, "react/wrap-multilines": 2 } };
module.exports = { "extends": "justinlocsei/configurations/es6", "ecmaFeatures": { "jsx": true }, "env": { "browser": true }, "plugins": [ "react" ], "rules": { "jsx-quotes": [2, "prefer-double"], "react/jsx-boolean-value": [2, "always"], "react/jsx-curly-spacing": [2, "never"], "react/jsx-handler-names": 2, "react/jsx-no-bind": 2, "react/jsx-no-duplicate-props": [2, {"ignoreCase": true}], "react/jsx-no-undef": 2, "react/jsx-pascal-case": 2, "react/jsx-uses-vars": 2, "react/jsx-wrap-multilines": 2, "react/no-did-mount-set-state": 2, "react/no-did-update-set-state": 2, "react/no-direct-mutation-state": 2, "react/no-multi-comp": 2, "react/no-unknown-property": 2, "react/prop-types": 2, "react/self-closing-comp": 2 } };
Update the named of a renamed React check
Update the named of a renamed React check
JavaScript
mit
justinlocsei/eslint-config-chiton
--- +++ @@ -19,14 +19,14 @@ "react/jsx-no-undef": 2, "react/jsx-pascal-case": 2, "react/jsx-uses-vars": 2, + "react/jsx-wrap-multilines": 2, "react/no-did-mount-set-state": 2, "react/no-did-update-set-state": 2, "react/no-direct-mutation-state": 2, "react/no-multi-comp": 2, "react/no-unknown-property": 2, "react/prop-types": 2, - "react/self-closing-comp": 2, - "react/wrap-multilines": 2 + "react/self-closing-comp": 2 } };
19b9def70f2bb1e827ba428527ebab8910ac46e2
app/documents/controllers/SearchController.js
app/documents/controllers/SearchController.js
module.exports = function($scope, $state, $location, $http, GlobalService, DocumentService, DocumentApiService, MathJaxService, QueryParser) { $scope.doSearch = function(){ var apiServer = GlobalService.apiServer() var query = QueryParser.parse($scope.searchText) console.log('query = ' + query) $http.get('http://' + apiServer + '/v1/documents' + '?' + query ) .then(function(response){ console.log(response.data['status']) console.log('Number of documents: ' + response.data['document_count']) var jsonData = response.data var documents = jsonData['documents'] DocumentService.setDocumentList(documents) var id = documents[0]['id'] console.log('SearchController, id: ' + id) DocumentApiService.getDocument(id) .then(function(response) { console.log('CURRENT STATE: ' + $state.current) $state.go('documents') $state.reload() $scope.$watch(function(scope) { return $scope.renderedText }, MathJaxService.reload('SearchController') ); }) }); }; }
module.exports = function($scope, $state, $location, $http, GlobalService, DocumentService, DocumentApiService, MathJaxService, QueryParser) { $scope.doSearch = function(){ var apiServer = GlobalService.apiServer() var query = QueryParser.parse($scope.searchText) console.log('query = ' + query) $http.get('http://' + apiServer + '/v1/documents' + '?' + query ) .then(function(response){ console.log(response.data['status']) console.log('Number of documents: ' + response.data['document_count']) var jsonData = response.data var documents = jsonData['documents'] DocumentService.setDocumentList(documents) var id = documents[0]['id'] console.log('SearchController, id: ' + id) DocumentApiService.getDocument(id) .then(function(response) { console.log('Document " + id + ' retrieved') console.log('CURRENT STATE: ' + $state.current) $state.go('documents') $state.reload() $scope.$watch(function(scope) { return $scope.renderedText }, MathJaxService.reload('SearchController') ); }) }); }; }
Fix search problem (but how??)
Fix search problem (but how??)
JavaScript
mit
jxxcarlson/ns_angular,jxxcarlson/ns_angular
--- +++ @@ -18,6 +18,7 @@ DocumentApiService.getDocument(id) .then(function(response) { + console.log('Document " + id + ' retrieved') console.log('CURRENT STATE: ' + $state.current) $state.go('documents') $state.reload()
a3e9428d38522008b933e258588bcc91868174d3
src/services/content/index.js
src/services/content/index.js
'use strict'; const request = require('request-promise-native'); const querystring = require('querystring'); const hooks = require('./hooks'); class Service { constructor(options) { this.options = options || {}; } find(params) { const options = {}; if(params.query.$limit) options["page[limit]"] = params.query.$limit; if(params.query.$skip) options["page[offset]"] = params.query.$skip; if(params.query.query) options.query = params.query.query; const contentServerUrl = `https://schul-cloud.org:8090/contents?${querystring.encode(options)}`; return request(contentServerUrl).then(string => { return JSON.parse(string); }); } /*get(id, params) { return Promise.resolve({ id, text: `A new message with ID: ${id}!` }); }*/ } module.exports = function () { const app = this; // Initialize our service with any options it requires app.use('/contents', new Service()); // Get our initialize service to that we can bind hooks const contentService = app.service('/contents'); // Set up our before hooks contentService.before(hooks.before); // Set up our after hooks contentService.after(hooks.after); }; module.exports.Service = Service;
'use strict'; const request = require('request-promise-native'); const querystring = require('querystring'); const hooks = require('./hooks'); class Service { constructor(options) { this.options = options || {}; } find(params) { const options = {}; if(params.query.$limit) options["page[limit]"] = params.query.$limit; if(params.query.$skip) options["page[offset]"] = params.query.$skip; if(params.query.query) options.query = params.query.query; const contentServerUrl = `https://schul-cloud.org:8090/contents?${querystring.encode(options)}`; return request(contentServerUrl).then(string => { let result = JSON.parse(string); result.total = result.meta.page.total; result.limit = result.meta.page.limit; result.skip = result.meta.page.offset; return result; }); } /*get(id, params) { return Promise.resolve({ id, text: `A new message with ID: ${id}!` }); }*/ } module.exports = function () { const app = this; // Initialize our service with any options it requires app.use('/contents', new Service()); // Get our initialize service to that we can bind hooks const contentService = app.service('/contents'); // Set up our before hooks contentService.before(hooks.before); // Set up our after hooks contentService.after(hooks.after); }; module.exports.Service = Service;
Add result page information in feathers format
Add result page information in feathers format
JavaScript
agpl-3.0
schul-cloud/schulcloud-server,schul-cloud/schulcloud-server,schul-cloud/schulcloud-server
--- +++ @@ -17,7 +17,11 @@ const contentServerUrl = `https://schul-cloud.org:8090/contents?${querystring.encode(options)}`; return request(contentServerUrl).then(string => { - return JSON.parse(string); + let result = JSON.parse(string); + result.total = result.meta.page.total; + result.limit = result.meta.page.limit; + result.skip = result.meta.page.offset; + return result; }); }
1941cfca63e0874c8bd71a24f27a80a66532a9f1
config.js
config.js
var config = module.exports = exports = {} config.items = { tmpDir: { def: 'tmp' } , outDir: { def: 'out' } , originalsPath: { def: 'originals' } , maxCols: { def: 10 } , maxTries: { def: 6 } , invalidRequestMessage: { def: "Invalid request. Make sure you are respecting the sprite maker api (https://github.com/vigour-io/vigour-img/blob/master/README.md#user-content-api) and that the requested data exists." } , port: { def: 8000 } , maxWidth: { def: 10000 } , maxHeight: { def: 10000 } , minFreeSpace: { def: 0.01 } } config.files = { def: null , env: "IMG_CONFIG" }
var config = module.exports = exports = {} config.items = { tmpDir: { def: 'tmp' } , outDir: { def: 'out' } , originalsPath: { def: 'originals' } , maxCols: { def: 10 } , maxTries: { def: 6 } , invalidRequestMessage: { def: "Invalid request. Make sure you are respecting the sprite maker api (https://github.com/vigour-io/vigour-img/blob/master/README.md#user-content-api) and that the requested data exists." } , port: { def: 8000 , cli: "-p, --port <nb>" , desc: "Port on which the server should listen" } , maxWidth: { def: 10000 } , maxHeight: { def: 10000 } , minFreeSpace: { def: 0.01 } } config.files = { def: null , env: "IMG_CONFIG" }
Add command-line option to change port
Add command-line option to change port
JavaScript
isc
vigour-io/shutter,vigour-io/vigour-img
--- +++ @@ -14,7 +14,10 @@ , invalidRequestMessage: { def: "Invalid request. Make sure you are respecting the sprite maker api (https://github.com/vigour-io/vigour-img/blob/master/README.md#user-content-api) and that the requested data exists." } , port: - { def: 8000 } + { def: 8000 + , cli: "-p, --port <nb>" + , desc: "Port on which the server should listen" + } , maxWidth: { def: 10000 } , maxHeight:
4211ee0bc2e124f5807fc6ad538896e60d6cef7d
lib/scan.js
lib/scan.js
'use strict'; var glob = require('glob'), _ = require('lodash'), async = require('async'), fs = require('fs'), lex = require('./lex'); function isFile(path) { var stat = fs.statSync(path); return stat.isFile(); } function getStrings(path, done) { glob(path, function(er, files) { var tokens = []; files = files.filter(isFile); async.reduce(files, tokens, function(tokens, file, next) { fs.readFile(file, function(err, src) { if (err) return next(); if (src.length === 0) return next(); tokens.push(lex(src.toString())); return next(null, tokens); }); }, done); }); } function scan(path, done) { getStrings(path, function(err, results) { var strings = []; if (err) return done(err, strings); strings = results.reduce(function(strings, result) { return strings.concat(result); }, []); return done(null, _.uniq(strings).sort()); }); } module.exports = scan;
'use strict'; var glob = require('glob'), _ = require('lodash'), async = require('async'), fs = require('fs'), lex = require('./lex'); function isFile(path) { var stat = fs.statSync(path); return stat.isFile(); } function getStrings(path, done) { glob(path, function(er, files) { var tokens = []; files = files.filter(isFile); async.reduce(files, tokens, function(tokens, file, next) { fs.readFile(file, function(err, src) { if (err) return next(); if (src.length === 0) return next(null, tokens); tokens.push(lex(src.toString())); return next(null, tokens); }); }, done); }); } function scan(path, done) { getStrings(path, function(err, results) { var strings = []; if (err) return done(err, strings); strings = results.reduce(function(strings, result) { return strings.concat(result); }, []); return done(null, _.uniq(strings).sort()); }); } module.exports = scan;
Fix to ensure that tokens is not undefined on the next iteration when the previous file was empty
Fix to ensure that tokens is not undefined on the next iteration when the previous file was empty
JavaScript
mit
onepercentclub/extract-gettext
--- +++ @@ -20,7 +20,7 @@ async.reduce(files, tokens, function(tokens, file, next) { fs.readFile(file, function(err, src) { if (err) return next(); - if (src.length === 0) return next(); + if (src.length === 0) return next(null, tokens); tokens.push(lex(src.toString())); return next(null, tokens);
be15a5d1d5f7b694728017494d217972d6481fd5
services/general_response.js
services/general_response.js
/** * General functions */ var general = {}; //General 404 error general.send404 = function(res){ res.status(404); res.jsonp({error: 'Not found'}); res.end(); }; //General 500 error general.send500 = function(res, msg){ res.status(500); res.jsonp({error:'Server error ' + msg}); res.end(); }; general.getOptions = function(res){ res.json({"Get Patients": "/patients", "Get One Patient": "/patient"`}); res.end(); }; module.exports = general;
/** * General functions */ var general = {}; //General 404 error general.send404 = function(res){ res.status(404); res.jsonp({error: 'Not found'}); res.end(); }; //General 500 error general.send500 = function(res, msg){ res.status(500); res.jsonp({error:'Server error ' + msg}); res.end(); }; general.getOptions = function(res){ res.json({"Get Patients": "/patients", "Get One Patient": "/patient"}); res.end(); }; module.exports = general;
Fix typo on getOptions response
Fix typo on getOptions response
JavaScript
mit
NextCenturyCorporation/healthcare-demo,NextCenturyCorporation/healthcare-demo,NextCenturyCorporation/healthcare-demo
--- +++ @@ -19,7 +19,7 @@ general.getOptions = function(res){ res.json({"Get Patients": "/patients", - "Get One Patient": "/patient"`}); + "Get One Patient": "/patient"}); res.end(); };
26742b0534c27cb9c615c182a867afa191d06bc2
static/js/states/adminHome.js
static/js/states/adminHome.js
define([ 'app' ], function(app) { 'use strict'; return { parent: 'admin_layout', url: '', templateUrl: 'partials/admin/home.html', controller: function($scope, $http, flash) { $scope.loading = true; $http.get('/api/0/systemstats/').success(function(data){ $scope.statusCounts = data.statusCounts; $scope.resultCounts = data.resultCounts; }).error(function(){ flash('error', 'There was an error loading system statistics.'); }).finally(function(){ $scope.loading = false; }); } }; });
define([ 'app' ], function(app) { 'use strict'; return { parent: 'admin_layout', url: '', templateUrl: 'partials/admin/home.html', controller: function($scope, $http, flash) { var timeoutId; $scope.loading = true; $scope.$on('$destory', function(){ if (timeoutId) { window.cancelTimeout(timeoutId); } }); function tick() { $http.get('/api/0/systemstats/').success(function(data){ $scope.statusCounts = data.statusCounts; $scope.resultCounts = data.resultCounts; }).error(function(){ flash('error', 'There was an error loading system statistics.'); }).finally(function(){ $scope.loading = false; }); timeoutId = window.setTimeout(tick, 5000); } tick(); } }; });
Add polling for system stats
Add polling for system stats
JavaScript
apache-2.0
dropbox/changes,bowlofstew/changes,wfxiang08/changes,wfxiang08/changes,bowlofstew/changes,wfxiang08/changes,wfxiang08/changes,dropbox/changes,bowlofstew/changes,bowlofstew/changes,dropbox/changes,dropbox/changes
--- +++ @@ -8,16 +8,30 @@ url: '', templateUrl: 'partials/admin/home.html', controller: function($scope, $http, flash) { + var timeoutId; + $scope.loading = true; - $http.get('/api/0/systemstats/').success(function(data){ - $scope.statusCounts = data.statusCounts; - $scope.resultCounts = data.resultCounts; - }).error(function(){ - flash('error', 'There was an error loading system statistics.'); - }).finally(function(){ - $scope.loading = false; + $scope.$on('$destory', function(){ + if (timeoutId) { + window.cancelTimeout(timeoutId); + } }); + + function tick() { + $http.get('/api/0/systemstats/').success(function(data){ + $scope.statusCounts = data.statusCounts; + $scope.resultCounts = data.resultCounts; + }).error(function(){ + flash('error', 'There was an error loading system statistics.'); + }).finally(function(){ + $scope.loading = false; + }); + + timeoutId = window.setTimeout(tick, 5000); + } + + tick(); } }; });
30728328443fd659a605850d27cb0925a941ac78
server/index.js
server/index.js
'use strict'; const app = require('./app'); const db = require('../db'); const PORT = process.env.PORT || 3000; const path = require('path'); app.listen(PORT, () => { console.log('Example app listening on port 3000!'); });
'use strict'; const app = require('./app'); const db = require('../db'); const PORT = process.env.PORT || 3000; const path = require('path'); app.listen(PORT, () => { console.log('Example app listening on port ' + PORT); });
Change the console log to show proper port
Change the console log to show proper port
JavaScript
mit
FuriousFridges/FuriousFridges,FuriousFridges/FuriousFridges
--- +++ @@ -5,5 +5,5 @@ const path = require('path'); app.listen(PORT, () => { - console.log('Example app listening on port 3000!'); + console.log('Example app listening on port ' + PORT); });
23a9512ffcad024bd7e51db5f7677b2688dcc2cd
server/trips/pastTripModel.js
server/trips/pastTripModel.js
// Todo Implement and export schema using mongoose // Reference angular sprint var mongoose = require('mongoose'); //var User = require('../users/UserModel.js'); var Schema = mongoose.Schema; var PastTripSchema = new Schema({ creator: { id:{ type: Schema.Types.ObjectId, ref: 'User' }, username: {type: String} }, participants: [{ id:{ type: Schema.Types.ObjectId, ref: 'User' }, username: {type: String} }], name: { type: String, required: true }, code: { type: String, required: true }, expenses: [ { name: String, amount: Number, date: Date, location: Schema.Types.Mixed, payer: { id:{ type: Schema.Types.ObjectId, ref: 'User' }, username: {type: String} }, stakeholders: [{ id:{ type: Schema.Types.ObjectId, ref: 'User' }, username: {type: String} }], } ], summary: [] }); module.exports = mongoose.model('pasttrips', PastTripSchema);
// Todo Implement and export schema using mongoose // Reference angular sprint var mongoose = require('mongoose'); //var User = require('../users/UserModel.js'); var Schema = mongoose.Schema; var PastTripSchema = new Schema({ creator: { id:{ type: Schema.Types.ObjectId, ref: 'User' }, username: {type: String} }, participants: [{ id:{ type: Schema.Types.ObjectId, ref: 'User' }, username: {type: String} }], name: { type: String, required: true }, code: { type: String, required: true }, expenses: [ { name: String, amount: Number, date: Date, locationString: String, expenseString: String, location: Schema.Types.Mixed, payer: { id:{ type: Schema.Types.ObjectId, ref: 'User' }, username: {type: String} }, stakeholders: [{ id:{ type: Schema.Types.ObjectId, ref: 'User' }, username: {type: String} }], } ], summary: [] }); module.exports = mongoose.model('pasttrips', PastTripSchema);
Add location and expense strings to pastTrip model
Add location and expense strings to pastTrip model
JavaScript
mit
OrgulousArtichoke/vacaypay,OrgulousArtichoke/vacaypay
--- +++ @@ -33,6 +33,8 @@ name: String, amount: Number, date: Date, + locationString: String, + expenseString: String, location: Schema.Types.Mixed, payer: { id:{
1a09bb1a60eaace841526c22b3d08d295082227a
test/filters/travis_filter.js
test/filters/travis_filter.js
"use strict"; var TravisFilter = function(name) { console.dir(process.env) name = name || "ON_TRAVIS"; // Get environmental variables that are known this.filter = function(test) { if(test.metadata == null) return false; if(test.metadata.ignore == null) return false; if(test.metadata.ignore.travis == null) return false; if(process.env[name] && test.metadata.ignore.travis == true) return true; return false; } } module.exports = TravisFilter;
"use strict"; var TravisFilter = function(name) { // console.dir(process.env) name = name || "TRAVIS_JOB_ID"; // Get environmental variables that are known this.filter = function(test) { if(test.metadata == null) return false; if(test.metadata.ignore == null) return false; if(test.metadata.ignore.travis == null) return false; if(process.env[name] != null && test.metadata.ignore.travis == true) return true; return false; } } module.exports = TravisFilter;
Fix ignore tests for travis
Fix ignore tests for travis
JavaScript
apache-2.0
mongodb/node-mongodb-native,mongodb/node-mongodb-native,capaj/node-mongodb-native,zhangyaoxing/node-mongodb-native,tuyndv/node-mongodb-native,thenaughtychild/node-mongodb-native,jqk6/node-mongodb-native,sarathms/node-mongodb-native,agclever/node-mongodb-native,amit777/node-mongodb-native,flyingfisher/node-mongodb-native,janaipakos/node-mongodb-native,nahidcse05/node-mongodb-native,Samicelus/node-mongodb-native,mvnnn/node-mongodb-native,HBOCodeLabs/node-mongodb-native,segmentio/node-mongodb-native,elijah513/node-mongodb-native,HiLittleCat/node-mongodb-native,patriksimek/node-mongodb-native,mongodb/node-mongodb-native,beni55/node-mongodb-native,d-mon-/node-mongodb-native,Lapixx/node-mongodb-native,christophehurpeau/node-mongodb-native,mongodb/node-mongodb-native,hgGeorg/node-mongodb-native,rafkhan/node-mongodb-native,pakokrew/node-mongodb-native,PeterWangPo/node-mongodb-native
--- +++ @@ -1,14 +1,14 @@ "use strict"; var TravisFilter = function(name) { - console.dir(process.env) - name = name || "ON_TRAVIS"; + // console.dir(process.env) + name = name || "TRAVIS_JOB_ID"; // Get environmental variables that are known this.filter = function(test) { if(test.metadata == null) return false; if(test.metadata.ignore == null) return false; if(test.metadata.ignore.travis == null) return false; - if(process.env[name] && test.metadata.ignore.travis == true) return true; + if(process.env[name] != null && test.metadata.ignore.travis == true) return true; return false; } }
ddb7437159ac6f01d84f59864b6e7708f0371df5
scripts/build.js
scripts/build.js
#!/usr/bin/env node var colors = require('colors'), exec = require('child_process').exec, pkg = require('../package.json'), preamble = '/*!\n' + ' * RadioRadio ' + pkg.version + '\n' + ' *\n' + ' * ' + pkg.description + '\n' + ' *\n' + ' * Source code available at: ' + pkg.homepage + '\n' + ' *\n' + ' * (c) 2015-present ' + pkg.author.name + ' (' + pkg.author.url + ')\n' + ' *\n' + ' * RadioRadio may be freely distributed under the ' + pkg.license + ' license.\n' + ' */\n'; exec('uglifyjs src/radioradio.js --beautify "indent-level=2" --preamble "' + preamble + '" --output dist/radioradio.js'); exec('uglifyjs src/radioradio.js --compress --mangle --preamble "' + preamble + '" --output dist/radioradio.min.js'); console.log(colors.green('RadioRadio %s built successfully!'), pkg.version);
#!/usr/bin/env node var colors = require('colors'), exec = require('child_process').exec, pkg = require('../package.json'), preamble = '/*!\n' + ' * RadioRadio ' + pkg.version + '\n' + ' *\n' + ' * ' + pkg.description + '\n' + ' *\n' + ' * Source code available at: ' + pkg.homepage + '\n' + ' *\n' + ' * (c) 2015-present ' + pkg.author.name + ' (' + pkg.author.url + ')\n' + ' *\n' + ' * RadioRadio may be freely distributed under the ' + pkg.license + ' license.\n' + ' */\n'; exec('$(npm bin)/uglifyjs src/radioradio.js --beautify "indent-level=2" --preamble "' + preamble + '" --output dist/radioradio.js'); exec('$(npm bin)/uglifyjs src/radioradio.js --compress --mangle --preamble "' + preamble + '" --output dist/radioradio.min.js'); console.log(colors.green('RadioRadio %s built successfully!'), pkg.version);
Add 'npm bin' to uglifyjs command.
Add 'npm bin' to uglifyjs command.
JavaScript
mit
jgarber623/RadioRadio,jgarber623/RadioRadio
--- +++ @@ -15,7 +15,7 @@ ' * RadioRadio may be freely distributed under the ' + pkg.license + ' license.\n' + ' */\n'; -exec('uglifyjs src/radioradio.js --beautify "indent-level=2" --preamble "' + preamble + '" --output dist/radioradio.js'); -exec('uglifyjs src/radioradio.js --compress --mangle --preamble "' + preamble + '" --output dist/radioradio.min.js'); +exec('$(npm bin)/uglifyjs src/radioradio.js --beautify "indent-level=2" --preamble "' + preamble + '" --output dist/radioradio.js'); +exec('$(npm bin)/uglifyjs src/radioradio.js --compress --mangle --preamble "' + preamble + '" --output dist/radioradio.min.js'); console.log(colors.green('RadioRadio %s built successfully!'), pkg.version);
55de12e099a43807e473cb5901439796804a3186
material.js
material.js
const Signal = require('signals') let MaterialID = 0 function Material (opts) { this.type = 'Material' this.id = 'Material_' + MaterialID++ this.changed = new Signal() this._uniforms = {} const ctx = opts.ctx this.baseColor = [0.95, 0.95, 0.95, 1] this.emissiveColor = [0, 0, 0, 1] this.metallic = 0.01 this.roughness = 0.5 this.displacement = 0 this.depthTest = true this.depthWrite = true this.depthFunc = opts.ctx.DepthFunc.LessEqual this.blendEnabled = false this.blendSrcRGBFactor = ctx.BlendFactor.ONE this.blendSrcAlphaFactor = ctx.BlendFactor.ONE this.blendDstRGBFactor = ctx.BlendFactor.ONE this.blendDstAlphaFactor = ctx.BlendFactor.ONE this.castShadows = false this.receiveShadows = false this.set(opts) } Material.prototype.init = function (entity) { this.entity = entity } Material.prototype.set = function (opts) { Object.assign(this, opts) Object.keys(opts).forEach((prop) => this.changed.dispatch(prop)) } module.exports = function (opts) { return new Material(opts) }
const Signal = require('signals') let MaterialID = 0 function Material (opts) { this.type = 'Material' this.id = 'Material_' + MaterialID++ this.changed = new Signal() this._uniforms = {} const ctx = opts.ctx this.baseColor = [0.95, 0.95, 0.95, 1] this.emissiveColor = [0, 0, 0, 1] this.metallic = 0.01 this.roughness = 0.5 this.displacement = 0 this.depthTest = true this.depthWrite = true this.depthFunc = opts.ctx.DepthFunc.LessEqual this.blendEnabled = false this.blendSrcRGBFactor = ctx.BlendFactor.ONE this.blendSrcAlphaFactor = ctx.BlendFactor.ONE this.blendDstRGBFactor = ctx.BlendFactor.ONE this.blendDstAlphaFactor = ctx.BlendFactor.ONE this.castShadows = false this.receiveShadows = false this.cullFaceEnabled = true this.set(opts) } Material.prototype.init = function (entity) { this.entity = entity } Material.prototype.set = function (opts) { Object.assign(this, opts) Object.keys(opts).forEach((prop) => this.changed.dispatch(prop)) } module.exports = function (opts) { return new Material(opts) }
Enable face culling by default
Enable face culling by default
JavaScript
mit
pex-gl/pex-renderer,pex-gl/pex-renderer
--- +++ @@ -26,6 +26,7 @@ this.blendDstAlphaFactor = ctx.BlendFactor.ONE this.castShadows = false this.receiveShadows = false + this.cullFaceEnabled = true this.set(opts) }
6437817486b732fb9d298ce14e363db13b07f43a
src/providers/mailer.js
src/providers/mailer.js
var util = require('util'), _ = require('lodash'), vow = require('vow'), nm = require('nodemailer'), transport = require('nodemailer-smtp-transport'), errors = require('../errors').Mailer, logger = require('./../logger'), mailer; module.exports = { /** * Initialize mailer module */ init: function (options) { logger.info('Initialize e-mail sending module', module); if (!options) { errors.createError(errors.CODES.MAILER_NOT_CONFIGURED).log('warn'); return vow.resolve(); } mailer = new nm.createTransport(transport({ host: options.host, port: options.port })); return vow.resolve(mailer); }, /** * Email sending * @param {Object} options - e-mail options object * @returns {*} */ send: function (options) { var base = { encoding: 'utf-8' }; logger.info(util.format('send email //subject: %s //body: %s', options.subject, options.text), module); if (!mailer) { errors.createError(errors.CODES.NOT_INITIALIZED).log(); return vow.resolve(); } var def = vow.defer(); mailer.sendMail(_.extend({}, base, options), function (err) { errors.createError(errors.CODES.COMMON, { err: err }).log(); err ? def.reject(err) : def.resolve(); }); return def.promise(); } };
var util = require('util'), _ = require('lodash'), vow = require('vow'), nm = require('nodemailer'), transport = require('nodemailer-smtp-transport'), errors = require('../errors').Mailer, logger = require('./../logger'), mailer; module.exports = { /** * Initialize mailer module */ init: function (options) { logger.info('Initialize e-mail sending module', module); if (!options) { errors.createError(errors.CODES.MAILER_NOT_CONFIGURED).log('warn'); return vow.resolve(); } mailer = new nm.createTransport(transport({ host: options.host, port: options.port })); return vow.resolve(mailer); }, /** * Email sending * @param {Object} options - e-mail options object * @returns {*} */ send: function (options) { var base = { encoding: 'utf-8' }; logger.info(util.format('send email //subject: %s //body: %s', options.subject, options.text), module); if (!mailer) { errors.createError(errors.CODES.NOT_INITIALIZED).log(); return vow.resolve(); } var def = vow.defer(); mailer.sendMail(_.extend({}, base, options), function (err) { if (err) { errors.createError(errors.CODES.COMMON, { err: err }).log(); def.reject(err); } else { def.resolve(); } }); return def.promise(); } };
Fix error with invalid error message while sending e-mail
Fix error with invalid error message while sending e-mail
JavaScript
mpl-2.0
bem-site/bse-admin,bem-site/bse-admin
--- +++ @@ -45,8 +45,12 @@ var def = vow.defer(); mailer.sendMail(_.extend({}, base, options), function (err) { - errors.createError(errors.CODES.COMMON, { err: err }).log(); - err ? def.reject(err) : def.resolve(); + if (err) { + errors.createError(errors.CODES.COMMON, { err: err }).log(); + def.reject(err); + } else { + def.resolve(); + } }); return def.promise();
b57a4d2ed50d373248041ec278e20e7bab8d0643
test/specs/operations.spec.js
test/specs/operations.spec.js
describe('Operations', function () { var isNode = typeof module !== 'undefined' && module.exports; var Parallel = isNode ? require('../../lib/parallel.js') : self.Parallel; it('should require(), map() and reduce correctly (check console errors)', function () { var p = new Parallel([0, 1, 2, 3, 4, 5, 6, 7, 8], { evalPath: isNode ? undefined : 'lib/eval.js' }); function add(d) { return d[0] + d[1]; } function factorial(n) { return n < 2 ? 1 : n * factorial(n - 1); } p.require(factorial); var done = false; runs(function () { p.map(function (n) { return Math.pow(10, n); }).reduce(add).then(function() { done = true; }); }); waitsFor(function () { return done; }, "it should finish", 500); }); });
describe('Operations', function () { var isNode = typeof module !== 'undefined' && module.exports; var Parallel = isNode ? require('../../lib/parallel.js') : self.Parallel; it('should require(), map() and reduce correctly (check console errors)', function () { var p = new Parallel([0, 1, 2, 3, 4, 5, 6, 7, 8], { evalPath: isNode ? undefined : 'lib/eval.js' }); function add(d) { return d[0] + d[1]; } function factorial(n) { return n < 2 ? 1 : n * factorial(n - 1); } p.require(factorial); var done = false; runs(function () { p.map(function (n) { return Math.pow(10, n); }).reduce(add).then(function() { done = true; }); }); waitsFor(function () { return done; }, "it should finish", 1000); }); });
Increase timeout slightly to avoid failing
Increase timeout slightly to avoid failing
JavaScript
mit
1aurabrown/parallel.js,parallel-js/parallel.js,adambom/parallel.js,SRobertZ/parallel.js,kidaa/parallel.js,1aurabrown/parallel.js,blackrabbit99/doubleW,blackrabbit99/parallel.js,colemakdvorak/parallel.js,blackrabbit99/parallel.js,kidaa/parallel.js,SRobertZ/parallel.js,parallel-js/parallel.js,colemakdvorak/parallel.js,blackrabbit99/doubleW,adambom/parallel.js
--- +++ @@ -19,6 +19,6 @@ waitsFor(function () { return done; - }, "it should finish", 500); + }, "it should finish", 1000); }); });
a5675bcb304623bcc28307751fd538f253c02fae
document/app.js
document/app.js
var express = require('express'); module.exports = function setup(options, imports, register) { var backend = imports.backend.app, frontend = imports.frontend.app; var plugin = { app: {}, documents: {} }; backend.get('/api/Documents', function (req, res, next) { res.json(module.documents); }); register(null, { document: plugin }); };
var express = require('express'); module.exports = function setup(options, imports, register) { var backend = imports.backend.app, frontend = imports.frontend.app; var plugin = { app: {}, documents: {}, addType: function (name, config) { this.documents[name] = config; } }; backend.get('/api/Documents', function (req, res, next) { res.json(module.documents); }); register(null, { document: plugin }); };
Add addType method to content
Add addType method to content
JavaScript
mit
bauhausjs/bauhausjs,bauhausjs/bauhausjs,bauhausjs/bauhausjs,bauhausjs/bauhausjs
--- +++ @@ -6,7 +6,10 @@ var plugin = { app: {}, - documents: {} + documents: {}, + addType: function (name, config) { + this.documents[name] = config; + } }; backend.get('/api/Documents', function (req, res, next) {
e1e7cf8bdbaf961b665f45254a190914801d6bac
server/server.js
server/server.js
const express = require('express'); const app = express(); app.use(express.static('dist')); app.listen(8080, function() { console.log('App started on port 8080!'); });
const express = require('express'); const app = express(); app.use(express.static('dist')); app.listen(3000, function() { console.log('Listening on port 3000!'); });
Use port 3000 for testing
Use port 3000 for testing
JavaScript
mit
codergvbrownsville/code-rgv-pwa,codergvbrownsville/code-rgv-pwa,codergvbrownsville/code-rgv-pwa,codergvbrownsville/code-rgv-pwa
--- +++ @@ -4,6 +4,6 @@ app.use(express.static('dist')); -app.listen(8080, function() { - console.log('App started on port 8080!'); +app.listen(3000, function() { + console.log('Listening on port 3000!'); });
50249d2fed6c2e8bd9f1a7abd60d53a6cbb33f59
backend/lib/openfisca/index.js
backend/lib/openfisca/index.js
/* ** Module dependencies */ var config = require('../../config/config'); var http = require('http'); var mapping = require('./mapping'); var url = require('url'); var openfiscaURL = url.parse(config.openfiscaApi); function sendOpenfiscaRequest(simulation, callback) { var postData = JSON.stringify(simulation); var options = { hostname: openfiscaURL.hostname, port: openfiscaURL.port, path: 'calculate', method: 'POST', headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(postData) } }; var request = http.request(options, function(response) { response.setEncoding('utf8'); var rawData = ''; response.on('data', function(chunk) { rawData += chunk; }); response.on('end', function() { try { var content = JSON.parse(rawData); if (response.statusCode == 200) { callback(null, content); } else { callback(content.error); } } catch (e) { callback({ code: 500, errors: 'Can\'t parse: ' + rawData, message: e.message, stack: e.stack, }); } }); }); request.write(postData); request.on('error', callback); request.end(); } var buildOpenFiscaRequest = exports.buildOpenFiscaRequest = mapping.buildOpenFiscaRequest; function calculate(situation, callback) { var request; try { request = buildOpenFiscaRequest(situation); } catch(e) { return callback({ message: e.message, name: e.name, stack: e.stack }); } sendOpenfiscaRequest(request, callback); } exports.calculate = calculate;
var config = require('../../config/config'); var mapping = require('./mapping'); var rp = require('request-promise'); var buildOpenFiscaRequest = exports.buildOpenFiscaRequest = mapping.buildOpenFiscaRequest; function sendToOpenfisca(endpoint) { return function(situation, callback) { var request; try { request = buildOpenFiscaRequest(situation); } catch(e) { return callback({ message: e.message, name: e.name, stack: e.stack }); } rp({ uri: config.openfiscaApi + '/' + endpoint, method: 'POST', body: request, json: true, }) .then(function(result) { callback(null, result); }).catch(callback); }; } exports.calculate = sendToOpenfisca('calculate'); exports.trace = sendToOpenfisca('trace');
Use request-promise to manage OpenFisca calls
Use request-promise to manage OpenFisca calls
JavaScript
agpl-3.0
sgmap/mes-aides-ui,sgmap/mes-aides-ui,sgmap/mes-aides-ui,sgmap/mes-aides-ui
--- +++ @@ -1,68 +1,31 @@ -/* -** Module dependencies -*/ var config = require('../../config/config'); -var http = require('http'); var mapping = require('./mapping'); -var url = require('url'); +var rp = require('request-promise'); -var openfiscaURL = url.parse(config.openfiscaApi); - -function sendOpenfiscaRequest(simulation, callback) { - var postData = JSON.stringify(simulation); - var options = { - hostname: openfiscaURL.hostname, - port: openfiscaURL.port, - path: 'calculate', - method: 'POST', - headers: { - 'Content-Type': 'application/json', - 'Content-Length': Buffer.byteLength(postData) +var buildOpenFiscaRequest = exports.buildOpenFiscaRequest = mapping.buildOpenFiscaRequest; +function sendToOpenfisca(endpoint) { + return function(situation, callback) { + var request; + try { + request = buildOpenFiscaRequest(situation); + } catch(e) { + return callback({ + message: e.message, + name: e.name, + stack: e.stack + }); } + rp({ + uri: config.openfiscaApi + '/' + endpoint, + method: 'POST', + body: request, + json: true, + }) + .then(function(result) { + callback(null, result); + }).catch(callback); }; - - var request = http.request(options, function(response) { - response.setEncoding('utf8'); - var rawData = ''; - response.on('data', function(chunk) { rawData += chunk; }); - response.on('end', function() { - try { - var content = JSON.parse(rawData); - if (response.statusCode == 200) { - callback(null, content); - } else { - callback(content.error); - } - } catch (e) { - callback({ - code: 500, - errors: 'Can\'t parse: ' + rawData, - message: e.message, - stack: e.stack, - }); - } - }); - }); - request.write(postData); - - request.on('error', callback); - request.end(); } -var buildOpenFiscaRequest = exports.buildOpenFiscaRequest = mapping.buildOpenFiscaRequest; - -function calculate(situation, callback) { - var request; - try { - request = buildOpenFiscaRequest(situation); - } catch(e) { - return callback({ - message: e.message, - name: e.name, - stack: e.stack - }); - } - sendOpenfiscaRequest(request, callback); -} - -exports.calculate = calculate; +exports.calculate = sendToOpenfisca('calculate'); +exports.trace = sendToOpenfisca('trace');
f63b1cd62f823d89e62d559ef5e86a70f504126c
javascripts/pong.js
javascripts/pong.js
(function() { 'use strict'; var canvas = document.getElementById('game'); var width = window.innerWidth; var height = window.innerHeight; canvas.width = width; canvas.height = height; var ctx = canvas.getContext('2d'); var FPS = 1000 / 60; var clear = function() { ctx.clearRect(0, 0, width, height); }; var update = function() { }; var render = function () { }; var step = function() { update(); render(); requestAnimationFrame(FPS); } requestAnimationFrame(step()); })();
(function() { 'use strict'; var canvas = document.getElementById('game'); var WIDTH = window.innerWidth; var HEIGHT = window.innerHeight; canvas.width = WIDTH; canvas.height = HEIGHT; var ctx = canvas.getContext('2d'); var FPS = 1000 / 60; var Paddle = function(x, y, width, height) { this.x = x; this.y = y; this.width = width; this.height = height; this.xSpeed = 0; this.ySpeed = 0; }; Paddle.prototype.render = function() { ctx.fillStyle = "#FFFFFF"; ctx.fillRect(this.x, this.y, this.width, this.height); } var clear = function() { ctx.clearRect(0, 0, WIDTH, HEIGHT); }; var update = function() { }; var render = function () { ctx.fillStyle = '#000000'; ctx.fillRect(0, 0, WIDTH, HEIGHT); }; var step = function() { update(); render(); requestAnimationFrame(FPS); } requestAnimationFrame(step()); })();
Define paddle object and a basic render function. Also capitalise width and height constants to easily distinguish them from object properties or parameters
Define paddle object and a basic render function. Also capitalise width and height constants to easily distinguish them from object properties or parameters
JavaScript
mit
msanatan/pong,msanatan/pong,msanatan/pong
--- +++ @@ -1,15 +1,29 @@ (function() { 'use strict'; var canvas = document.getElementById('game'); - var width = window.innerWidth; - var height = window.innerHeight; - canvas.width = width; - canvas.height = height; + var WIDTH = window.innerWidth; + var HEIGHT = window.innerHeight; + canvas.width = WIDTH; + canvas.height = HEIGHT; var ctx = canvas.getContext('2d'); var FPS = 1000 / 60; + var Paddle = function(x, y, width, height) { + this.x = x; + this.y = y; + this.width = width; + this.height = height; + this.xSpeed = 0; + this.ySpeed = 0; + }; + + Paddle.prototype.render = function() { + ctx.fillStyle = "#FFFFFF"; + ctx.fillRect(this.x, this.y, this.width, this.height); + } + var clear = function() { - ctx.clearRect(0, 0, width, height); + ctx.clearRect(0, 0, WIDTH, HEIGHT); }; var update = function() { @@ -17,7 +31,8 @@ }; var render = function () { - + ctx.fillStyle = '#000000'; + ctx.fillRect(0, 0, WIDTH, HEIGHT); }; var step = function() {
ddfc71983fb71ccb81f5196f97f5bb040637cdf0
jive-sdk-service/generator/examples/todo/tiles/todo/public/javascripts/main.js
jive-sdk-service/generator/examples/todo/tiles/todo/public/javascripts/main.js
(function() { var clientid; jive.tile.onOpen(function(config, options, other, container ) { osapi.jive.corev3.systemExtProps.get({}).execute(function (resp) { if( resp && resp.content ) { clientid = resp.content.clientid; } }); gadgets.window.adjustHeight(); if ( typeof config === "string" ) { config = JSON.parse(config); } var json = config || { }; json.project = json.project || container.name; // prepopulate the sequence input dialog $("#project").val( json.project); $("#btn_submit").click( function() { config.project = $("#project").val(); config.clientid = clientid; jive.tile.close(config, {} ); gadgets.window.adjustHeight(300); }); }); })();
(function() { var clientid; jive.tile.onOpen(function(config, options, other, container ) { osapi.jive.corev3.systemExtProps.get({}).execute(function (resp) { if( resp && resp.content ) { clientid = resp.content.clientid; } }); gadgets.window.adjustHeight(); if ( typeof config === "string" ) { config = JSON.parse(config); } var json = config || { }; json.project = json.project || (container && container.name) || ""; // prepopulate the sequence input dialog $("#project").val( json.project); $("#btn_submit").click( function() { config.project = $("#project").val(); config.clientid = clientid; jive.tile.close(config, {} ); gadgets.window.adjustHeight(300); }); }); })();
Handle when container is undefined.
Handle when container is undefined.
JavaScript
apache-2.0
jivesoftware/jive-sdk,jivesoftware/jive-sdk,jivesoftware/jive-sdk
--- +++ @@ -15,7 +15,7 @@ var json = config || { }; - json.project = json.project || container.name; + json.project = json.project || (container && container.name) || ""; // prepopulate the sequence input dialog $("#project").val( json.project);
3f84b85e5524743a35237116b3e8ba9fdf3d1e2d
src/TopItems.js
src/TopItems.js
import React, { Component } from 'react'; import Item from './Item'; import sortByScore from './sorter'; var TopItems = React.createClass({ sortByScore: function() { this.setState({items: sortByScore(this.props.items)}); }, render: function() { var rank = 0; var all_items = this.props.items.map(function(item) { rank++; return ( <Item key={item.id} rank={rank} item={item} /> ); }); // Retired, sort button // <SortButton items={this.props.items} sortByScore={this.sortByScore}/> return ( <div> <div className="top-stories"> {all_items} </div> </div> ); } }); var SortButton = React.createClass({ render: function() { return ( <div> <a className='button' onClick={this.props.sortByScore}>Sort!</a> </div> ); } }); export default TopItems;
import React, { Component } from 'react'; import Item from './Item'; var TopItems = React.createClass({ render: function() { var rank = 0; var all_items = this.props.items.map(function(item) { rank++; return ( <Item key={item.id} rank={rank} item={item} /> ); }); return ( <div> <div className="top-stories"> {all_items} </div> </div> ); } }); export default TopItems;
Remove sort button, as we sort by default now
Remove sort button, as we sort by default now
JavaScript
mit
danbartlett/hn_minimal,danbartlett/hn_minimal
--- +++ @@ -1,12 +1,7 @@ import React, { Component } from 'react'; import Item from './Item'; -import sortByScore from './sorter'; var TopItems = React.createClass({ - sortByScore: function() { - this.setState({items: sortByScore(this.props.items)}); - }, - render: function() { var rank = 0; var all_items = this.props.items.map(function(item) { @@ -16,8 +11,6 @@ ); }); - // Retired, sort button - // <SortButton items={this.props.items} sortByScore={this.sortByScore}/> return ( <div> <div className="top-stories"> @@ -28,14 +21,4 @@ } }); -var SortButton = React.createClass({ - render: function() { - return ( - <div> - <a className='button' onClick={this.props.sortByScore}>Sort!</a> - </div> - ); - } -}); - export default TopItems;
a8376d565326e347fcd6ef955d8de19483e7261d
lib/apps.js
lib/apps.js
/** * Copyright (c) ActiveState 2013 - ALL RIGHTS RESERVED. */ define([ './collection'], function (Collection) { var apps = function (api) { this.api = api; this.collection = 'apps'; }; apps.prototype = Object.create(new Collection()); apps.prototype.getAppInstances = function (guid, done) { this.api.get('/v2/apps/' + guid + '/instances', {status_code: 200}, function (err, res) { if (err) { return done(err); } done(null, res.body); }); }; apps.prototype.getFiles = function (guid, instance_index, path, done) { this.api.get(this.getCollectionUrl() + '/' + guid + '/instances/' + instance_index + '/files/' + path, {status_code: 200}, done); }; // TODO: Pull out in to Stackato specific extension apps.prototype.getLogTail = function (guid, line_count, done) { this.api.get(this.getCollectionUrl() + '/' + guid + '/stackato_logs', {query: '?num=' + (line_count || 25) + '&monolith=1', status_code: 200}, done) }; return apps; } );
/** * Copyright (c) ActiveState 2013 - ALL RIGHTS RESERVED. */ define([ './collection'], function (Collection) { var apps = function (api) { this.api = api; this.collection = 'apps'; }; apps.prototype = Object.create(new Collection()); apps.prototype.getAppInstances = function (guid, done) { this.api.get('/v2/apps/' + guid + '/instances', {status_code: 200}, function (err, res) { if (err) { return done(err); } done(null, res.body); }); }; apps.prototype.getFiles = function (guid, instance_index, path, done) { this.api.get(this.getCollectionUrl() + '/' + guid + '/instances/' + instance_index + '/files/' + path, {query: '?allow_redirect=false', status_code: 200}, done); }; // TODO: Pull out in to Stackato specific extension apps.prototype.getLogTail = function (guid, line_count, done) { this.api.get(this.getCollectionUrl() + '/' + guid + '/stackato_logs', {query: '?num=' + (line_count || 25) + '&monolith=1', status_code: 200}, done) }; return apps; } );
Disable redirect when browsing files from browser
Disable redirect when browsing files from browser
JavaScript
mit
ActiveState/cloud-foundry-client-js,18F/cloud-foundry-client-js,18F/cloud-foundry-client-js,hpcloud/cloud-foundry-client-js,hpcloud/cloud-foundry-client-js,ActiveState/cloud-foundry-client-js,morikat/cloud-foundry-client-js,morikat/cloud-foundry-client-js
--- +++ @@ -24,7 +24,7 @@ }; apps.prototype.getFiles = function (guid, instance_index, path, done) { - this.api.get(this.getCollectionUrl() + '/' + guid + '/instances/' + instance_index + '/files/' + path, {status_code: 200}, done); + this.api.get(this.getCollectionUrl() + '/' + guid + '/instances/' + instance_index + '/files/' + path, {query: '?allow_redirect=false', status_code: 200}, done); }; // TODO: Pull out in to Stackato specific extension
e37507356b99586b31f888ba8405b1fc320f8400
lib/main.js
lib/main.js
"use babel"; "use strict"; import fs from "fs"; import path from "path"; import {CompositeDisposable} from "atom"; import {name as packageName} from "../package.json"; export default { subscriptions: null, activate(state) { this.subscriptions = new CompositeDisposable(); this.subscriptions.add(atom.themes.onDidChangeActiveThemes(() => { this.subscriptions.add(atom.config.observe(`${packageName}.subtheme`, value => { this.apply(value); })); })); }, deactivate() { this.subscriptions.dispose(); }, apply(value) { let newData = `@import "colors/${value}";\n`, file = path.join(__dirname, "..", "styles", "syntax-variables.less"), oldData = fs.readFileSync(file, "utf8"); if (newData !== oldData) { fs.writeFileSync(file, newData); this.reloadAllStylesheets(); } }, reloadAllStylesheets() { atom.themes.deactivateThemes(); atom.themes.refreshLessCache(); let promises = [], ref = atom.themes.getEnabledThemeNames(); for (let i = 0, len = ref.length; i < len; i++) { let themeName = ref[i]; promises.push(atom.packages.activatePackage(themeName)); } Promise.all(promises).then(() => { atom.themes.addActiveThemeClasses(); atom.themes.refreshLessCache(); atom.themes.loadUserStylesheet(); atom.themes.reloadBaseStylesheets(); }); } };
"use babel"; "use strict"; import fs from "fs"; import path from "path"; import {CompositeDisposable} from "atom"; import {name as packageName} from "../package.json"; export default { subscriptions: null, activate(state) { this.subscriptions = new CompositeDisposable(); this.subscriptions.add(atom.themes.onDidChangeActiveThemes(() => { this.subscriptions.add(atom.config.observe(`${packageName}.subtheme`, value => { this.apply(value); })); })); }, deactivate() { this.subscriptions.dispose(); }, apply(value) { let newData = `@import "colors/${value}";\n`, file = path.join(__dirname, "..", "styles", "syntax-variables.less"), oldData = fs.readFileSync(file, "utf8"); if (newData !== oldData) { fs.writeFileSync(file, newData); this.reloadAllStylesheets(); } }, reloadAllStylesheets() { atom.themes.loadUserStylesheet(); atom.themes.reloadBaseStylesheets(); let ref = atom.packages.getActivePackages(); for (let i = 0, len = ref.length; i < len; i++) { let pack = ref[i]; pack.reloadStylesheets(); } } };
Revert ":bug: Fix stylesheets issue when changing subtheme"
Revert ":bug: Fix stylesheets issue when changing subtheme" This reverts commit a9b1f3c3e9932fc0d049a6be64c3c8ecc01c7f4f.
JavaScript
mit
gt-rios/firefox-syntax
--- +++ @@ -35,22 +35,14 @@ }, reloadAllStylesheets() { - atom.themes.deactivateThemes(); - atom.themes.refreshLessCache(); - let promises = [], - ref = atom.themes.getEnabledThemeNames(); + atom.themes.loadUserStylesheet(); + atom.themes.reloadBaseStylesheets(); + let ref = atom.packages.getActivePackages(); for (let i = 0, len = ref.length; i < len; i++) { - let themeName = ref[i]; - promises.push(atom.packages.activatePackage(themeName)); + let pack = ref[i]; + pack.reloadStylesheets(); } - - Promise.all(promises).then(() => { - atom.themes.addActiveThemeClasses(); - atom.themes.refreshLessCache(); - atom.themes.loadUserStylesheet(); - atom.themes.reloadBaseStylesheets(); - }); } };
5c8bfc9df05fe7d13a4435085df1ba52f27bb376
lib/main.js
lib/main.js
'use babel'; let lineEndingTile = null; export function activate() { atom.workspace.observeActivePaneItem((item) => { let ending = getLineEnding(item); if (lineEndingTile) lineEndingTile.firstChild.textContent = ending; }); } export function consumeStatusBar(statusBar) { lineEndingTile = document.createElement('div'); lineEndingTile.style.display = "inline-block"; lineEndingTile.className = "line-ending-tile"; lineEndingTile.innerHTML = "<a></a>"; statusBar.addRightTile({item: lineEndingTile, priority: 200}); } function getLineEnding(item) { if (!item) return ""; let hasLF = false; let hasCRLF = false; if (item && item.scan) { item.scan(/\n|\r\n/g, ({matchText}) => { if (matchText === "\n") hasLF = true; if (matchText === "\r\n") hasCRLF = true; }); } if (hasLF && hasCRLF) return "Mixed"; if (hasLF) return "LF"; if (hasCRLF) return "CRLF"; if (process.platform === 'win32') return "CRLF"; return "LF"; }
'use babel'; let lineEndingTile = null; export function activate() { atom.workspace.observeActivePaneItem((item) => { let ending = getLineEnding(item); if (lineEndingTile) lineEndingTile.textContent = ending; }); } export function consumeStatusBar(statusBar) { lineEndingTile = document.createElement('a'); lineEndingTile.className = "line-ending-tile"; statusBar.addRightTile({item: lineEndingTile, priority: 200}); } function getLineEnding(item) { if (!item) return ""; let hasLF = false; let hasCRLF = false; if (item && item.scan) { item.scan(/\n|\r\n/g, ({matchText}) => { if (matchText === "\n") hasLF = true; if (matchText === "\r\n") hasCRLF = true; }); } if (hasLF && hasCRLF) return "Mixed"; if (hasLF) return "LF"; if (hasCRLF) return "CRLF"; if (process.platform === 'win32') return "CRLF"; return "LF"; }
Remove unneeded div around tile element
Remove unneeded div around tile element Signed-off-by: Max Brunsfeld <78036c9b69b887700d5846f26a788d53b201ffbb@gmail.com>
JavaScript
mit
clintwood/line-ending-selector,download13/line-ending-selector,atom/line-ending-selector,bolinfest/line-ending-selector
--- +++ @@ -5,15 +5,13 @@ export function activate() { atom.workspace.observeActivePaneItem((item) => { let ending = getLineEnding(item); - if (lineEndingTile) lineEndingTile.firstChild.textContent = ending; + if (lineEndingTile) lineEndingTile.textContent = ending; }); } export function consumeStatusBar(statusBar) { - lineEndingTile = document.createElement('div'); - lineEndingTile.style.display = "inline-block"; + lineEndingTile = document.createElement('a'); lineEndingTile.className = "line-ending-tile"; - lineEndingTile.innerHTML = "<a></a>"; statusBar.addRightTile({item: lineEndingTile, priority: 200}); }
b6339fe3e288d639efb0236bf029b6a94602f706
lib/assets/test/spec/new-dashboard/unit/specs/store/user/user.spec.js
lib/assets/test/spec/new-dashboard/unit/specs/store/user/user.spec.js
import UserStore from 'new-dashboard/store/user'; import { testAction } from '../helpers'; jest.mock('carto-node'); const mutations = UserStore.mutations; const actions = UserStore.actions; describe('UserStore', () => { describe('mutations', () => { it('setUserData', () => { const state = { email: 'example@example.org', username: 'example', website: 'https://carto.com' }; const userData = { email: 'example@carto.com', username: 'carto' }; mutations.setUserData(state, userData); expect(state).toEqual({ email: 'example@carto.com', username: 'carto', website: 'https://carto.com' }); }); }); describe('actions', () => { describe('updateData', () => { let state; beforeEach(() => { state = { email: 'example@example.org', username: 'example', website: 'https://carto.com' }; }); it('success', done => { const newConfigData = { email: 'example@carto.com', username: 'carto' }; testAction(actions.updateData, null, state, [ { type: 'setUserData', payload: newConfigData } ], [], done); }); }); }); });
import UserStore from 'new-dashboard/store/user'; import { testAction2 } from '../helpers'; jest.mock('carto-node'); const mutations = UserStore.mutations; const actions = UserStore.actions; describe('UserStore', () => { describe('mutations', () => { it('setUserData', () => { const state = { email: 'example@example.org', username: 'example', website: 'https://carto.com' }; const userData = { email: 'example@carto.com', username: 'carto' }; mutations.setUserData(state, userData); expect(state).toEqual({ email: 'example@carto.com', username: 'carto', website: 'https://carto.com' }); }); }); describe('actions', () => { describe('updateData', () => { let state; beforeEach(() => { state = { email: 'example@example.org', username: 'example', website: 'https://carto.com' }; }); it('success', done => { const newConfigData = { email: 'example@carto.com', username: 'carto' }; const expectedMutations = [ { type: 'setUserData', payload: newConfigData } ]; testAction2({ action: actions.updateData, state, expectedMutations, done }); }); }); }); });
Use new test action function
test: Use new test action function
JavaScript
bsd-3-clause
CartoDB/cartodb,CartoDB/cartodb,CartoDB/cartodb,CartoDB/cartodb,CartoDB/cartodb
--- +++ @@ -1,5 +1,5 @@ import UserStore from 'new-dashboard/store/user'; -import { testAction } from '../helpers'; +import { testAction2 } from '../helpers'; jest.mock('carto-node'); @@ -45,10 +45,10 @@ email: 'example@carto.com', username: 'carto' }; - - testAction(actions.updateData, null, state, [ + const expectedMutations = [ { type: 'setUserData', payload: newConfigData } - ], [], done); + ]; + testAction2({ action: actions.updateData, state, expectedMutations, done }); }); }); });
39ea495532f1d113a0ca6e98cd81848943e1695a
src/browser/home/HomePage.js
src/browser/home/HomePage.js
/* @flow */ import type { State } from '../../common/types'; import React from 'react'; import AddrListByRoom from './AddressListByRoom'; import AddrList from './AddressList'; import { connect } from 'react-redux'; import linksMessages from '../../common/app/linksMessages'; import { isEmpty, pathOr, reject } from 'ramda'; import { Block, Title, View, } from '../components'; import { Box } from 'reflexbox'; type HomePageProps = { smartHomeState: Object, location: Object, }; const HomePage = ({ smartHomeState, location }: HomePageProps) => { const { livestate, prefs } = smartHomeState; /* Built address-list, remove some address-types which should not be displayed */ const addresses = reject(addr => addr.type === 'fb', livestate); if (isEmpty(addresses)) { return ( <Block> <p>Waiting for SmartHome-State...</p> </Block> ); } const viewType = pathOr('changes', ['pathname'], location); const addrList = viewType === 'changes' ? <AddrList addresses={addresses} /> : <AddrListByRoom addresses={addresses} prefs={prefs} />; return ( <View> <Title message={linksMessages.home} /> <Box py={2}> {addrList} </Box> </View> ); }; export default connect( (state: State) => ({ smartHomeState: state.smartHome, }), )(HomePage);
/* @flow */ import type { State } from '../../common/types'; import React from 'react'; import AddrListByRoom from './AddressListByRoom'; import AddrList from './AddressList'; import { connect } from 'react-redux'; import linksMessages from '../../common/app/linksMessages'; import { isEmpty, pathOr, reject, test } from 'ramda'; import { Block, Title, View } from '../components'; import { Box } from 'reflexbox'; type HomePageProps = { smartHomeState: Object, location: Object, }; const HomePage = ({ smartHomeState, location }: HomePageProps) => { const { livestate, prefs } = smartHomeState; /* Built address-list, remove some address-types which should not be displayed */ const addresses = reject(addr => addr.type === 'fb', livestate); if (isEmpty(addresses)) { return ( <Block> <p>Waiting for SmartHome-State...</p> </Block> ); } const viewType = pathOr('changes', ['pathname'], location); const addrList = test(/rooms$/, viewType) ? <AddrListByRoom addresses={addresses} prefs={prefs} /> : <AddrList addresses={addresses} />; return ( <View> <Title message={linksMessages.home} /> <Box py={2}> {addrList} </Box> </View> ); }; export default connect((state: State) => ({ smartHomeState: state.smartHome, }))(HomePage);
Improve tolerance when matching url-paths for router-navigation.
Improve tolerance when matching url-paths for router-navigation.
JavaScript
mit
cjk/smart-home-app
--- +++ @@ -5,13 +5,9 @@ import AddrList from './AddressList'; import { connect } from 'react-redux'; import linksMessages from '../../common/app/linksMessages'; -import { isEmpty, pathOr, reject } from 'ramda'; +import { isEmpty, pathOr, reject, test } from 'ramda'; -import { - Block, - Title, - View, -} from '../components'; +import { Block, Title, View } from '../components'; import { Box } from 'reflexbox'; @@ -35,9 +31,9 @@ } const viewType = pathOr('changes', ['pathname'], location); - const addrList = viewType === 'changes' - ? <AddrList addresses={addresses} /> - : <AddrListByRoom addresses={addresses} prefs={prefs} />; + const addrList = test(/rooms$/, viewType) + ? <AddrListByRoom addresses={addresses} prefs={prefs} /> + : <AddrList addresses={addresses} />; return ( <View> @@ -49,8 +45,6 @@ ); }; -export default connect( - (state: State) => ({ - smartHomeState: state.smartHome, - }), -)(HomePage); +export default connect((state: State) => ({ + smartHomeState: state.smartHome, +}))(HomePage);
7ced1f20afd2b52ac687bfae21ca33537b635ae6
src/routes/Player/components/PlayerController/PlayerControllerContainer.js
src/routes/Player/components/PlayerController/PlayerControllerContainer.js
import PlayerController from './PlayerController' import { connect } from 'react-redux' import { ensureState } from 'redux-optimistic-ui' import getOrderedQueue from 'routes/Queue/selectors/getOrderedQueue' import { playerLeave, playerError, playerLoad, playerPlay, playerStatus, } from '../../modules/player' import { playerVisualizerError } from '../../modules/playerVisualizer' const mapActionCreators = { playerLeave, playerError, playerLoad, playerPlay, playerStatus, playerVisualizerError, } const mapStateToProps = (state) => { const { player, playerVisualizer, prefs } = state const queue = ensureState(state.queue) return { cdgAlpha: player.cdgAlpha, cdgSize: player.cdgSize, historyJSON: state.status.historyJSON, // @TODO use state.player instead? isAtQueueEnd: player.isAtQueueEnd, isErrored: player.isErrored, isPlaying: player.isPlaying, isPlayingNext: player.isPlayingNext, isQueueEmpty: queue.result.length === 0, isReplayGainEnabled: prefs.isReplayGainEnabled, isWebGLSupported: player.isWebGLSupported, mp4Alpha: player.mp4Alpha, queue: getOrderedQueue(state), queueId: player.queueId, volume: player.volume, visualizer: playerVisualizer, } } export default connect(mapStateToProps, mapActionCreators)(PlayerController)
import PlayerController from './PlayerController' import { connect } from 'react-redux' import { ensureState } from 'redux-optimistic-ui' import getOrderedQueue from 'routes/Queue/selectors/getOrderedQueue' import { playerLeave, playerError, playerLoad, playerPlay, playerStatus, } from '../../modules/player' import { playerVisualizerError } from '../../modules/playerVisualizer' const mapActionCreators = { playerLeave, playerError, playerLoad, playerPlay, playerStatus, playerVisualizerError, } const mapStateToProps = (state) => { const { player, playerVisualizer, prefs } = state const queue = ensureState(state.queue) return { cdgAlpha: player.cdgAlpha, cdgSize: player.cdgSize, historyJSON: player.historyJSON, isAtQueueEnd: player.isAtQueueEnd, isErrored: player.isErrored, isPlaying: player.isPlaying, isPlayingNext: player.isPlayingNext, isQueueEmpty: queue.result.length === 0, isReplayGainEnabled: prefs.isReplayGainEnabled, isWebGLSupported: player.isWebGLSupported, mp4Alpha: player.mp4Alpha, queue: getOrderedQueue(state), queueId: player.queueId, volume: player.volume, visualizer: playerVisualizer, } } export default connect(mapStateToProps, mapActionCreators)(PlayerController)
Use internal player history instead of emitted status
Use internal player history instead of emitted status
JavaScript
isc
bhj/karaoke-forever,bhj/karaoke-forever
--- +++ @@ -27,7 +27,7 @@ return { cdgAlpha: player.cdgAlpha, cdgSize: player.cdgSize, - historyJSON: state.status.historyJSON, // @TODO use state.player instead? + historyJSON: player.historyJSON, isAtQueueEnd: player.isAtQueueEnd, isErrored: player.isErrored, isPlaying: player.isPlaying,
373dfb4090d23fceb878278a244b64ecde31efb0
lib/util.js
lib/util.js
exports = module.exports = require('util'); exports.formatDate = function(date){ if (typeof date === 'string') return date; date = new Date(date); var month = date.getMonth() + 1, day = date.getDate(), str = date.getFullYear(); str += '-'; if (month < 10) str += '0'; str += month; str += '-'; if (day < 10) str += '0'; str += day; return str; }; exports.formatError = function(data){ return new Error(data.message + ' (Code: ' + data.code + ')'); };
exports = module.exports = require('util'); exports.formatDate = function(date){ if (typeof date === 'string') return date; date = new Date(date); var month = date.getMonth() + 1, day = date.getDate(), str = date.getFullYear(); str += '-'; if (month < 10) str += '0'; str += month; str += '-'; if (day < 10) str += '0'; str += day; return str; }; exports.formatError = function(data){ var err = new Error(data.message + ' (Code: ' + data.code + ')'); err.code = data.code; return err; };
Add code to error object
Add code to error object
JavaScript
mit
tommy351/node-flurry-api
--- +++ @@ -20,5 +20,8 @@ }; exports.formatError = function(data){ - return new Error(data.message + ' (Code: ' + data.code + ')'); + var err = new Error(data.message + ' (Code: ' + data.code + ')'); + err.code = data.code; + + return err; };
b3e10b4bc710a4892d430efeb2f41ef6900fb72c
src/components/OAuthLogin.js
src/components/OAuthLogin.js
import React from 'react'; import {FormattedMessage} from "react-intl"; import queryString from "query-string"; const OAuthLogin = ({providers, onLogin}) => { const location = window.location; const targetUrl = `${location.protocol}//${location.host}/login`; const loginUrlQueryString = `?next=${encodeURIComponent(targetUrl)}`; return <div className="pt-button-group pt-vertical pt-align-left pt-large"> {providers.map(provider => <p key={provider.name}> <a href={`${provider.login}${loginUrlQueryString}`} className="pt-button pt-intent-primary pt-icon-log-in"> <FormattedMessage id="login.provider" defaultMessage="Sign in with {label}" values={{label: provider.label}}/> </a> </p>)} </div> }; export const handleOAuthCallback = (onLoginFn) => { const parsedHash = queryString.parse(location.hash); if (parsedHash.token) { onLoginFn(parsedHash.token); location.hash = ''; } }; export default OAuthLogin;
import React from 'react'; import {FormattedMessage} from "react-intl"; import {AnchorButton, Intent} from '@blueprintjs/core'; import queryString from "query-string"; const OAuthLogin = ({providers, onLogin}) => { const location = window.location; const targetUrl = `${location.protocol}//${location.host}/login`; const loginUrlQueryString = `?next=${encodeURIComponent(targetUrl)}`; return <div className="pt-button-group pt-vertical pt-align-left pt-large"> {providers.map(provider => <p key={provider.name}> <AnchorButton href={`${provider.login}${loginUrlQueryString}`} intent={Intent.PRIMARY}> <FormattedMessage id="login.provider" defaultMessage="Sign in with {label}" values={{label: provider.label}}/> </AnchorButton> </p>)} </div> }; export const handleOAuthCallback = (onLoginFn) => { const parsedHash = queryString.parse(location.hash); if (parsedHash.token) { onLoginFn(parsedHash.token); location.hash = ''; } }; export default OAuthLogin;
Use AnchorButton for anchor button
Use AnchorButton for anchor button
JavaScript
mit
alephdata/aleph,pudo/aleph,pudo/aleph,alephdata/aleph,alephdata/aleph,alephdata/aleph,alephdata/aleph,pudo/aleph
--- +++ @@ -1,5 +1,6 @@ import React from 'react'; import {FormattedMessage} from "react-intl"; +import {AnchorButton, Intent} from '@blueprintjs/core'; import queryString from "query-string"; const OAuthLogin = ({providers, onLogin}) => { @@ -9,10 +10,10 @@ return <div className="pt-button-group pt-vertical pt-align-left pt-large"> {providers.map(provider => <p key={provider.name}> - <a href={`${provider.login}${loginUrlQueryString}`} className="pt-button pt-intent-primary pt-icon-log-in"> + <AnchorButton href={`${provider.login}${loginUrlQueryString}`} intent={Intent.PRIMARY}> <FormattedMessage id="login.provider" defaultMessage="Sign in with {label}" values={{label: provider.label}}/> - </a> + </AnchorButton> </p>)} </div> };
84bad5d57dff7d5591d24bcc5caf6698e17e40b6
src/Aggregrid.js
src/Aggregrid.js
Ext.define('Jarvus.aggregrid.Aggregrid', { extend: 'Ext.Component', html: 'Hello World' });
Ext.define('Jarvus.aggregrid.Aggregrid', { extend: 'Ext.Component', config: { columnsStore: null, rowsStore: null }, html: 'Hello World', // config handlers applyColumnsStore: function(store) { return Ext.StoreMgr.lookup(store); }, applyRowsStore: function(store) { return Ext.StoreMgr.lookup(store); } });
Add columnsStore and rowsStore configs
Add columnsStore and rowsStore configs
JavaScript
mit
JarvusInnovations/jarvus-aggregrid,JarvusInnovations/jarvus-aggregrid,JarvusInnovations/jarvus-aggregrid
--- +++ @@ -1,5 +1,21 @@ Ext.define('Jarvus.aggregrid.Aggregrid', { extend: 'Ext.Component', - html: 'Hello World' + + config: { + columnsStore: null, + rowsStore: null + }, + + html: 'Hello World', + + + // config handlers + applyColumnsStore: function(store) { + return Ext.StoreMgr.lookup(store); + }, + + applyRowsStore: function(store) { + return Ext.StoreMgr.lookup(store); + } });
b8fdcaf0033348f8ec7203bc1150f66d188c6259
src/Constants.js
src/Constants.js
export const BLOCK_TYPE = { // This is used to represent a normal text block (paragraph). UNSTYLED: 'unstyled', HEADER_ONE: 'header-one', HEADER_TWO: 'header-two', HEADER_THREE: 'header-three', HEADER_FOUR: 'header-four', HEADER_FIVE: 'header-five', HEADER_SIX: 'header-six', UNORDERED_LIST_ITEM: 'unordered-list-item', ORDERED_LIST_ITEM: 'ordered-list-item', BLOCKQUOTE: 'blockquote', PULLQUOTE: 'pullquote', CODE: 'code-block', ATOMIC: 'atomic', }; export const ENTITY_TYPE = { LINK: 'LINK', }; export const INLINE_STYLE = { BOLD: 'BOLD', CODE: 'CODE', ITALIC: 'ITALIC', STRIKETHROUGH: 'STRIKETHROUGH', UNDERLINE: 'UNDERLINE', }; export default { BLOCK_TYPE, ENTITY_TYPE, INLINE_STYLE, };
export const BLOCK_TYPE = { // This is used to represent a normal text block (paragraph). UNSTYLED: 'unstyled', HEADER_ONE: 'header-one', HEADER_TWO: 'header-two', HEADER_THREE: 'header-three', HEADER_FOUR: 'header-four', HEADER_FIVE: 'header-five', HEADER_SIX: 'header-six', UNORDERED_LIST_ITEM: 'unordered-list-item', ORDERED_LIST_ITEM: 'ordered-list-item', BLOCKQUOTE: 'blockquote', PULLQUOTE: 'pullquote', CODE: 'code-block', ATOMIC: 'atomic', }; export const ENTITY_TYPE = { LINK: 'LINK', IMAGE: 'IMAGE' }; export const INLINE_STYLE = { BOLD: 'BOLD', CODE: 'CODE', ITALIC: 'ITALIC', STRIKETHROUGH: 'STRIKETHROUGH', UNDERLINE: 'UNDERLINE', }; export default { BLOCK_TYPE, ENTITY_TYPE, INLINE_STYLE, };
Add Image to ENTITY_TYPE Enum
Add Image to ENTITY_TYPE Enum Useful for rich text editor inline image support
JavaScript
isc
draft-js-utils/draft-js-utils
--- +++ @@ -17,6 +17,7 @@ export const ENTITY_TYPE = { LINK: 'LINK', + IMAGE: 'IMAGE' }; export const INLINE_STYLE = {
c66a58685ab7fd556634f123c5d0389c52ac2a71
js/components/developer/payment-info-screen/paymentInfoScreenStyle.js
js/components/developer/payment-info-screen/paymentInfoScreenStyle.js
import { StyleSheet } from 'react-native'; const paymentInfoStyle = StyleSheet.create({ addCardButton: { padding: 20, }, }); module.exports = paymentInfoStyle;
import { StyleSheet } from 'react-native'; const paymentInfoStyle = StyleSheet.create({ addCardButton: { padding: 10, }, }); module.exports = paymentInfoStyle;
Reduce button padding in PaymentInfoScreen
Reduce button padding in PaymentInfoScreen
JavaScript
mit
justarrived/p2p-client,justarrived/p2p-client,justarrived/p2p-client,justarrived/p2p-client
--- +++ @@ -2,7 +2,7 @@ const paymentInfoStyle = StyleSheet.create({ addCardButton: { - padding: 20, + padding: 10, }, });
969fc9567cc94d0a7a7d79528f989f8179cb3053
ukelonn.web.frontend/src/main/frontend/sagas/modifyPaymenttypeSaga.js
ukelonn.web.frontend/src/main/frontend/sagas/modifyPaymenttypeSaga.js
import { takeLatest, call, put } from 'redux-saga/effects'; import axios from 'axios'; import { MODIFY_PAYMENTTYPE_REQUEST, MODIFY_PAYMENTTYPE_RECEIVE, MODIFY_PAYMENTTYPE_FAILURE, } from '../actiontypes'; function doModifyPaymenttype(paymenttype) { return axios.post('/ukelonn/api/admin/paymenttype/modify', paymenttype); } function* requestReceiveModifyPaymenttypeSaga(action) { try { const response = yield call(doModifyPaymenttype, action.payload); const paymenttypes = (response.headers['content-type'] == 'application/json') ? response.data : []; yield put(MODIFY_PAYMENTTYPE_RECEIVE(paymenttypes)); } catch (error) { yield put(MODIFY_PAYMENTTYPE_FAILURE(error)); } } export default function* modifyPaymenttypeSaga() { yield takeLatest(MODIFY_PAYMENTTYPE_REQUEST, requestReceiveModifyPaymenttypeSaga); }
import { takeLatest, call, put } from 'redux-saga/effects'; import axios from 'axios'; import { MODIFY_PAYMENTTYPE_REQUEST, MODIFY_PAYMENTTYPE_RECEIVE, MODIFY_PAYMENTTYPE_FAILURE, CLEAR_PAYMENT_TYPE_FORM, } from '../actiontypes'; function doModifyPaymenttype(paymenttype) { return axios.post('/ukelonn/api/admin/paymenttype/modify', paymenttype); } function* requestReceiveModifyPaymenttypeSaga(action) { try { const response = yield call(doModifyPaymenttype, action.payload); const paymenttypes = (response.headers['content-type'] == 'application/json') ? response.data : []; yield put(MODIFY_PAYMENTTYPE_RECEIVE(paymenttypes)); } catch (error) { yield put(MODIFY_PAYMENTTYPE_FAILURE(error)); } } function* clearPaymenttypeForm() { yield put(CLEAR_PAYMENT_TYPE_FORM()); } export default function* modifyPaymenttypeSaga() { yield takeLatest(MODIFY_PAYMENTTYPE_REQUEST, requestReceiveModifyPaymenttypeSaga); yield takeLatest(MODIFY_PAYMENTTYPE_RECEIVE, clearPaymenttypeForm); }
Clear payment type form data after succesfully saving a modified payment type
Clear payment type form data after succesfully saving a modified payment type
JavaScript
apache-2.0
steinarb/ukelonn,steinarb/ukelonn,steinarb/ukelonn
--- +++ @@ -4,6 +4,7 @@ MODIFY_PAYMENTTYPE_REQUEST, MODIFY_PAYMENTTYPE_RECEIVE, MODIFY_PAYMENTTYPE_FAILURE, + CLEAR_PAYMENT_TYPE_FORM, } from '../actiontypes'; function doModifyPaymenttype(paymenttype) { @@ -20,6 +21,11 @@ } } +function* clearPaymenttypeForm() { + yield put(CLEAR_PAYMENT_TYPE_FORM()); +} + export default function* modifyPaymenttypeSaga() { yield takeLatest(MODIFY_PAYMENTTYPE_REQUEST, requestReceiveModifyPaymenttypeSaga); + yield takeLatest(MODIFY_PAYMENTTYPE_RECEIVE, clearPaymenttypeForm); }
c37dcfb3438de31be8ad7fc7dd5847d840bd05d6
app/assets/javascripts/angular/common/models/user-model.js
app/assets/javascripts/angular/common/models/user-model.js
(function(){ 'use strict'; angular .module('secondLead') .factory('UserModel',['Auth', 'Restangular', 'store', function(Auth, Restangular, store) { var baseUsers = Restangular.all('users'); return { getAll: baseUsers.getList().$object, getOne: function(userId) { return Restangular.one('users', userId).get() }, isLoggedIn: function (user) { return store.get('user'); }, register: function(newUser){ return baseUsers.post({"user": { first_name: newUser.firstName, last_name: newUser.lastName, email: newUser.email, username: newUser.username, password: newUser.password } }); }, login: function (user) { return Auth.login({ username: user.username, password: user.password }); } }; }]) })();
(function(){ 'use strict'; angular .module('secondLead') .factory('UserModel',['Auth', 'Restangular', '$rootScope', 'store', function(Auth, Restangular, $rootScope, store) { var baseUsers = Restangular.all('users'); var loggedIn = false; function setLoggedIn(state){ loggedIn = state; $rootScope.$broadcast('loggedIn:updated',state); }; return { currentUser: function() { return store.get('user'); }, getAll: baseUsers.getList().$object, getOne: function(userId) { return Restangular.one('users', userId).get() }, getStatus: function() { return { loggedIn: loggedIn } }, login: function (user) { var auth = Auth.login({ username: user.username, password: user.password }); return auth; }, register: function(newUser){ return baseUsers.post({"user": { first_name: newUser.firstName, last_name: newUser.lastName, email: newUser.email, username: newUser.username, password: newUser.password } }); }, setLoggedIn: setLoggedIn } ; }]) })();
Refactor user model to broadcast changes to login state
Refactor user model to broadcast changes to login state
JavaScript
mit
ac-adekunle/secondlead,ac-adekunle/secondlead,ac-adekunle/secondlead
--- +++ @@ -4,19 +4,41 @@ angular .module('secondLead') - .factory('UserModel',['Auth', 'Restangular', 'store', function(Auth, Restangular, store) { + .factory('UserModel',['Auth', 'Restangular', '$rootScope', 'store', function(Auth, Restangular, $rootScope, store) { var baseUsers = Restangular.all('users'); + var loggedIn = false; + + function setLoggedIn(state){ + loggedIn = state; + $rootScope.$broadcast('loggedIn:updated',state); + }; + return { + + currentUser: function() { + return store.get('user'); + }, + getAll: baseUsers.getList().$object, getOne: function(userId) { return Restangular.one('users', userId).get() }, - - isLoggedIn: function (user) { - return store.get('user'); + + getStatus: function() { + return { + loggedIn: loggedIn + } }, + + login: function (user) { + var auth = Auth.login({ + username: user.username, + password: user.password + }); + return auth; + }, register: function(newUser){ return baseUsers.post({"user": { @@ -28,14 +50,9 @@ }); }, - login: function (user) { - return Auth.login({ - username: user.username, - password: user.password - }); - } + setLoggedIn: setLoggedIn - }; + } ; }])
e40b9eb6927bfeb12a1f2e477c009076bbb7bcab
lib/startup/restoreOverwrittenFilesWithOriginals.js
lib/startup/restoreOverwrittenFilesWithOriginals.js
/* * Copyright (c) 2014-2020 Bjoern Kimminich. * SPDX-License-Identifier: MIT */ const glob = require('glob') const path = require('path') const fs = require('fs') const logger = require('../logger') const restoreOverwrittenFilesWithOriginals = () => { fs.copyFileSync(path.resolve(__dirname, '../../data/static/legal.md'), path.resolve(__dirname, '../../ftp/legal.md')) if (fs.existsSync('../../frontend/dist')) { fs.copyFileSync(path.resolve(__dirname, '../../data/static/JuiceShopJingle.vtt'), path.resolve(__dirname, '../../frontend/dist/frontend/assets/public/videos/JuiceShopJingle.vtt')) } glob(path.join(__dirname, '../../data/static/i18n/*.json'), (err, files) => { if (err) { logger.warn('Error listing JSON files in /data/static/i18n folder: ' + err.message) } else { files.forEach(filename => { fs.copyFileSync(filename, path.resolve(__dirname, '../../i18n/', filename.substring(filename.lastIndexOf('/') + 1))) }) } }) } module.exports = restoreOverwrittenFilesWithOriginals
/* * Copyright (c) 2014-2020 Bjoern Kimminich. * SPDX-License-Identifier: MIT */ const glob = require('glob') const path = require('path') const fs = require('fs') const logger = require('../logger') const restoreOverwrittenFilesWithOriginals = () => { fs.copyFileSync(path.resolve(__dirname, '../../data/static/legal.md'), path.resolve(__dirname, '../../ftp/legal.md')) if (fs.existsSync(path.resolve(__dirname,'../../frontend/dist'))) { fs.copyFileSync(path.resolve(__dirname, '../../data/static/JuiceShopJingle.vtt'), path.resolve(__dirname, '../../frontend/dist/frontend/assets/public/videos/JuiceShopJingle.vtt')) } glob(path.join(__dirname, '../../data/static/i18n/*.json'), (err, files) => { if (err) { logger.warn('Error listing JSON files in /data/static/i18n folder: ' + err.message) } else { files.forEach(filename => { fs.copyFileSync(filename, path.resolve(__dirname, '../../i18n/', filename.substring(filename.lastIndexOf('/') + 1))) }) } }) } module.exports = restoreOverwrittenFilesWithOriginals
Check for correct folder before copying subtitle file
Check for correct folder before copying subtitle file
JavaScript
mit
bkimminich/juice-shop,bkimminich/juice-shop,bkimminich/juice-shop,bkimminich/juice-shop,bkimminich/juice-shop,bkimminich/juice-shop
--- +++ @@ -10,7 +10,7 @@ const restoreOverwrittenFilesWithOriginals = () => { fs.copyFileSync(path.resolve(__dirname, '../../data/static/legal.md'), path.resolve(__dirname, '../../ftp/legal.md')) - if (fs.existsSync('../../frontend/dist')) { + if (fs.existsSync(path.resolve(__dirname,'../../frontend/dist'))) { fs.copyFileSync(path.resolve(__dirname, '../../data/static/JuiceShopJingle.vtt'), path.resolve(__dirname, '../../frontend/dist/frontend/assets/public/videos/JuiceShopJingle.vtt')) } glob(path.join(__dirname, '../../data/static/i18n/*.json'), (err, files) => {
22bcd6224d7424504b4cc7f24c04ff62443d0d46
components/calendar/day.js
components/calendar/day.js
import Event from './event'; const Day = ({ events }) => { let id = 0; let eventList = []; for (let e of events) { eventList.push(<Event title={e.title} start_time={e.start_time} content={e.content} key={id}/>); id++; } const DAY_NAMES = [ 'Mandag', 'Tirsdag', 'Onsdag', 'Torsdag', 'Fredag', 'Lørdag', 'Søndag' ]; const MONTH_NAMES = [ 'januar', 'februar', 'mars', 'april', 'mai', 'juni', 'juli', 'august', 'september', 'oktober', 'november', 'desember' ]; const DAY = events[ 0 ].start_time; const DAY_NAME = DAY_NAMES[ DAY.getDay() ]; const DATE = DAY.getDate(); const MONTH_NAME = MONTH_NAMES[ DAY.getMonth() ]; return ( <div> <h2>{`${DAY_NAME} ${DATE}. ${MONTH_NAME}`}</h2> {eventList} <br /> </div> ); }; export default Day;
import Event from './event'; const Day = ({ events }) => { const DAY_NAMES = [ 'Mandag', 'Tirsdag', 'Onsdag', 'Torsdag', 'Fredag', 'Lørdag', 'Søndag' ]; const MONTH_NAMES = [ 'januar', 'februar', 'mars', 'april', 'mai', 'juni', 'juli', 'august', 'september', 'oktober', 'november', 'desember' ]; const DAY = events[ 0 ].start_time; const DAY_NAME = DAY_NAMES[ DAY.getDay() ]; const DATE = DAY.getDate(); const MONTH_NAME = MONTH_NAMES[ DAY.getMonth() ]; return ( <div> <h2>{`${DAY_NAME} ${DATE}. ${MONTH_NAME}`}</h2> { events.map((e, id) => { return <Event title={e.title} start_time={e.start_time} content={e.content} key={id}/> })} <br /> </div> ); }; export default Day;
Remove the for-loop in favor of mapping the array into event components
Remove the for-loop in favor of mapping the array into event components
JavaScript
mit
dotKom/glowing-fortnight,dotKom/glowing-fortnight
--- +++ @@ -1,14 +1,6 @@ import Event from './event'; const Day = ({ events }) => { - - let id = 0; - let eventList = []; - - for (let e of events) { - eventList.push(<Event title={e.title} start_time={e.start_time} content={e.content} key={id}/>); - id++; - } const DAY_NAMES = [ 'Mandag', 'Tirsdag', 'Onsdag', 'Torsdag', 'Fredag', 'Lørdag', 'Søndag' ]; const MONTH_NAMES = [ 'januar', 'februar', 'mars', 'april', 'mai', 'juni', 'juli', 'august', 'september', 'oktober', 'november', 'desember' ]; @@ -21,7 +13,9 @@ return ( <div> <h2>{`${DAY_NAME} ${DATE}. ${MONTH_NAME}`}</h2> - {eventList} + { events.map((e, id) => { + return <Event title={e.title} start_time={e.start_time} content={e.content} key={id}/> + })} <br /> </div> );
822874ab19a96ebdab6f7232fdfdc3cfe411ab6d
config/ldap.js
config/ldap.js
const LDAP = require('ldap-client'), config = require('./config'); let protocol = config.get('ssl') ? 'ldaps://' : 'ldap://'; let host = config.get('ldap').hostname; let port = config.get('ldap').port; module.exports = new LDAP({ uri: protocol + [host, port].join(':'), base: config.get('ldap').searchBase });
'use strict'; const LDAP = require('ldap-client'), config = require('./config'); let protocol = config.get('ldap').ssl ? 'ldaps://' : 'ldap://'; let host = config.get('ldap').hostname; let port = config.get('ldap').port; module.exports = new LDAP({ uri: protocol + [host, port].join(':'), base: config.get('ldap').searchBase });
Fix let bug on older node
Fix let bug on older node
JavaScript
apache-2.0
mfinelli/cautious-ldap,mfinelli/cautious-ldap
--- +++ @@ -1,7 +1,9 @@ +'use strict'; + const LDAP = require('ldap-client'), config = require('./config'); -let protocol = config.get('ssl') ? 'ldaps://' : 'ldap://'; +let protocol = config.get('ldap').ssl ? 'ldaps://' : 'ldap://'; let host = config.get('ldap').hostname; let port = config.get('ldap').port;
d4444f33c32a56db9dc5b59d1174c79b5f04aafa
client/store/configureStore.js
client/store/configureStore.js
import {applyMiddleware, createStore} from 'redux'; import rootReducer from '../reducers'; import thunkMiddleware from 'redux-thunk'; export default function configureStore (initialState) { const create = typeof window !== 'undefined' && window.devToolsExtension ? window.devToolsExtension()(createStore) : createStore; const createStoreWithMiddleware = applyMiddleware(thunkMiddleware)(create); return createStoreWithMiddleware(rootReducer, initialState); }
import {applyMiddleware, compose, createStore} from 'redux'; import reducer from '../reducers'; import thunk from 'redux-thunk'; export default function configureStore (initialState) { return createStore( reducer, initialState, compose( applyMiddleware(thunk), typeof window !== 'undefined' && window.devToolsExtension ? window.devToolsExtension() : (f) => f ) ); }
Clean up store using compose
Clean up store using compose
JavaScript
mit
richardkall/react-starter,Thomas0c/react-starter,adamjking3/react-redux-apollo-starter
--- +++ @@ -1,13 +1,14 @@ -import {applyMiddleware, createStore} from 'redux'; -import rootReducer from '../reducers'; -import thunkMiddleware from 'redux-thunk'; +import {applyMiddleware, compose, createStore} from 'redux'; +import reducer from '../reducers'; +import thunk from 'redux-thunk'; export default function configureStore (initialState) { - const create = typeof window !== 'undefined' && window.devToolsExtension - ? window.devToolsExtension()(createStore) - : createStore; - - const createStoreWithMiddleware = applyMiddleware(thunkMiddleware)(create); - - return createStoreWithMiddleware(rootReducer, initialState); + return createStore( + reducer, + initialState, + compose( + applyMiddleware(thunk), + typeof window !== 'undefined' && window.devToolsExtension ? window.devToolsExtension() : (f) => f + ) + ); }
4813e914f56cd9e5ad82f04c449c509fc8e04034
src/api/model.js
src/api/model.js
import express from 'express'; import {addAction} from '../lib/database'; import ModelStore from '../store/model-store'; let app = express(); app.get('/', (req, res) => { let model = ModelStore.getModelById(req.query.id); res.successJson({ model: { address: model.address, name: model.name } }); }); app.get('/all-models', (req, res) => { res.successJson({ models: ModelStore.getAllModels() }); }); app.post('/', (req, res) => { addAction('NEW_MODEL', { name: req.body.name }) .then(actionId => { let model = ModelStore.getModelByActionId(actionId); res.successJson({ address: model.address }); }) .catch(e => { res.failureJson(e.message); }); }); export default app;
import express from 'express'; import { addAction } from '../lib/database'; import ModelStore from '../store/model-store'; let app = express(); app.get('/', (req, res) => { let model = ModelStore.getModelById(req.query.id); res.successJson({ model: { address: model.address, name: model.name } }); }); app.get('/all', (req, res) => { res.successJson({ models: ModelStore.getAllModels() }); }); app.post('/', (req, res) => { addAction('NEW_MODEL', { name: req.body.name }) .then(actionId => { let model = ModelStore.getModelByActionId(actionId); res.successJson({ address: model.address }); }) .catch(e => { res.failureJson(e.message); }); }); export default app;
Fix the things Jordan didn't
Fix the things Jordan didn't
JavaScript
unlicense
TheFourFifths/consus,TheFourFifths/consus
--- +++ @@ -1,5 +1,5 @@ import express from 'express'; -import {addAction} from '../lib/database'; +import { addAction } from '../lib/database'; import ModelStore from '../store/model-store'; let app = express(); @@ -13,7 +13,7 @@ } }); }); -app.get('/all-models', (req, res) => { +app.get('/all', (req, res) => { res.successJson({ models: ModelStore.getAllModels() });
69ea3ae14fba2cca826f4c40d2e4ed8914029560
ghost/admin/app/utils/route.js
ghost/admin/app/utils/route.js
import Route from '@ember/routing/route'; import {inject as service} from '@ember/service'; Route.reopen({ config: service(), billing: service(), router: service(), actions: { willTransition(transition) { if (this.get('upgradeStatus.isRequired')) { transition.abort(); this.upgradeStatus.requireUpgrade(); return false; } else if (this.config.get('hostSettings.forceUpgrade')) { transition.abort(); // Catch and redirect every route in a force upgrade state this.billing.openBillingWindow(this.router.currentURL, '/pro'); return false; } else { return true; } } } });
import Route from '@ember/routing/route'; import {inject as service} from '@ember/service'; Route.reopen({ config: service(), billing: service(), router: service(), actions: { willTransition(transition) { if (this.get('upgradeStatus.isRequired')) { transition.abort(); this.upgradeStatus.requireUpgrade(); return false; } else if (this.config.get('hostSettings.forceUpgrade') && transition.to?.name !== 'signout') { transition.abort(); // Catch and redirect every route in a force upgrade state this.billing.openBillingWindow(this.router.currentURL, '/pro'); return false; } else { return true; } } } });
Allow signout in `forceUpgrade` state
Allow signout in `forceUpgrade` state
JavaScript
mit
TryGhost/Ghost,TryGhost/Ghost,TryGhost/Ghost
--- +++ @@ -12,7 +12,7 @@ transition.abort(); this.upgradeStatus.requireUpgrade(); return false; - } else if (this.config.get('hostSettings.forceUpgrade')) { + } else if (this.config.get('hostSettings.forceUpgrade') && transition.to?.name !== 'signout') { transition.abort(); // Catch and redirect every route in a force upgrade state this.billing.openBillingWindow(this.router.currentURL, '/pro');
d7c846fd0e3289c25f40046c36e5f3046e4b74ea
src/banks/CBE.js
src/banks/CBE.js
/* eslint class-methods-use-this: ["error", { "exceptMethods": ["scraper"] }] */ import cheerio from 'cheerio'; import Bank from './Bank'; const banksNames = require('./banks_names.json'); export default class CBE extends Bank { constructor() { const url = 'http://www.cbe.org.eg/en/EconomicResearch/Statistics/Pages/ExchangeRatesListing.aspx'; super(banksNames.CBE, url); } /** * Scrape rates from html * @param {Object} html html of bank web page to scrape */ scraper(html) { const $ = cheerio.load(html); const tableRows = $('tbody').last().children(); tableRows.each((index, row) => { const currencyName = $(row) .children() .eq(0) .text() .trim(); const currencyBuy = $(row) .children() .eq(1) .text() .trim(); const currencySell = $(row) .children() .eq(2) .text() .trim(); }); const rates = []; return rates; } }
/* eslint class-methods-use-this: ["error", { "exceptMethods": ["scraper"] }] */ import cheerio from 'cheerio'; import Bank from './Bank'; const banksNames = require('./banks_names.json'); export default class CBE extends Bank { constructor() { const url = 'http://www.cbe.org.eg/en/EconomicResearch/Statistics/Pages/ExchangeRatesListing.aspx'; super(banksNames.CBE, url); } static getCurrencyCode(name) { const dict = { 'US Dollar​': 'USD', 'Euro​': 'EUR', 'Pound Sterling​': 'GBP', 'Swiss Franc​': 'CHF', 'Japanese Yen 100​': 'JPY', 'Saudi Riyal​': 'SAR', 'Kuwaiti Dinar​': 'KWD', 'UAE Dirham​': 'AED', 'Chinese yuan​': 'CNY', }; return (dict[name]); } /** * Scrape rates from html * @param {Object} html html of bank web page to scrape */ scraper(html) { const $ = cheerio.load(html); const tableRows = $('tbody').last().children(); const rates = []; tableRows.each((index, row) => { const currencyName = $(row) .children() .eq(0) .text() .trim(); const currencyBuy = $(row) .children() .eq(1) .text() .trim(); const currencySell = $(row) .children() .eq(2) .text() .trim(); rates.push({ code: CBE.getCurrencyCode(currencyName), buy: currencyBuy, sell: currencySell, }); }); return rates; } }
Convert currency name to currency iso code
Convert currency name to currency iso code
JavaScript
mit
MMayla/egypt-banks-scraper
--- +++ @@ -12,6 +12,22 @@ super(banksNames.CBE, url); } + static getCurrencyCode(name) { + const dict = { + 'US Dollar​': 'USD', + 'Euro​': 'EUR', + 'Pound Sterling​': 'GBP', + 'Swiss Franc​': 'CHF', + 'Japanese Yen 100​': 'JPY', + 'Saudi Riyal​': 'SAR', + 'Kuwaiti Dinar​': 'KWD', + 'UAE Dirham​': 'AED', + 'Chinese yuan​': 'CNY', + }; + + return (dict[name]); + } + /** * Scrape rates from html * @param {Object} html html of bank web page to scrape @@ -19,6 +35,7 @@ scraper(html) { const $ = cheerio.load(html); const tableRows = $('tbody').last().children(); + const rates = []; tableRows.each((index, row) => { const currencyName = $(row) .children() @@ -35,8 +52,13 @@ .eq(2) .text() .trim(); + + rates.push({ + code: CBE.getCurrencyCode(currencyName), + buy: currencyBuy, + sell: currencySell, + }); }); - const rates = []; return rates; } }
b453399b7913fec129a54b16f7e4e8e9f27f839d
src/server/api/put-drawing.js
src/server/api/put-drawing.js
import cuid from 'cuid'; import tinify from 'tinify'; import awsConfig from '@/config/tinify-aws'; import firebase from '@/config/firebase-admin'; tinify.key = process.env.TINYPNG_API_KEY; export default function putImages(req, res) { const drawingId = cuid(); const base64Data = req.body.source.split(',')[1].replace(/\s/g, '+'); const imgBuffer = Buffer.from(base64Data, 'base64'); const ref = firebase.database().ref(`/posts/${req.body.postid}/drawings/${drawingId}`); const publishedRef = firebase.database().ref(`/published/${req.body.postid}/drawings/${drawingId}`); tinify .fromBuffer(imgBuffer) .store(awsConfig(`bolg/drawings/${drawingId}.png`)) .meta() .then((meta) => { ref.set(meta.location); publishedRef.set(meta.location); res.send('ok'); }) .catch((err) => { res.error(err); }); }
import cuid from 'cuid'; import tinify from 'tinify'; import awsConfig from '@/config/tinify-aws'; import firebase from '@/config/firebase-admin'; tinify.key = process.env.TINYPNG_API_KEY; export default function putImages(req, res) { const drawingId = cuid(); const base64Data = req.body.source.split(',')[1].replace(/\s/g, '+'); const imgBuffer = Buffer.from(base64Data, 'base64'); const ref = firebase.database().ref(`/posts/${req.body.postid}/drawings/${drawingId}`); const publishedRef = firebase.database().ref(`/published/${req.body.postid}/drawings/${drawingId}`); tinify .fromBuffer(imgBuffer) .store(awsConfig(`bolg/drawings/${drawingId}.png`)) .meta() .then((meta) => { const cloudFront = `https://d3ieg3cxah9p4i.cloudfront.net/${meta.location.split('/bolg/')[1]}`; ref.set(cloudFront); publishedRef.set(cloudFront); res.send('ok'); }) .catch((err) => { res.error(err); }); }
Use cloudfront link to store drawings
Use cloudfront link to store drawings
JavaScript
mit
tuelsch/bolg,tuelsch/bolg
--- +++ @@ -17,8 +17,10 @@ .store(awsConfig(`bolg/drawings/${drawingId}.png`)) .meta() .then((meta) => { - ref.set(meta.location); - publishedRef.set(meta.location); + const cloudFront = `https://d3ieg3cxah9p4i.cloudfront.net/${meta.location.split('/bolg/')[1]}`; + ref.set(cloudFront); + publishedRef.set(cloudFront); + res.send('ok'); }) .catch((err) => {
b980b03d21e5941ffdf22491fd4fe786bf914094
native/packages/react-native-bpk-component-button-link/src/styles.js
native/packages/react-native-bpk-component-button-link/src/styles.js
/* * Backpack - Skyscanner's Design System * * Copyright 2018 Skyscanner 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. */ /* @flow */ import { StyleSheet } from 'react-native'; import { colorBlue500, colorGray300, spacingSm, spacingXl, } from 'bpk-tokens/tokens/base.react.native'; const styles = StyleSheet.create({ view: { height: spacingXl, flexDirection: 'row', alignItems: 'center', justifyContent: 'center', }, viewLarge: { height: spacingXl + spacingSm, }, viewLeading: { flexDirection: 'row-reverse', }, text: { color: colorBlue500, }, textDisabled: { color: colorGray300, }, icon: { color: colorBlue500, marginLeft: spacingSm, }, iconLeading: { marginLeft: 0, marginRight: spacingSm, }, }); export default styles;
/* * Backpack - Skyscanner's Design System * * Copyright 2018 Skyscanner 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. */ /* @flow */ import { StyleSheet } from 'react-native'; import { colorBlue500, colorGray300, spacingSm, spacingXl, } from 'bpk-tokens/tokens/base.react.native'; const styles = StyleSheet.create({ view: { minHeight: spacingXl, flexDirection: 'row', alignItems: 'center', justifyContent: 'center', }, viewLarge: { minHeight: spacingXl + spacingSm, }, viewLeading: { flexDirection: 'row-reverse', }, text: { color: colorBlue500, }, textDisabled: { color: colorGray300, }, icon: { color: colorBlue500, marginLeft: spacingSm, }, iconLeading: { marginLeft: 0, marginRight: spacingSm, }, }); export default styles;
Add dynamic text to Link buttons
[BPK-1716] Add dynamic text to Link buttons
JavaScript
apache-2.0
Skyscanner/backpack,Skyscanner/backpack,Skyscanner/backpack
--- +++ @@ -28,13 +28,13 @@ const styles = StyleSheet.create({ view: { - height: spacingXl, + minHeight: spacingXl, flexDirection: 'row', alignItems: 'center', justifyContent: 'center', }, viewLarge: { - height: spacingXl + spacingSm, + minHeight: spacingXl + spacingSm, }, viewLeading: { flexDirection: 'row-reverse',
16ebd7082ce2dff40de666cfeb06c939e7e92159
src/Jadu/Pulsar/Twig.js/Extension/RelativeTimeExtension.js
src/Jadu/Pulsar/Twig.js/Extension/RelativeTimeExtension.js
var _ = require('lodash'), moment = require('moment'); function RelativeTimeExtension() { moment.locale('en', { relativeTime : { future: "in %s", past: "%s ago", s: function (number, withoutSuffix, key, isFuture) { var plural = (number < 2) ? " second" : " seconds"; return number + plural; }, m: "%d minute", mm: "%d minutes", h: "%d hour", hh: "%d hours", d: "%d day", dd: "%d days", M: "%d month", MM: "%d months", y: "%d year", yy: "%d years" } }); } RelativeTimeExtension.prototype.getName = function () { return 'relative_time_extension'; }; RelativeTimeExtension.prototype.timeAgo = function (time_from) { if (time_from === undefined || time_from === null) { return false; } if (_.isDate(time_from)) { time_from = time_from.getTime()/1000; } var time_now = new Date().getTime(); if ((time_from*1000-time_now) === 0) { return 'just now'; } return moment.unix(time_from).fromNow(); }; module.exports = RelativeTimeExtension;
var _ = require('lodash'), moment = require('moment'); function RelativeTimeExtension() { moment.updateLocale('en', { relativeTime : { future: "in %s", past: "%s ago", s: function (number, withoutSuffix, key, isFuture) { var plural = (number < 2) ? " second" : " seconds"; return number + plural; }, m: "%d minute", mm: "%d minutes", h: "%d hour", hh: "%d hours", d: "%d day", dd: "%d days", M: "%d month", MM: "%d months", y: "%d year", yy: "%d years" } }); } RelativeTimeExtension.prototype.getName = function () { return 'relative_time_extension'; }; RelativeTimeExtension.prototype.timeAgo = function (time_from) { if (time_from === undefined || time_from === null) { return false; } if (_.isDate(time_from)) { time_from = time_from.getTime()/1000; } var time_now = new Date().getTime(); if ((time_from*1000-time_now) === 0) { return 'just now'; } return moment.unix(time_from).fromNow(); }; module.exports = RelativeTimeExtension;
Fix deprecation warning from moment
Fix deprecation warning from moment
JavaScript
mit
jadu/pulsar,jadu/pulsar,jadu/pulsar
--- +++ @@ -2,7 +2,7 @@ moment = require('moment'); function RelativeTimeExtension() { - moment.locale('en', { + moment.updateLocale('en', { relativeTime : { future: "in %s", past: "%s ago",
e8bf6e4214d906771ae27f2ba843825cc61eb62b
geotrek/jstests/_nav-utils.js
geotrek/jstests/_nav-utils.js
var fs = require('fs'); module.exports = (function() { const PATH_COOKIES = '/tmp/cookies.txt'; function setUp() { casper.options.viewportSize = {width: 1280, height: 768}; casper.options.waitTimeout = 10000; casper.userAgent('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.97 Safari/537.11'); casper.on('remote.message', function(msg) { this.echo("Error: " + msg, "ERROR"); }); casper.on('page.error', function(msg, trace) { this.echo("Error: " + msg, "ERROR"); for(var i=0; i<trace.length; i++) { var step = trace[i]; this.echo(' ' + step.file + ' (line ' + step.line + ')', "ERROR"); } }); } function saveCookies(path) { path = path || PATH_COOKIES; var cookies = JSON.stringify(phantom.cookies); fs.write(path, cookies, 600); } function loadCookies(path) { path = path || PATH_COOKIES; var data = fs.read(path); phantom.cookies = JSON.parse(data); } return { saveCookies: saveCookies, loadCookies: loadCookies }; })();
var fs = require('fs'); module.exports = (function() { const PATH_COOKIES = '/tmp/cookies.txt'; function setUp() { casper.options.viewportSize = {width: 1280, height: 768}; casper.options.waitTimeout = 10000; casper.userAgent('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.97 Safari/537.11'); casper.on('remote.message', function(msg) { this.echo("Error: " + msg, "ERROR"); }); casper.on('page.error', function(msg, trace) { this.echo("Error: " + msg, "ERROR"); for(var i=0; i<trace.length; i++) { var step = trace[i]; this.echo(' ' + step.file + ' (line ' + step.line + ')', "ERROR"); } }); } function saveCookies(path) { path = path || PATH_COOKIES; var cookies = JSON.stringify(phantom.cookies); fs.write(path, cookies, 600); } function loadCookies(path) { path = path || PATH_COOKIES; var data = fs.read(path); phantom.cookies = JSON.parse(data); } return { saveCookies: saveCookies, loadCookies: loadCookies, setUp: setUp }; })();
Fix nav test utils export
Fix nav test utils export
JavaScript
bsd-2-clause
GeotrekCE/Geotrek-admin,johan--/Geotrek,Anaethelion/Geotrek,makinacorpus/Geotrek,GeotrekCE/Geotrek-admin,johan--/Geotrek,mabhub/Geotrek,Anaethelion/Geotrek,makinacorpus/Geotrek,GeotrekCE/Geotrek-admin,makinacorpus/Geotrek,camillemonchicourt/Geotrek,GeotrekCE/Geotrek-admin,mabhub/Geotrek,johan--/Geotrek,Anaethelion/Geotrek,makinacorpus/Geotrek,camillemonchicourt/Geotrek,Anaethelion/Geotrek,mabhub/Geotrek,johan--/Geotrek,camillemonchicourt/Geotrek,mabhub/Geotrek
--- +++ @@ -36,6 +36,7 @@ return { saveCookies: saveCookies, - loadCookies: loadCookies + loadCookies: loadCookies, + setUp: setUp }; })();
74b8de8809ce6b2343657a996768b96320d7c242
src/gulpfile.js
src/gulpfile.js
var elixir = require('laravel-elixir'); elixir(function(mix) { mix.copy( 'node_modules/bootstrap/dist/fonts', 'public/fonts' ); mix.copy( 'node_modules/font-awesome/fonts', 'public/fonts' ); mix.copy( 'node_modules/ionicons/dist/fonts', 'public/fonts' ); mix.scripts([ '../../../node_modules/jquery/dist/jquery.min.js', '../../../node_modules/bootstrap/dist/js/bootstrap.min.js' ], 'public/js/vendor.js'); mix.scripts([ 'app.js' ], 'public/js/app.js'); mix.less([ '../../../node_modules/bootstrap/less/bootstrap.less', '../../../node_modules/font-awesome/less/font-awesome.less', '../../../node_modules/ionicons/dist/css/ionicons.min.css', 'admin-lte/AdminLTE.less', 'admin-lte/skins/_all-skins.less' ], 'public/css/vendor.css'); mix.less([ 'app.less' ], 'public/css/app.css'); mix.less([ 'welcome.less' ], 'public/css/welcome.css'); mix.version([ 'public/css/app.css', 'public/css/welcome.css', 'public/css/vendor.css', 'public/js/app.js', 'public/js/vendor.js' ]); });
var elixir = require('laravel-elixir'); elixir(function(mix) { mix.copy( 'node_modules/bootstrap/dist/fonts', 'public/build/fonts' ); mix.copy( 'node_modules/font-awesome/fonts', 'public/build/fonts' ); mix.copy( 'node_modules/ionicons/dist/fonts', 'public/build/fonts' ); mix.scripts([ '../../../node_modules/jquery/dist/jquery.min.js', '../../../node_modules/bootstrap/dist/js/bootstrap.min.js' ], 'public/js/vendor.js'); mix.scripts([ 'app.js' ], 'public/js/app.js'); mix.less([ '../../../node_modules/bootstrap/less/bootstrap.less', '../../../node_modules/font-awesome/less/font-awesome.less', '../../../node_modules/ionicons/dist/css/ionicons.min.css', 'adminlte/AdminLTE.less', 'adminlte/skins/_all-skins.less' ], 'public/css/vendor.css'); mix.less([ 'app.less' ], 'public/css/app.css'); mix.less([ 'welcome.less' ], 'public/css/welcome.css'); mix.version([ 'public/css/app.css', 'public/css/welcome.css', 'public/css/vendor.css', 'public/js/app.js', 'public/js/vendor.js' ]); });
Change path tot adminlte less file Copy the fonts to build folder because we will be using elixir
Change path tot adminlte less file Copy the fonts to build folder because we will be using elixir
JavaScript
mit
syahzul/admin-theme
--- +++ @@ -4,17 +4,17 @@ mix.copy( 'node_modules/bootstrap/dist/fonts', - 'public/fonts' + 'public/build/fonts' ); mix.copy( 'node_modules/font-awesome/fonts', - 'public/fonts' + 'public/build/fonts' ); mix.copy( 'node_modules/ionicons/dist/fonts', - 'public/fonts' + 'public/build/fonts' ); mix.scripts([ @@ -30,8 +30,8 @@ '../../../node_modules/bootstrap/less/bootstrap.less', '../../../node_modules/font-awesome/less/font-awesome.less', '../../../node_modules/ionicons/dist/css/ionicons.min.css', - 'admin-lte/AdminLTE.less', - 'admin-lte/skins/_all-skins.less' + 'adminlte/AdminLTE.less', + 'adminlte/skins/_all-skins.less' ], 'public/css/vendor.css'); mix.less([
7fa1ebf356afb1c8b7e1f0bc013428f1d4377fb1
src/Native/D3/index.js
src/Native/D3/index.js
Elm.Native.D3 = {}; import "JavaScript" import "Render" import "Color" import "Selection" import "Event" import "Transition" import "Voronoi"
Elm.Native.D3 = {}; import "JavaScript" import "Render" import "Color" import "Selection" import "Event" import "Transition" import "Voronoi" Elm.Native.D3.Scales = {}; import "Scales/Quantitative"
Index will include scales during compilation
Index will include scales during compilation
JavaScript
bsd-3-clause
NigelThorne/elm-d3,seliopou/elm-d3,NigelThorne/elm-d3
--- +++ @@ -9,3 +9,5 @@ import "Event" import "Transition" import "Voronoi" +Elm.Native.D3.Scales = {}; +import "Scales/Quantitative"
93b31e51d8a7e1017f7cd2d3603023ca4ecf1bc1
src/views/plugins/Markdown.js
src/views/plugins/Markdown.js
import MarkdownIt from 'markdown-it'; import gh from 'github-url-to-object'; function toAbsolute(baseUrl, src) { try { return new URL(src, baseUrl).toString(); } catch (e) { return src; } } const GH_CDN = 'https://raw.githubusercontent.com'; export default class extends MarkdownIt { constructor(opts) { super(opts); const rules = this.renderer.rules; this.renderer.rules = { ...rules, // Rewrite relative URLs. image(tokens, idx, ...args) { const token = tokens[idx]; // Rewrite repository-relative urls to the github CDN. const repository = opts.package.repository; if (repository && repository.type === 'git') { const github = gh(repository.url); if (github) { token.attrSet('src', toAbsolute( `${GH_CDN}/${github.user}/${github.repo}/${github.branch}/`, token.attrGet('src'))); } } return rules.image(tokens, idx, ...args); }, }; } }
import MarkdownIt from 'markdown-it'; import gh from 'github-url-to-object'; import { before } from 'meld'; function toAbsolute(baseUrl, src) { try { return new URL(src, baseUrl).toString(); } catch (e) { return src; } } const GH_CDN = 'https://raw.githubusercontent.com'; export default class extends MarkdownIt { constructor(opts) { super(opts); // Rewrite relative image URLs. before(this.renderer.rules, 'image', (tokens, idx) => { const token = tokens[idx]; // Rewrite repository-relative urls to the github CDN. const repository = opts.package.repository; if (repository && repository.type === 'git') { const github = gh(repository.url); if (github) { token.attrSet('src', toAbsolute( `${GH_CDN}/${github.user}/${github.repo}/${github.branch}/`, token.attrGet('src'))); } } }); } }
Use `meld` to override markdown image handling.
Use `meld` to override markdown image handling.
JavaScript
mit
ExtPlug/ExtPlug
--- +++ @@ -1,5 +1,6 @@ import MarkdownIt from 'markdown-it'; import gh from 'github-url-to-object'; +import { before } from 'meld'; function toAbsolute(baseUrl, src) { try { @@ -15,26 +16,20 @@ constructor(opts) { super(opts); - const rules = this.renderer.rules; - this.renderer.rules = { - ...rules, - // Rewrite relative URLs. - image(tokens, idx, ...args) { - const token = tokens[idx]; + // Rewrite relative image URLs. + before(this.renderer.rules, 'image', (tokens, idx) => { + const token = tokens[idx]; - // Rewrite repository-relative urls to the github CDN. - const repository = opts.package.repository; - if (repository && repository.type === 'git') { - const github = gh(repository.url); - if (github) { - token.attrSet('src', toAbsolute( - `${GH_CDN}/${github.user}/${github.repo}/${github.branch}/`, - token.attrGet('src'))); - } + // Rewrite repository-relative urls to the github CDN. + const repository = opts.package.repository; + if (repository && repository.type === 'git') { + const github = gh(repository.url); + if (github) { + token.attrSet('src', toAbsolute( + `${GH_CDN}/${github.user}/${github.repo}/${github.branch}/`, + token.attrGet('src'))); } - - return rules.image(tokens, idx, ...args); - }, - }; + } + }); } }
327a3e9edc2d44fc6e5dc6dfbab2f783efac471e
src/bot/index.js
src/bot/index.js
import 'babel-polyfill'; import { existsSync } from 'fs'; import { resolve } from 'path'; import merge from 'lodash.merge'; import TipsBot from './Tipsbot'; const tokenPath = resolve(__dirname, '..', '..', 'token.js'); const defaultToken = existsSync(tokenPath) ? require(tokenPath) : ''; const defaultName = 'Tipsbot'; const defaultTips = resolve(__dirname, '..', '..', 'data', 'pragmatic-programmer.json'); const defaultChannel = 'general'; const defaultSchedule = '0 9 * * 1,2,3,4,5'; // 09:00 on monday-friday const defaultStartIndex = 0; const defaultIconURL = ''; export const create = (options = {}) => { let defaults = { token: process.env.BOT_API_KEY || defaultToken, name: process.env.BOT_NAME || defaultName, filePath: process.env.BOT_FILE_PATH || defaultTips, channel: process.env.BOT_CHANNEL || defaultChannel, schedule: process.env.BOT_SCHEDULE || defaultSchedule, startIndex: process.env.BOT_START_INDEX || defaultStartIndex, iconURL: process.env.BOT_ICON_URL || defaultIconURL, }; return new TipsBot(merge(defaults, options)); }
import 'babel-polyfill'; import { existsSync } from 'fs'; import { resolve } from 'path'; import merge from 'lodash.merge'; import TipsBot from './Tipsbot'; const tokenPath = resolve(__dirname, '..', '..', 'token.js'); const defaultToken = existsSync(tokenPath) ? require(tokenPath) : ''; const defaultName = 'Tipsbot'; const defaultTips = resolve(__dirname, '..', '..', 'data', 'pragmatic-programmer.json'); const defaultChannel = 'general'; const defaultSchedule = '0 9 * * 1-5'; // 09:00 on monday-friday const defaultStartIndex = 0; const defaultIconURL = ''; export const create = (options = {}) => { let defaults = { token: process.env.BOT_API_KEY || defaultToken, name: process.env.BOT_NAME || defaultName, filePath: process.env.BOT_FILE_PATH || defaultTips, channel: process.env.BOT_CHANNEL || defaultChannel, schedule: process.env.BOT_SCHEDULE || defaultSchedule, startIndex: process.env.BOT_START_INDEX || defaultStartIndex, iconURL: process.env.BOT_ICON_URL || defaultIconURL, }; return new TipsBot(merge(defaults, options)); }
Fix to default cron time
Fix to default cron time
JavaScript
mit
simon-johansson/tipsbot
--- +++ @@ -11,7 +11,7 @@ const defaultName = 'Tipsbot'; const defaultTips = resolve(__dirname, '..', '..', 'data', 'pragmatic-programmer.json'); const defaultChannel = 'general'; -const defaultSchedule = '0 9 * * 1,2,3,4,5'; // 09:00 on monday-friday +const defaultSchedule = '0 9 * * 1-5'; // 09:00 on monday-friday const defaultStartIndex = 0; const defaultIconURL = '';
dbb9c0957a5485a0a86f982c61eeb6b8c44cf3b9
horizon/static/horizon/js/horizon.metering.js
horizon/static/horizon/js/horizon.metering.js
horizon.metering = { init_create_usage_report_form: function() { horizon.datepickers.add('input[data-date-picker="True"]'); horizon.metering.add_change_event_to_period_dropdown(); horizon.metering.show_or_hide_date_fields(); }, init_stats_page: function() { if (typeof horizon.d3_line_chart !== 'undefined') { horizon.d3_line_chart.init("div[data-chart-type='line_chart']", {'auto_resize': true}); } horizon.metering.add_change_event_to_period_dropdown(); horizon.metering.show_or_hide_date_fields(); }, show_or_hide_date_fields: function() { $("#date_from .controls input, #date_to .controls input").val(''); if ($("#id_period").find("option:selected").val() === "other"){ $("#id_date_from, #id_date_to").parent().parent().show(); return true; } else { $("#id_date_from, #id_date_to").parent().parent().hide(); return false; } }, add_change_event_to_period_dropdown: function() { $("#id_period").change(function(evt) { if (horizon.metering.show_or_hide_date_fields()) { evt.stopPropagation(); } }); } };
horizon.metering = { init_create_usage_report_form: function() { horizon.datepickers.add('input[data-date-picker]'); horizon.metering.add_change_event_to_period_dropdown(); horizon.metering.show_or_hide_date_fields(); }, init_stats_page: function() { if (typeof horizon.d3_line_chart !== 'undefined') { horizon.d3_line_chart.init("div[data-chart-type='line_chart']", {'auto_resize': true}); } horizon.metering.add_change_event_to_period_dropdown(); horizon.metering.show_or_hide_date_fields(); }, show_or_hide_date_fields: function() { $("#date_from .controls input, #date_to .controls input").val(''); if ($("#id_period").find("option:selected").val() === "other"){ $("#id_date_from, #id_date_to").parent().parent().show(); return true; } else { $("#id_date_from, #id_date_to").parent().parent().hide(); return false; } }, add_change_event_to_period_dropdown: function() { $("#id_period").change(function(evt) { if (horizon.metering.show_or_hide_date_fields()) { evt.stopPropagation(); } }); } };
Change widget attribute to string
Change widget attribute to string In Django 1.8, widget attribute data-date-picker=True will be rendered as 'data-date-picker'. This patch will just look for the presence of the attribute, ignoring the actual value. Change-Id: I0beabddfe13c060ef2222a09636738428135040a Closes-Bug: #1467935 (cherry picked from commit f4581dd48a7ffdcdf1b0061951e837c69caf9420)
JavaScript
apache-2.0
Daniex/horizon,NCI-Cloud/horizon,wangxiangyu/horizon,wangxiangyu/horizon,NCI-Cloud/horizon,wangxiangyu/horizon,VaneCloud/horizon,izadorozhna/dashboard_integration_tests,VaneCloud/horizon,izadorozhna/dashboard_integration_tests,Daniex/horizon,VaneCloud/horizon,Daniex/horizon,NCI-Cloud/horizon,Daniex/horizon,NCI-Cloud/horizon,wangxiangyu/horizon,VaneCloud/horizon
--- +++ @@ -1,6 +1,6 @@ horizon.metering = { init_create_usage_report_form: function() { - horizon.datepickers.add('input[data-date-picker="True"]'); + horizon.datepickers.add('input[data-date-picker]'); horizon.metering.add_change_event_to_period_dropdown(); horizon.metering.show_or_hide_date_fields(); },
301d8c45b157cd4b673f40a70965a19af2c4275d
addon/utils/get-mutable-attributes.js
addon/utils/get-mutable-attributes.js
import Ember from 'ember'; var getMutValue = Ember.__loader.require('ember-htmlbars/hooks/get-value')['default']; export default function getMutableAttributes(attrs) { return Object.keys(attrs).reduce((acc, attr) => { acc[attr] = getMutValue(attrs[attr]); return acc; }, {}); }
import Ember from 'ember'; const emberMajorMinorVersion = Ember.VERSION.match(/(\d+\.\d+)\.*/)[1]; const isGlimmer = Number(emberMajorMinorVersion) >= 2.10; let getMutValue; if (isGlimmer) { const { MUTABLE_CELL } = Ember.__loader.require('ember-views/compat/attrs'); getMutValue = (value) => { if (value && value[MUTABLE_CELL]) { return value.value; } else { return value; } }; } else { getMutValue = Ember.__loader.require('ember-glimmer/hooks/get-value')['default']; } export default function getMutableAttributes(attrs) { return Object.keys(attrs).reduce((acc, attr) => { acc[attr] = getMutValue(attrs[attr]); return acc; }, {}); }
Fix for getting mutable attributes in glimmer
Fix for getting mutable attributes in glimmer
JavaScript
mit
pswai/ember-cli-react,pswai/ember-cli-react
--- +++ @@ -1,6 +1,22 @@ import Ember from 'ember'; -var getMutValue = Ember.__loader.require('ember-htmlbars/hooks/get-value')['default']; +const emberMajorMinorVersion = Ember.VERSION.match(/(\d+\.\d+)\.*/)[1]; +const isGlimmer = Number(emberMajorMinorVersion) >= 2.10; + +let getMutValue; + +if (isGlimmer) { + const { MUTABLE_CELL } = Ember.__loader.require('ember-views/compat/attrs'); + getMutValue = (value) => { + if (value && value[MUTABLE_CELL]) { + return value.value; + } else { + return value; + } + }; +} else { + getMutValue = Ember.__loader.require('ember-glimmer/hooks/get-value')['default']; +} export default function getMutableAttributes(attrs) { return Object.keys(attrs).reduce((acc, attr) => {
9474e5cb8a16fd2beb8aa5c73f8189c0d78cfd25
tasks/parallel-behat.js
tasks/parallel-behat.js
'use strict'; var glob = require('glob'), _ = require('underscore'), ParallelExec = require('./lib/ParallelExec'), BehatTask = require('./lib/BehatTask'), defaults = { src: './**/*.feature', bin: './bin/behat', cwd: './', config: './behat.yml', flags: '', maxProcesses: 10000, baseDir: './', debug: false, numRetries: 0, timeout: 600000 }; /** * Grunt task for executing behat feature files in parallel * * @param {Grunt} grunt */ function GruntTask (grunt) { var options = _.defaults(grunt.config('behat') || {}, defaults), executor = new ParallelExec(options.maxProcesses, {cwd: options.cwd, timeout: options.timeout}), behat; grunt.registerTask('behat', 'Parallel behat', function () { var done = this.async(); glob(options.src, function (err, files) { options.files = files; options.done = done; options.executor = executor; options.log = grunt.log.writeln; behat = new BehatTask(options); behat.run(); }); }); } module.exports = GruntTask;
'use strict'; var glob = require('glob'), _ = require('underscore'), ParallelExec = require('./lib/ParallelExec'), BehatTask = require('./lib/BehatTask'), defaults = { src: './**/*.feature', bin: './bin/behat', cwd: './', config: './behat.yml', flags: '', maxProcesses: 10000, baseDir: './', debug: false, numRetries: 0, timeout: 600000 }; /** * Grunt task for executing behat feature files in parallel * * @param {Grunt} grunt */ function GruntTask (grunt) { grunt.registerMultiTask('behat', 'Parallel behat', function () { var done = this.async(), options = this.options(defaults), executor = new ParallelExec(options.maxProcesses, {cwd: options.cwd, timeout: options.timeout}), behat; options.files = this.filesSrc; options.done = done; options.executor = executor; options.log = grunt.log.writeln; behat = new BehatTask(options); behat.run(); }); } module.exports = GruntTask;
Fix options loading and turn into MultiTask
Fix options loading and turn into MultiTask
JavaScript
mit
linusnorton/grunt-parallel-behat
--- +++ @@ -24,22 +24,20 @@ * @param {Grunt} grunt */ function GruntTask (grunt) { - var options = _.defaults(grunt.config('behat') || {}, defaults), - executor = new ParallelExec(options.maxProcesses, {cwd: options.cwd, timeout: options.timeout}), - behat; - grunt.registerTask('behat', 'Parallel behat', function () { - var done = this.async(); + grunt.registerMultiTask('behat', 'Parallel behat', function () { + var done = this.async(), + options = this.options(defaults), + executor = new ParallelExec(options.maxProcesses, {cwd: options.cwd, timeout: options.timeout}), + behat; - glob(options.src, function (err, files) { - options.files = files; - options.done = done; - options.executor = executor; - options.log = grunt.log.writeln; + options.files = this.filesSrc; + options.done = done; + options.executor = executor; + options.log = grunt.log.writeln; - behat = new BehatTask(options); - behat.run(); - }); + behat = new BehatTask(options); + behat.run(); }); }
cab68ae620e449e49385a6125d233129d7d325cf
src/js/route.js
src/js/route.js
var route = function(name, params = {}, absolute = true) { var domain = (namedRoutes[name].domain || baseUrl).replace(/\/+$/,'') + '/', url = (absolute ? domain : '') + namedRoutes[name].uri return url.replace( /\{([^}]+)\}/gi, function (tag) { var key = tag.replace(/\{|\}/gi, ''); if (params[key] === undefined) { throw 'Ziggy Error: "' + key + '" key is required for route "' + name + '"'; } return params[key]; } ); } if (typeof exports !== 'undefined'){ exports.route = route }
var route = function(name, params = {}, absolute = true) { var domain = (namedRoutes[name].domain || baseUrl).replace(/\/+$/,'') + '/', url = (absolute ? domain : '') + namedRoutes[name].uri, arrayKey = 0; return url.replace( /\{([^}]+)\}/gi, function (tag) { var key = Array.isArray(params) ? arrayKey : tag.replace(/\{|\}/gi, ''); if (params[key] === undefined) { throw 'Ziggy Error: "' + key + '" key is required for route "' + name + '"'; } arrayKey++; return params[key]; } ); } if (typeof exports !== 'undefined'){ exports.route = route }
Add support for unkeyed params array.
Add support for unkeyed params array.
JavaScript
mit
tightenco/ziggy,tightenco/ziggy
--- +++ @@ -1,14 +1,16 @@ var route = function(name, params = {}, absolute = true) { var domain = (namedRoutes[name].domain || baseUrl).replace(/\/+$/,'') + '/', - url = (absolute ? domain : '') + namedRoutes[name].uri + url = (absolute ? domain : '') + namedRoutes[name].uri, + arrayKey = 0; return url.replace( /\{([^}]+)\}/gi, function (tag) { - var key = tag.replace(/\{|\}/gi, ''); + var key = Array.isArray(params) ? arrayKey : tag.replace(/\{|\}/gi, ''); if (params[key] === undefined) { throw 'Ziggy Error: "' + key + '" key is required for route "' + name + '"'; } + arrayKey++; return params[key]; } );
dff0317c05d48588f6e86b80ebc3b1bdc3b0b8f7
editor/static/editor.js
editor/static/editor.js
var app var project var checkout var host var session window.addEventListener('load', () => { project = substance.getQueryStringParam('project'); checkout = substance.getQueryStringParam('checkout'); host = substance.getQueryStringParam('host'); session = substance.getQueryStringParam('session'); // If a session is provided then connect directly to that host // otherwise use the top level v0 API to create a new session if (host && session) { window.STENCILA_HOSTS = `${host}/v1/sessions!/${session}`; } else if (host) { window.STENCILA_HOSTS = `${host}/v0`; } // Mount the app substance.substanceGlobals.DEBUG_RENDERING = substance.platform.devtools; app = stencila.StencilaWebApp.mount({ archiveId: checkout, storageType: 'fs', storageUrl: '/edit/storage' }, window.document.body); // Remove the loading var loading = document.getElementById('loading'); loading.parentNode.removeChild(loading) // Commit button var commitBtn = document.getElementById('commit'); commitBtn.addEventListener('click', () => { commitBtn.disabled = true; commit().then(() => { commitBtn.disabled = false; }) }) }); window.addEventListener('beforeunload', () => { // Commit changes when window closed commit() }) function commit () { return app._save().then(() => { fetch(`/checkouts/${checkout}/commit`, { credentials: 'same-origin' }) }) }
var app var checkout var key var host var session window.addEventListener('load', () => { checkout = substance.getQueryStringParam('checkout'); key = substance.getQueryStringParam('key'); host = substance.getQueryStringParam('host'); session = substance.getQueryStringParam('session'); // If a session is provided then connect directly to that host // otherwise use the top level v0 API to create a new session if (host && session) { window.STENCILA_HOSTS = `${host}/v1/sessions!/${session}`; } else if (host) { window.STENCILA_HOSTS = `${host}/v0`; } // Mount the app substance.substanceGlobals.DEBUG_RENDERING = substance.platform.devtools; app = stencila.StencilaWebApp.mount({ archiveId: key, storageType: 'fs', storageUrl: '/edit/storage' }, window.document.body); // Remove the loading var loading = document.getElementById('loading'); loading.parentNode.removeChild(loading) // Commit button var commitBtn = document.getElementById('commit'); commitBtn.addEventListener('click', () => { commitBtn.disabled = true; commit().then(() => { commitBtn.disabled = false; }) }) }); window.addEventListener('beforeunload', () => { // Commit changes when window closed commit() }) function commit () { return app._save().then(() => { fetch(`/checkouts/${checkout}/save/`, { method: 'POST', credentials: 'same-origin' }) }) }
Change var names and use save endpoint
Change var names and use save endpoint
JavaScript
apache-2.0
stencila/hub,stencila/hub,stencila/hub,stencila/hub,stencila/hub
--- +++ @@ -1,13 +1,13 @@ var app -var project var checkout +var key var host var session window.addEventListener('load', () => { - project = substance.getQueryStringParam('project'); checkout = substance.getQueryStringParam('checkout'); + key = substance.getQueryStringParam('key'); host = substance.getQueryStringParam('host'); session = substance.getQueryStringParam('session'); @@ -22,7 +22,7 @@ // Mount the app substance.substanceGlobals.DEBUG_RENDERING = substance.platform.devtools; app = stencila.StencilaWebApp.mount({ - archiveId: checkout, + archiveId: key, storageType: 'fs', storageUrl: '/edit/storage' }, window.document.body); @@ -49,7 +49,8 @@ function commit () { return app._save().then(() => { - fetch(`/checkouts/${checkout}/commit`, { + fetch(`/checkouts/${checkout}/save/`, { + method: 'POST', credentials: 'same-origin' }) })
6bb1a3ca881b6c7e0a20e5e049c211a79183ff6e
src/disclosures/js/dispatchers/get-school-values.js
src/disclosures/js/dispatchers/get-school-values.js
'use strict'; var stringToNum = require( '../utils/handle-string-input' ); var getSchoolValues = { var values = {}; init: function( ) { values.programLength = this.getProgramLength(); values.gradRate = this.getGradRate(); values.medianDebt = this.getMedianDebt(); values.defaultRate = this.getDefaultRate(); values.medianSalary = this.getMedianSalary(); return values; }, getProgramLength: function() { // Rounds up to the nearest number of years. // Might need to change later, to address 18 month or 30 month programs. return Math.ceil(window.programData.programLength / 12) || ''; }, getGradRate: function() { if ( window.programData.completionRate == 'None' ) { return window.schoolData.gradRate; } else { return window.programData.completionRate || window.schoolData.gradRate; } }, getMedianDebt: function() { return window.programData.medianStudentLoanCompleters || window.schoolData.medianMonthlyDebt; }, getDefaultRate: function() { return (window.programData.defaultRate / 100) || window.schoolData.defaultRate; }, getMedianSalary: function() { return window.programData.salary || window.schoolData.medianAnnualPay; } }; module.exports = getSchoolValues;
'use strict'; var getSchoolValues = { var values = {}; init: function( ) { values.programLength = this.getProgramLength(); values.gradRate = this.getGradRate(); values.medianDebt = this.getMedianDebt(); values.defaultRate = this.getDefaultRate(); values.medianSalary = this.getMedianSalary(); return values; }, getProgramLength: function() { // Rounds up to the nearest number of years. // Might need to change later, to address 18 month or 30 month programs. return Math.ceil(window.programData.programLength / 12) || ''; }, getGradRate: function() { if ( window.programData.completionRate == 'None' ) { return window.schoolData.gradRate; } else { return window.programData.completionRate || window.schoolData.gradRate; } }, getMedianDebt: function() { return window.programData.medianStudentLoanCompleters || window.schoolData.medianMonthlyDebt; }, getDefaultRate: function() { return (window.programData.defaultRate / 100) || window.schoolData.defaultRate; }, getMedianSalary: function() { return window.programData.salary || window.schoolData.medianAnnualPay; } }; module.exports = getSchoolValues;
Remove lingering but unneeded requirement call
Remove lingering but unneeded requirement call
JavaScript
cc0-1.0
mistergone/college-costs,mistergone/college-costs,mistergone/college-costs,mistergone/college-costs
--- +++ @@ -1,6 +1,4 @@ 'use strict'; - -var stringToNum = require( '../utils/handle-string-input' ); var getSchoolValues = {
c76fda7d6ed6ca449330a9d2b084732a9ffd295e
test/index.js
test/index.js
import test from "ava"; import {newUnibeautify, Beautifier} from "unibeautify"; import beautifier from "../dist"; test.beforeEach((t) => { t.context.unibeautify = newUnibeautify(); }); test("should successfully install beautifier", (t) => { const {unibeautify} = t.context; unibeautify.loadBeautifier(beautifier); t.is(unibeautify.beautifiers[0].name, beautifier.name); }); test("should successfully beautify JavaScript text", (t) => { const {unibeautify} = t.context; unibeautify.loadBeautifier(beautifier); const text = `function test(n){return n+1;}`; const beautifierResult = `function test(n) { return n + 1; }`; return unibeautify.beautify({ languageName: "JavaScript", options: { JavaScript: { indent_char: " ", indent_size: 2 } }, text }).then((results) => { t.is(results, beautifierResult); }); });
import test from "ava"; import { newUnibeautify, Beautifier } from "unibeautify"; import beautifier from "../dist"; test.beforeEach(t => { t.context.unibeautify = newUnibeautify(); }); test("should successfully install beautifier", t => { const { unibeautify } = t.context; unibeautify.loadBeautifier(beautifier); t.is(unibeautify.beautifiers[0].name, beautifier.name); }); test("should successfully beautify JavaScript text with 2 space indentation", t => { const { unibeautify } = t.context; unibeautify.loadBeautifier(beautifier); const text = `function test(n){return n+1;}`; const beautifierResult = `function test(n) { return n + 1; }`; return unibeautify .beautify({ languageName: "JavaScript", options: { JavaScript: { indent_char: " ", indent_size: 2 } }, text }) .then(results => { t.is(results, beautifierResult); }); }); test("should successfully beautify JavaScript text with double quotes", t => { const { unibeautify } = t.context; unibeautify.loadBeautifier(beautifier); const text = `console.log('hello world');`; const beautifierResult = `console.log("hello world");`; return unibeautify .beautify({ languageName: "JavaScript", options: { JavaScript: { indent_char: " ", indent_size: 2, convert_quotes: "double" } }, text }) .then(results => { t.is(results, beautifierResult); }); });
Add test for double quotes
Add test for double quotes
JavaScript
mit
Unibeautify/beautifier-prettydiff,Unibeautify/beautifier-prettydiff
--- +++ @@ -1,31 +1,56 @@ import test from "ava"; -import {newUnibeautify, Beautifier} from "unibeautify"; +import { newUnibeautify, Beautifier } from "unibeautify"; import beautifier from "../dist"; -test.beforeEach((t) => { +test.beforeEach(t => { t.context.unibeautify = newUnibeautify(); }); -test("should successfully install beautifier", (t) => { - const {unibeautify} = t.context; +test("should successfully install beautifier", t => { + const { unibeautify } = t.context; unibeautify.loadBeautifier(beautifier); t.is(unibeautify.beautifiers[0].name, beautifier.name); }); -test("should successfully beautify JavaScript text", (t) => { - const {unibeautify} = t.context; + +test("should successfully beautify JavaScript text with 2 space indentation", t => { + const { unibeautify } = t.context; unibeautify.loadBeautifier(beautifier); const text = `function test(n){return n+1;}`; const beautifierResult = `function test(n) { return n + 1; }`; - return unibeautify.beautify({ - languageName: "JavaScript", - options: { - JavaScript: { - indent_char: " ", - indent_size: 2 - } - }, - text - }).then((results) => { - t.is(results, beautifierResult); - }); + return unibeautify + .beautify({ + languageName: "JavaScript", + options: { + JavaScript: { + indent_char: " ", + indent_size: 2 + } + }, + text + }) + .then(results => { + t.is(results, beautifierResult); + }); }); + +test("should successfully beautify JavaScript text with double quotes", t => { + const { unibeautify } = t.context; + unibeautify.loadBeautifier(beautifier); + const text = `console.log('hello world');`; + const beautifierResult = `console.log("hello world");`; + return unibeautify + .beautify({ + languageName: "JavaScript", + options: { + JavaScript: { + indent_char: " ", + indent_size: 2, + convert_quotes: "double" + } + }, + text + }) + .then(results => { + t.is(results, beautifierResult); + }); +});
00f048fe44190a4df276a6c9ddf2a80359ecd1a8
test/reverse_urlSpec.js
test/reverse_urlSpec.js
(function () { 'use strict'; describe('Unit: angular-reverse-url', function () { beforeEach(module('angular-reverse-url')); describe('reverseUrl filter', function () { }); }); }());
(function () { 'use strict'; var reverseUrl, $route; var routeMock = {}; routeMock.routes = { '/testRoute1/': { controller: 'TestController1', originalPath: '/test-route-1/' }, '/testRoute1/:params/': { controller: 'TestController1', originalPath: '/test-route-1/:param/' }, '/testRoute2/': { name: 'TestRoute2', originalPath: '/test-route-2/' }, }; describe('Unit: angular-reverse-url', function () { beforeEach(module('angular-reverse-url', function ($provide) { $provide.value('$route', routeMock); })); describe('reverseUrl filter', function () { beforeEach(inject(function ($injector) { $route = $injector.get('$route') reverseUrl = $injector.get('$filter')('reverseUrl'); })); it('should correctly match to a basic route by controller', function () { expect(reverseUrl('TestController1')).toEqual('#/test-route-1/'); }); it('should correctly match to a basic route by name', function () { expect(reverseUrl('TestRoute2')).toEqual('#/test-route-2/'); }); it('should correctly match to a route with params', function () { expect(reverseUrl('TestController1', {param: 'foobar'})).toEqual('#/test-route-1/foobar/'); }); }); }); }());
Add tests for existing functionality
Add tests for existing functionality
JavaScript
mit
incuna/angular-reverse-url
--- +++ @@ -2,12 +2,49 @@ 'use strict'; + var reverseUrl, $route; + var routeMock = {}; + + routeMock.routes = { + '/testRoute1/': { + controller: 'TestController1', + originalPath: '/test-route-1/' + }, + '/testRoute1/:params/': { + controller: 'TestController1', + originalPath: '/test-route-1/:param/' + }, + '/testRoute2/': { + name: 'TestRoute2', + originalPath: '/test-route-2/' + }, + }; + describe('Unit: angular-reverse-url', function () { - beforeEach(module('angular-reverse-url')); + beforeEach(module('angular-reverse-url', function ($provide) { + $provide.value('$route', routeMock); + })); describe('reverseUrl filter', function () { - + + beforeEach(inject(function ($injector) { + $route = $injector.get('$route') + reverseUrl = $injector.get('$filter')('reverseUrl'); + })); + + it('should correctly match to a basic route by controller', function () { + expect(reverseUrl('TestController1')).toEqual('#/test-route-1/'); + }); + + it('should correctly match to a basic route by name', function () { + expect(reverseUrl('TestRoute2')).toEqual('#/test-route-2/'); + }); + + it('should correctly match to a route with params', function () { + expect(reverseUrl('TestController1', {param: 'foobar'})).toEqual('#/test-route-1/foobar/'); + }); + }); });
f7215986927ab3136b878bda5654d6fffc2d0fc1
app/components/github-team-notices.js
app/components/github-team-notices.js
import DashboardWidgetComponent from 'appkit/components/dashboard-widget'; var GithubTeamNotices = DashboardWidgetComponent.extend({ init: function() { this._super(); this.set("contents", []); }, actions: { receiveEvent: function(data) { var items = Ember.A(JSON.parse(data)); this.updatePullRequests(items.pull_requests); // eventually Issues too } }, updatePullRequests: function(items) { var contents = this.get("contents"); if (!Ember.isEmpty(items)) { // Remove items that have disappeared. var itemsToRemove = []; contents.forEach(function(existingItem) { var isNotPresent = !items.findBy("url", existingItem.get("url")); if (isNotPresent) { itemsToRemove.pushObject(existingItem); } }); contents.removeObjects(itemsToRemove); // Process current items. items.forEach(function(item) { var existingItem = contents.findBy("url", item.url); if (Ember.isEmpty(existingItem)) { // Add new items. var newItem = contents.pushObject(Ember.Object.create(item)); newItem.set("dashEventType", "Pull Request"); } else { // Update existing items. existingItem.setProperties(item); } }); } } }); export default GithubTeamNotices;
import DashboardWidgetComponent from 'appkit/components/dashboard-widget'; var GithubTeamNotices = DashboardWidgetComponent.extend({ init: function() { this._super(); this.set("contents", []); }, actions: { receiveEvent: function(data) { var items = Ember.A(JSON.parse(data)); this.updatePullRequests(items.pull_requests); // eventually Issues too } }, updatePullRequests: function(items) { var contents = this.get("contents"); if (!Ember.isEmpty(items)) { // Remove items that have disappeared. var itemsToRemove = []; contents.forEach(function(existingItem) { var isNotPresent = !items.findBy("id", existingItem.get("id")); if (isNotPresent) { itemsToRemove.pushObject(existingItem); } }); contents.removeObjects(itemsToRemove); // Process current items. items.forEach(function(item) { var existingItem = contents.findBy("url", item.id); if (Ember.isEmpty(existingItem)) { // Add new items. var newItem = contents.pushObject(Ember.Object.create(item)); newItem.set("dashEventType", "Pull Request"); } else { // Update existing items. existingItem.setProperties(item); } }); } } }); export default GithubTeamNotices;
Fix existing item recognition in "Code" widget.
Fix existing item recognition in "Code" widget.
JavaScript
mit
substantial/substantial-dash-client
--- +++ @@ -22,7 +22,7 @@ // Remove items that have disappeared. var itemsToRemove = []; contents.forEach(function(existingItem) { - var isNotPresent = !items.findBy("url", existingItem.get("url")); + var isNotPresent = !items.findBy("id", existingItem.get("id")); if (isNotPresent) { itemsToRemove.pushObject(existingItem); } @@ -31,7 +31,7 @@ // Process current items. items.forEach(function(item) { - var existingItem = contents.findBy("url", item.url); + var existingItem = contents.findBy("url", item.id); if (Ember.isEmpty(existingItem)) { // Add new items. var newItem = contents.pushObject(Ember.Object.create(item)); @@ -41,6 +41,7 @@ existingItem.setProperties(item); } }); + } }
b5c332043213eaf57bc56c00b24c51728a6f3041
test/server/app_test.js
test/server/app_test.js
var should = require('chai').should(), expect = require('chai').expect, supertest = require('supertest'), config = require('config'), port = config.get('port'), testingUrl = 'http://localhost:' + port, api = supertest(testingUrl) describe('Get /', () => { it('should render the homepage', (done) => { api.get('/') .expect(200, done) }) } ) describe('Post ', () =>{ var user = JSON.stringify({ email: "dude@gmail.com", password: "abcde"}) it('creates an account', (done) => { api.post('/signup') .set('Accept', 'application/json') .set('Content-Type', 'application/json') .send(user) .expect(200) .expect((res) => { user_response = res.body.user return (user_response.hasOwnProperty('email') && user_response.hasOwnProperty('username') && user_response.hasOwnProperty('firstName') && user_response.hasOwnProperty('lastName')) }) .end(done) })
var should = require('chai').should(), expect = require('chai').expect, supertest = require('supertest'), config = require('config'), port = config.get('port'), testingUrl = 'http://localhost:' + port, api = supertest(testingUrl) describe('Get /', () => { it('should render the homepage', (done) => { api.get('/') .expect(200, done) }) } ) describe('Post ', () =>{ var user = JSON.stringify({ email: "dude@gmail.com", password: "abcde"}) it('creates an account', (done) => { api.post('/signup') .set('Accept', 'application/json') .set('Content-Type', 'application/json') .send(user) .expect(200) .expect((res) => { user_response = res.body.user return (user_response.hasOwnProperty('email') && user_response.hasOwnProperty('username') && user_response.hasOwnProperty('firstName') && user_response.hasOwnProperty('lastName')) }) .end(done) })}) describe('Post ', () =>{ //need to have an exising user var user = JSON.stringify({ email: "dude@gmail.com", password: "abcde"}) it('logs into an account', (done) => { // user should already exist bc there is currently no setup or teardown api.post('/login') .set('Accept', 'application/json') .set('Content-Type', 'application/json') .send(user) .expect(200) .expect((res) => { login_response = res.body.user // not sure this is right either return ((login_response.hasOwnProperty('user') && login_response.hasOwnProperty('token'))) }) .end(done) } ) })
Add failing test for login
Add failing test for login
JavaScript
mit
tylergreen/react-redux-express-app,tylergreen/react-redux-express-app
--- +++ @@ -31,8 +31,29 @@ user_response.hasOwnProperty('lastName')) }) .end(done) - }) + })}) +describe('Post ', () =>{ + //need to have an exising user + var user = JSON.stringify({ email: "dude@gmail.com", + password: "abcde"}) + it('logs into an account', (done) => { + // user should already exist bc there is currently no setup or teardown + api.post('/login') + .set('Accept', 'application/json') + .set('Content-Type', 'application/json') + .send(user) + .expect(200) + .expect((res) => { + login_response = res.body.user // not sure this is right either + return ((login_response.hasOwnProperty('user') && + login_response.hasOwnProperty('token'))) + }) + .end(done) + } + ) + +})
3f5acc776fed90572762275e82bab94224c52bcf
app/src/index.js
app/src/index.js
import 'babel-polyfill'; import React from 'react'; import ReactDOM from 'react-dom'; import MainScreen from './react/MainScreen'; import config from './config'; import SculptureApp from './app'; window.onload = () => { const manifest = chrome.runtime.getManifest(); console.log(`Version: ${manifest.version}`); config.applyLocalConfig(anyware_config); const app = new SculptureApp(config); ReactDOM.render(<MainScreen app={app} restart={() => chrome.runtime.reload()}/>, document.getElementById('anyware-root')); };
import 'babel-polyfill'; import React from 'react'; import ReactDOM from 'react-dom'; import MainScreen from './react/MainScreen'; import config from './config'; import SculptureApp from './app'; // Read all all local storage and overwrite the corresponding values in the given config object // Returns a promise function applyFromLocalStorage(config) { return new Promise((resolve, reject) => { chrome.storage.local.get(null, (items) => { if (chrome.runtime.lastError) { reject(chrome.runtime.lastError); } else { for (let key of Object.keys(items)) { config[key] = items[key]; } resolve(true); } }); }); } window.onload = async () => { const manifest = chrome.runtime.getManifest(); console.log(`Version: ${manifest.version}`); // Apply config from Chrome local storage to anyware_config await applyFromLocalStorage(anyware_config); // Apply config from the global variable anyware_config config.applyLocalConfig(anyware_config); const app = new SculptureApp(config); ReactDOM.render(<MainScreen app={app} restart={() => chrome.runtime.reload()}/>, document.getElementById('anyware-root')); };
Support per-sculpture overrides in local storage
Support per-sculpture overrides in local storage
JavaScript
mit
anyWareSculpture/sculpture-client,anyWareSculpture/sculpture-client,anyWareSculpture/sculpture-client
--- +++ @@ -8,10 +8,31 @@ import config from './config'; import SculptureApp from './app'; -window.onload = () => { +// Read all all local storage and overwrite the corresponding values in the given config object +// Returns a promise +function applyFromLocalStorage(config) { + return new Promise((resolve, reject) => { + chrome.storage.local.get(null, (items) => { + if (chrome.runtime.lastError) { + reject(chrome.runtime.lastError); + } + else { + for (let key of Object.keys(items)) { + config[key] = items[key]; + } + resolve(true); + } + }); + }); +} + +window.onload = async () => { const manifest = chrome.runtime.getManifest(); console.log(`Version: ${manifest.version}`); + // Apply config from Chrome local storage to anyware_config + await applyFromLocalStorage(anyware_config); + // Apply config from the global variable anyware_config config.applyLocalConfig(anyware_config); const app = new SculptureApp(config); ReactDOM.render(<MainScreen app={app} restart={() => chrome.runtime.reload()}/>, document.getElementById('anyware-root'));
217b9501b2b3e371e8c4c7fdbd534f9c1f6ca440
build/build.js
build/build.js
var extend = require('extend'); var path = require('path'); var cleanDist = require('./tasks/clean_dist'); var copy = require('./tasks/copy'); var sass = require('./tasks/sass'); var javascript = require('./tasks/javascript'); var polyfillJS = require('./tasks/polyfillJS'); module.exports = function(options) { /** * Default options for the build * * `components` is configuration for which components should be included in the * build. This defaults to only Govuk core stuff. The local build scripts also include * the "Build" category which contains styles for example pages */ var config = extend({ mode: 'development', cache: true, components: true, destination: 'dist' }, options); return new Promise(function(resolve, reject) { cleanDist(config) .then(function() { return copy.govUkTemplateAssets(config); }) .then(function() { return copy.govUkToolkitAssets(config); }) .then(function() { return copy.landregistryComponentAssets(config); }) .then(function() { return sass(config); }) .then(function() { return javascript.compile(config); }) .then(function() { resolve(path.join(config.destination, 'assets')); }) .catch(function(e) { reject(e); }); }); }
var extend = require('extend'); var path = require('path'); var cleanDist = require('./tasks/clean_dist'); var copy = require('./tasks/copy'); var sass = require('./tasks/sass'); var javascript = require('./tasks/javascript'); module.exports = function(options) { /** * Default options for the build * * `components` is configuration for which components should be included in the * build. This defaults to only Govuk core stuff. The local build scripts also include * the "Build" category which contains styles for example pages */ var config = extend({ mode: 'development', cache: true, components: true, destination: 'dist' }, options); return new Promise(function(resolve, reject) { cleanDist(config) .then(function() { return copy.govUkTemplateAssets(config); }) .then(function() { return copy.govUkToolkitAssets(config); }) .then(function() { return copy.landregistryComponentAssets(config); }) .then(function() { return sass(config); }) .then(function() { return javascript.compile(config); }) .then(function() { resolve(path.join(config.destination, 'assets')); }) .catch(function(e) { reject(e); }); }); }
Fix JS bug caused by previous commit
Fix JS bug caused by previous commit
JavaScript
mit
LandRegistry/land-registry-elements,LandRegistry/land-registry-elements,LandRegistry/land-registry-elements,LandRegistry/land-registry-elements,LandRegistry/land-registry-elements
--- +++ @@ -4,7 +4,6 @@ var copy = require('./tasks/copy'); var sass = require('./tasks/sass'); var javascript = require('./tasks/javascript'); -var polyfillJS = require('./tasks/polyfillJS'); module.exports = function(options) {
9393b0303d6b991ef27758ebadaed670a290d7fc
generators/app/templates/_app/_app.js
generators/app/templates/_app/_app.js
var express = require('express'), path = require('path'), cookieParser = require('cookie-parser'), bodyParser = require('body-parser'); var routes = require('./routes'); var app = express(); // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'ejs'); app.use(bodyParser.json()); app.use(bodyParser.urlencoded()); app.use(cookieParser()); app.use(express.static(path.join(__dirname, 'public'))); app.get('/', routes.index); app.set('port', process.env.PORT || 3000); var server = app.listen(app.get('port'), function() { // log a message to console! }); module.exports = app;
var express = require('express'), path = require('path'), cookieParser = require('cookie-parser'), bodyParser = require('body-parser'); var routes = require('./routes'); var app = express(); // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'ejs'); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.use(cookieParser()); app.use(express.static(path.join(__dirname, 'public'))); app.get('/', routes.index); app.set('port', process.env.PORT || 3000); var server = app.listen(app.get('port'), function() { // log a message to console! }); module.exports = app;
Fix 'body-parser deprecated urlencoded' warning
Fix 'body-parser deprecated urlencoded' warning
JavaScript
mit
christiannwamba/generator-wean,christiannwamba/generator-wean
--- +++ @@ -12,7 +12,7 @@ app.set('view engine', 'ejs'); app.use(bodyParser.json()); -app.use(bodyParser.urlencoded()); +app.use(bodyParser.urlencoded({ extended: true })); app.use(cookieParser()); app.use(express.static(path.join(__dirname, 'public')));
72aa328e3dcd2118c03a45781d9674976fc447dc
src/utils/convertJsToSass.js
src/utils/convertJsToSass.js
function convertJsToSass(obj, syntax) { const suffix = syntax === 'sass' ? '' : ';' const keys = Object.keys(obj) const lines = keys.map(key => `$${key}: ${formatValue(obj[key], syntax)}${suffix}`) return lines.join('\n') } function formatNestedObject(obj, syntax) { const keys = Object.keys(obj) return keys.map(key => `${key}: ${formatValue(obj[key], syntax)}`).join(', ') } function withQuotesIfNecessary(value) { const hasQuotes = /^['"](\n|.)*['"]$/gm.test(value) const requiresQuotes = /^[0 ]/.test(value) return hasQuotes || !requiresQuotes ? value : `"${value}"` } function formatValue(value, syntax) { if (value instanceof Array) { return `(${value.map(formatValue).join(', ')})` } if (typeof value === 'object') { return `(${formatNestedObject(value, syntax)})` } if (typeof value === 'string') { return withQuotesIfNecessary(value) } return JSON.stringify(value) } module.exports = convertJsToSass
function convertJsToSass(obj, syntax) { const suffix = syntax === 'sass' ? '' : ';' const keys = Object.keys(obj) const lines = keys.map(key => `$${key}: ${formatValue(obj[key], syntax)}${suffix}`) return lines.join('\n') } function formatNestedObject(obj, syntax) { const keys = Object.keys(obj) return keys.map(key => `${key}: ${formatValue(obj[key], syntax)}`).join(', ') } function formatValue(value, syntax) { if (value instanceof Array) { return `(${value.map(formatValue).join(', ')})` } if (typeof value === 'object') { return `(${formatNestedObject(value, syntax)})` } if (typeof value === 'string') { return value } return JSON.stringify(value) } module.exports = convertJsToSass
Remove quotes from string because they break e.g. box shadows
Remove quotes from string because they break e.g. box shadows
JavaScript
mit
epegzz/sass-vars-loader,epegzz/sass-vars-loader,epegzz/sass-vars-loader
--- +++ @@ -10,12 +10,6 @@ return keys.map(key => `${key}: ${formatValue(obj[key], syntax)}`).join(', ') } -function withQuotesIfNecessary(value) { - const hasQuotes = /^['"](\n|.)*['"]$/gm.test(value) - const requiresQuotes = /^[0 ]/.test(value) - return hasQuotes || !requiresQuotes ? value : `"${value}"` -} - function formatValue(value, syntax) { if (value instanceof Array) { return `(${value.map(formatValue).join(', ')})` @@ -26,7 +20,7 @@ } if (typeof value === 'string') { - return withQuotesIfNecessary(value) + return value } return JSON.stringify(value)
6951e92d15472187976538ed98cb9d572ce426bc
build/start.js
build/start.js
const childProcess = require("child_process"); const electron = require("electron"); const webpack = require("webpack"); const config = require("./webpack.app.config"); const compiler = webpack(config({ development: true })); let electronStarted = false; const watching = compiler.watch({}, (err, stats) => { if (err != null) { console.log(err); } else if (!electronStarted) { electronStarted = true; childProcess .spawn(electron, ["."], { stdio: "inherit" }) .on("close", () => { watching.close(); }); } console.log(stats.toString({ colors: true })); });
const childProcess = require("child_process"); const readline = require("readline"); const electron = require("electron"); const webpack = require("webpack"); const config = require("./webpack.app.config"); const compiler = webpack(config({ development: true })); let electronStarted = false; const clearTerminal = () => { if (process.stdout.isTTY) { const blankLines = "\n".repeat(process.stdout.rows); console.log(blankLines); readline.cursorTo(process.stdout, 0, 0); readline.clearScreenDown(process.stdout); } }; const watching = compiler.watch({}, (err, stats) => { if (err != null) { console.log(err); } else if (!electronStarted) { electronStarted = true; childProcess .spawn(electron, ["."], { stdio: "inherit" }) .on("close", () => { watching.close(); }); } if (stats != null) { clearTerminal(); console.log(stats.toString({ colors: true })); } });
Clear terminal with each webpack rebuild
Clear terminal with each webpack rebuild
JavaScript
mit
szwacz/electron-boilerplate,szwacz/electron-boilerplate
--- +++ @@ -1,10 +1,20 @@ const childProcess = require("child_process"); +const readline = require("readline"); const electron = require("electron"); const webpack = require("webpack"); const config = require("./webpack.app.config"); const compiler = webpack(config({ development: true })); let electronStarted = false; + +const clearTerminal = () => { + if (process.stdout.isTTY) { + const blankLines = "\n".repeat(process.stdout.rows); + console.log(blankLines); + readline.cursorTo(process.stdout, 0, 0); + readline.clearScreenDown(process.stdout); + } +}; const watching = compiler.watch({}, (err, stats) => { if (err != null) { @@ -18,5 +28,8 @@ }); } - console.log(stats.toString({ colors: true })); + if (stats != null) { + clearTerminal(); + console.log(stats.toString({ colors: true })); + } });
c2e2b863bb2f18f3825a1c1ae19983c345a8db30
frontend/src/components/App.js
frontend/src/components/App.js
import React, { PropTypes } from 'react'; import { Link, IndexLink } from 'react-router'; // This is a class-based component because the current // version of hot reloading won't hot reload a stateless // component at the top-level. class App extends React.Component { render() { return ( <div> <div id="header-bar"> <span>{"2016 Presidental Debates "}</span> <IndexLink to="/">About</IndexLink> {' | '} <Link to="/play">Play</Link> {' | '} <Link to="/stats">Stats</Link> </div> <div className="pure-g"> <div className="pure-u-1-24 pure-u-sm-1-5"></div> <div className="pure-u-22-24 pure-u-sm-3-5"> {this.props.children} </div> <div className="pure-u-1-24 pure-u-sm-1-5"></div> </div> </div> ); } } App.propTypes = { children: PropTypes.element }; export default App;
import React, { PropTypes } from 'react'; import { Link, IndexLink } from 'react-router'; // This is a class-based component because the current // version of hot reloading won't hot reload a stateless // component at the top-level. class App extends React.Component { render() { return ( <div> <div id="header-bar"> <span>{"2016 Presidental Debates "}</span> <IndexLink to="/">About</IndexLink> {' | '} <Link to="/play">Play</Link> {' | '} <Link to="/stats">Stats</Link> </div> <div className="pure-g"> <div className="pure-u-1-24 pure-u-lg-1-5"></div> <div className="pure-u-22-24 pure-u-lg-3-5"> {this.props.children} </div> <div className="pure-u-1-24 pure-u-lg-1-5"></div> </div> </div> ); } } App.propTypes = { children: PropTypes.element }; export default App;
Break gutters only on large devices
Break gutters only on large devices
JavaScript
mit
user01/PresidentialDebates,user01/PresidentialDebates,user01/PresidentialDebates
--- +++ @@ -17,11 +17,11 @@ <Link to="/stats">Stats</Link> </div> <div className="pure-g"> - <div className="pure-u-1-24 pure-u-sm-1-5"></div> - <div className="pure-u-22-24 pure-u-sm-3-5"> + <div className="pure-u-1-24 pure-u-lg-1-5"></div> + <div className="pure-u-22-24 pure-u-lg-3-5"> {this.props.children} </div> - <div className="pure-u-1-24 pure-u-sm-1-5"></div> + <div className="pure-u-1-24 pure-u-lg-1-5"></div> </div> </div> );
a57628e33816f3740ccb39dd295310f34583b85d
guides/place-my-order/steps/add-data/list.js
guides/place-my-order/steps/add-data/list.js
import { Component } from 'can'; import './list.less'; import view from './list.stache'; import Restaurant from '~/models/restaurant'; const RestaurantList = Component.extend({ tag: 'pmo-restaurant-list', view, ViewModel: { // EXTERNAL STATEFUL PROPERTIES // These properties are passed from another component. Example: // value: {type: "number"} // INTERNAL STATEFUL PROPERTIES // These properties are owned by this component. restaurants: { default() { return Restaurant.getList({}); } }, // DERIVED PROPERTIES // These properties combine other property values. Example: // get valueAndMessage(){ return this.value + this.message; } // METHODS // Functions that can be called by the view. Example: // incrementValue() { this.value++; } // SIDE EFFECTS // The following is a good place to perform changes to the DOM // or do things that don't fit in to one of the areas above. connectedCallback(element){ } } }); export default RestaurantList; export const ViewModel = RestaurantList.ViewModel; import Component from 'can-component'; import DefineMap from 'can-define/map/'; import './list.less'; import view from './list.stache'; import Restaurant from '~/models/restaurant'; export const ViewModel = DefineMap.extend({ restaurants: { value() { return Restaurant.getList({}); } } }); export default Component.extend({ tag: 'pmo-restaurant-list', ViewModel, view });
import { Component } from 'can'; import './list.less'; import view from './list.stache'; import Restaurant from '~/models/restaurant'; const RestaurantList = Component.extend({ tag: 'pmo-restaurant-list', view, ViewModel: { // EXTERNAL STATEFUL PROPERTIES // These properties are passed from another component. Example: // value: {type: "number"} // INTERNAL STATEFUL PROPERTIES // These properties are owned by this component. restaurants: { default() { return Restaurant.getList({}); } }, // DERIVED PROPERTIES // These properties combine other property values. Example: // get valueAndMessage(){ return this.value + this.message; } // METHODS // Functions that can be called by the view. Example: // incrementValue() { this.value++; } // SIDE EFFECTS // The following is a good place to perform changes to the DOM // or do things that don't fit in to one of the areas above. connectedCallback(element){ } } }); export default RestaurantList; export const ViewModel = RestaurantList.ViewModel;
Remove redundant source from PMO
Remove redundant source from PMO This removes the redundant source that was left over from the DoneJS 2 guide. Fixes #1156
JavaScript
mit
donejs/donejs,donejs/donejs
--- +++ @@ -38,24 +38,3 @@ export default RestaurantList; export const ViewModel = RestaurantList.ViewModel; - - -import Component from 'can-component'; -import DefineMap from 'can-define/map/'; -import './list.less'; -import view from './list.stache'; -import Restaurant from '~/models/restaurant'; - -export const ViewModel = DefineMap.extend({ - restaurants: { - value() { - return Restaurant.getList({}); - } - } -}); - -export default Component.extend({ - tag: 'pmo-restaurant-list', - ViewModel, - view -});
ffbd3bf025e9f8f72f8b4cb42e9be653ecdb08b3
js/FeaturedExperiences.ios.js
js/FeaturedExperiences.ios.js
/** * Copyright 2015-present 650 Industries. All rights reserved. * * @providesModule FeaturedExperiences */ 'use strict'; function setReferrer(newReferrer) { // NOOP. Shouldn't get here. } function getFeatured() { return [ { url: 'exp://exp.host/@exponent/floatyplane', manifest: { name: 'Floaty Plane', desc: 'Touch the plane until you die!', iconUrl: 'https://s3-us-west-2.amazonaws.com/examples-exp/floaty_icon.png', }, }, { url: 'exp://exp.host/@exponent/react-native-for-curious-people', manifest: { name: 'React Native for Curious People', desc: 'Learn about React Native.', iconUrl: 'https://s3.amazonaws.com/rnfcp/icon.png', }, }, { url: 'exp://exp.host/@exponent/pomodoro', manifest: { name: 'Pomodoro', desc: 'Be careful or the tomatoes might explode!', iconUrl: 'https://s3.amazonaws.com/pomodoro-exp/icon.png', }, }, ]; } module.exports = { setReferrer, getFeatured, };
/** * Copyright 2015-present 650 Industries. All rights reserved. * * @providesModule FeaturedExperiences */ 'use strict'; function setReferrer(newReferrer) { // NOOP. Shouldn't get here. } function getFeatured() { return [ { url: 'exp://exp.host/@exponent/floatyplane', manifest: { name: 'Floaty Plane', desc: 'Touch the plane until you die!', iconUrl: 'https://s3-us-west-2.amazonaws.com/examples-exp/floaty_icon.png', }, }, { url: 'exp://exp.host/@exponent/react-native-for-curious-people', manifest: { name: 'React Native for Curious People', desc: 'Learn about React Native.', iconUrl: 'https://s3.amazonaws.com/rnfcp/icon.png', }, }, { url: 'exp://exp.host/@exponent/pomodoro', manifest: { name: 'Pomodoro', desc: 'Be careful or the tomatoes might explode!', iconUrl: 'https://s3.amazonaws.com/pomodoro-exp/icon.png', }, }, { url: 'exp://exp.host/@notbrent/native-component-list', manifest: { name: 'Native Component List', desc: 'Demonstration of some native components.', iconUrl: 'https://s3.amazonaws.com/exp-brand-assets/ExponentEmptyManifest_192.png', }, }, ]; } module.exports = { setReferrer, getFeatured, };
Add native component list to featured experiences
Add native component list to featured experiences fbshipit-source-id: 7a6210a
JavaScript
bsd-3-clause
jolicloud/exponent,jolicloud/exponent,exponent/exponent,exponentjs/exponent,jolicloud/exponent,exponentjs/exponent,jolicloud/exponent,exponent/exponent,exponentjs/exponent,exponent/exponent,exponentjs/exponent,exponentjs/exponent,exponent/exponent,exponentjs/exponent,exponentjs/exponent,exponentjs/exponent,exponent/exponent,jolicloud/exponent,jolicloud/exponent,exponent/exponent,exponent/exponent,jolicloud/exponent,exponentjs/exponent,jolicloud/exponent,jolicloud/exponent,exponent/exponent,exponent/exponent
--- +++ @@ -35,6 +35,14 @@ iconUrl: 'https://s3.amazonaws.com/pomodoro-exp/icon.png', }, }, + { + url: 'exp://exp.host/@notbrent/native-component-list', + manifest: { + name: 'Native Component List', + desc: 'Demonstration of some native components.', + iconUrl: 'https://s3.amazonaws.com/exp-brand-assets/ExponentEmptyManifest_192.png', + }, + }, ]; }
ae0031e09a40434d24bfa344bf099aa4c8cbaad5
src/components/Board.js
src/components/Board.js
import React, {Component, PropTypes} from 'react' import BoardContainer from './BoardContainer' import {Provider} from 'react-redux' import {createStore} from 'redux' import boardReducer from '../reducers/BoardReducer' let store = createStore(boardReducer, window && window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()) export default class Board extends Component { render () { return <Provider store={store}> <BoardContainer {...this.props} /> </Provider> } } Board.propTypes = { data: PropTypes.object.isRequired, onLaneScroll: PropTypes.func, onCardClick: PropTypes.func, eventBusHandle: PropTypes.func, laneSortFunction: PropTypes.func, draggable: PropTypes.bool, handleDragStart: PropTypes.func, handleDragEnd: PropTypes.func, onDataChange: PropTypes.func }
import React, {Component, PropTypes} from 'react' import BoardContainer from './BoardContainer' import {Provider} from 'react-redux' import {createStore} from 'redux' import boardReducer from '../reducers/BoardReducer' let store = createStore(boardReducer, typeof(window) !== 'undefined' && window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()) export default class Board extends Component { render () { return <Provider store={store}> <BoardContainer {...this.props} /> </Provider> } } Board.propTypes = { data: PropTypes.object.isRequired, onLaneScroll: PropTypes.func, onCardClick: PropTypes.func, eventBusHandle: PropTypes.func, laneSortFunction: PropTypes.func, draggable: PropTypes.bool, handleDragStart: PropTypes.func, handleDragEnd: PropTypes.func, onDataChange: PropTypes.func }
Use typeof(window) to check if being used in non browser environments
fix(): Use typeof(window) to check if being used in non browser environments https://github.com/rcdexta/react-trello/issues/15
JavaScript
mit
rcdexta/react-trello,rcdexta/react-trello
--- +++ @@ -4,7 +4,7 @@ import {createStore} from 'redux' import boardReducer from '../reducers/BoardReducer' -let store = createStore(boardReducer, window && window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()) +let store = createStore(boardReducer, typeof(window) !== 'undefined' && window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()) export default class Board extends Component {
01c5311c3027c893ddd76cfbec42d88baece1564
lib/daab-run.js
lib/daab-run.js
#!/usr/bin/env node // daab run var fs = require('fs'); var spawn = require('child_process').spawn; var program = require('commander'); var auth = require('./auth'); program .allowUnknownOption() .parse(process.argv); if (! auth.hasToken()) { console.log('At first, try "daab login"'); process.exit(); } var hubot = spawn('bin/hubot', ['run'].concat(process.argv.slice(2)), { stdio: 'inherit' });
#!/usr/bin/env node // daab run var fs = require('fs'); var spawn = require('child_process').spawn; var program = require('commander'); var auth = require('./auth'); program .allowUnknownOption() .parse(process.argv); if (! auth.hasToken()) { console.log('At first, try "daab login"'); process.exit(); } var cmd = process.platform === 'win32' ? 'bin\\hubot.cmd' : 'bin/hubot'; var hubot = spawn(cmd, ['run'].concat(process.argv.slice(2)), { stdio: 'inherit' });
Fix launch command on windows platform.
Fix launch command on windows platform.
JavaScript
mit
lisb/daab,lisb/daab,lisb/daab
--- +++ @@ -15,6 +15,7 @@ process.exit(); } -var hubot = spawn('bin/hubot', ['run'].concat(process.argv.slice(2)), { +var cmd = process.platform === 'win32' ? 'bin\\hubot.cmd' : 'bin/hubot'; +var hubot = spawn(cmd, ['run'].concat(process.argv.slice(2)), { stdio: 'inherit' });
cb7ab80f26922a025297d20fe791e8c0b0a01ca7
settings.js
settings.js
//app-specific sentence module.exports = { serverPort : 8080, pingInteralInMilliseconds : 1000*5, // server main loop interval. 6 hours postBeforeTheMatch : true, postAfterTheMatch : true, preMatchWindowInMinutes: "in 5 minutes", // moment.js humanize expression postMatchWindowInHours: "2 hours ago" // moment.js humanize expression };
//app-specific sentence module.exports = { serverPort : 8080, pingInteralInMilliseconds : 1000*60, // server main loop interval. 6 hours postBeforeTheMatch : true, postAfterTheMatch : true, preMatchWindowInMinutes: "in 5 minutes", // moment.js humanize expression postMatchWindowInHours: "2 hours ago" // moment.js humanize expression };
Set default loop interval to 1 minute
Set default loop interval to 1 minute
JavaScript
mit
matijaabicic/Moubot,d48/Moubot,matijaabicic/Moubot,matijaabicic/Moubot,dougmolineux/Moubot
--- +++ @@ -2,7 +2,7 @@ module.exports = { serverPort : 8080, - pingInteralInMilliseconds : 1000*5, // server main loop interval. 6 hours + pingInteralInMilliseconds : 1000*60, // server main loop interval. 6 hours postBeforeTheMatch : true, postAfterTheMatch : true, preMatchWindowInMinutes: "in 5 minutes", // moment.js humanize expression
b569d9e348d345f6c6b1135c5fbb49a189e21f42
src/components/Menu.js
src/components/Menu.js
import * as React from 'react' import { Link } from 'gatsby' import { Container } from './Container' import { CloseIcon } from './icons/Close' export const Menu = ({ showMenu, onClick }) => { return ( <div className={`${ showMenu ? 'fixed' : 'hidden' } inset-0 z-40 h-screen bg-black w-full bg-opacity-25`} > <div className="h-full px-5 mx-auto mr-32 antialiased bg-white sm:px-8 md:px-12 lg:px-0"> <Container className="flex flex-col space-y-4"> <Link to="/articles" className="font-bold text-gray-500 text-normal hover:underline" > Articles </Link> <Link to="/projects" className="font-bold text-gray-500 text-normal hover:underline" > Projects </Link> </Container> </div> <div className="absolute bottom-0 right-0 p-4 m-6 text-white bg-black rounded-full"> <CloseIcon className="w-6 h-6" onClick={() => onClick((prevState) => !prevState)} /> </div> </div> ) }
import * as React from 'react' import { Link } from 'gatsby' import { Container } from './Container' import { CloseIcon } from './icons/Close' export const Menu = ({ showMenu, onClick }) => { return ( <div className={`${ showMenu ? 'fixed' : 'hidden' } inset-0 z-40 h-full bg-black w-full bg-opacity-25`} > <div className="h-full px-5 mx-auto mr-32 antialiased bg-white sm:px-8 md:px-12 lg:px-0"> <Container className="flex flex-col space-y-4"> <Link to="/articles" className="font-bold text-gray-500 text-normal hover:underline" > Articles </Link> <Link to="/projects" className="font-bold text-gray-500 text-normal hover:underline" > Projects </Link> </Container> </div> <div className="absolute bottom-0 right-0 p-4 m-6 text-white bg-black rounded-full"> <CloseIcon className="w-6 h-6" onClick={() => onClick((prevState) => !prevState)} /> </div> </div> ) }
Fix menu close btn position
Fix menu close btn position
JavaScript
mit
dtjv/dtjv.github.io
--- +++ @@ -9,7 +9,7 @@ <div className={`${ showMenu ? 'fixed' : 'hidden' - } inset-0 z-40 h-screen bg-black w-full bg-opacity-25`} + } inset-0 z-40 h-full bg-black w-full bg-opacity-25`} > <div className="h-full px-5 mx-auto mr-32 antialiased bg-white sm:px-8 md:px-12 lg:px-0"> <Container className="flex flex-col space-y-4">
210c0478bd061571f62bb0a841400bd24e325acb
lib/check.js
lib/check.js
var check = { isNaN : function(value) { "use strict"; return isNaN(value); }, isZero : function(value) { "use strict"; return value === 0; }, isPositiveZero : function(value) { "use strict"; return value === 0 && 1 / value === Infinity; }, isNegativeZero : function(value) { "use strict"; return value === 0 && 1 / value === -Infinity; }, isFinite : function(value) { "use strict" return !isNaN(value) && value !== Infinity && value !== -Infinity; }, isInfinity : function(value) { "use strict"; return value === Infinity || value === -Infinity; }, isPositiveInfinity : function(value) { "use strict"; return value === Infinity; }, isNegativeInfinity : function(value) { "use strict"; return value === -Infinity; } }; module.exports = check;
var check = { isNaN : isNaN, isZero : function(value) { "use strict"; return value === 0; }, isPositiveZero : function(value) { "use strict"; return value === 0 && 1 / value === Infinity; }, isNegativeZero : function(value) { "use strict"; return value === 0 && 1 / value === -Infinity; }, isFinite : isFinite, isInfinity : function(value) { "use strict"; return value === Infinity || value === -Infinity; }, isPositiveInfinity : function(value) { "use strict"; return value === Infinity; }, isNegativeInfinity : function(value) { "use strict"; return value === -Infinity; } }; module.exports = check;
Make isFinite() and isNaN() direct ref copy of the builtin functions
Make isFinite() and isNaN() direct ref copy of the builtin functions
JavaScript
mit
kchapelier/node-mathp
--- +++ @@ -1,9 +1,5 @@ var check = { - isNaN : function(value) { - "use strict"; - - return isNaN(value); - }, + isNaN : isNaN, isZero : function(value) { "use strict"; @@ -19,11 +15,7 @@ return value === 0 && 1 / value === -Infinity; }, - isFinite : function(value) { - "use strict" - - return !isNaN(value) && value !== Infinity && value !== -Infinity; - }, + isFinite : isFinite, isInfinity : function(value) { "use strict";
b4b33ec346e1f6e6fb7f5eea1c9674d33a6d2831
client/hide.js
client/hide.js
/* Hide posts you don't like */ let main = require('./main'); // Remember hidden posts for 7 days only, to perevent the cookie from // eclipsing the Sun let hidden = new main.Memory('hide', 7, true); main.reply('hide', function(model) { // Hiding your own posts would open up the gates for a ton of bugs. Fuck // that. if (model.get('mine')) return; const count = hidden.write(model.get('num')); model.remove(); // Forward number to options menu main.request('hide:render', count); }); main.reply('hide:clear', hidden.purgeAll); // Initial render main.defer(() => main.request('hide:render', hidden.size()));
/* Hide posts you don't like */ let main = require('./main'); // Remember hidden posts for 7 days only, to perevent the cookie from // eclipsing the Sun let hidden = new main.Memory('hide', 7, true); main.reply('hide', function(model) { // Hiding your own posts would open up the gates for a ton of bugs. Fuck // that. if (model.get('mine')) return; const count = hidden.write(model.get('num')); model.remove(); // Forward number to options menu main.request('hide:render', count); }); main.reply('hide:clear', () => hidden.purgeAll()); // Initial render main.defer(() => main.request('hide:render', hidden.size()));
Fix purging hidden post list
Fix purging hidden post list
JavaScript
mit
theGaggle/sleepingpizza,KoinoAoi/meguca,KoinoAoi/meguca,theGaggle/sleepingpizza,reiclone/doushio,reiclone/doushio,reiclone/doushio,theGaggle/sleepingpizza,reiclone/doushio,theGaggle/sleepingpizza,KoinoAoi/meguca,KoinoAoi/meguca,KoinoAoi/meguca,theGaggle/sleepingpizza,theGaggle/sleepingpizza,reiclone/doushio
--- +++ @@ -19,7 +19,7 @@ main.request('hide:render', count); }); -main.reply('hide:clear', hidden.purgeAll); +main.reply('hide:clear', () => hidden.purgeAll()); // Initial render main.defer(() => main.request('hide:render', hidden.size()));
38733fd891f6d3022a5c0bd7aef98c4ee7ad5b55
packages/ember-engines/lib/utils/deeply-non-duplicated-addon.js
packages/ember-engines/lib/utils/deeply-non-duplicated-addon.js
'use strict'; /** * Deduplicate one addon's children addons recursively from hostAddons. * * @private * @param {Object} hostAddons * @param {EmberAddon} dedupedAddon * @param {String} treeName */ module.exports = function deeplyNonDuplicatedAddon(hostAddons, dedupedAddon, treeName) { if (dedupedAddon.addons.length === 0) { return; } dedupedAddon._orginalAddons = dedupedAddon.addons; dedupedAddon.addons = dedupedAddon.addons.filter(addon => { // nested lazy engine will have it's own deeplyNonDuplicatedAddon, just keep it here if (addon.lazyLoading && addon.lazyLoading.enabled) { return true; } if (addon.addons.length > 0) { addon._orginalAddons = addon.addons; deeplyNonDuplicatedAddon(hostAddons, addon, treeName); } let hostAddon = hostAddons[addon.name]; if (hostAddon && hostAddon.cacheKeyForTree) { let innerCacheKey = addon.cacheKeyForTree(treeName); let hostAddonCacheKey = hostAddon.cacheKeyForTree(treeName); if ( innerCacheKey != null && innerCacheKey === hostAddonCacheKey ) { // the addon specifies cache key and it is the same as host instance of the addon, skip the tree return false; } } return true; }); }
'use strict'; // Array of addon names that should not be deduped. const ADDONS_TO_EXCLUDE_FROM_DEDUPE = [ 'ember-cli-babel', ]; /** * Deduplicate one addon's children addons recursively from hostAddons. * * @private * @param {Object} hostAddons * @param {EmberAddon} dedupedAddon * @param {String} treeName */ module.exports = function deeplyNonDuplicatedAddon(hostAddons, dedupedAddon, treeName) { if (dedupedAddon.addons.length === 0) { return; } dedupedAddon._orginalAddons = dedupedAddon.addons; dedupedAddon.addons = dedupedAddon.addons.filter(addon => { // nested lazy engine will have it's own deeplyNonDuplicatedAddon, just keep it here if (addon.lazyLoading && addon.lazyLoading.enabled) { return true; } if (ADDONS_TO_EXCLUDE_FROM_DEDUPE.includes(addon.name)) { return true; } if (addon.addons.length > 0) { addon._orginalAddons = addon.addons; deeplyNonDuplicatedAddon(hostAddons, addon, treeName); } let hostAddon = hostAddons[addon.name]; if (hostAddon && hostAddon.cacheKeyForTree) { let innerCacheKey = addon.cacheKeyForTree(treeName); let hostAddonCacheKey = hostAddon.cacheKeyForTree(treeName); if ( innerCacheKey != null && innerCacheKey === hostAddonCacheKey ) { // the addon specifies cache key and it is the same as host instance of the addon, skip the tree return false; } } return true; }); }
Add exclude list to addon dedupe logic
Add exclude list to addon dedupe logic
JavaScript
mit
ember-engines/ember-engines,ember-engines/ember-engines
--- +++ @@ -1,4 +1,9 @@ 'use strict'; + +// Array of addon names that should not be deduped. +const ADDONS_TO_EXCLUDE_FROM_DEDUPE = [ + 'ember-cli-babel', +]; /** * Deduplicate one addon's children addons recursively from hostAddons. @@ -20,6 +25,10 @@ return true; } + if (ADDONS_TO_EXCLUDE_FROM_DEDUPE.includes(addon.name)) { + return true; + } + if (addon.addons.length > 0) { addon._orginalAddons = addon.addons; deeplyNonDuplicatedAddon(hostAddons, addon, treeName);
5ecc6a9de257eb6872946a01f5929a2bfa94bf79
lib/macgyver.js
lib/macgyver.js
var pristineEnv = require('./pristine-env'); function macgyver(thing) { if (Object.prototype.toString.call(thing) === '[object Array]') { return (new pristineEnv().Array(0)).concat(thing); } else { return thing; } } module.exports = macgyver;
var pristineEnv = require('./pristine-env'); var pristineObject = pristineEnv().Object; var pristineArray = pristineEnv().Array; function macgyver(thing) { if (pristineObject.prototype.toString.call(thing) === '[object Array]') { return (new pristineArray()).concat(thing); } else { return thing; } } module.exports = macgyver;
Use pristine Object to work out if a thing is an array
Use pristine Object to work out if a thing is an array
JavaScript
mit
customcommander/macgyver
--- +++ @@ -1,8 +1,11 @@ var pristineEnv = require('./pristine-env'); +var pristineObject = pristineEnv().Object; +var pristineArray = pristineEnv().Array; + function macgyver(thing) { - if (Object.prototype.toString.call(thing) === '[object Array]') { - return (new pristineEnv().Array(0)).concat(thing); + if (pristineObject.prototype.toString.call(thing) === '[object Array]') { + return (new pristineArray()).concat(thing); } else { return thing; }
8d62ce5afa50ccbe21b516f3cc39d0c7ca20b922
lib/index.js
lib/index.js
require('./db/connection'); const Koa = require('koa'); const bodyParser = require('koa-bodyparser'); const logger = require('koa-logger'); const json = require('koa-json'); const onerror = require('koa-onerror'); const router = require('./routes'); const cors = require('./helpers/cors'); const auth = require('./helpers/auth'); (() => { const app = new Koa(); onerror(app); app.use(bodyParser({})) .use(json()) .use(logger()) .use(cors()) router.map(el => app.use(el.routes())); app.listen(3003); })();
require('./db/connection'); const Koa = require('koa'); const bodyParser = require('koa-bodyparser'); const logger = require('koa-logger'); const json = require('koa-json'); const onerror = require('koa-onerror'); const router = require('./routes'); const cors = require('./helpers/cors'); (() => { const app = new Koa(); onerror(app); app.use(bodyParser({})) .use(json()) .use(logger()) .use(cors()); router.map(el => app.use(el.routes())); app.listen(process.env.PORT || 3003); })();
ADD - PORT env var
ADD - PORT env var
JavaScript
apache-2.0
fkanout/NotifyDrive-API
--- +++ @@ -7,7 +7,6 @@ const onerror = require('koa-onerror'); const router = require('./routes'); const cors = require('./helpers/cors'); -const auth = require('./helpers/auth'); (() => { const app = new Koa(); @@ -15,7 +14,7 @@ app.use(bodyParser({})) .use(json()) .use(logger()) - .use(cors()) + .use(cors()); router.map(el => app.use(el.routes())); - app.listen(3003); + app.listen(process.env.PORT || 3003); })();
30b859c827ed450fbf7a52a18aa92af79c11e5e4
lib/index.js
lib/index.js
'use strict'; var bunyan = require('bunyan'); var config = require('coyno-config'); function createLogger() { var log; if (!!config.log.pretty) { var PrettyStream = require('bunyan-prettystream'); var prettyStdOut = new PrettyStream(); prettyStdOut.pipe(process.stdout); log = bunyan.createLogger({ name: 'queue', streams: [{ level: config.log.level, type: 'raw', stream: prettyStdOut }] }); } else { log = bunyan.createLogger({name: 'queue'}); } return log; } module.exports = createLogger();
'use strict'; var bunyan = require('bunyan'); var config = require('coyno-config'); function createLogger() { var log; if (!!config.log.pretty) { var PrettyStream = require('bunyan-prettystream'); var prettyStdOut = new PrettyStream(); prettyStdOut.pipe(process.stdout); log = bunyan.createLogger({ name: 'queue', streams: [{ level: config.log.level, type: 'raw', stream: prettyStdOut }] }); } else { log = bunyan.createLogger({name: 'queue', level: config.log.level}); } return log; } module.exports = createLogger();
Handle log level correctly for raw logs
Handle log level correctly for raw logs
JavaScript
apache-2.0
blooks/log
--- +++ @@ -22,7 +22,7 @@ }); } else { - log = bunyan.createLogger({name: 'queue'}); + log = bunyan.createLogger({name: 'queue', level: config.log.level}); } return log;
fe4d6b89e779c357d6bdc00c46c6c28bc549ecc5
Source/Scene/Pass.js
Source/Scene/Pass.js
/*global define*/ define([ '../Core/freezeObject' ], function( freezeObject) { "use strict"; /** * The render pass for a command. * * @private */ var Pass = { GLOBE : 0, OPAQUE : 1, TRANSLUCENT : 2, OVERLAY : 3, NUMBER_OF_PASSES : 4 }; return freezeObject(Pass); });
/*global define*/ define([ '../Core/freezeObject' ], function( freezeObject) { "use strict"; /** * The render pass for a command. * * @private */ var Pass = { GLOBE : 0, OPAQUE : 1, // Commands are executed in order by pass up to the translucent pass. // Translucent geometry needs special handling (sorting/OIT). Overlays // are also special (they're executed last, they're not sorted by frustum). TRANSLUCENT : 2, OVERLAY : 3, NUMBER_OF_PASSES : 4 }; return freezeObject(Pass); });
Add comment about the order of passes.
Add comment about the order of passes.
JavaScript
apache-2.0
CesiumGS/cesium,AnimatedRNG/cesium,likangning93/cesium,denverpierce/cesium,jason-crow/cesium,ggetz/cesium,kiselev-dv/cesium,esraerik/cesium,esraerik/cesium,emackey/cesium,omh1280/cesium,soceur/cesium,jason-crow/cesium,emackey/cesium,YonatanKra/cesium,YonatanKra/cesium,omh1280/cesium,AnimatedRNG/cesium,kiselev-dv/cesium,hodbauer/cesium,josh-bernstein/cesium,geoscan/cesium,denverpierce/cesium,kiselev-dv/cesium,aelatgt/cesium,NaderCHASER/cesium,CesiumGS/cesium,omh1280/cesium,wallw-bits/cesium,emackey/cesium,ggetz/cesium,hodbauer/cesium,josh-bernstein/cesium,esraerik/cesium,progsung/cesium,kiselev-dv/cesium,denverpierce/cesium,wallw-bits/cesium,likangning93/cesium,AnalyticalGraphicsInc/cesium,soceur/cesium,AnalyticalGraphicsInc/cesium,oterral/cesium,likangning93/cesium,emackey/cesium,CesiumGS/cesium,likangning93/cesium,CesiumGS/cesium,hodbauer/cesium,oterral/cesium,wallw-bits/cesium,aelatgt/cesium,wallw-bits/cesium,CesiumGS/cesium,progsung/cesium,kaktus40/cesium,denverpierce/cesium,omh1280/cesium,ggetz/cesium,YonatanKra/cesium,YonatanKra/cesium,AnimatedRNG/cesium,esraerik/cesium,jasonbeverage/cesium,soceur/cesium,jason-crow/cesium,jasonbeverage/cesium,AnimatedRNG/cesium,kaktus40/cesium,jason-crow/cesium,geoscan/cesium,oterral/cesium,aelatgt/cesium,likangning93/cesium,ggetz/cesium,aelatgt/cesium,NaderCHASER/cesium,NaderCHASER/cesium
--- +++ @@ -13,6 +13,9 @@ var Pass = { GLOBE : 0, OPAQUE : 1, + // Commands are executed in order by pass up to the translucent pass. + // Translucent geometry needs special handling (sorting/OIT). Overlays + // are also special (they're executed last, they're not sorted by frustum). TRANSLUCENT : 2, OVERLAY : 3, NUMBER_OF_PASSES : 4
f315636aec6965e0fe1394775bc4e97a67ad11aa
CodeWars/js/death-by-coffee.js
CodeWars/js/death-by-coffee.js
// https://www.codewars.com/kata/death-by-coffee/javascript const coffeeLimits = function(y,m,d) { let healthNumber = y * 10000 + m * 100 + d; let currentHex; let current; let i; let result = [0,0]; for(i=1;i<=5000;i++){ current = healthNumber + i * 0xcafe; currentHex = current.toString(16); if(currentHex.includes("dead")){ result[0]=i; break; } } for(i=1;i<=5000;i++){ current = healthNumber + i * 0xdecaf; currentHex = current.toString(16); if(currentHex.includes("dead")){ result[1]=i; break; } } return result; }
// https://www.codewars.com/kata/death-by-coffee/javascript const coffeeLimits = function(y,m,d) { let healthNumber = y * 10000 + m * 100 + d; let currentHex; let current; let i; let result = [0,0]; for(i=1;i<=5000;i++){ current = healthNumber + i * 0xcafe; currentHex = current.toString(16); if(currentHex.includes("dead")){ result[0]=i; break; } } for(i=1;i<=5000;i++){ current = healthNumber + i * 0xdecaf; currentHex = current.toString(16); if(currentHex.includes("dead")){ result[1]=i; break; } } return result; } export { coffeeLimits };
Add export to use as module
Add export to use as module
JavaScript
mit
sunnysetia93/competitive-coding-problems,sunnysetia93/competitive-coding-problems,sunnysetia93/competitive-coding-problems,sunnysetia93/competitive-coding-problems,sunnysetia93/competitive-coding-problems,sunnysetia93/competitive-coding-problems
--- +++ @@ -25,4 +25,4 @@ return result; } - +export { coffeeLimits };
fcf4357086a308bf9a9164f496c167e02e01ba17
lib/template.js
lib/template.js
const Handlebars = require('handlebars'); Handlebars.registerHelper('removeBreak', (text) => { text = Handlebars.Utils.escapeExpression(text); text = text.replace(/(\r\n|\n|\r)/gm, ' '); return new Handlebars.SafeString(text); }); const Template = class { constructor(templateString, data) { this.template = Handlebars.compile(templateString || ''); this.data = data || {}; } setTemplate(templateString) { this.template = Handlebars.compile(templateString || ''); } parse(callback) { callback(this.template(this.data)); } }; module.exports = Template;
const Handlebars = require('handlebars'); Handlebars.registerHelper('removeBreak', (text) => { text = Handlebars.Utils.escapeExpression(text); text = text.replace(/(\r\n|\n|\r)/gm, ' '); return new Handlebars.SafeString(text); }); const Template = class { constructor(templateString, data) { this.template = Handlebars.compile(templateString || ''); this.data = data || {}; } parse(callback) { callback(this.template(this.data)); } }; module.exports = Template;
Remove class method of Template
Remove class method of Template
JavaScript
mit
t32k/stylestats
--- +++ @@ -12,10 +12,6 @@ this.data = data || {}; } - setTemplate(templateString) { - this.template = Handlebars.compile(templateString || ''); - } - parse(callback) { callback(this.template(this.data)); }
ffdfc42c910a9d09d4cddc9c5df46d44d1e10ca8
grunt/contrib-jshint.js
grunt/contrib-jshint.js
// Check JS assets for code quality module.exports = function(grunt) { grunt.config('jshint', { all: ['Gruntfile.js', 'scripts/main.js'], }); grunt.loadNpmTasks('grunt-contrib-jshint'); };
// Check JS assets for code quality module.exports = function(grunt) { grunt.config('jshint', { all: ['Gruntfile.js', 'grunt/*.js', 'scripts/main.js'], }); grunt.loadNpmTasks('grunt-contrib-jshint'); };
Include Grunt partials in jshint task.
Include Grunt partials in jshint task.
JavaScript
mit
yellowled/yl-bp,yellowled/yl-bp
--- +++ @@ -2,6 +2,7 @@ module.exports = function(grunt) { grunt.config('jshint', { all: ['Gruntfile.js', + 'grunt/*.js', 'scripts/main.js'], });
db31f1d00912d3720c8b2af5257d8727347e4d94
lib/redis.js
lib/redis.js
const redis = require('redis') const config = require('config') const url = require('url') const logger = require('./logger.js')() const initRedisClient = function () { let client, redisInfo if (config.redis.url) { redisInfo = url.parse(config.redis.url) client = redis.createClient(redisInfo.port, redisInfo.hostname) } else { client = redis.createClient(config.redis.port, 'localhost') } const closeRedisConnection = function (error, exitCode) { if (error) { logger.error(error) } client.quit() client.on('end', function () { console.log('Disconnected from Redis') }) } // We do not want too many connections being made to Redis (especially for Streetmix production), // so before a process exits, close the connection to Redis. process.on('beforeExit', closeRedisConnection) process.on('SIGINT', closeRedisConnection) process.on('uncaughtException', closeRedisConnection) client.on('error', closeRedisConnection) client.on('connect', function () { console.log('Connected to Redis') const redisAuth = (config.redis.url && redisInfo) ? redisInfo.auth.split(':')[1] : config.redis.password if (redisAuth) { client.auth(redisAuth, function (error) { if (error) throw error }) } }) return client } module.exports = initRedisClient
const redis = require('redis') const config = require('config') const logger = require('./logger.js')() const initRedisClient = function () { let client, redisInfo if (config.redis.url) { redisInfo = new URL(config.redis.url) client = redis.createClient(redisInfo.port, redisInfo.hostname) } else { client = redis.createClient(config.redis.port, 'localhost') } const closeRedisConnection = function (error, exitCode) { if (error) { logger.error(error) } client.quit() client.on('end', function () { logger.info('Disconnected from Redis') }) } // We do not want too many connections being made to Redis (especially for Streetmix production), // so before a process exits, close the connection to Redis. process.on('beforeExit', closeRedisConnection) process.on('SIGINT', closeRedisConnection) process.on('uncaughtException', closeRedisConnection) client.on('error', closeRedisConnection) client.on('connect', function () { logger.info('Connected to Redis') // Use the password in the URL if provided; otherwise use the one provided by config const redisAuth = (config.redis.url && redisInfo) ? redisInfo.password : config.redis.password if (redisAuth) { client.auth(redisAuth, function (error) { if (error) throw error }) } }) return client } module.exports = initRedisClient
Replace deprecated url.parse() with WHATWG URL API
Replace deprecated url.parse() with WHATWG URL API
JavaScript
bsd-3-clause
codeforamerica/streetmix,codeforamerica/streetmix,codeforamerica/streetmix
--- +++ @@ -1,12 +1,12 @@ const redis = require('redis') const config = require('config') -const url = require('url') const logger = require('./logger.js')() const initRedisClient = function () { let client, redisInfo + if (config.redis.url) { - redisInfo = url.parse(config.redis.url) + redisInfo = new URL(config.redis.url) client = redis.createClient(redisInfo.port, redisInfo.hostname) } else { client = redis.createClient(config.redis.port, 'localhost') @@ -19,7 +19,7 @@ client.quit() client.on('end', function () { - console.log('Disconnected from Redis') + logger.info('Disconnected from Redis') }) } @@ -32,9 +32,11 @@ client.on('error', closeRedisConnection) client.on('connect', function () { - console.log('Connected to Redis') + logger.info('Connected to Redis') - const redisAuth = (config.redis.url && redisInfo) ? redisInfo.auth.split(':')[1] : config.redis.password + // Use the password in the URL if provided; otherwise use the one provided by config + const redisAuth = (config.redis.url && redisInfo) ? redisInfo.password : config.redis.password + if (redisAuth) { client.auth(redisAuth, function (error) { if (error) throw error
030d0f7d611c4b99819564f984354a659b2fa35a
core/src/main/public/static/js/find/app/page/search/results/state-token-strategy.js
core/src/main/public/static/js/find/app/page/search/results/state-token-strategy.js
/* * Copyright 2016 Hewlett-Packard Development Company, L.P. * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. */ define(['underscore'], function(_) { return { waitForIndexes: _.constant(false), promotions: _.constant(true), requestParams: function(queryModel) { return { text: queryModel.get('queryText'), state_match_ids: queryModel.get('stateMatchIds'), state_dont_match_ids: queryModel.get('stateDontMatchIds'), summary: 'context' }; }, validateQuery: function(queryModel) { return !_.isEmpty(queryModel.get('stateMatchIds')); } }; });
/* * Copyright 2016 Hewlett-Packard Development Company, L.P. * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. */ define(['underscore'], function(_) { return { waitForIndexes: _.constant(false), promotions: _.constant(false), requestParams: function(queryModel) { return { text: queryModel.get('queryText'), state_match_ids: queryModel.get('stateMatchIds'), state_dont_match_ids: queryModel.get('stateDontMatchIds'), summary: 'context' }; }, validateQuery: function(queryModel) { return !_.isEmpty(queryModel.get('stateMatchIds')); } }; });
Stop saved snapshots querying for promotions [rev: jon.soul]
[FIND-57] Stop saved snapshots querying for promotions [rev: jon.soul]
JavaScript
mit
hpautonomy/find,hpautonomy/find,LinkPowerHK/find,hpe-idol/java-powerpoint-report,hpautonomy/find,hpe-idol/find,hpautonomy/find,LinkPowerHK/find,hpe-idol/find,hpe-idol/find,hpe-idol/find,hpe-idol/java-powerpoint-report,LinkPowerHK/find,hpe-idol/find,LinkPowerHK/find,LinkPowerHK/find,hpautonomy/find
--- +++ @@ -8,7 +8,7 @@ return { waitForIndexes: _.constant(false), - promotions: _.constant(true), + promotions: _.constant(false), requestParams: function(queryModel) { return {
5c0a550bc9c68f0281bd1b61e93985cbaed962c0
src/lib/render-image.js
src/lib/render-image.js
// Utility for rendering html images to files 'use strict'; const webshot = require('webshot'); const Jimp = require('jimp'); const fs = require(`fs`); const webshotOptions = { windowSize: { width: 1024, height: 768 } , shotSize: { width: 1024, height: 'all' } , phantomPath: 'phantomjs' , siteType: 'html' , streamType: 'png' , renderDelay: 0 }; function renderImageFromHtml(html, outputPath) { return new Promise((resolve, reject) => { const tempFile = `${outputPath}.tmp.png`; webshot(html, tempFile, webshotOptions, (err) => { if (err) { console.error(`WEBSHOT ERROR: ${err}`); reject(err); return; } Jimp.read(tempFile) .then(image => image.autocrop().write(outputPath)) .then(() => { setTimeout(() => resolve(outputPath), 50); }) .then(() => fs.unlink(tempFile, (err) => { if (err) { console.error(err); reject(err); } })) .catch(err => { console.error('\n *** Failed to create trimmed png:'); console.error(err.stack); reject(err); }); }); }); } module.exports = { fromHtml: renderImageFromHtml };
// Utility for rendering html images to files 'use strict'; const webshot = require('webshot'); const Jimp = require('jimp'); const fs = require(`fs`); const webshotOptions = { windowSize: { width: 1024, height: 768 } , shotSize: { width: 1024, height: 'all' } , phantomPath: 'phantomjs' , siteType: 'html' , streamType: 'png' , renderDelay: 0 }; function renderImageFromHtml(html, outputPath) { return new Promise((resolve, reject) => { const tempFile = `${outputPath}.tmp.png`; webshot(html, tempFile, webshotOptions, (err) => { if (err) { console.error(`WEBSHOT ERROR: ${err}`); reject(err); return; } Jimp.read(tempFile) .then(image => image.autocrop().write(outputPath)) .then(() => { setTimeout(() => resolve(outputPath), 1000); }) .then(() => fs.unlink(tempFile, (err) => { if (err) { console.error(err); reject(err); } })) .catch(err => { console.error('\n *** Failed to create trimmed png:'); console.error(err.stack); reject(err); }); }); }); } module.exports = { fromHtml: renderImageFromHtml };
Increase delay before considering file written
Increase delay before considering file written
JavaScript
mit
GoodGamery/mtgnewsbot,GoodGamery/mtgnewsbot
--- +++ @@ -27,7 +27,7 @@ Jimp.read(tempFile) .then(image => image.autocrop().write(outputPath)) .then(() => { - setTimeout(() => resolve(outputPath), 50); + setTimeout(() => resolve(outputPath), 1000); }) .then(() => fs.unlink(tempFile, (err) => { if (err) {
8e279cc54dcc083bf49940a572b0574881bbeea8
www/lib/collections/photos.js
www/lib/collections/photos.js
Photo = function (doc) { _.extend(this, doc); }; _.extend(Photo.prototype, { getImgTag: function (dimension) { return { 'class': 'lazy', 'data-src': _.str.sprintf( '%s/photos/%s/%s', Meteor.settings.public.uri.cdn, dimension, this.filename ), 'data-src-retina': _.str.sprintf( '%s/photos/%s@2x/%s', Meteor.settings.public.uri.cdn, dimension, this.filename ), alt: this.title, width: dimension, height: dimension }; } }); Photos = new Mongo.Collection('Photos', { transform: function (doc) { return new Photo(doc); } });
Photo = function (doc) { _.extend(this, doc); }; _.extend(Photo.prototype, { getImgTag: function (dimension) { return { 'class': 'lazy', src: 'data:image/gif;base64,' + 'R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==', 'data-src': _.str.sprintf( '%s/photos/%s/%s', Meteor.settings.public.uri.cdn, dimension, this.filename ), 'data-src-retina': _.str.sprintf( '%s/photos/%s@2x/%s', Meteor.settings.public.uri.cdn, dimension, this.filename ), alt: this.title, width: dimension, height: dimension }; } }); Photos = new Mongo.Collection('Photos', { transform: function (doc) { return new Photo(doc); } });
Use a placeholder png to hold the image size
Use a placeholder png to hold the image size
JavaScript
mit
nburka/black-white
--- +++ @@ -6,6 +6,8 @@ getImgTag: function (dimension) { return { 'class': 'lazy', + src: 'data:image/gif;base64,' + + 'R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==', 'data-src': _.str.sprintf( '%s/photos/%s/%s', Meteor.settings.public.uri.cdn,
54306bafd423daff49272d4605bf84ae7a7471c8
js/metronome.js
js/metronome.js
function Metronome(tempo, beatsPerMeasure){ this.tempo = Number(tempo); this.beatsPerMeasure = Number(beatsPerMeasure); this.interval = null; } Metronome.prototype.start = function(){ var millisecondsToWait = this.tempoToMilliseconds(this.tempo); this.interval = window.setInterval(this.updateCounterView, millisecondsToWait, this.beatsPerMeasure); } Metronome.prototype.tempoToMilliseconds = function(tempo){ return (1000 * 60)/tempo; } Metronome.prototype.updateCounterView = function(beatsPerMeasure){ var counter = document.getElementById("metronome-counter"); var pastBeat = Number(counter.innerHTML); if (pastBeat < beatsPerMeasure){ counter.innerHTML = pastBeat + 1; } else { counter.innerHTML = 1; } Metronome.prototype.stop = function(){ window.clearInterval(this.interval); } }
function Metronome(tempo, beatsPerMeasure){ this.tempo = Number(tempo); this.beatsPerMeasure = Number(beatsPerMeasure); this.interval = null; } Metronome.prototype.start = function(){ var millisecondsToWait = this.tempoToMilliseconds(this.tempo); this.interval = window.setInterval(this.updateCounterView, millisecondsToWait, this.beatsPerMeasure); } Metronome.prototype.tempoToMilliseconds = function(tempo){ return (1000 * 60)/tempo; } Metronome.prototype.updateCounterView = function(beatsPerMeasure){ var counter = document.getElementById("metronome-counter"); var pastBeat = Number(counter.innerHTML); if (pastBeat < beatsPerMeasure){ counter.innerHTML = pastBeat + 1; } else { counter.innerHTML = 1; } Metronome.prototype.stop = function(){ window.clearInterval(this.interval); counter.innerHTML = ""; } }
Clear counter when Metronome is stopped
Clear counter when Metronome is stopped
JavaScript
mit
dmilburn/beatrice,dmilburn/beatrice
--- +++ @@ -25,5 +25,6 @@ Metronome.prototype.stop = function(){ window.clearInterval(this.interval); + counter.innerHTML = ""; } }
dba8dc2f41ffdf023bbfb8dbf92826c6c799a0b0
js/nbpreview.js
js/nbpreview.js
(function () { var root = this; var $file_input = document.querySelector("input#file"); var $holder = document.querySelector("#notebook-holder"); var render_notebook = function (ipynb) { var notebook = root.notebook = nb.parse(ipynb); while ($holder.hasChildNodes()) { $holder.removeChild($holder.lastChild); } $holder.appendChild(notebook.render()); Prism.highlightAll(); }; $file_input.onchange = function (e) { var reader = new FileReader(); reader.onload = function (e) { var parsed = JSON.parse(this.result); render_notebook(parsed); }; reader.readAsText(this.files[0]); }; }).call(this);
(function () { var root = this; var $file_input = document.querySelector("input#file"); var $holder = document.querySelector("#notebook-holder"); var render_notebook = function (ipynb) { var notebook = root.notebook = nb.parse(ipynb); while ($holder.hasChildNodes()) { $holder.removeChild($holder.lastChild); } $holder.appendChild(notebook.render()); Prism.highlightAll(); }; var load_file = function (file) { var reader = new FileReader(); reader.onload = function (e) { var parsed = JSON.parse(this.result); render_notebook(parsed); }; reader.readAsText(file); }; $file_input.onchange = function (e) { load_file(this.files[0]); }; window.addEventListener('dragover', function (e) { e.stopPropagation(); e.preventDefault(); e.dataTransfer.dropEffect = 'copy'; // Explicitly show this is a root.document.body.style.opacity = 0.5; }, false); window.addEventListener('dragleave', function (e) { root.document.body.style.opacity = 1; }, false); window.addEventListener('drop', function (e) { e.stopPropagation(); e.preventDefault(); load_file(e.dataTransfer.files[0]); $file_input.style.display = "none"; root.document.body.style.opacity = 1; }, false); }).call(this);
Add support for dropping files into window.
Add support for dropping files into window.
JavaScript
mit
jsvine/nbpreview,jsvine/nbpreview
--- +++ @@ -12,12 +12,36 @@ Prism.highlightAll(); }; - $file_input.onchange = function (e) { + var load_file = function (file) { var reader = new FileReader(); reader.onload = function (e) { var parsed = JSON.parse(this.result); render_notebook(parsed); }; - reader.readAsText(this.files[0]); + reader.readAsText(file); }; + + $file_input.onchange = function (e) { + load_file(this.files[0]); + }; + + window.addEventListener('dragover', function (e) { + e.stopPropagation(); + e.preventDefault(); + e.dataTransfer.dropEffect = 'copy'; // Explicitly show this is a + root.document.body.style.opacity = 0.5; + }, false); + + window.addEventListener('dragleave', function (e) { + root.document.body.style.opacity = 1; + }, false); + + window.addEventListener('drop', function (e) { + e.stopPropagation(); + e.preventDefault(); + load_file(e.dataTransfer.files[0]); + $file_input.style.display = "none"; + root.document.body.style.opacity = 1; + }, false); + }).call(this);
c3f9e5eff4b8b7e7de0e4a6f7da1faad077b23ee
templates/system/modules/ph7cms-donation/themes/base/js/donationbox.js
templates/system/modules/ph7cms-donation/themes/base/js/donationbox.js
/* * Author: Pierre-Henry Soria <hello@ph7cms.com> * Copyright: (c) 2015-2017, Pierre-Henry Soria. All Rights Reserved. * License: GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory. */ var $validationBox = (function () { $.get(pH7Url.base + 'ph7cms-donation/main/donationbox', function (oData) { $.colorbox({ width: '100%', maxWidth: '450px', maxHeight: '85%', speed: 500, scrolling: false, html: $(oData).find('#box_block') }) }) }); $validationBox();
/* * Author: Pierre-Henry Soria <hello@ph7cms.com> * Copyright: (c) 2015-2017, Pierre-Henry Soria. All Rights Reserved. * License: GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory. */ var $validationBox = (function () { $.get(pH7Url.base + 'ph7cms-donation/main/donationbox', function (oData) { $.colorbox({ width: '100%', width: '200px', height: '155px', speed: 500, scrolling: false, html: $(oData).find('#box_block') }) }) }); $validationBox();
Change size of donation popup
Change size of donation popup
JavaScript
mit
pH7Software/pH7-Social-Dating-CMS,pH7Software/pH7-Social-Dating-CMS,pH7Software/pH7-Social-Dating-CMS,pH7Software/pH7-Social-Dating-CMS
--- +++ @@ -8,8 +8,8 @@ $.get(pH7Url.base + 'ph7cms-donation/main/donationbox', function (oData) { $.colorbox({ width: '100%', - maxWidth: '450px', - maxHeight: '85%', + width: '200px', + height: '155px', speed: 500, scrolling: false, html: $(oData).find('#box_block')
7044032b4ace71eda06a99a5389edf0289179602
src/list.js
src/list.js
import { debuglog } from 'util'; import AbstractCache from './abstract'; export default class ListCache extends AbstractCache { constructor() { super(); this._log = debuglog('cache'); this._date = null; this.touch(); } touch() { this._date = Date.now(); return this; } get(key, callback) { this._log('ListCache get %s', key); this._client.get(key, (error, value) => { if (error) { callback(error); return; } if (!value) { callback(); return; } if (value.date < this._date) { this._client.del(key, () => callback()); return; } callback(null, value.data); }); } set(key, data, callback) { this._log('ListCache set %s', key); const value = { data, date: Date.now() }; this._client.set(key, value, (error) => { if (error) { callback(error); return; } callback(null, data); }); } del(key, callback) { this._log('ListCache del %s', key); this._client.del(key, callback); } }
import { debuglog } from 'util'; import AbstractCache from './abstract'; export default class ListCache extends AbstractCache { constructor() { super(); this._log = debuglog('cache'); this._date = Date.now(); } date(value = null) { if (value === null) { return this._date; } this._log('ListCache date %s', value); this._date = value; return this; } get(key, callback) { this._log('ListCache get %s', key); this._client.get(key, (error, value) => { if (error) { callback(error); return; } if (!value) { callback(); return; } if (value.date < this._date) { this._client.del(key, () => callback()); return; } callback(null, value.data); }); } set(key, data, callback) { this._log('ListCache set %s', key); const value = { data, date: Date.now() }; this._client.set(key, value, (error) => { if (error) { callback(error); return; } callback(null, data); }); } del(key, callback) { this._log('ListCache del %s', key); this._client.del(key, callback); } }
Replace touch with date get/setter
Replace touch with date get/setter
JavaScript
mit
scola84/node-api-cache
--- +++ @@ -6,13 +6,17 @@ super(); this._log = debuglog('cache'); - this._date = null; - - this.touch(); + this._date = Date.now(); } - touch() { - this._date = Date.now(); + date(value = null) { + if (value === null) { + return this._date; + } + + this._log('ListCache date %s', value); + + this._date = value; return this; }
d4660759d672c90a23fe0944082cff0083d691a0
src/main.js
src/main.js
import Vue from 'vue'; import VueResource from 'vue-resource'; import VueRouter from 'vue-router'; import App from './App.vue'; import About from './components/About.vue'; import store from './store'; import routes from './router'; import components from './components'; import filters from './filters' Vue.use(VueResource); Vue.use(VueRouter); components(Vue); filters(Vue); export const router = new VueRouter({ routes: routes, base: __dirname }); new Vue({ router, store, el: '#app', components: { App } });
import Vue from 'vue'; import VueResource from 'vue-resource'; import VueRouter from 'vue-router'; import App from './App.vue'; import About from './components/About.vue'; import store from './store'; import routes from './router'; import components from './components'; import filters from './filters' Vue.use(VueResource); Vue.use(VueRouter); components(Vue); filters(Vue); export const router = new VueRouter({ mode: 'history', routes: routes, base: __dirname }); new Vue({ router, store, el: '#app', components: { App } });
Switch router to history mode
Switch router to history mode
JavaScript
mit
dmurtari/mbu-frontend,dmurtari/mbu-frontend
--- +++ @@ -17,6 +17,7 @@ filters(Vue); export const router = new VueRouter({ + mode: 'history', routes: routes, base: __dirname });
a1694721011727b4570e21d444e6b23835d42a1c
src/main.js
src/main.js
'use strict'; var resourcify = angular.module('resourcify', []); function resourcificator ($http, $q) { var $resourcifyError = angular.$$minErr('resourcify'), requestOptions = ['query', 'get', '$get', '$save', '$update', '$delete'], requestMethods = { 'query': 'GET', 'get': 'GET', '$get': 'GET', '$save': 'POST', '$update': 'PUT', '$delete': 'DELETE' }, validMethods = ['GET', 'PUT', 'POST', 'DELETE', 'PATCH'], bodyMethods = ['$save', '$update', '$delete', 'PUT', 'POST', 'DELETE', 'PATCH']; function validMethod (method) { if (!~validMethods.indexOf(method)) { throw $resourcifyError('requesttype', '"@{0}" is not a valid request method.', method); } return method; } function replaceParams (params, url) { } } resourcificator.$inject = ['$http', '$q']; resourcify.service('resourcify', resourcificator);
'use strict'; var resourcify = angular.module('resourcify', []); function resourcificator ($http, $q) { var $resourcifyError = angular.$$minErr('resourcify'), requestOptions = ['query', 'get', '$get', '$save', '$update', '$delete'], requestMethods = { 'query': 'GET', 'get': 'GET', '$get': 'GET', '$save': 'POST', '$update': 'PUT', '$delete': 'DELETE' }, bodyMethods = ['$save', '$update', '$delete', 'PUT', 'POST', 'DELETE', 'PATCH']; // Finds and replaces query params and path params function replaceParams (params, url) { var findParam = /[\/=](:\w*[a-zA-Z]\w*)/g, copiedPath = angular.copy(url); } } resourcificator.$inject = ['$http', '$q']; resourcify.service('resourcify', resourcificator);
Add regex for finding path params
Add regex for finding path params
JavaScript
mit
erikdonohoo/resourcify,erikdonohoo/resourcify
--- +++ @@ -14,18 +14,11 @@ '$update': 'PUT', '$delete': 'DELETE' }, - validMethods = ['GET', 'PUT', 'POST', 'DELETE', 'PATCH'], bodyMethods = ['$save', '$update', '$delete', 'PUT', 'POST', 'DELETE', 'PATCH']; - function validMethod (method) { - if (!~validMethods.indexOf(method)) { - throw $resourcifyError('requesttype', '"@{0}" is not a valid request method.', method); - } - return method; - } - + // Finds and replaces query params and path params function replaceParams (params, url) { - + var findParam = /[\/=](:\w*[a-zA-Z]\w*)/g, copiedPath = angular.copy(url); } }
b3827c12d2092ec93813470ec0b9a81d4d554d08
lib/client/satisfactionratings.js
lib/client/satisfactionratings.js
//SatisfactionRatings.js: Client for the zendesk API. var util = require('util'), Client = require('./client').Client, defaultgroups = require('./helpers').defaultgroups; var SatisfactionRatings = exports.SatisfactionRatings = function (options) { this.jsonAPIName = 'satisfaction_ratings'; Client.call(this, options); }; // Inherit from Client base object util.inherits(SatisfactionRatings, Client); // ######################################################## SatisfactionRatings // ====================================== Listing SatisfactionRatings SatisfactionRatings.prototype.list = function (cb) { this.requestAll('GET', ['satisfaction_ratings'], cb);//all }; SatisfactionRatings.prototype.received = function (cb) { this.requestAll('GET', ['satisfaction_ratings', 'received'], cb);//all }; SatisfactionRatings.prototype.show = function (satisfactionRatingID, cb) { this.request('GET', ['satisfaction_ratings', satisfactionRatingID], cb);//all };
//SatisfactionRatings.js: Client for the zendesk API. var util = require('util'), Client = require('./client').Client, defaultgroups = require('./helpers').defaultgroups; var SatisfactionRatings = exports.SatisfactionRatings = function (options) { this.jsonAPIName = 'satisfaction_ratings'; Client.call(this, options); }; // Inherit from Client base object util.inherits(SatisfactionRatings, Client); // ######################################################## SatisfactionRatings // ====================================== Listing SatisfactionRatings SatisfactionRatings.prototype.list = function (cb) { this.requestAll('GET', ['satisfaction_ratings'], cb);//all }; SatisfactionRatings.prototype.received = function (cb) { this.requestAll('GET', ['satisfaction_ratings', 'received'], cb);//all }; SatisfactionRatings.prototype.show = function (satisfactionRatingID, cb) { this.request('GET', ['satisfaction_ratings', satisfactionRatingID], cb);//all }; // ====================================== Posting SatisfactionRatings SatisfactionRatings.prototype.create = function (ticketID, satisfactionRating, cb) { this.request('POST', ['tickets', ticketId, 'satisfaction_rating'], satisfactionRating, cb); };
Add support for creating Satisfaction Ratings
Add support for creating Satisfaction Ratings As documented at https://developer.zendesk.com/rest_api/docs/core/satisfaction_ratings#create-a-satisfaction-rating
JavaScript
mit
blakmatrix/node-zendesk,blakmatrix/node-zendesk
--- +++ @@ -28,4 +28,7 @@ this.request('GET', ['satisfaction_ratings', satisfactionRatingID], cb);//all }; - +// ====================================== Posting SatisfactionRatings +SatisfactionRatings.prototype.create = function (ticketID, satisfactionRating, cb) { + this.request('POST', ['tickets', ticketId, 'satisfaction_rating'], satisfactionRating, cb); +};
30100c0d4d320abbe3004f795b7121d3dfebdaf5
logger.js
logger.js
const chalk = require('chalk'); LOG_TYPES = { NONE: 0, ERROR: 1, NORMAL: 2, DEBUG: 3 }; let logType = LOG_TYPES.NORMAL; const setLogType = (type) => { if (!(type in Object.values(LOG_TYPES))) return; logType = type; }; const logTime = () => { let nowDate = new Date(); return nowDate.toLocaleDateString() + ' ' + nowDate.toLocaleTimeString([], { hour12: false }); }; const log = (...args) => { if (logType < LOG_TYPES.NORMAL) return; console.log(logTime(), chalk.bold.green('[INFO]'), ...args); }; const error = (...args) => { if (logType < LOG_TYPES.ERROR) return; console.log(logTime(), chalk.bold.red('[ERROR]'), ...args); }; const debug = (...args) => { if (logType < LOG_TYPES.DEBUG) return; console.log(logTime(), chalk.bold.blue('[DEBUG]'), ...args); }; module.exports = { LOG_TYPES, setLogType, log, error, debug }
const chalk = require('chalk'); LOG_TYPES = { NONE: 0, ERROR: 1, NORMAL: 2, DEBUG: 3 }; let logType = LOG_TYPES.NORMAL; const setLogType = (type) => { if (typeof type !== 'number') return; logType = type; }; const logTime = () => { let nowDate = new Date(); return nowDate.toLocaleDateString() + ' ' + nowDate.toLocaleTimeString([], { hour12: false }); }; const log = (...args) => { if (logType < LOG_TYPES.NORMAL) return; console.log(logTime(), chalk.bold.green('[INFO]'), ...args); }; const error = (...args) => { if (logType < LOG_TYPES.ERROR) return; console.log(logTime(), chalk.bold.red('[ERROR]'), ...args); }; const debug = (...args) => { if (logType < LOG_TYPES.DEBUG) return; console.log(logTime(), chalk.bold.blue('[DEBUG]'), ...args); }; module.exports = { LOG_TYPES, setLogType, log, error, debug }
Fix nodejs v6 'TypeError: Object.values is not a function'
Fix nodejs v6 'TypeError: Object.values is not a function'
JavaScript
mit
illuspas/Node-Media-Server,illuspas/Node-Media-Server
--- +++ @@ -10,7 +10,7 @@ let logType = LOG_TYPES.NORMAL; const setLogType = (type) => { - if (!(type in Object.values(LOG_TYPES))) return; + if (typeof type !== 'number') return; logType = type; };
789eb9cc78ecaf8e7e04dc8ca1dc8ac7b48f86de
src/node.js
src/node.js
import fs from 'fs'; import { pdf, View, Text, Link, Page, Font, Note, Image, version, Document, StyleSheet, PDFRenderer, createInstance, } from './index'; export const renderToStream = function(element) { return pdf(element).toBuffer(); }; export const renderToFile = function(element, filePath, callback) { const output = renderToStream(element); const stream = fs.createWriteStream(filePath); output.pipe(stream); return new Promise((resolve, reject) => { stream.on('finish', () => { if (callback) callback(output, filePath); resolve(output); }); stream.on('error', reject); }); }; export const render = renderToFile; export { pdf, View, Text, Link, Page, Font, Note, Image, version, Document, StyleSheet, PDFRenderer, createInstance, } from './index'; export default { pdf, View, Text, Link, Page, Font, Note, Image, version, Document, StyleSheet, PDFRenderer, createInstance, renderToStream, renderToFile, render, };
import fs from 'fs'; import { pdf, View, Text, Link, Page, Font, Note, Image, version, Document, StyleSheet, PDFRenderer, createInstance, } from './index'; export const renderToStream = function(element) { return pdf(element).toBuffer(); }; export const renderToFile = function(element, filePath, callback) { const output = renderToStream(element); const stream = fs.createWriteStream(filePath); output.pipe(stream); return new Promise((resolve, reject) => { stream.on('finish', () => { if (callback) callback(output, filePath); resolve(output); }); stream.on('error', reject); }); }; const throwEnvironmentError = name => { throw new Error( `${name} is a web specific API. Or you're either using this component on Node, or your bundler is not loading react-pdf from the appropiate web build.`, ); }; export const PDFViewer = () => { throwEnvironmentError('PDFViewer'); }; export const PDFDownloadLink = () => { throwEnvironmentError('PDFDownloadLink'); }; export const BlobProvider = () => { throwEnvironmentError('BlobProvider'); }; export const render = renderToFile; export { pdf, View, Text, Link, Page, Font, Note, Image, version, Document, StyleSheet, PDFRenderer, createInstance, } from './index'; export default { pdf, View, Text, Link, Page, Font, Note, Image, version, Document, StyleSheet, PDFRenderer, createInstance, renderToStream, renderToFile, render, };
Throw error when trying to use web specific APIs on Node
Throw error when trying to use web specific APIs on Node
JavaScript
mit
diegomura/react-pdf,diegomura/react-pdf
--- +++ @@ -32,6 +32,24 @@ }); stream.on('error', reject); }); +}; + +const throwEnvironmentError = name => { + throw new Error( + `${name} is a web specific API. Or you're either using this component on Node, or your bundler is not loading react-pdf from the appropiate web build.`, + ); +}; + +export const PDFViewer = () => { + throwEnvironmentError('PDFViewer'); +}; + +export const PDFDownloadLink = () => { + throwEnvironmentError('PDFDownloadLink'); +}; + +export const BlobProvider = () => { + throwEnvironmentError('BlobProvider'); }; export const render = renderToFile;
caf9ce480560406d0354cf20a93323e2e08ca7c1
src/app/rules/references.service.js
src/app/rules/references.service.js
define(['rules/rules.module' ], function() { angular.module('rules').factory('references', [ function() { function generateReference(query) { var url = ('#/rules/explain?inference=' + encodeURIComponent(angular.toJson(query, false))); var reference = { P854: [{ datatype: 'url', datavalue: { type: 'string', value: url }, snaktype: 'value', property: 'P854' }] }; return [{ snaks: reference, 'snaks-order': ['P854'] }]; } return { generateReference: generateReference }; }]); return {}; });
define(['rules/rules.module' ], function() { angular.module('rules').factory('references', [ function() { function generateReference(query) { var bindings = []; angular.forEach(query.bindings, function(binding) { if ('id' in binding) { bindings.push(binding.id); } }); var info = { rule: query.rule, query: query.query, bindings: bindings, constraints: query.constraints }; var url = ('#/rules/explain?inference=' + encodeURIComponent(angular.toJson(info, false))); var reference = { P854: [{ datatype: 'url', datavalue: { type: 'string', value: url }, snaktype: 'value', property: 'P854' }] }; return [{ snaks: reference, 'snaks-order': ['P854'] }]; } return { generateReference: generateReference }; }]); return {}; });
Reduce amount of information in reference links
Reduce amount of information in reference links
JavaScript
apache-2.0
Wikidata/SQID,Wikidata/WikidataClassBrowser,Wikidata/WikidataClassBrowser,Wikidata/SQID,Wikidata/SQID,Wikidata/WikidataClassBrowser,Wikidata/SQID,Wikidata/SQID,Wikidata/SQID,Wikidata/SQID
--- +++ @@ -5,8 +5,21 @@ [ function() { function generateReference(query) { + var bindings = []; + + angular.forEach(query.bindings, function(binding) { + if ('id' in binding) { + bindings.push(binding.id); + } + }); + + var info = { rule: query.rule, + query: query.query, + bindings: bindings, + constraints: query.constraints + }; var url = ('#/rules/explain?inference=' + - encodeURIComponent(angular.toJson(query, false))); + encodeURIComponent(angular.toJson(info, false))); var reference = { P854: [{ datatype: 'url', datavalue: { type: 'string', value: url