commit
stringlengths
40
40
old_file
stringlengths
4
236
new_file
stringlengths
4
236
old_contents
stringlengths
1
3.26k
new_contents
stringlengths
16
4.43k
subject
stringlengths
16
624
message
stringlengths
17
3.29k
lang
stringclasses
5 values
license
stringclasses
13 values
repos
stringlengths
5
91.5k
6d9d315ca741f5472902c0f961591fdff9bbf946
src/js/utils/time.js
src/js/utils/time.js
// ========================================================================== // Time utils // ========================================================================== import is from './is'; // Time helpers export const getHours = value => parseInt((value / 60 / 60) % 60, 10); export const getMinutes = value => parseInt((value / 60) % 60, 10); export const getSeconds = value => parseInt(value % 60, 10); // Format time to UI friendly string export function formatTime(time = 0, displayHours = false, inverted = false) { // Bail if the value isn't a number if (!is.number(time)) { return formatTime(null, displayHours, inverted); } // Format time component to add leading zero const format = value => `0${value}`.slice(-2); // Breakdown to hours, mins, secs let hours = getHours(time); const mins = getMinutes(time); const secs = getSeconds(time); // Do we need to display hours? if (displayHours || hours > 0) { hours = `${hours}:`; } else { hours = ''; } // Render return `${inverted && time > 0 ? '-' : ''}${hours}${format(mins)}:${format(secs)}`; }
// ========================================================================== // Time utils // ========================================================================== import is from './is'; // Time helpers export const getHours = value => Math.trunc((value / 60 / 60) % 60, 10); export const getMinutes = value => Math.trunc((value / 60) % 60, 10); export const getSeconds = value => Math.trunc(value % 60, 10); // Format time to UI friendly string export function formatTime(time = 0, displayHours = false, inverted = false) { // Bail if the value isn't a number if (!is.number(time)) { return formatTime(null, displayHours, inverted); } // Format time component to add leading zero const format = value => `0${value}`.slice(-2); // Breakdown to hours, mins, secs let hours = getHours(time); const mins = getMinutes(time); const secs = getSeconds(time); // Do we need to display hours? if (displayHours || hours > 0) { hours = `${hours}:`; } else { hours = ''; } // Render return `${inverted && time > 0 ? '-' : ''}${hours}${format(mins)}:${format(secs)}`; }
Use Math.trunc instead of parseInt
fix: Use Math.trunc instead of parseInt
JavaScript
mit
dacostafilipe/plyr,dacostafilipe/plyr,sampotts/plyr,Selz/plyr
5ea305a1fa5591bb50d1b180546ce1e8efa4b258
scripts/chris.js
scripts/chris.js
var audio = document.getElementById("chris"); function pauseChris() { if (audio.currentTime >= 331000) { audio.pause(); } } function playChris() { audio.currentTime = 952; audio.play(); var interval = setInterval(pauseChris, 1000); alert(interval); } function addChrisButton() { var div = document.getElementById("audioContainer"); var button = document.createElement("BUTTON"); button.setAttribute("type", "button"); button.addEventListener("click", playChris); button.innerText = "Escuchar a Chris"; div.insertBefore(button, audio); } addChrisButton();
var audio = document.getElementById("chris"); function pauseChris() { if (audio.currentTime >= 331000) { audio.pause(); alert(interval); } } function playChris() { audio.currentTime = 952; audio.play(); var interval = setInterval(pauseChris, 1000); } function addChrisButton() { var div = document.getElementById("audioContainer"); var button = document.createElement("BUTTON"); button.setAttribute("type", "button"); button.addEventListener("click", playChris); button.innerText = "Escuchar a Chris"; div.insertBefore(button, audio); } addChrisButton();
Test with alert in pause
Test with alert in pause
JavaScript
mit
nvdaes/nvdaes.github.io,nvdaes/nvdaes.github.io
ae8d93f223107d6fde7c1426187ac36e4747b010
src/utils/isReactModuleName.js
src/utils/isReactModuleName.js
/* * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @flow * */ var reactModules = ['react', 'react/addons']; /** * Takes a module name (string) and returns true if it refers to a root react * module name. */ export default function isReactModuleName(moduleName: string): boolean { return reactModules.some(function(reactModuleName) { return reactModuleName === moduleName.toLowerCase(); }); }
/* * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @flow * */ var reactModules = ['react', 'react/addons', 'react-native']; /** * Takes a module name (string) and returns true if it refers to a root react * module name. */ export default function isReactModuleName(moduleName: string): boolean { return reactModules.some(function(reactModuleName) { return reactModuleName === moduleName.toLowerCase(); }); }
Add support for PropTypes import from react-native
Add support for PropTypes import from react-native See issue #43
JavaScript
mit
fkling/react-docgen,reactjs/react-docgen,janicduplessis/react-docgen,reactjs/react-docgen,reactjs/react-docgen
453c689050e6cb8277f47eed16035b7cd608f262
server/server.js
server/server.js
'use strict'; var loopback = require('loopback'); var boot = require('loopback-boot'); var path = require('path'); var bodyParser = require('body-parser'); var app = module.exports = loopback(); // configure view handler app.set('view engine', 'ejs'); app.set('views', path.join(__dirname, 'views')); // configure body parser app.use(bodyParser.urlencoded({extended: true})); app.use(loopback.token()); app.start = function() { // start the web server return app.listen(function() { app.emit('started'); var baseUrl = app.get('url').replace(/\/$/, ''); console.log('Web server listening at: %s', baseUrl); if (app.get('loopback-component-explorer')) { var explorerPath = app.get('loopback-component-explorer').mountPath; console.log('Browse your REST API at %s%s', baseUrl, explorerPath); } }); }; // Bootstrap the application, configure models, datasources and middleware. // Sub-apps like REST API are mounted via boot scripts. boot(app, __dirname, function(err) { if (err) throw err; // start the server if `$ node server.js` if (require.main === module) app.start(); });
'use strict' var loopback = require('loopback') var boot = require('loopback-boot') var path = require('path') var bodyParser = require('body-parser') var app = module.exports = loopback() // configure body parser app.use(bodyParser.urlencoded({extended: true})) app.use(loopback.token({ model: app.models.accessToken, currentUserLiteral: 'me' })) app.start = function() { // start the web server return app.listen(function() { app.emit('started') var baseUrl = app.get('url').replace(/\/$/, '') console.log('Web server listening at: %s', baseUrl) if (app.get('loopback-component-explorer')) { var explorerPath = app.get('loopback-component-explorer').mountPath console.log('Browse your REST API at %s%s', baseUrl, explorerPath) } }) } // Bootstrap the application, configure models, datasources and middleware. // Sub-apps like REST API are mounted via boot scripts. boot(app, __dirname, function(err) { if (err) throw err // start the server if `$ node server.js` if (require.main === module) app.start() })
Remove Extra EJS Routes Handler and Add Caching Process to AccessToken
Remove Extra EJS Routes Handler and Add Caching Process to AccessToken
JavaScript
mit
Flieral/Publisher-Service,Flieral/Publisher-Service
5db936da218aafcb5480119c655fbb9dc4071b94
lib/text-align.js
lib/text-align.js
var _ = require('lodash') var fs = require('fs') var gzip = require('gzip-size') var filesize = require('filesize') var cssstats = require('cssstats') var module = require('tachyons-text-align/package.json') var moduleCss = fs.readFileSync('node_modules/tachyons-text-align/tachyons-text-align.min.css', 'utf8') var moduleObj = cssstats(moduleCss) var moduleSize = filesize(moduleObj.gzipSize) var srcCSS = fs.readFileSync('./src/_text-align.css', 'utf8') var template = fs.readFileSync('./templates/docs/text-align/index.html', 'utf8') var tpl = _.template(template) var html = tpl({ moduleVersion: module.version, moduleSize: moduleSize, moduleObj: moduleObj, srcCSS: srcCSS }) fs.writeFileSync('./docs/typography/text-align/index.html', html)
var _ = require('lodash') var fs = require('fs') var gzip = require('gzip-size') var filesize = require('filesize') var cssstats = require('cssstats') var module = require('tachyons-text-align/package.json') var moduleCss = fs.readFileSync('node_modules/tachyons-text-align/tachyons-text-align.min.css', 'utf8') var moduleObj = cssstats(moduleCss) var moduleSize = filesize(moduleObj.gzipSize) var srcCSS = fs.readFileSync('./src/_text-align.css', 'utf8') var navDocs = fs.readFileSync('./templates/nav_docs.html', 'utf8') var template = fs.readFileSync('./templates/docs/text-align/index.html', 'utf8') var tpl = _.template(template) var html = tpl({ moduleVersion: module.version, moduleSize: moduleSize, moduleObj: moduleObj, srcCSS: srcCSS, navDocs: navDocs }) fs.writeFileSync('./docs/typography/text-align/index.html', html)
Update with reference to global nav partial
Update with reference to global nav partial
JavaScript
mit
getfrank/tachyons,topherauyeung/portfolio,topherauyeung/portfolio,matyikriszta/moonlit-landing-page,fenderdigital/css-utilities,tachyons-css/tachyons,fenderdigital/css-utilities,cwonrails/tachyons,pietgeursen/pietgeursen.github.io,topherauyeung/portfolio
d4f7822658f0c67952bc861f8efc10431c481cb1
put_comma.js
put_comma.js
var num; var num_str; var result = ''; // check args if (process.argv.length < 3) { // sample value num = Math.floor(Math.random() * 1000000000) + 1; } else { num = process.argv[2]; } num_str = num.toString(); console.log('input: ' + num_str); while (num_str.length > 0) { var three_digits = num_str.slice(-3); // get 3 digits result = three_digits + result; num_str = num_str.slice(0, -3); // remove 3 digits if (num_str.length >= 1) { result = ',' + result; } } console.log(result);
var num; var num_str; var result = ''; // check args if (process.argv.length < 3) { // sample value num = Math.floor(Math.random() * 1000000000) + 1; } else { num = process.argv[2]; } console.log('input: ' + num); num_str = Number(num).toString(); while (num_str.length > 0) { var three_digits = num_str.slice(-3); // get 3 digits result = three_digits + result; num_str = num_str.slice(0, -3); // remove 3 digits if (num_str.length >= 1) { result = ',' + result; } } console.log(result);
Deal with a case starting 0, e.g. input: 01234, output: 1,234
Deal with a case starting 0, e.g. input: 01234, output: 1,234
JavaScript
mit
moji29nabe/quiz
020d181694878a374fa1ae8606942a0b77d40ae7
app/js/pointer-lock.js
app/js/pointer-lock.js
import THREE from 'three'; export default function pointerLock( controls ) { const hasPointerLock = 'pointerLockElement' in document || 'mozPointerLockElement' in document || 'webkitPointerLockElement' in document; if ( !hasPointerLock ) { return; } const element = document.body; const dispatcher = new THREE.EventDispatcher(); function onPointerLockChange() { if ( document.pointerLockElement === element || document.mozPointerLockElement === element || document.webkitPointerLockElement === element ) { controls.enabled = true; } else { controls.enabled = false; } dispatcher.dispatchEvent({ type: 'change', enabled: controls.enabled }); } function onPointerLockError() { dispatcher.dispatchEvent({ type: 'error' }); } document.addEventListener( 'pointerlockchange', onPointerLockChange ); document.addEventListener( 'mozpointerlockchange', onPointerLockChange ); document.addEventListener( 'webkitpointerlockchange', onPointerLockChange ); document.addEventListener( 'pointerlockerror', onPointerLockError ); document.addEventListener( 'mozpointerlockerror', onPointerLockError ); document.addEventListener( 'webkitpointerlockerror', onPointerLockError ); element.requestPointerLock = element.requestPointerLock || element.mozRequestPointerLock || element.webkitRequestPointerLock; document.addEventListener( 'click', () => element.requestPointerLock() ); return dispatcher; }
import THREE from 'three'; export default function pointerLock( controls, element = document.body ) { const hasPointerLock = ( 'pointerLockElement' in document || 'mozPointerLockElement' in document || 'webkitPointerLockElement' in document ); if ( !hasPointerLock ) { return; } const dispatcher = new THREE.EventDispatcher(); function onPointerLockChange() { controls.enabled = ( element === document.pointerLockElement || element === document.mozPointerLockElement || element === document.webkitPointerLockElement ); dispatcher.dispatchEvent({ type: 'change', enabled: controls.enabled }); } function onPointerLockError() { dispatcher.dispatchEvent({ type: 'error' }); } document.addEventListener( 'pointerlockchange', onPointerLockChange ); document.addEventListener( 'mozpointerlockchange', onPointerLockChange ); document.addEventListener( 'webkitpointerlockchange', onPointerLockChange ); document.addEventListener( 'pointerlockerror', onPointerLockError ); document.addEventListener( 'mozpointerlockerror', onPointerLockError ); document.addEventListener( 'webkitpointerlockerror', onPointerLockError ); element.requestPointerLock = ( element.requestPointerLock || element.mozRequestPointerLock || element.webkitRequestPointerLock ); document.addEventListener( 'click', () => element.requestPointerLock() ); return dispatcher; }
Add pointerLock() custom element support.
Add pointerLock() custom element support. Increase readability.
JavaScript
mit
razh/third-person-camera-tests,razh/third-person-camera-tests
e215805c984d8f3da9e5b4380ddf20ea76a88e9e
app/routes/accounts.js
app/routes/accounts.js
import Ember from 'ember'; export default Ember.Route.extend({ model: function(params) { return this.store.find('namespace', btoa(params.namespace)); } });
import Ember from 'ember'; export default Ember.Route.extend({ setupController: function(controller, model) { // Model Hook is called only when the page is accessed via direct // navigation var namespace = this.store.fetch('namespace', btoa(model.namespace)); controller.set('model', namespace); }, });
Fix model hook not being called when performing 'transitionToRoute'
Fix model hook not being called when performing 'transitionToRoute'
JavaScript
mit
nihey/firehon,nihey/firehon
833e6dc23b1d9d2b6d81cd0c68654a904f045578
src/modules/gallery-lazy-load.js
src/modules/gallery-lazy-load.js
import axios from 'axios'; function Loader(options = {}) { this.page = options.page || 0; this.limit = options.limit || 1; this.url = options.url || ''; this.nextPage = () => { this.page += 1; return axios.get(this.url, { params: { page: this.page, limit: this.limit, }, responseType: 'text', }); }; } function observeLastPost(observer) { const posts = document.querySelectorAll('.gallery-post'); const lastPost = posts[posts.length - 1]; observer.observe(lastPost); return lastPost; } export default (options) => { let observer; const galleryContainer = document.querySelector('.gallery-posts'); const loader = new Loader({ url: '/api/gallery', page: 2, limit: 1, }); const handler = (entries) => { entries.forEach((entry) => { if (entry.isIntersecting) { observer.unobserve(entry.target); loader.nextPage() .then(({ data: postHtml }) => { galleryContainer.insertAdjacentHTML('beforeend', postHtml); const lastPost = observeLastPost(observer); if (options.afterInsert && typeof options.afterInsert === 'function') { options.afterInsert(lastPost); } }).catch(() => { // No more posts }); } }); }; observer = new IntersectionObserver(handler, { threshold: 0, }); observeLastPost(observer); }
import Loader from 'src/modules/lazy-loader'; let observer; let galleryContainer; const loader = new Loader({ url: '/api/gallery', page: 2, limit: 1, }); function lastPost() { const posts = document.querySelectorAll('.gallery-post'); return posts[posts.length - 1]; } function observeLastPost() { if (!observer) return false; observer.observe(lastPost()); return lastPost; } export default (options) => { galleryContainer = document.querySelector('.gallery-posts'); const next = () => { loader.nextPage() .then(({ data: html }) => { galleryContainer.insertAdjacentHTML('beforeend', html); if (observer) observeLastPost(); if (options.afterInsert && typeof options.afterInsert === 'function') { options.afterInsert(lastPost()); } }) .catch(() => { // No more posts }); } const observerHandler = (entries) => { entries.forEach((entry) => { if (entry.isIntersecting) { if (observer) observer.unobserve(entry.target); next(); } }); }; if (!('IntersectionObserver' in window)) { // Alternative routine document.body.classList.add('no-intersection-observer'); document .querySelector('button.compat-int-obs') .addEventListener('click', next); } else { // Modern browser observer = new IntersectionObserver(observerHandler, { threshold: 0, }); observeLastPost(); } }
Add old browser compat routine for loading pictures
Add old browser compat routine for loading pictures
JavaScript
mit
tuelsch/bolg,tuelsch/bolg
616cfb178b1af953a73e01febef0bc8aac6017f3
templates/footer.handlebars.js
templates/footer.handlebars.js
let tpl = ` </body> </html> `; exports.tpl = () => tpl;
let tpl = ` <hr /> <address>MirrorJson version 0.90. Idea, design and implementation by Arne Bakkebø, Making Waves in 2017.</address> </body> </html> `; exports.tpl = () => tpl;
Add footer info and version number
Add footer info and version number
JavaScript
mit
makingwaves/mirrorjson,makingwaves/mirrorjson
4f6b6937c7f67aa02898478e34506ed80c9e33a4
resources/public/js/monitor.js
resources/public/js/monitor.js
var maxColumns = 3 var buildStatusPadding = 10 var fontResizeFactor = 1.6 function buildStatusCount() { return $('li').size() } function numberOfColumns() { return Math.min(maxColumns, buildStatusCount()) } function numberOfRows() { return Math.ceil(buildStatusCount() / maxColumns) } function buildStatusWidth() { return window.innerWidth / numberOfColumns() - buildStatusPadding } function buildStatusHeight() { return window.innerHeight / numberOfRows() - buildStatusPadding } function scaleFontToContainerSize() { $(".outerContainer").fitText(fontResizeFactor) } function styleListItems() { $('.outerContainer').height(buildStatusHeight()).width(buildStatusWidth()) scaleFontToContainerSize() } function addBuildStatusToScreen(project) { var buildStatus = project.lastBuildStatus if(buildStatus !== "Success"){ $('#projects').append("<li><div class=outerContainer><div class=innerContainer>" + project.name + "</div></div></li>") } } function addListItems(data) { $('#projects').empty() data.body.forEach(addBuildStatusToScreen) } function updateBuildMonitor() { $.getJSON("/projects").then(function(data){ addListItems(data) styleListItems() }) } updateBuildMonitor() // run immediately setInterval(updateBuildMonitor, 5000)
function Styler() { this.maxColumns = 3 this.buildStatusPadding = 10 this.fontResizeFactor = 1.6 function buildStatusCount() { return $('li').size() } function numberOfColumns() { return Math.min(maxColumns, buildStatusCount()) } function numberOfRows() { return Math.ceil(buildStatusCount() / maxColumns) } function buildStatusWidth() { return window.innerWidth / numberOfColumns() - buildStatusPadding } function buildStatusHeight() { return window.innerHeight / numberOfRows() - buildStatusPadding } function scaleFontToContainerSize() { $(".outerContainer").fitText(fontResizeFactor) } this.styleListItems = function () { $('.outerContainer').height(buildStatusHeight()).width(buildStatusWidth()) scaleFontToContainerSize() } } function StatusAppender(projects) { this.projects = projects function addBuildStatusToScreen(project) { var buildStatus = project.lastBuildStatus if(buildStatus !== "Success"){ $('#projects').append("<li><div class=outerContainer><div class=innerContainer>" + project.name + "</div></div></li>") } } this.addListItems = function() { $('#projects').empty() projects.forEach(addBuildStatusToScreen) } } function updateBuildMonitor() { $.getJSON("/projects").then(function(data){ new StatusAppender(data.body).addListItems() new Styler().styleListItems() }) } updateBuildMonitor() // run immediately setInterval(updateBuildMonitor, 5000)
Introduce JS enclosing functions to separate Styling from DOM manipulation
Introduce JS enclosing functions to separate Styling from DOM manipulation
JavaScript
epl-1.0
antoniou/nevergreen-standalone,cburgmer/nevergreen,darrenhaken/nevergreen,darrenhaken/nevergreen,cburgmer/nevergreen,darrenhaken/nevergreen,antoniou/nevergreen-standalone,build-canaries/nevergreen,build-canaries/nevergreen,cburgmer/nevergreen,antoniou/nevergreen-standalone,build-canaries/nevergreen,build-canaries/nevergreen
4d3fd2b55084f8033cad20ee5e939b0bdbac25a5
blob-feature-check.js
blob-feature-check.js
var svg = new Blob( ["<svg xmlns='http://www.w3.org/2000/svg'></svg>"], {type: "image/svg+xml;charset=utf-8"} ); var img = new Image(); var featureDiv = document.getElementById("blob-urls"); img.onload = function() { featureDiv.className += " feature-supported"; }; img.onerror = function() { featureDiv.className += " feature-unsupported"; }; img.src = URL.createObjectURL(svg);
var svg = new Blob( ["<svg xmlns='http://www.w3.org/2000/svg'></svg>"], {type: "image/svg+xml;charset=utf-8"} ); var img = new Image(); var featureDiv = document.getElementById("blob-urls"); img.onload = function() { featureDiv.className += " feature-supported"; }; img.onerror = function() { featureDiv.className += " feature-unsupported"; }; // Safari 6 uses "webkitURL". var url = window.webkitURL || window.URL; img.src = url.createObjectURL(svg);
Use webkitURL for Safari 6
Use webkitURL for Safari 6 Other browsers use window.URL, but Safari 6 namespaced it to "webkit".
JavaScript
mit
ssorallen/blob-feature-check,ssorallen/blob-feature-check
8c03d3e088db12b410cdc6d7e301a05b6ebd8745
js/views/conversation_list_view.js
js/views/conversation_list_view.js
/* * vim: ts=4:sw=4:expandtab */ (function () { 'use strict'; window.Whisper = window.Whisper || {}; Whisper.ConversationListView = Whisper.ListView.extend({ tagName: 'div', itemView: Whisper.ConversationListItemView, sort: function(conversation) { console.log('sorting conversation', conversation.id); var $el = this.$('.' + conversation.cid); if ($el && $el.length > 0) { var index = getInboxCollection().indexOf(conversation); if (index > 0) { $el.insertBefore(this.$('.conversation-list-item')[index+1]); } else { this.$el.prepend($el); } } } }); })();
/* * vim: ts=4:sw=4:expandtab */ (function () { 'use strict'; window.Whisper = window.Whisper || {}; Whisper.ConversationListView = Whisper.ListView.extend({ tagName: 'div', itemView: Whisper.ConversationListItemView, sort: function(conversation) { console.log('sorting conversation', conversation.id); var $el = this.$('.' + conversation.cid); if ($el && $el.length > 0) { var index = getInboxCollection().indexOf(conversation); if (index === 0) { this.$el.prepend($el); } else if (index === this.collection.length - 1) { this.$el.append($el); } else { $el.insertBefore(this.$('.conversation-list-item')[index+1]); } } } }); })();
Fix sorting of the last element
Fix sorting of the last element // FREEBIE
JavaScript
agpl-3.0
nrizzio/Signal-Desktop,nrizzio/Signal-Desktop,nrizzio/Signal-Desktop,nrizzio/Signal-Desktop
589baa87b799e86d070c3c446e32c21e193b9c61
test/app.js
test/app.js
/** * @license * Copyright (c) 2016 The IBM Research Emergent Solutions authors. All rights reserved. * This code may only be used under the MIT style license found at https://ibmresearch.github.io/LICENSE.txt * The complete set of authors may be found at https://ibmresearch.github.io/AUTHORS.txt * The complete set of contributors may be found at https://ibmresearch.github.io/CONTRIBUTORS.txt */ 'use strict'; var path = require('path'); var assert = require('yeoman-assert'); var helpers = require('yeoman-test'); describe('generator-polymer-init-ibm-element:app', function() { before(function() { return helpers.run(path.join(__dirname, '../generators/app')) .withPrompts({ elementName: 'ibm-element', elementDescription: 'IBM element description', githubOrganization: 'IBMResearch' }) .toPromise(); }); it('creates files', function() { assert.file([ 'demo/index.html', 'test/ibm-element.html', 'test/index.html', '.gitignore', 'ibm-element.html', 'bower.json', 'index.html', 'LICENSE', 'README.md' ]); }); });
/** * @license * Copyright (c) 2016 The IBM Research Emergent Solutions authors. All rights reserved. * This code may only be used under the MIT style license found at https://ibmresearch.github.io/LICENSE.txt * The complete set of authors may be found at https://ibmresearch.github.io/AUTHORS.txt * The complete set of contributors may be found at https://ibmresearch.github.io/CONTRIBUTORS.txt */ 'use strict'; var path = require('path'); var assert = require('yeoman-assert'); var helpers = require('yeoman-test'); describe('generator-polymer-init-ibm-element:app', function() { before(function() { return helpers.run(path.join(__dirname, '../generators/app')) .withPrompts({ elementName: 'ibm-element', elementDescription: 'IBM element description', githubOrganization: 'IBMResearch' }) .toPromise(); }); it('creates files', function() { assert.file([ 'demo/index.html', 'test/ibm-element.html', 'test/index.html', '.gitignore', '.eslintrc.json', 'bower.json', 'ibm-element.html', 'index.html', 'LICENSE', 'README.md' ]); }); });
Add missed file to the test
Add missed file to the test
JavaScript
mit
IBMResearch/generator-polymer-init-ibm-element,IBMResearch/generator-polymer-init-ibm-element
681d637a01145bb623f035b9dec7a1fe5a1d7255
lib/matchers/hashmap.js
lib/matchers/hashmap.js
var _ = require('lodash'); var Matcher = require('../matcher'); var factory = require('../factory'); var compile = require('../compile'); var s = require('../strummer'); module.exports = factory({ initialize: function(opts) { var matchers = { keys: null, values: null }; if (opts instanceof Matcher) { matchers.values = opts; } else if (typeof opts === 'object') { matchers.keys = opts.keys ? compile.spec(opts.keys) : null; matchers.values = opts.values ? compile.spec(opts.values) : null; } else if (opts) { matchers.values = compile.spec(opts); } this.matchers = matchers; }, match: function(path, obj) { if (obj == null || typeof obj !== 'object') { return [{path: path, value: obj, message: 'should be a hashmap'}]; } var errors = []; if (this.matchers.keys) { var keyErrors = s.array({of: this.matchers.keys}).match(path + '.keys', Object.keys(obj)); errors.push(keyErrors); } if (this.matchers.values) { errors.push(_.map(obj, function(val, key) { return this.matchers.values.match(path + '[' + key + ']', val); }, this)); } return _.compact(_.flattenDeep(errors)); } });
var _ = require('lodash'); var Matcher = require('../matcher'); var factory = require('../factory'); var compile = require('../compile'); var s = require('../strummer'); module.exports = factory({ initialize: function(opts) { var matchers = { keys: null, values: null }; if (opts instanceof Matcher) { matchers.values = opts; } else if (typeof opts === 'object') { matchers.keys = opts.keys ? compile.spec(opts.keys) : null; matchers.values = opts.values ? compile.spec(opts.values) : null; } else if (opts) { matchers.values = compile.spec(opts); } this.matchers = matchers; }, match: function(path, obj) { if (obj == null || typeof obj !== 'object') { return [{path: path, value: obj, message: 'should be a hashmap'}]; } var errors = []; if (this.matchers.keys) { var keyErrors = s.array({of: this.matchers.keys}).match(path + '.keys', Object.keys(obj)); errors.push(keyErrors); } if (this.matchers.values) { var self = this; errors.push(_.map(obj, function(val, key) { return self.matchers.values.match(path + '[' + key + ']', val); })); } return _.compact(_.flattenDeep(errors)); } });
Fix error with lodash map
Fix error with lodash map
JavaScript
mit
TabDigital/strummer
aa5fe28d4a40438849c88ff067b072cb78ae7940
src/server/routes.js
src/server/routes.js
'use strict'; const router = require('express').Router(); const authRouter = require('./auth/authRouter'); const trackRouter = require('./track/trackRouter'); router.get('/', function(req, res) { res.send('Scrawble dat track j0!'); }); router.use('/auth', authRouter); router.use('/scrobbles', trackRouter); module.exports = router;
'use strict'; const router = require('express').Router(); const authRouter = require('./auth/authRouter'); const trackRouter = require('./track/trackRouter'); router.get('/', function(req, res) { res.send(`Your token is ${req.query.token}. Scrawble dat track j0!`); }); router.use('/auth', authRouter); router.use('/scrobbles', trackRouter); module.exports = router;
Send back token as part of response
Send back token as part of response
JavaScript
mit
FTLam11/Audio-Station-Scrobbler,FTLam11/Audio-Station-Scrobbler
49c6c49ad5934b45de95571a6ecb31223cda589a
run/index.js
run/index.js
var path = require('path') var command = process.argv[2] var restArguments = process.argv.slice(2) var root = path.join(__dirname, '..') var execute = require('./execute')({ BIN: path.join(root, 'node_modules', '.bin'), JS_INPUT: path.join(root, 'src', 'app.js'), JS_OUTPUT: path.join(root, 'dist', 'bundle.js') }) var formattedOutput = require('./formatted_output') function run(task) { formattedOutput.start({ taskname: task }) return execute(task) .then(formattedOutput.success) .catch(formattedOutput.fail) } var tasks = { js() { run('browserify') }, watch_js() { run('watchify') } } if (command in tasks) { tasks[command](restArguments) } else { console.error(`The task ${command} doesn't exist.`) process.exit(1) } module.exports = run
var path = require('path') var [ command, ...restArguments ] = process.argv.slice(2) var root = path.join(__dirname, '..') var execute = require('./execute')({ BIN: path.join(root, 'node_modules', '.bin'), JS_INPUT: path.join(root, 'src', 'app.js'), JS_OUTPUT: path.join(root, 'dist', 'bundle.js') }) var formattedOutput = require('./formatted_output') function run(task) { formattedOutput.start({ taskname: task }) return execute(task) .then(formattedOutput.success) .catch(formattedOutput.fail) } var tasks = { js() { run('browserify') }, watch_js() { run('watchify') } } if (command in tasks) { tasks[command](restArguments) } else { console.error(`The task ${command} doesn't exist.`) process.exit(1) } module.exports = run
Improve parsing of cli arguments
Improve parsing of cli arguments
JavaScript
mit
scriptype/salinger,scriptype/salinger
f8b68dae34c8f3308531bb2c28a3ff7047c0f4e1
tests/bind.spec.js
tests/bind.spec.js
import { Vue, firebase, firestore, VueTick, randomString } from './TestCase' let vm, collection, doc let collectionName = randomString() let documentName = randomString() describe('Manual binding', () => { beforeEach(async () => { collection = firestore.collection('items') doc = firestore.doc('collectionOfDocs/doc') vm = new Vue({ data: () => ({ // }) }) await VueTick() }) test('Bind collection manually', async () => { await vm.$binding(collectionName, firestore.collection(collectionName)) expect(vm[collectionName]).toEqual([]) await vm.$firestore[collectionName].add({name: 'item'}) expect(vm[collectionName].length).toEqual(1) expect(vm[collectionName][0].name).toEqual('item') }) test('Bind document manually', async () => { await vm.$binding(documentName, doc) expect(vm.$firestore[documentName]).toBe(doc) expect(vm[documentName]).toEqual({'.key': 'doc', 'name': 'docName'}) }) test('Binding collection returns promise', async () => { expect(vm.$binding('someCollections', collection) instanceof Promise).toBe(true) }) test('Binding document returns promise', async () => { expect(vm.$binding('someCollections', doc) instanceof Promise).toBe(true) }) })
import { Vue, firebase, firestore, VueTick, randomString } from './TestCase' let vm, collection, doc let collectionName = randomString() let documentName = randomString() describe('Manual binding', () => { beforeEach(async () => { collection = firestore.collection('items') doc = firestore.doc('collectionOfDocs/doc') vm = new Vue({ data: () => ({ // }) }) await VueTick() }) test('Bind collection manually', async () => { await vm.$binding(collectionName, firestore.collection(collectionName)) expect(vm[collectionName]).toEqual([]) await vm.$firestore[collectionName].add({name: 'item'}) expect(vm[collectionName].length).toEqual(1) expect(vm[collectionName][0].name).toEqual('item') let updatedItem = vm[collectionName][0] await vm.$firestore[collectionName].doc(updatedItem['.key']).update({name: 'item2'}) expect(vm[collectionName].length).toEqual(1) expect(vm[collectionName][0].name).toEqual('item2') }) test('Bind document manually', async () => { await vm.$binding(documentName, doc) expect(vm.$firestore[documentName]).toBe(doc) expect(vm[documentName]).toEqual({'.key': 'doc', 'name': 'docName'}) }) test('Binding collection returns promise', async () => { expect(vm.$binding('someCollections', collection) instanceof Promise).toBe(true) }) test('Binding document returns promise', async () => { expect(vm.$binding('someCollections', doc) instanceof Promise).toBe(true) }) })
Add tests for update doc in collection
Add tests for update doc in collection
JavaScript
mit
gdg-tangier/vue-firestore
49006a90b6ed3184f706a2688b3a51fa34de8d8f
routerpwn.js
routerpwn.js
var csv = require('./lib/csv.js'); //Object to hold all the data var vendors = {}; var init = function(callback) { csv.each(__dirname + '/macVendor/vendors.csv').on('data', function(data) { vendors[data[1]] = { 'prefix': data[1], 'manufacturer': data[2], 'manufacturerAdress': data[3] }; }).on('end', function() { console.log('Finished'); if(callback) { callback(vendors); } }); }; var getVendorForMac = function(macAddress) { for(var macPrefix in vendors) { if(macAddress.startsWith(macPrefix)) { return vendors[macPrefix]; } } }; var pwn = function(macAddress) { var vendor = getVendorForMac(macAddress); switch (vendor.manufacturer) { case 'Arcadyan Technology Corporation': return require(__dirname + '/exploits/easybox.js')(macAddress); break; } } module.exports = { init: init, getVendorForMac: getVendorForMac, pwn: pwn };
var csv = require('./lib/csv.js'); //Object to hold all the data var vendors = {}; var init = function(callback) { csv.each(__dirname + '/macVendor/vendors.csv').on('data', function(data) { vendors[data[1]] = { 'prefix': data[1], 'manufacturer': data[2], 'manufacturerAdress': data[3] }; }).on('end', function() { console.log('Finished'); if(callback) { callback(vendors); } }); }; var getVendorForMac = function(macAddress) { for(var macPrefix in vendors) { if(macAddress.startsWith(macPrefix)) { return vendors[macPrefix]; } } }; var pwn = function(macAddress) { var vendor = getVendorForMac(macAddress.replace(/:/g, '').replace(/-/g, '')); switch (vendor.manufacturer) { case 'Arcadyan Technology Corporation': return require(__dirname + '/exploits/easybox.js')(macAddress); break; } } module.exports = { init: init, getVendorForMac: getVendorForMac, pwn: pwn };
Replace ':' and '-' to check the MAC-prefix
Replace ':' and '-' to check the MAC-prefix
JavaScript
mit
jannickfahlbusch/node-routerpwn
3be1f95dcaafb09e8836979d79b02aeede891487
routes/index.js
routes/index.js
var express = require('express'); var router = express.Router(); /* GET home page. */ router.get('/', function(req, res, next) { res.render('index'); }); /* Mode selection page. */ router.get('/select', function(req, res, next) { res.render('select'); }); /* Page to start a new room with friends. */ router.get('/start-room', function(req, res, next) { res.render('start-room'); }); /* Page to join a room of friends. */ router.get('/join-room', function(req, res, next) { res.render('join-room'); }); /* Page to join a random room. */ router.get('/join-random', function(req, res, next) { res.render('join-random'); }); /* Gameplay page components. Should be called with AJAX. */ router.post('/game', function(req, res, next) { res.render('game', { playerId: req.body.playerId}); }); /* If people directly try to access /play, redirect them home. * This URL is displayed when playing the game. */ router.get('/play', function(req, res, next) { res.redirect('/'); }); module.exports = router;
var express = require('express'); var router = express.Router(); /* GET home page. */ router.get('/', function(req, res, next) { res.render('index'); }); /* Mode selection page. */ router.get('/select', function(req, res, next) { res.render('select'); }); /* Page to start a new room with friends. */ router.get('/start-room', function(req, res, next) { res.render('start-room'); }); /* Page to join a room of friends. */ router.get('/join-room', function(req, res, next) { res.render('join-room'); }); /* Page to join a random room. */ router.get('/join-random', function(req, res, next) { res.render('join-random'); }); /* Gameplay page components. Should be called with AJAX. */ router.post('/game', function(req, res, next) { res.render('game', { playerId: req.body.playerId}); }); /* If people directly try to access /play, redirect them home. * This URL is displayed when playing the game. */ router.get('/play', function(req, res, next) { res.redirect('/'); }); module.exports = router;
Fix indentation on routes page.
Fix indentation on routes page.
JavaScript
mit
nashkevin/Turing-Party,nashkevin/Turing-Party
5c110374d1c75c8892f074a9ea15dbb73744924e
.eslintrc.js
.eslintrc.js
module.exports = { env: { browser: true, es2021: true, }, extends: [ 'standard', ], parserOptions: { ecmaVersion: 12, sourceType: 'module', }, plugins: [ 'svelte3', ], overrides: [ { files: ['**/*.svelte'], processor: 'svelte3/svelte3', rules: { 'import/first': ['off', 'always'], 'no-multiple-empty-lines': ['error', { max: 1, maxBOF: 2, maxEOF: 0 }], }, }, ], rules: { indent: ['error', 4], } }
module.exports = { env: { browser: true, es2021: true, }, extends: [ 'standard', ], parserOptions: { ecmaVersion: 12, sourceType: 'module', }, plugins: [ 'svelte3', ], overrides: [ { files: ['**/*.svelte'], processor: 'svelte3/svelte3', rules: { 'import/first': ['off', 'always'], 'no-multiple-empty-lines': ['error', { max: 1, maxBOF: 2, maxEOF: 0 }], }, }, ], rules: { 'comma-dangle': ['off', 'always'], 'indent': ['error', 4], 'no-console': ['warn', {}], } }
Allow dangling commas and warn about console statements
eslint: Allow dangling commas and warn about console statements
JavaScript
mit
peterhil/ninhursag,peterhil/ninhursag,peterhil/ninhursag,peterhil/ninhursag
da6a95170c50d33180da30775d460ce160f2101b
app/assets/javascripts/views/dashboard_report_view.js
app/assets/javascripts/views/dashboard_report_view.js
// ELMO.Views.DashboardReport // // View model for the dashboard report ELMO.Views.DashboardReportView = class DashboardReportView extends ELMO.Views.ApplicationView { get el() { return '.report'; } get events() { return { 'change .report-chooser': 'handleReportChange', 'click .action-link-close': 'handleReportClose', }; } handleReportChange(e) { const id = $(e.target).val(); if (id) { this.changeReport(id, $(e.target).find('option:selected').text()); } } handleReportClose(e) { e.preventDefault(); this.changeReport(null, I18n.t('activerecord.models.report/report.one')); } changeReport(id, name) { this.toggleLoader(true); this.$('.report-title-text').html(name); this.$('.report-chooser').find('option').attr('selected', false); this.$('.report-output-and-modal').empty(); this.$('.action-link').hide(); this.$el.load(ELMO.app.url_builder.build(`dashboard/report?id=${id || ''}`)); } toggleLoader(bool) { $('.report-pane-header .inline-load-ind img').toggle(bool); } };
// ELMO.Views.DashboardReport // // View model for the dashboard report ELMO.Views.DashboardReportView = class DashboardReportView extends ELMO.Views.ApplicationView { get el() { return '.report'; } get events() { return { 'change .report-chooser': 'handleReportChange', 'click .action-link-close': 'handleReportClose', }; } handleReportChange(e) { const id = $(e.target).val(); if (id) { this.changeReport(id, $(e.target).find('option:selected').text()); } } handleReportClose(e) { e.preventDefault(); this.changeReport(null, I18n.t('activerecord.models.report/report.one')); } changeReport(id, name) { if (this.request) { this.request.abort(); } this.toggleLoader(true); this.$('.report-title-text').html(name); this.$('.report-chooser').find('option').attr('selected', false); this.$('.report-output-and-modal').empty(); this.$('.action-link').hide(); const url = ELMO.app.url_builder.build(`dashboard/report?id=${id || ''}`); this.request = $.get(url, this.handleReportLoaded.bind(this)); } handleReportLoaded(html) { this.request = null; this.$el.html(html); } toggleLoader(bool) { $('.report-pane-header .inline-load-ind img').toggle(bool); } };
Abort running request if new one fired
11239: Abort running request if new one fired
JavaScript
apache-2.0
thecartercenter/elmo,thecartercenter/elmo,thecartercenter/elmo
d88889401bf3f1532ee55eb3cf3f157fb4a47719
BikeMates/BikeMates.Web/Scripts/App_Scripts/ProfileScript.js
BikeMates/BikeMates.Web/Scripts/App_Scripts/ProfileScript.js
$(document).ready(function () { function AppViewModel() { var self = this; self.FirstName = ko.observable(""); self.SecondName = ko.observable(""); self.About = ko.observable(""); self.Picture = ko.observable(""); self.fullName = ko.computed(function () { return self.FirstName() + " " + self.SecondName(); }, this); $.ajax({ url: "http://localhost:51952/api/profile", contentType: "application/json", type: "GET", header:{"Authorization" : "Bearer "+ sessionStorage.getItem(tokenKey) }, success: function (data) { self.FirstName(data.firstName); self.SecondName(data.secondName); self.About(data.about); self.Picture(data.picture); }, error: function (data) { alert("error occured"); } }); } // Activates knockout.js // bind view model to referring view ko.applyBindings(new AppViewModel()); });
$(document).ready(function () { var tokenKey = sessionStorage.getItem() function AppViewModel() { var self = this; self.FirstName = ko.observable(""); self.SecondName = ko.observable(""); self.About = ko.observable(""); self.Picture = ko.observable(""); self.fullName = ko.computed(function () { return self.FirstName() + " " + self.SecondName(); }, this); $.ajax({ url: "api/profile", contentType: "application/json", type: "GET", header: {"Authorization " : " Bearer " + sessionStorage.getItem(tokenKey) }, // + sessionStorage.getItem(tokenKey) success: function (data) { self.FirstName(data.firstName); self.SecondName(data.secondName); self.About(data.about); self.Picture(data.picture); }, error: function (data) { alert("error occured"); } }); } // Activates knockout.js // bind view model to referring view ko.applyBindings(new AppViewModel()); });
Create BLL for profile - edit js files
Create BLL for profile - edit js files
JavaScript
mit
BikeMates/bike-mates,BikeMates/bike-mates,BikeMates/bike-mates
bdeeb9cc823025cfed65340caeb69ae6cde91e22
server/index.js
server/index.js
var gpio = require('pi-gpio'); gpio.open(7, "in"); setInterval(function () { gpio.read(7, function (err, value) { if(err) { console.log(err); } else { console.log(value); } }); }, 5000); process.on('SIGINT', function() { console.log('Shutting down GPIO'); gpio.close(7); });
var gpio = require('pi-gpio'); gpio.open(7, "in"); setInterval(function () { gpio.read(7, function (err, value) { if(err) { console.log(err); } else { console.log(value); } }); }, 5000); process.on('SIGINT', function() { console.log('Shutting down GPIO'); gpio.close(7); process.exit(); });
Add missing process exit call
Add missing process exit call
JavaScript
mit
Sephizor/openboiler,Sephizor/openboiler,Sephizor/openboiler
f696511e83678c4fcc7fd78b8590ef859c61f8ac
src/js/_fontawesome-collection.js
src/js/_fontawesome-collection.js
import fontawesome from '@fortawesome/fontawesome' import faCustomIcons from './_fontawesome-harrix-icons.js' //import fontawesomeFreeRegular from '@fortawesome/fontawesome-free-regular' import faSearch from '@fortawesome/fontawesome-free-solid/faSearch' import faGithub from '@fortawesome/fontawesome-free-brands/faGithub' fontawesome.library.add(faSearch); fontawesome.library.add(faGithub);
import fontawesome from '@fortawesome/fontawesome' import faCustomIcons from './_fontawesome-harrix-icons.js' import faSearch from '@fortawesome/fontawesome-free-solid/faSearch' import faGithub from '@fortawesome/fontawesome-free-brands/faGithub' fontawesome.library.add(faSearch); fontawesome.library.add(faGithub);
Delete unnecessary lines in the code
Delete unnecessary lines in the code
JavaScript
mit
Harrix/Harrix-Html-Template
db872fe4b98311d5ee3e459268e9d2ec133871b5
tasks/check_clean.js
tasks/check_clean.js
/* * grunt-check-clean * https://github.com/the-software-factory/grunt-check-clean * * Copyright (c) 2015 Stéphane Bisinger * Licensed under the MIT license. */ 'use strict'; module.exports = function(grunt) { // Please see the Grunt documentation for more information regarding task // creation: http://gruntjs.com/creating-tasks grunt.registerTask('check_clean', 'Ensure the git index is clean and that there are no untracked files or directories.', function() { var done = this.async(); grunt.util.spawn({ cmd: 'git', args: ['status', '--porcelain'] }, function(error, result) { var ret = 0; if (error !== 0 || result.stdout.length > 0) { ret = new Error("The git index is not clean. Ensure there are no uncommitted changes or untracked files."); } done(ret); }); }); };
/* * grunt-check-clean * https://github.com/the-software-factory/grunt-check-clean * * Copyright (c) 2015 Stéphane Bisinger * Licensed under the MIT license. */ 'use strict'; module.exports = function(grunt) { // Please see the Grunt documentation for more information regarding task // creation: http://gruntjs.com/creating-tasks grunt.registerTask('check_clean', 'Ensure the git index is clean and that there are no untracked files or directories.', function() { var done = this.async(); grunt.util.spawn({ cmd: 'git', args: ['status', '--porcelain'] }, function(error, result) { var ret = 0; if (error || result.stdout.length > 0) { console.log(error); console.log(result.stdout); ret = new Error("The git index is not clean. Ensure there are no uncommitted changes or untracked files."); } done(ret); }); }); };
Fix check on error messages.
Fix check on error messages.
JavaScript
mit
the-software-factory/grunt-check-clean
6306c7760de7e15a3e32143e19c0662d554d2091
test/ios/findProject.spec.js
test/ios/findProject.spec.js
jest.autoMockOff(); const findProject = require('../../src/config/ios/findProject'); const mockFs = require('mock-fs'); const projects = require('../fixtures/projects'); describe('ios::findProject', () => { beforeEach(() => { mockFs({ testDir: projects }); }); it('should return path to xcodeproj if found', () => { const userConfig = {}; mockFs(projects.flat); expect(findProject('')).toContain('.xcodeproj'); }); it('should ignore xcodeproj from example folders', () => { const userConfig = {}; mockFs({ examples: projects.flat, Examples: projects.flat, example: projects.flat, KeychainExample: projects.flat, Zpp: projects.flat, }); expect(findProject('').toLowerCase()).not.toContain('example'); }); it('should ignore xcodeproj from test folders at any level', () => { const userConfig = {}; mockFs({ test: projects.flat, IntegrationTests: projects.flat, tests: projects.flat, Zpp: { tests: projects.flat, src: projects.flat, }, }); expect(findProject('').toLowerCase()).not.toContain('test'); }); afterEach(mockFs.restore); });
jest.autoMockOff(); const findProject = require('../../src/config/ios/findProject'); const mockFs = require('mock-fs'); const projects = require('../fixtures/projects'); const userConfig = {}; describe('ios::findProject', () => { beforeEach(() => { mockFs({ testDir: projects }); }); it('should return path to xcodeproj if found', () => { mockFs(projects.flat); expect(findProject('')).toContain('.xcodeproj'); }); it('should return null if there\'re no projects', () => { expect(findProject('')).toBe(null); }); it('should ignore xcodeproj from example folders', () => { mockFs({ examples: projects.flat, Examples: projects.flat, example: projects.flat, KeychainExample: projects.flat, Zpp: projects.flat, }); expect(findProject('').toLowerCase()).not.toContain('example'); }); it('should ignore xcodeproj from test folders at any level', () => { mockFs({ test: projects.flat, IntegrationTests: projects.flat, tests: projects.flat, Zpp: { tests: projects.flat, src: projects.flat, }, }); expect(findProject('').toLowerCase()).not.toContain('test'); }); afterEach(mockFs.restore); });
Cover null case in ios/findProject
Cover null case in ios/findProject
JavaScript
mit
rnpm/rnpm
82c8799e9ae313c00e042d9943855bea9ee3e5c2
src/index.js
src/index.js
try { require('external:electron-react-devtools').install(); } catch (e) {} import React from 'react'; import ReactDOM from 'react-dom'; import RecorderUI from './ui/RecorderUI'; ReactDOM.render( <div> <RecorderUI /> </div>, document.querySelector('main') );
if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === 'undefined') { try { require('external:electron-react-devtools').install(); } catch (e) { console.error(e); } } import React from 'react'; import ReactDOM from 'react-dom'; import RecorderUI from './ui/RecorderUI'; ReactDOM.render( <div> <RecorderUI /> </div>, document.querySelector('main') );
Fix for noisy console warning
Fix for noisy console warning
JavaScript
mit
mattbasta/pinecast-studio,mattbasta/pinecast-studio
117753105085c46615ff9de6ed273df200abb8fa
src/index.js
src/index.js
import fetch from 'isomorphic-fetch' export default function fetchDispatch(url, action) { return (dispatch) => { return fetch(url, { credentials: 'include' }) .then( (response) => { return response.json() }) .then( (json) => { dispatch(action(json)) }) .catch( (error) => { console.log(error) }) } }
import fetch from 'isomorphic-fetch' export default function fetchDispatch(url, options = {}, actions = {}) { return (dispatch) => { if (typeof actions.request === 'function') { actions.request() } return fetch(url, options) .then( (response) => { return response.json() }) .then( (json) => { if (typeof actions.success === 'function') { dispatch(action(json)) } return json }) .catch( (err) => { if (typeof actions.fail === 'function') { dispatch(actions.fail(err)) } }) } }
Add options and actions to fetchDispatch
Add options and actions to fetchDispatch
JavaScript
mit
KaleoSoftware/redux-fetch-dispatch
90af5bbbf68e061030a8b671978d7999f9088c4c
src/Index.js
src/Index.js
module.exports = { BarChart: require('./components/BarChart'), Button: require('./components/Button'), ButtonGroup: require('./components/ButtonGroup'), Calendar: require('./components/Calendar'), Column: require('./components/grid/Column'), DatePicker: require('./components/DatePicker'), DatePickerFullScreen: require('./components/DatePickerFullScreen'), DateRangePicker: require('./components/DateRangePicker'), DateTimePicker: require('./components/DateTimePicker'), DisplayInput: require('./components/DisplayInput'), DonutChart: require('./components/DonutChart'), Drawer: require('./components/Drawer'), FileUpload: require('./components/FileUpload'), Icon: require('./components/Icon'), Loader: require('./components/Loader'), Modal: require('./components/Modal'), PageIndicator: require('./components/PageIndicator'), ProgressBar: require('./components/ProgressBar'), RadioButton: require('./components/RadioButton'), RajaIcon: require('./components/RajaIcon'), Row: require('./components/grid/Row'), RangeSelector: require('./components/RangeSelector'), SearchInput: require('./components/SearchInput'), Select: require('./components/Select'), SelectFullScreen: require('./components/SelectFullScreen'), SimpleInput: require('./components/SimpleInput'), SimpleSelect: require('./components/SimpleSelect'), Spin: require('./components/Spin'), TimeBasedLineChart: require('./components/TimeBasedLineChart'), ToggleSwitch: require('./components/ToggleSwitch'), Tooltip: require('./components/Tooltip'), TypeAhead: require('./components/TypeAhead'), AppConstants: require('./constants/App'), Styles: require('./constants/Style') };
module.exports = { BarChart: require('./components/BarChart'), Button: require('./components/Button'), ButtonGroup: require('./components/ButtonGroup'), Calendar: require('./components/Calendar'), Column: require('./components/grid/Column'), DatePicker: require('./components/DatePicker'), DatePickerFullScreen: require('./components/DatePickerFullScreen'), DateRangePicker: require('./components/DateRangePicker'), DateTimePicker: require('./components/DateTimePicker'), DisplayInput: require('./components/DisplayInput'), DonutChart: require('./components/DonutChart'), Drawer: require('./components/Drawer'), FileUpload: require('./components/FileUpload'), Gauge: require('./components/Gauge'), Icon: require('./components/Icon'), Loader: require('./components/Loader'), Modal: require('./components/Modal'), PageIndicator: require('./components/PageIndicator'), ProgressBar: require('./components/ProgressBar'), RadioButton: require('./components/RadioButton'), RajaIcon: require('./components/RajaIcon'), Row: require('./components/grid/Row'), RangeSelector: require('./components/RangeSelector'), SearchInput: require('./components/SearchInput'), Select: require('./components/Select'), SelectFullScreen: require('./components/SelectFullScreen'), SimpleInput: require('./components/SimpleInput'), SimpleSelect: require('./components/SimpleSelect'), Spin: require('./components/Spin'), TimeBasedLineChart: require('./components/TimeBasedLineChart'), ToggleSwitch: require('./components/ToggleSwitch'), Tooltip: require('./components/Tooltip'), TypeAhead: require('./components/TypeAhead'), AppConstants: require('./constants/App'), Styles: require('./constants/Style') };
Add Gauge component to src/index
Add Gauge component to src/index
JavaScript
mit
mxenabled/mx-react-components,derek-boman/mx-react-components
56c7c34c64b3fac897c02e583562f2472319dadb
src/matchNode.js
src/matchNode.js
/* * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var hasOwn = Object.prototype.hasOwnProperty.call.bind(Object.prototype.hasOwnProperty); /** * Checks whether needle is a strict subset of haystack. * * @param {Object} haystack The object to test * @param {Object} needle The properties to look for in test * @return {bool} */ function matchNode(haystack, needle) { var props = Object.keys(needle); return props.every(function(prop) { if (!hasOwn(haystack, prop)) { return false; } if (haystack[prop] && typeof haystack[prop] === 'object' && typeof needle[prop] === 'object') { return matchNode(haystack[prop], needle[prop]); } return haystack[prop] === needle[prop]; }); } module.exports = matchNode;
/* * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var hasOwn = Object.prototype.hasOwnProperty.call.bind(Object.prototype.hasOwnProperty); /** * Checks whether needle is a strict subset of haystack. * * @param {Object} haystack The object to test * @param {Object|Function} needle The properties to look for in test * @return {bool} */ function matchNode(haystack, needle) { if (typeof needle === 'function') { return needle(haystack); } var props = Object.keys(needle); return props.every(function(prop) { if (!hasOwn(haystack, prop)) { return false; } if (haystack[prop] && typeof haystack[prop] === 'object' && typeof needle[prop] === 'object') { return matchNode(haystack[prop], needle[prop]); } return haystack[prop] === needle[prop]; }); } module.exports = matchNode;
Allow matching nodes with a function
Allow matching nodes with a function
JavaScript
mit
fkling/jscodeshift,facebook/jscodeshift
49f59fea35e8753ebeca12b88ab2cf5d54bc8cfc
test/helpers/auth.js
test/helpers/auth.js
module.exports.getUser = function(name) { return { username: name, password: name, }; }; module.exports.login = function(user) { browser.driver.manage().window().setSize(1600, 900); browser.get('/#/login/'); element(by.css('div.login-form a[data-role="switch-login-form"]')).click(); element(by.model('auth.user.username')).sendKeys(user.username); element(by.model('auth.user.password')).sendKeys(user.password); element(by.css('div.inputs-box input[type=submit]')).click(); }; module.exports.logout = function(user) { browser.get('/#/dashboard/'); element(by.css('ul.nav-list.context > li:nth-child(3) > a')).click(); element(by.cssContainingText('ul.nav-list.context > li:nth-child(3) > ul > li > a', 'Logout')).click(); };
module.exports.getUser = function(name) { return { username: name, password: name, }; }; module.exports.login = function(user) { browser.driver.manage().window().setSize(1600, 900); browser.get('/#/login/'); element(by.model('auth.user.username')).sendKeys(user.username); element(by.model('auth.user.password')).sendKeys(user.password); element(by.css('.button-login')).click(); }; module.exports.logout = function(user) { browser.get('/#/dashboard/'); element(by.css('ul.nav-list.context > li:nth-child(3) > a')).click(); element(by.cssContainingText('ul.nav-list.context > li:nth-child(3) > ul > li > a', 'Logout')).click(); };
Fix test after changed of login page (SAAS-256)
Fix test after changed of login page (SAAS-256) Upgrated css paths in auth helper.
JavaScript
mit
opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport
cffe6c5880fec9e421bd2d9cc654ae91b1536d16
src/outro.js
src/outro.js
// get at whatever the global object is, like window in browsers }( (function() {return this;}.call()) ));
// Get a reference to the global object, like window in browsers }( (function() { return this; }.call()) ));
Fix formatting and improve the comment
Outro: Fix formatting and improve the comment
JavaScript
mit
qunitjs/qunit,qunitjs/qunit,danielgindi/qunit
c3d816f009b81291a93d3d3c8d976c37e537d67a
test/writeNewHtml.js
test/writeNewHtml.js
var assert = require('assert') var fs = require('fs') var writeNewHtml = require('./../writeNewHtml') describe('writeNewHtml', () => { it('should write html file to wf/',done => { var html = `<!DOCTYPE> <html> <body> <script class="923ad49f0ca1962716d34bd60433de8a207570f7"></script> </body> </html>` fs.mkdir(__dirname + '/wf', err => { writeNewHtml(html, 'test/wf/index'); setTimeout(() => { var wroteHtml = fs.statSync(__dirname + '/wt/index.html').isFile() fs.unlink(__dirname + '/wf/index.html', err => { console.log('unlinking...') fs.rmdir(__dirname + '/wf', err => { assert.equal(true, wroteHtml) done() }) }) }, 1500) }) }) })
var assert = require('assert') var fs = require('fs') var writeNewHtml = require('./../writeNewHtml') describe('writeNewHtml', () => { it('should write html file to wf/',done => { var html = `<!DOCTYPE> <html> <body> <script class="923ad49f0ca1962716d34bd60433de8a207570f7"></script> </body> </html>` fs.mkdir(__dirname + '/wf', err => { writeNewHtml(html, 'test/wf/index'); var wroteHtml = fs.statSync(__dirname + '/wf/index.html').isFile() fs.unlink(__dirname + '/wf/index.html', err => { fs.rmdir(__dirname + '/wf', err => { assert.equal(true, wroteHtml) done() }) }) }) }) })
Test for write new html
Test for write new html
JavaScript
mit
CarolAG/WebFlight,coryc5/WebFlight
cf2487ba7929bf33695a16aebdc98f5e0ee412d0
src/pages/App.js
src/pages/App.js
import React, { Component, PropTypes } from 'react' import { Link } from 'react-router' import 'normalize.css/normalize.css' import '../styles/defaults.scss' import classNames from './App.scss' import { trackTiming } from '../analytics' import { APP_NAME, AUTHOR_URL, SOURCE_URL, SEPARATOR } from '../config' export default class App extends Component { static propTypes = { children: PropTypes.node }; componentDidMount () { if (window.performance) { trackTiming('react', 'firstrender', Math.round(window.performance.now())) } } render () { return ( <div className={classNames.app}> <header className={classNames.header}> <h1 className={classNames.title}> <Link to='/'> {APP_NAME} </Link> </h1> {SEPARATOR} <a href={SOURCE_URL} target='_blank'>Source</a> {SEPARATOR} by <a href={AUTHOR_URL} target='_blank'>CookPete</a> </header> { this.props.children } </div> ) } }
import React, { Component, PropTypes } from 'react' import { Link } from 'react-router' import 'normalize.css/normalize.css' import '../styles/defaults.scss' import classNames from './App.scss' import { trackTiming } from '../analytics' import { APP_NAME, AUTHOR_URL, SOURCE_URL, SEPARATOR } from '../config' export default class App extends Component { static propTypes = { children: PropTypes.node }; componentDidMount () { if (window.performance) { trackTiming('react', 'firstrender', Math.round(window.performance.now())) } } render () { return ( <div className={classNames.app}> <header className={classNames.header}> <h1 className={classNames.title}> <Link to='/'> {APP_NAME} </Link> </h1> {SEPARATOR} by <a href={AUTHOR_URL} target='_blank'>CookPete</a> {SEPARATOR} <a href={SOURCE_URL} target='_blank'>Source</a> </header> { this.props.children } </div> ) } }
Reorder source and author links
Reorder source and author links
JavaScript
cc0-1.0
CookPete/reddit-player,CookPete/rplayr,CookPete/rplayr,CookPete/reddit-player
d24f4d335470d664a019763e9f3780f339120de2
packages/example-usecase/webpack.config.js
packages/example-usecase/webpack.config.js
const path = require('path') const webpack = require('webpack') module.exports = { entry: './src/index.js', output: { filename: './bundle.js', path: path.resolve('public') }, module: { rules: [ { test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader' } ] }, plugins: [ new webpack.DefinePlugin({ 'process.env': { 'NODE_ENV': JSON.stringify('production') } }), new webpack.IgnorePlugin(/(languageData|compile).*\.dev$/) ], devServer: { hot: true, inline: true, contentBase: path.resolve('public') } }
const path = require('path') const webpack = require('webpack') module.exports = { entry: './src/index.js', output: { filename: './bundle.js', path: path.resolve('public') }, module: { rules: [ { test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader' } ] }, plugins: [ new webpack.DefinePlugin({ 'process.env': { 'NODE_ENV': JSON.stringify('production') } }), new webpack.optimize.UglifyJsPlugin(), new webpack.IgnorePlugin(/\.dev$/, /lingui-i18n/) ], devServer: { hot: true, inline: true, contentBase: path.resolve('public') } }
Remove dev code in production
feat(example): Remove dev code in production
JavaScript
mit
lingui/js-lingui,lingui/js-lingui
007c357d7f3fe9a8e14e495fab5f166ac4c9b84a
packages/vega-scenegraph/src/Scenegraph.js
packages/vega-scenegraph/src/Scenegraph.js
import Bounds from './Bounds'; import GroupItem from './GroupItem'; export default function Scenegraph() { this.root = createMark({ marktype: 'group', interactive: false }); this.root.items = [new GroupItem(this.root)]; } var prototype = Scenegraph.prototype; prototype.select = function(path, markdef) { var items = this.root.items[0], node, i, n; for (i=0, n=path.length-1; i<n; ++i) { items = items.items[path[i]]; if (!items) error('Invalid scenegraph path: ' + path); } items = items.items; if (!(node = items[path[n]])) { if (markdef) items[path[n]] = node = createMark(markdef); else error('Invalid scenegraph path: ' + path); } return node; }; function error(msg) { throw Error(msg); } function createMark(def) { return { bounds: new Bounds(), clip: !!def.clip, interactive: def.interactive === false ? false : true, items: [], marktype: def.marktype, name: def.name || undefined, role: def.role || undefined }; }
import Bounds from './Bounds'; import GroupItem from './GroupItem'; export default function Scenegraph() { this.root = createMark({ marktype: 'group', interactive: false }); this.root.items = [new GroupItem(this.root)]; } var prototype = Scenegraph.prototype; prototype.select = function(path, markdef) { var group = this.root.items[0], mark = group.items[path[0]], i, n; try { for (i=1, n=path.length-1; i<n; ++i) { group = mark.items[path[i++]]; mark = group.items[path[i]]; } if (!mark && !markdef) throw n; if (markdef) { mark = createMark(markdef, group); group.items[path[n]] = mark; } return mark; } catch (err) { error('Invalid scenegraph path: ' + path); } }; function error(msg) { throw Error(msg); } function createMark(def, group) { return { bounds: new Bounds(), clip: !!def.clip, group: group, interactive: def.interactive === false ? false : true, items: [], marktype: def.marktype, name: def.name || undefined, role: def.role || undefined }; }
Add group reference to new mark instances.
Add group reference to new mark instances.
JavaScript
bsd-3-clause
vega/vega,vega/vega,vega/vega,lgrammel/vega,vega/vega
14d6537cd2000ae28320366934d769846f3610cf
src/index.js
src/index.js
import React, { Component, PropTypes } from 'react' import ReactDOM from 'react-dom' import ReactDOMServer from 'react-dom/server' import SVGInjector from 'svg-injector' export default class ReactSVG extends Component { static defaultProps = { callback: () => {}, className: '', evalScripts: 'once', style: {} } static propTypes = { callback: PropTypes.func, className: PropTypes.string, evalScripts: PropTypes.oneOf([ 'always', 'once', 'never' ]), path: PropTypes.string.isRequired, style: PropTypes.object } renderSVG(props = this.props) { const { callback: each, className, evalScripts, path, style } = props this.container = this.container || ReactDOM.findDOMNode(this) const div = document.createElement('div') div.innerHTML = ReactDOMServer.renderToStaticMarkup( <img className={className} data-src={path} style={style} /> ) const img = this.container.appendChild(div.firstChild) SVGInjector(img, { evalScripts, each }) } removeSVG() { this.container.removeChild(this.container.firstChild) } componentDidMount() { this.renderSVG() } componentWillReceiveProps(nextProps) { this.removeSVG() this.renderSVG(nextProps) } shouldComponentUpdate() { return false } componentWillUnmount() { this.removeSVG() } render() { return <div /> } }
import React, { Component, PropTypes } from 'react' import ReactDOMServer from 'react-dom/server' import SVGInjector from 'svg-injector' export default class ReactSVG extends Component { static defaultProps = { callback: () => {}, className: '', evalScripts: 'once', style: {} } static propTypes = { callback: PropTypes.func, className: PropTypes.string, evalScripts: PropTypes.oneOf([ 'always', 'once', 'never' ]), path: PropTypes.string.isRequired, style: PropTypes.object } refCallback = (container) => { if (!container) { this.removeSVG() return } this.container = container this.renderSVG() } renderSVG(props = this.props) { const { callback: each, className, evalScripts, path, style } = props const div = document.createElement('div') div.innerHTML = ReactDOMServer.renderToStaticMarkup( <img className={className} data-src={path} style={style} /> ) const img = this.container.appendChild(div.firstChild) SVGInjector(img, { evalScripts, each }) } removeSVG() { this.container.removeChild(this.container.firstChild) } componentWillReceiveProps(nextProps) { this.removeSVG() this.renderSVG(nextProps) } shouldComponentUpdate() { return false } render() { return <div ref={this.refCallback} /> } }
Handle mounting and unmounting via ref callback
Handle mounting and unmounting via ref callback
JavaScript
mit
atomic-app/react-svg
decd9e03343b62f2de598bbdb2a51794b71176f0
src/index.js
src/index.js
import fs from 'fs' import _ from 'lodash' import postcss from 'postcss' import stylefmt from 'stylefmt' import defaultConfig from './defaultConfig' import mergeConfig from './util/mergeConfig' import generateUtilities from './lib/generateUtilities' import substituteHoverableAtRules from './lib/substituteHoverableAtRules' import substituteResponsiveAtRules from './lib/substituteResponsiveAtRules' import substituteBreakpointAtRules from './lib/substituteBreakpointAtRules' import substituteClassApplyAtRules from './lib/substituteClassApplyAtRules' const plugin = postcss.plugin('tailwind', (options = {}) => { if (_.isFunction(options)) { options = options() } const config = mergeConfig(defaultConfig, options) return postcss([ generateUtilities(config), substituteHoverableAtRules(config), substituteResponsiveAtRules(config), substituteBreakpointAtRules(config), substituteClassApplyAtRules(config), stylefmt, ]) }) module.exports = plugin
import fs from 'fs' import _ from 'lodash' import postcss from 'postcss' import stylefmt from 'stylefmt' import defaultConfig from './defaultConfig' import mergeConfig from './util/mergeConfig' import generateUtilities from './lib/generateUtilities' import substituteHoverableAtRules from './lib/substituteHoverableAtRules' import substituteResponsiveAtRules from './lib/substituteResponsiveAtRules' import substituteBreakpointAtRules from './lib/substituteBreakpointAtRules' import substituteClassApplyAtRules from './lib/substituteClassApplyAtRules' const plugin = postcss.plugin('tailwind', (options = {}) => { const config = mergeConfig(defaultConfig, options) return postcss([ generateUtilities(config), substituteHoverableAtRules(config), substituteResponsiveAtRules(config), substituteBreakpointAtRules(config), substituteClassApplyAtRules(config), stylefmt, ]) }) module.exports = plugin
Revert "Allow passing config as lazy-evaluated function"
Revert "Allow passing config as lazy-evaluated function" This reverts commit 1819cf67d3f24ebe055b4c54b4e037a6621b3734.
JavaScript
mit
tailwindcss/tailwindcss,tailwindlabs/tailwindcss,tailwindlabs/tailwindcss,tailwindlabs/tailwindcss
e3038c549a27d65ace8e4dcf69ba18cddd70ccc3
src/index.js
src/index.js
'use strict'; import 'source-map-support/register'; import http from 'http'; import express from 'express'; import RED from 'node-red'; // Create an Express app let app = express(); // Create a server let server = http.createServer(app); // Create the settings object - see default settings.js file for other options let settings = { verbose: true, disableEditor: false, httpAdminRoot: '/red', httpNodeRoot: '/api', userDir: (process.env.HOME || process.env.USERPROFILE) + '/.node-red', functionGlobalContext: { } // enables global context }; // Initialise the runtime with a server and settings RED.init(server, settings); // Add a simple route for static content served from 'public' app.use('/', express.static('public')); if (settings.httpAdminRoot) { app.get('/', (_, res) => { res.redirect(settings.httpAdminRoot); }); } // Serve the editor UI from /red app.use(settings.httpAdminRoot, RED.httpAdmin); // Serve the http nodes UI from /api app.use(settings.httpNodeRoot, RED.httpNode); server.listen(8000); // Start the runtime RED.start();
'use strict'; import 'source-map-support/register'; import http from 'http'; import express from 'express'; import RED from 'node-red'; // Exit handler process.stdin.resume(); function exitHandler(err) { if (err instanceof Error) { console.log(err.stack); process.exit(1); } else if (isNaN(err)) { process.exit(); } else { process.exit(err); } } process.on('exit', exitHandler); process.on('SIGINT', exitHandler); process.on('uncaughtException', exitHandler); // Create an Express app let app = express(); // Create a server let server = http.createServer(app); // Create the settings object - see default settings.js file for other options let settings = { verbose: true, disableEditor: false, httpAdminRoot: '/red', httpNodeRoot: '/api', userDir: (process.env.HOME || process.env.USERPROFILE) + '/.node-red', functionGlobalContext: { } // enables global context }; // Initialise the runtime with a server and settings RED.init(server, settings); // Add a simple route for static content served from 'public' app.use('/', express.static('public')); if (settings.httpAdminRoot) { app.get('/', (_, res) => { res.redirect(settings.httpAdminRoot); }); } // Serve the editor UI from /red app.use(settings.httpAdminRoot, RED.httpAdmin); // Serve the http nodes UI from /api app.use(settings.httpNodeRoot, RED.httpNode); server.listen(8000); // Start the runtime RED.start();
Add the process exit handler to perform finalization process
Add the process exit handler to perform finalization process
JavaScript
unknown
dbaba/candy-red,dbaba/candy-red,CANDY-LINE/candy-red,dbaba/candy-red,CANDY-LINE/candy-red,CANDY-LINE/candy-red
a7848664c8c5d80f8bf98e93523daec60c54512b
src/Store.js
src/Store.js
import AsyncStorage from '@react-native-community/async-storage'; import { persistStore, persistReducer } from 'redux-persist'; import { applyMiddleware, createStore } from 'redux'; import thunk from 'redux-thunk'; import { createReactNavigationReduxMiddleware } from 'react-navigation-redux-helpers'; import reducers from './reducers'; // Create middleware and connect const appNavigatorMiddleware = createReactNavigationReduxMiddleware(state => state.nav, 'root'); const persistConfig = { keyPrefix: '', key: 'root', storage: AsyncStorage, blacklist: [ 'nav', 'pages', 'user', 'prescription', 'patient', 'form', 'prescriber', 'wizard', 'payment', ], }; const persistedReducer = persistReducer(persistConfig, reducers); const store = createStore(persistedReducer, {}, applyMiddleware(thunk, appNavigatorMiddleware)); const persistedStore = persistStore(store); export { store, persistedStore };
import AsyncStorage from '@react-native-community/async-storage'; import { persistStore, persistReducer } from 'redux-persist'; import { applyMiddleware, createStore } from 'redux'; import thunk from 'redux-thunk'; import { createReactNavigationReduxMiddleware } from 'react-navigation-redux-helpers'; import reducers from './reducers'; // Create middleware and connect const appNavigatorMiddleware = createReactNavigationReduxMiddleware(state => state.nav, 'root'); const persistConfig = { keyPrefix: '', key: 'root', storage: AsyncStorage, blacklist: [ 'nav', 'pages', 'user', 'prescription', 'patient', 'form', 'prescriber', 'wizard', 'payment', 'insurance', ], }; const persistedReducer = persistReducer(persistConfig, reducers); const store = createStore(persistedReducer, {}, applyMiddleware(thunk, appNavigatorMiddleware)); const persistedStore = persistStore(store); export { store, persistedStore };
Add insurance shape to blacklist
Add insurance shape to blacklist
JavaScript
mit
sussol/mobile,sussol/mobile,sussol/mobile,sussol/mobile
ee0297dc6068c1e0cdec22e73f84cb6dfae2cde6
src/store.js
src/store.js
import _merge from 'lodash/merge' import moment from 'moment' let today = moment().format('YYYY-MM-DD') export default { loading: true, schedule: {}, // Restore saved preferences to over default lunches and classes lunches: _merge({ 'Monday': 1, 'Tuesday': 1, 'Wednesday': 1, 'Thursday': 1, 'Friday': 1 }, JSON.parse(localStorage.getItem('lunches')) || {}), classes: _merge({ 1: '', 2: '', 3: '', 4: '', 5: '', 6: '', 7: '' }, JSON.parse(localStorage.getItem('classes')) || {}), // Design constants colors: ['#3F51B5', '#1976D2', '#03A9F4', '#00BCD4', '#009688', '#4CAF50', '#8BC34A'], // Check if client is crawler so it doesn't see a countdown in the title! isCrawler: /bot|googlebot|crawler|spider|robot|crawling/i.test(navigator.userAgent), // Set default dates to determine week to display displayDate: today, today, // Set default countdown so checking each blocks begins with the first one countdown: { i: 0 }, // Queue for next countdown call (a timeout Promise) queue: null }
import _merge from 'lodash/merge' import moment from 'moment' let today = moment().format('YYYY-MM-DD') export default { loading: true, schedule: {}, // Restore saved preferences to over default lunches and classes lunches: _merge({ 'Monday': 1, 'Tuesday': 1, 'Wednesday': 1, 'Thursday': 1, 'Friday': 1 }, JSON.parse(localStorage.getItem('lunches')) || {}), classes: _merge({ 1: '', 2: '', 3: '', 4: '', 5: '', 6: '', 7: '' }, JSON.parse(localStorage.getItem('classes')) || {}), // Design constants colors: ['#3F51B5', '#1976D2', '#039BE5', '#00BCD4', '#009688', '#43A047', '#7CB342'], // Check if client is crawler so it doesn't see a countdown in the title! isCrawler: /bot|googlebot|crawler|spider|robot|crawling/i.test(navigator.userAgent), // Set default dates to determine week to display displayDate: today, today, // Set default countdown so checking each blocks begins with the first one countdown: { i: 0 }, // Queue for next countdown call (a timeout Promise) queue: null }
Modify block colors for greater contrast
Modify block colors for greater contrast
JavaScript
mit
Foo-Bear/beartime-web,Foo-Bear/beartime-web
9e50914060d36a4f6836280ba1d70d08e255ff23
tests/jest.config.js
tests/jest.config.js
const baseConfig = require('tdd-buffet/config/jest.config'); const path = require('path'); const { pathsToModuleNameMapper } = require('ts-jest/utils'); const { compilerOptions } = require('../tsconfig'); const rootDir = path.join(__dirname, '../'); module.exports = { ...baseConfig, rootDir, // For some reason Jest will complain that this is duplicating the packages/mugshot/package.json. modulePathIgnorePatterns: ['<rootDir>/package.json'], moduleNameMapper: { ...pathsToModuleNameMapper(compilerOptions.paths, { prefix: '<rootDir>/packages/' }), // For some reason the ts-jest helper doesn't pick this one up. '^mugshot/(.*)$': '<rootDir>/packages/mugshot/$1' } };
const baseConfig = require('tdd-buffet/config/jest.config'); const path = require('path'); const { pathsToModuleNameMapper } = require('ts-jest/utils'); const { compilerOptions } = require('../tsconfig'); const rootDir = path.join(__dirname, '../'); module.exports = { ...baseConfig, rootDir, // For some reason Jest will complain that this is duplicating the packages/mugshot/package.json. modulePathIgnorePatterns: ['<rootDir>/package.json'], moduleNameMapper: { ...pathsToModuleNameMapper(compilerOptions.paths, { prefix: '<rootDir>/packages/' }), // For some reason the ts-jest helper doesn't pick this one up. '^mugshot/(.*)$': '<rootDir>/packages/mugshot/$1' }, // We're doing multiple coverage runs so we don't want to print the table every time // and we want to check thresholds once at the end with nyc. coverageReporters: ['json', 'html'], coverageThreshold: undefined };
Check coverage at the end
Check coverage at the end
JavaScript
mit
uberVU/mugshot,uberVU/mugshot
bfc138deca8d789387fb12e91a874948c440b29c
src/index.js
src/index.js
import * as components from './components' import config, { setOptions } from './utils/config' import { use, registerComponentProgrammatic } from './utils/plugins' const Buefy = { install(Vue, options = {}) { // Options setOptions(Object.assign(config, options)) // Components for (let componentKey in components) { Vue.use(components[componentKey]) } // Config component const BuefyProgrammatic = { setOptions(options) { setOptions(Object.assign(config, options)) } } registerComponentProgrammatic(Vue, '$buefy', BuefyProgrammatic) } } use(Buefy) export default Buefy
import * as components from './components' import config, { setOptions } from './utils/config' import { use, registerComponentProgrammatic } from './utils/plugins' const Buefy = { install(Vue, options = {}) { // Options setOptions(Object.assign(config, options)) // Components for (let componentKey in components) { Vue.use(components[componentKey]) } // Config component const BuefyProgrammatic = { setOptions(options) { setOptions(Object.assign(config, options)) } } registerComponentProgrammatic(Vue, '$buefy', BuefyProgrammatic) } } use(Buefy) export default Buefy export * from './components'
Add export all components in src
Add export all components in src
JavaScript
mit
rafaelpimpa/buefy,rafaelpimpa/buefy,rafaelpimpa/buefy
ceb46510b3dba3846a51ea9a96983338ac349250
src/index.js
src/index.js
var coffeeScript = require("coffee-script"); var commands = codebox.require("core/commands"); var File = codebox.require("models/file"); commands.register({ id: "coffeescript.preview", title: "CoffeeScript: Preview", context: ["editor"], shortcuts: [ "ctrl+shift+c" ], run: function(args, context) { var name = context.model.get("name").replace(context.model.getExtension(), ".js"); var code, error; try { code = coffeeScript.compile(context.getContent()); } catch (e) { error = e; code = e.toString(); name = "Error at compilation"; } var f = File.buffer(name, code); return commands.run("file.open", { file: f }) .then(function() { if (error) throw error; }); } });
var coffeeScript = require("coffee-script"); var commands = codebox.require("core/commands"); var File = codebox.require("models/file"); commands.register({ id: "coffeescript.preview", title: "CoffeeScript: Preview", context: ["editor"], shortcuts: [ "ctrl+shift+c" ], run: function(args, ctx) { var name = ctx.editor.model.get("name").replace(ctx.editor.model.getExtension(), ".js"); var code, error; try { code = coffeeScript.compile(ctx.editor.getContent()); } catch (e) { error = e; code = e.toString(); name = "Error at compilation"; } var f = File.buffer(name, code); return commands.run("file.open", { file: f }) .then(function() { if (error) throw error; }); } });
Use new multiple cmd contexts
Use new multiple cmd contexts
JavaScript
apache-2.0
CodeboxIDE/package-coffeescript
abea4b81b50c55fa2fdda58804dcab30a4c5d65e
src/index.js
src/index.js
import React from "react"; import ReactDOM from "react-dom"; import { RoutingApp } from "./modules/RoutingApp"; import store from "./store"; import { Provider } from "react-redux"; import { STUY_SPEC_API_URL } from "./constants"; import { ApolloProvider } from "react-apollo"; import { ApolloClient } from "apollo-client"; import { HttpLink } from "apollo-link-http"; import { InMemoryCache } from "apollo-cache-inmemory"; import { objectFilter } from "./utils"; const apolloClient = new ApolloClient({ link: new HttpLink({ uri: `${STUY_SPEC_API_URL}/graphql` }), cache: new InMemoryCache(), }); Object.filter = objectFilter; const App = () => ( <Provider store={store}> <ApolloProvider client={apolloClient}> <RoutingApp /> </ApolloProvider> </Provider> ); ReactDOM.render( <App />, document.getElementById("app"), );
import React from "react"; import ReactDOM from "react-dom"; import { RoutingApp } from "./modules/RoutingApp"; import store from "./store"; import { Provider } from "react-redux"; import { STUY_SPEC_API_URL } from "./constants"; import { ApolloProvider } from "react-apollo"; import { ApolloClient } from "apollo-client"; import { HttpLink } from "apollo-link-http"; import { InMemoryCache } from "apollo-cache-inmemory"; import { objectFilter } from "./utils"; const apolloClient = new ApolloClient({ link: new HttpLink({ uri: `${STUY_SPEC_API_URL}/graphql` }), cache: new InMemoryCache(), connectToDevTools: true }); Object.filter = objectFilter; const App = () => ( <Provider store={store}> <ApolloProvider client={apolloClient}> <RoutingApp /> </ApolloProvider> </Provider> ); ReactDOM.render( <App />, document.getElementById("app"), );
Enable Apollo devtools in production
Enable Apollo devtools in production
JavaScript
mit
stuyspec/client-app
95a364f75062d73bc219c21debb69de7ca2c016c
test/spec/leafbird.spec.js
test/spec/leafbird.spec.js
/* Copyright 2015 Leafbird 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. */ describe('configure', function() { it('Confugure changes on original config.', function() { var leafbrd = Leafbird({}); leafbrd.configure({}); expect(leafbrd.config).toEqual(undefined); }); });
/* Copyright 2015 Leafbird 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. */ describe('configure', function() { it('Confugure changes on original config.', function() { var leafbrd = Leafbird({}); leafbrd.configure({}); expect(leafbrd.config).toEqual(undefined); }); it('verify if a leafbird global object has defined', function(){ expect(leafbird).toBeDefined(); }); });
Verify if leafbird variable has defined on the global scope
Verify if leafbird variable has defined on the global scope
JavaScript
apache-2.0
bscherer/leafbird,bscherer/leafbird,lucasb/leafbird,lucasb/leafbird,leafbirdjs/leafbird,leafbirdjs/leafbird
bab883be3f5f8eb4969021fe4924253090d58614
js/application.js
js/application.js
$(document).ready(function(){ var arrayOfColumnNames = [ "c0", "c1", "c2", "c3", "c4", "c5", "c6", ]; for (var i=0; i<7; i++) { $("#board").append("<div class='column-div' id=" + arrayOfColumnNames[i] + "></div>"); // console.log($('#' + arrayOfColumnNames[i])); var thisColumn = $('#' + arrayOfColumnNames[i]); for (var j=0; j<6; j++) { $('#' + arrayOfColumnNames[i]).append("<div class='row-div' id=" + arrayOfColumnNames[i] + "-" + j + "></div>"); } } });
$(document).ready(function(){ var arrayOfColumnNames = [ "c0", "c1", "c2", "c3", "c4", "c5", "c6", ]; for (var i=0; i<7; i++) { $("#board").append("<div class='column-div' id=" + arrayOfColumnNames[i] + "></div>"); // console.log($('#' + arrayOfColumnNames[i])); var thisColumn = $('#' + arrayOfColumnNames[i]); for (var j=5; j>=0; j--) { $('#' + arrayOfColumnNames[i]).append("<div class='row-div' id=" + arrayOfColumnNames[i] + "-" + j + "></div>"); } } var board = [ [], [], [], [], [], [], [] ]; var turns = 0; $('.column-div').on('click', function(){ //gives us column that was clicked on var column = parseInt($(this).attr('id').slice(-1)); //alternates red and black pieces depending on turn count if (board[column].length < 6){ turns += 1; var color = (turns % 2) ? "red" : "black"; //adds piece to board board[column].push(color); var row = board[column].length - 1; $('#c' + column + '-' + row).css('background-color', color); } console.log(board); }); });
Add pieces to the board
Add pieces to the board
JavaScript
mit
RNBrandt/Connect-4,RNBrandt/Connect-4
7b7c5befdb6404705ca905bf3e2ae8c8aebe4271
source/setup/components/VaultPage.js
source/setup/components/VaultPage.js
import React, { Component } from "react"; import PropTypes from "prop-types"; import BUI, { VaultProvider, VaultUI } from "@buttercup/ui"; class VaultPage extends Component { static propTypes = { sourceID: PropTypes.string.isRequired, vault: PropTypes.object }; state = { masterPassword: "" }; componentDidMount() { this.props.fetchVaultFacade(this.props.sourceID); } render() { console.log("COMPS", BUI); return ( <div> <Choose> <When condition={this.props.vault}> <VaultProvider vault={this.props.vault} onUpdate={() => {}}> <VaultUI /> </VaultProvider> </When> <Otherwise> <i>Loading...</i> </Otherwise> </Choose> </div> ); } } export default VaultPage;
import React, { Component } from "react"; import PropTypes from "prop-types"; import { VaultProvider, VaultUI } from "@buttercup/ui"; class VaultPage extends Component { static propTypes = { sourceID: PropTypes.string.isRequired, vault: PropTypes.object }; state = { masterPassword: "" }; componentDidMount() { this.props.fetchVaultFacade(this.props.sourceID); } render() { return ( <div> <Choose> <When condition={this.props.vault}> <VaultProvider vault={this.props.vault} onUpdate={() => {}}> <VaultUI /> </VaultProvider> </When> <Otherwise> <i>Loading...</i> </Otherwise> </Choose> </div> ); } } export default VaultPage;
Remove testing for vault ui
Remove testing for vault ui
JavaScript
mit
buttercup-pw/buttercup-browser-extension,buttercup-pw/buttercup-browser-extension,perry-mitchell/buttercup-chrome,perry-mitchell/buttercup-chrome
03f2023117163b855f447ef842712f549e6235a4
lib/webrat/selenium/location_strategy_javascript/webratlink.js
lib/webrat/selenium/location_strategy_javascript/webratlink.js
var links = inDocument.getElementsByTagName('a'); var candidateLinks = $A(links).select(function(candidateLink) { var textMatched = PatternMatcher.matches(locator, getText(candidateLink)); var idMatched = PatternMatcher.matches(locator, candidateLink.id); var titleMatched = PatternMatcher.matches(locator, candidateLink.title); return textMatched || idMatched || titleMatched; }); if (candidateLinks.length == 0) { return null; } //reverse length sort candidateLinks = candidateLinks.sortBy(function(s) { return s.length * -1; }); return candidateLinks.first();
var links = inDocument.getElementsByTagName('a'); var candidateLinks = $A(links).select(function(candidateLink) { var textMatched = false; var titleMatched = false; var idMatched = false; if (getText(candidateLink).toLowerCase().indexOf(locator.toLowerCase()) != -1) { textMatched = true; } if (candidateLink.title.toLowerCase().indexOf(locator.toLowerCase()) != -1) { titleMatched = true; } if (candidateLink.id.toLowerCase().indexOf(locator.toLowerCase()) != -1) { idMatched = true; } return textMatched || idMatched || titleMatched; }); if (candidateLinks.length == 0) { return null; } //reverse length sort candidateLinks = candidateLinks.sortBy(function(s) { return s.length * -1; }); return candidateLinks.first();
Make link location in Selenium more reliable and consistent with non-Selenium
Make link location in Selenium more reliable and consistent with non-Selenium
JavaScript
mit
brynary/webrat,jacksonfish/webrat,irfanah/webrat,johnbintz/webrat,jacksonfish/webrat,irfanah/webrat,johnbintz/webrat,irfanah/webrat,brynary/webrat
282a542462c9a738aa150c8fe785e264f42cf98a
src/geo/leaflet/leaflet-cartodb-webgl-layer-group-view.js
src/geo/leaflet/leaflet-cartodb-webgl-layer-group-view.js
var TC = require('tangram.cartodb'); var LeafletLayerView = require('./leaflet-layer-view'); var LeafletCartoDBVectorLayerGroupView = window.L.TileLayer.extend({ includes: [ LeafletLayerView.prototype ], options: { minZoom: 0, maxZoom: 28, tileSize: 256, zoomOffset: 0, tileBuffer: 50 }, events: { featureOver: null, featureOut: null, featureClick: null }, initialize: function (layerGroupModel, map) { LeafletLayerView.call(this, layerGroupModel, this, map); layerGroupModel.bind('change:urls', this._onURLsChanged, this); this.tangram = new TC(map); layerGroupModel.each(this._onLayerAdded, this); layerGroupModel.onLayerAdded(this._onLayerAdded.bind(this)); }, onAdd: function (map) { }, _onLayerAdded: function (layer) { var self = this; layer.bind('change:meta', function (e) { self.tangram.addLayer(e.attributes); }); }, _onURLsChanged: function (e, res) { this.tangram.addDataSource(res.tiles[0]); } }); module.exports = LeafletCartoDBVectorLayerGroupView;
var TC = require('tangram.cartodb'); var LeafletLayerView = require('./leaflet-layer-view'); var L = require('leaflet'); var LeafletCartoDBVectorLayerGroupView = L.Layer.extend({ includes: [ LeafletLayerView.prototype ], options: { minZoom: 0, maxZoom: 28, tileSize: 256, zoomOffset: 0, tileBuffer: 50 }, events: { featureOver: null, featureOut: null, featureClick: null }, initialize: function (layerGroupModel, map) { LeafletLayerView.call(this, layerGroupModel, this, map); layerGroupModel.bind('change:urls', this._onURLsChanged, this); this.tangram = new TC(map); layerGroupModel.each(this._onLayerAdded, this); layerGroupModel.onLayerAdded(this._onLayerAdded.bind(this)); }, onAdd: function (map) { L.Layer.prototype.onAdd.call(this, map); }, _onLayerAdded: function (layer) { var self = this; layer.bind('change:meta', function (e) { self.tangram.addLayer(e.attributes); }); }, _onURLsChanged: function (e, res) { this.tangram.addDataSource(res.tiles[0]); } }); module.exports = LeafletCartoDBVectorLayerGroupView;
Extend from the proper layer
Extend from the proper layer
JavaScript
bsd-3-clause
splashblot/cartodb.js,splashblot/cartodb.js,splashblot/cartodb.js,splashblot/cartodb.js
17d2056799f9560f0340efa18447a6ea7dd52e56
src/mixin.js
src/mixin.js
function Mixin(proto, properties) { for (const property in properties) { const value = properties[property]; if (proto[property] && typeof value == "function") { inherit(proto, property, value); } else { proto[property] = value; } } } function inherit(proto, name, func) { var parentFunc = proto[name]; proto[name] = function () { var old = this.callParent; this.callParent = parentFunc; var ret = func.apply(this, arguments); if (old) { this.callParent = old; } return ret; }; } module.exports = Mixin;
function Mixin(proto, properties) { for (const property in properties) { const value = properties[property]; if (proto[property] && typeof value == "function") { inherit(proto, property, value); } else { proto[property] = value; } } } function inherit(proto, property, func) { var parentFunc = proto[property]; proto[property] = function () { var old = this.callParent; this.callParent = parentFunc; var ret = func.apply(this, arguments); if (old) { this.callParent = old; } return ret; }; } module.exports = Mixin;
Make name `name` match in `inherit` helper
Make name `name` match in `inherit` helper This function uses approximately the same variable names to add to the prototype. Lets match `Mixin`.
JavaScript
mit
iFixit/node-markup,iFixit/node-markup,iFixit/node-markup
ce62829374960f487c98c974be3725b244fc1ff6
LayoutTests/crypto/resources/worker-infinite-loop-generateKey.js
LayoutTests/crypto/resources/worker-infinite-loop-generateKey.js
importScripts('common.js'); function continuouslyGenerateRsaKey() { var extractable = false; var usages = ['encrypt', 'decrypt']; // Note that the modulus length is small. var algorithm = {name: "RSAES-PKCS1-v1_5", modulusLength: 512, publicExponent: hexStringToUint8Array("010001")}; return crypto.subtle.generateKey(algorithm, extractable, usages).then(function(result) { // Infinite recursion intentional! return continuouslyGenerateRsaKey(); }); } // Starts a Promise which continually generates new RSA keys. var unusedPromise = continuouslyGenerateRsaKey(); // Inform the outer script that the worker started. postMessage("Worker started");
importScripts('common.js'); function continuouslyGenerateRsaKey() { var extractable = false; var usages = ['sign', 'verify']; // Note that the modulus length is small. var algorithm = {name: "RSASSA-PKCS1-v1_5", modulusLength: 512, publicExponent: hexStringToUint8Array("010001"), hash: {name: 'sha-1'}}; return crypto.subtle.generateKey(algorithm, extractable, usages).then(function(result) { // Infinite recursion intentional! return continuouslyGenerateRsaKey(); }); } // Starts a Promise which continually generates new RSA keys. var unusedPromise = continuouslyGenerateRsaKey(); // Inform the outer script that the worker started. postMessage("Worker started");
Remove a lingering usage of RSA-ES.
[webcrypto] Remove a lingering usage of RSA-ES. TBR=jww BUG=372920,245025 Review URL: https://codereview.chromium.org/344503003 git-svn-id: bf5cd6ccde378db821296732a091cfbcf5285fbd@176389 bbb929c8-8fbe-4397-9dbb-9b2b20218538
JavaScript
bsd-3-clause
primiano/blink-gitcs,primiano/blink-gitcs,primiano/blink-gitcs,primiano/blink-gitcs,primiano/blink-gitcs,primiano/blink-gitcs,primiano/blink-gitcs,primiano/blink-gitcs,primiano/blink-gitcs
86e7de3cb692cc025512546876e4bb733f130d7c
packages/pundle-transformer-js/lib/plugin-remove-dead-nodes.js
packages/pundle-transformer-js/lib/plugin-remove-dead-nodes.js
// @flow import * as t from '@babel/types' // Empty out bodies of falsy parts of if/else statements // to avoid requiring modules that aren't needed aka // if (process.env.NODE_ENV === 'production') module.exports = require('./prod-version') else module.exports = require('./dev-version') // OR // module.exports = process.env.NODE_ENV === 'production' ? require('./prod-version') : require('./dev-version') function processBooleanConditional(path: $FlowFixMe) { const { node } = path if (!t.isBooleanLiteral(node.test)) return function visitIfNode(leafNode) { if (!t.isBooleanLiteral(leafNode.test)) return const { test, consequent, alternate } = node if (test.value) { path.replaceWithMultiple(consequent.body) return } node.consequent.body = [] if (t.isIfStatement(alternate)) { visitIfNode(alternate) } else if (t.isBlockStatement(alternate)) { path.replaceWithMultiple(alternate.body) } } if (t.isIfStatement(node)) { visitIfNode(node) } else { path.replaceWith(node.test.value ? node.consequent : node.alternate) } } export default { visitor: { IfStatement: processBooleanConditional, ConditionalExpression: processBooleanConditional, }, }
// @flow import * as t from '@babel/types' // Empty out bodies of falsy parts of if/else statements // to avoid requiring modules that aren't needed aka // if (process.env.NODE_ENV === 'production') module.exports = require('./prod-version') else module.exports = require('./dev-version') // OR // module.exports = process.env.NODE_ENV === 'production' ? require('./prod-version') : require('./dev-version') function processBooleanConditional(path: $FlowFixMe) { const { node } = path if (!t.isBooleanLiteral(node.test)) return function visitIfNode(leafNode) { if (!t.isBooleanLiteral(leafNode.test)) return const { test, consequent, alternate } = leafNode if (test.value) { if (t.isBlockStatement(consequent)) { path.replaceWithMultiple(consequent.body) } else path.replaceWith(consequent) return } consequent.body = [] if (t.isIfStatement(alternate)) { visitIfNode(alternate) } else if (t.isBlockStatement(alternate)) { path.replaceWithMultiple(alternate.body) } else if (t.isExpressionStatement(alternate)) { path.replaceWith(alternate) } } if (t.isIfStatement(node)) { visitIfNode(node) } else { path.replaceWith(node.test.value ? node.consequent : node.alternate) } } export default { visitor: { IfStatement: processBooleanConditional, ConditionalExpression: processBooleanConditional, }, }
Fix issue with non-block if/else blocks
:bug: Fix issue with non-block if/else blocks
JavaScript
mit
steelbrain/pundle,motion/pundle,steelbrain/pundle,steelbrain/pundle
fa1bcd93bb50dfed00a56e908270a1338ca36b67
src/xmlWriter.js
src/xmlWriter.js
/* global jasmineImporter */ const {GLib} = imports.gi; const Utils = jasmineImporter.utils; function Node(name) { this.name = name; this.attrs = {}; this.children = []; this.text = ''; } function _attrsToString(attrs) { return Object.keys(attrs).map(key => { const value = attrs[key].toString(); return ` ${key}="${GLib.markup_escape_text(value, -1)}"`; }).join(''); } function _prettyprint(node) { if (node.children.length === 0 && node.text.length === 0) return `<${node.name}${_attrsToString(node.attrs)}/>\n`; const elementTop = `<${node.name}${_attrsToString(node.attrs)}>\n`; const elementBottom = `</${node.name}>\n`; const children = node.children.map(_prettyprint).join(''); let text = GLib.markup_escape_text(node.text, -1).trim(); if (text.length !== 0) text += '\n'; return elementTop + Utils.indent(children, 2) + Utils.indent(text, 2) + elementBottom; } Node.prototype.toString = function () { return `<?xml version="1.0" encoding="UTF-8"?>\n${_prettyprint(this)}`; };
/* global jasmineImporter */ /* exported Node */ const {GLib} = imports.gi; const Utils = jasmineImporter.utils; var Node = class Node { constructor(name) { this.name = name; this.attrs = {}; this.children = []; this.text = ''; } toString() { return `<?xml version="1.0" encoding="UTF-8"?>\n${_prettyprint(this)}`; } }; function _attrsToString(attrs) { return Object.keys(attrs).map(key => { const value = attrs[key].toString(); return ` ${key}="${GLib.markup_escape_text(value, -1)}"`; }).join(''); } function _prettyprint(node) { if (node.children.length === 0 && node.text.length === 0) return `<${node.name}${_attrsToString(node.attrs)}/>\n`; const elementTop = `<${node.name}${_attrsToString(node.attrs)}>\n`; const elementBottom = `</${node.name}>\n`; const children = node.children.map(_prettyprint).join(''); let text = GLib.markup_escape_text(node.text, -1).trim(); if (text.length !== 0) text += '\n'; return elementTop + Utils.indent(children, 2) + Utils.indent(text, 2) + elementBottom; }
Change XMLWriter.Node to an ES6 class
Change XMLWriter.Node to an ES6 class This was still using the old way without syntactic sugar.
JavaScript
mit
ptomato/jasmine-gjs,ptomato/jasmine-gjs
fa4465e3705fd2d75011401a9ec2167842d4f5ce
static/js/vcs.js
static/js/vcs.js
var $ = $ || function() {}; // Keeps from throwing ref errors. function swapselected(from, to) { $(to).html(options[$(from).val()]); } function detailselected(from, to) { $(to).text(details[$(from).val()]); } $(function() { $("#grp-slct").change( function() { swapselected("#grp-slct", "#subgrp-slct"); }); $("#subgrp-slct").change( function() { detailselected("#subgrp-slct", "#detail-msg"); }); });
var $ = $ || function() {}; // Keeps from throwing ref errors. function swapselected(from, to) { $(to).html(options[$(from).val()]); } function detailselected(from, to) { $(to).text(details[$(from).val()]); } $(function() { $("#grp-slct").change( function() { swapselected("#grp-slct", "#subgrp-slct"); }); $("#subgrp-slct").change( function() { detailselected("#subgrp-slct", "#detail-msg"); $("#activity_key").attr("value", $("#subgrp-slct").val()); }); });
Add the hidden activity value to the form so we know which activity has been selected.
Add the hidden activity value to the form so we know which activity has been selected.
JavaScript
bsd-3-clause
AeroNotix/django-timetracker,AeroNotix/django-timetracker,AeroNotix/django-timetracker
4bc5e394580543c2f31ac2d4d7424fef6e47a21a
.eslintrc.js
.eslintrc.js
module.exports = { extends: "eslint:recommended", rules: { "no-console": 0, "object-curly-spacing": ["error", "always"], "comma-dangle": ["error", "always-multiline"], quotes: ["error", "backtick"], semi: ["error", "never"], }, env: { node: true, }, parserOptions: { ecmaVersion: 2017, sourceType: "module", }, }
module.exports = { extends: "eslint:recommended", rules: { "no-console": 0, "object-curly-spacing": ["error", "always"], "comma-dangle": ["error", "always-multiline"], quotes: ["error", "backtick"], semi: ["error", "never"], "arrow-body-style": [ "error", "as-needed", { requireReturnForObjectLiteral: true }, ], }, env: { node: true, es6: true, }, parserOptions: { ecmaVersion: 2017, sourceType: "module", }, }
Add explicit rule for arrow functions and add support for es6 globals
Add explicit rule for arrow functions and add support for es6 globals
JavaScript
mit
mattdean1/contentful-text-search
a2603a86697b856749a1df9027505adf11908cad
src/components/ReviewRecipe.js
src/components/ReviewRecipe.js
import React from 'react'; import { Link } from 'react-router-dom'; import { Button } from 'react-bootstrap'; import ModifyTitle from '../containers/ModifyTitle'; import ModifyIngredients from '../containers/ModifyIngredients'; import PropTypes from 'prop-types'; const ReviewRecipe = (props) => { return ( <div> <h4>Review Recipe</h4> <ModifyTitle nextButton={false} /> <ModifyIngredients nextButton={false} plusButton={false} /> <Link to="/"> <Button bsStyle="primary" bsSize="large" style={props.buttonStyle} onClick={() => { props.tempRecipe.editMode ? props.editRecipe(props.tempRecipe.id, props.tempRecipe) : props.addRecipe(props.tempRecipe); props.clearTempRecipe(); }} block > Submit </Button> </Link> <Link to="/modify-ingredients"> <Button bsSize="large" block>Back</Button> </Link> </div> ); }; ReviewRecipe.propTypes = { buttonStyle: PropTypes.object.isRequired, addRecipe: PropTypes.func.isRequired, tempRecipe: PropTypes.object.isRequired, clearTempRecipe: PropTypes.func.isRequired }; export default ReviewRecipe;
import React from 'react'; import { Link } from 'react-router-dom'; import { Button } from 'react-bootstrap'; import ModifyTitle from '../containers/ModifyTitle'; import ModifyIngredients from '../containers/ModifyIngredients'; import PropTypes from 'prop-types'; const ReviewRecipe = (props) => { return ( <div> <h4>Review Recipe</h4> <ModifyTitle nextButton={false} /> <ModifyIngredients nextButton={false} plusButton={false} /> <Link to="/"> <Button bsStyle="primary" bsSize="large" style={props.buttonStyle} onClick={() => { if (props.tempRecipe.editMode) { props.editRecipe(props.tempRecipe.id, props.tempRecipe); } else { props.addRecipe(props.tempRecipe); } props.clearTempRecipe(); }} block > Submit </Button> </Link> <Link to="/modify-ingredients"> <Button bsSize="large" block>Back</Button> </Link> </div> ); }; ReviewRecipe.propTypes = { buttonStyle: PropTypes.object.isRequired, addRecipe: PropTypes.func.isRequired, tempRecipe: PropTypes.object.isRequired, clearTempRecipe: PropTypes.func.isRequired }; export default ReviewRecipe;
Refactor if statement for clarity.
Refactor if statement for clarity.
JavaScript
mit
phuchle/recipeas,phuchle/recipeas
0a3273bbb40e2c7c9c84f2df01ce53a8b379a86e
app/components/common/cityModule/cityElectionsController.js
app/components/common/cityModule/cityElectionsController.js
'use strict'; function cityElectionsController($scope, ballot) { $scope.ballot = ballot; $scope.isOffice = isOffice; $scope.isReferendum = isReferendum; function isOffice(contest) { return contest.type === 'office'; } function isReferendum(contest) { return contest.type === 'referendum'; } } module.exports = cityElectionsController;
'use strict'; function cityElectionsController($scope, ballot) { $scope.ballot = ballot; $scope.isOffice = isOffice; $scope.isReferendum = isReferendum; function isOffice(contest) { return contest.contest_type === 'office'; } function isReferendum(contest) { return contest.contest_type === 'referendum'; } } module.exports = cityElectionsController;
Fix the contest type property
Fix the contest type property
JavaScript
mit
KyleW/disclosure-frontend,caciviclab/disclosure-frontend,caciviclab/disclosure-frontend,KyleW/disclosure-frontend,caciviclab/disclosure-frontend-alpha,KyleW/disclosure-frontend,caciviclab/disclosure-frontend,caciviclab/disclosure-frontend-alpha,caciviclab/disclosure-frontend-alpha
8c999c55254a61185589743e2e8aebf4e71bca06
modules/data-selection/components/formatter/formatter.component.js
modules/data-selection/components/formatter/formatter.component.js
(function () { 'use strict'; angular .module('dpDataSelection') .component('dpDataSelectionFormatter', { bindings: { variables: '<', formatter: '@', useInline: '<' }, templateUrl: 'modules/data-selection/components/formatter/formatter.html', controller: DpDataSelectionFormatterController, controllerAs: 'vm' }); DpDataSelectionFormatterController.$inject = ['$filter']; function DpDataSelectionFormatterController ($filter) { let vm = this, variablesObj = {}; if (vm.formatter) { if (vm.variables.length === 1) { // Just pass the value (String) when there is only one variable vm.formattedValue = $filter(vm.formatter)(vm.variables[0].value); } else { // Pass all variables as an Object if there are more variables vm.variables.forEach(({key, value}) => variablesObj[key] = value); vm.formattedValue = $filter(vm.formatter)(variablesObj); } } else { // If there is no formatter; concatenate all values vm.formattedValue = vm.variables.map(variable => { return variable.value; }).join(' '); } } })();
(function () { 'use strict'; angular .module('dpDataSelection') .component('dpDataSelectionFormatter', { bindings: { variables: '<', formatter: '@', useInline: '<' }, templateUrl: 'modules/data-selection/components/formatter/formatter.html', controller: DpDataSelectionFormatterController, controllerAs: 'vm' }); DpDataSelectionFormatterController.$inject = ['$filter']; function DpDataSelectionFormatterController ($filter) { let vm = this, variablesObj = {}; if (vm.formatter) { if (vm.variables.length === 1) { // Just pass the value (String) when there is only one variable vm.formattedValue = $filter(vm.formatter)(vm.variables[0].value); } else { // Pass all variables as an Object if there are more variables vm.variables.forEach(({key, value}) => variablesObj[key] = value); vm.formattedValue = $filter(vm.formatter)(variablesObj); } } else { // If there is no formatter; concatenate all values vm.formattedValue = vm.variables.map(variable => { return variable.value; }).join(' '); } console.log(formattedValue); } })();
Debug thing pushing to adw..
Debug thing pushing to adw..
JavaScript
mpl-2.0
DatapuntAmsterdam/atlas_prototype,Amsterdam/atlas,DatapuntAmsterdam/atlas_prototype,DatapuntAmsterdam/atlas,DatapuntAmsterdam/atlas,Amsterdam/atlas,Amsterdam/atlas,Amsterdam/atlas,DatapuntAmsterdam/atlas
0165ba27355a4ea2125abf4875a212257bf2567e
lib/flux_mixin.js
lib/flux_mixin.js
module.exports = function(React) { return { propTypes: { flux: React.PropTypes.object.isRequired }, childContextTypes: { flux: React.PropTypes.object }, getChildContext: function() { return { flux: this.props.flux }; } }; };
var FluxMixin = function(React) { return { propTypes: { flux: React.PropTypes.object.isRequired }, childContextTypes: { flux: React.PropTypes.object }, getChildContext: function() { return { flux: this.props.flux }; } }; }; FluxMixin.componentWillMount = function() { throw new Error("Fluxbox.FluxMixin is a function that takes React as a " + "parameter and returns the mixin, e.g.: mixins[Fluxbox.FluxMixin(React)]"); }; module.exports = FluxMixin;
Throw if Fluxbox.FluxMixin used as a mixin instead of a function
Throw if Fluxbox.FluxMixin used as a mixin instead of a function
JavaScript
mit
hoanglamhuynh/fluxxor,STRML/fluxxor,alcedo/fluxxor,davesag/fluxxor,nagyistoce/fluxxor,BinaryMuse/fluxxor,VincentHoang/fluxxor,davesag/fluxxor,chimpinano/fluxxor,davesag/fluxxor,dantman/fluxxor,nagyistoce/fluxxor,andrewslater/fluxxor,webcoding/fluxxor,chimpinano/fluxxor,SqREL/fluxxor,dantman/fluxxor,hoanglamhuynh/fluxxor,thomasboyt/fluxxor,VincentHoang/fluxxor,STRML/fluxxor,vsakaria/fluxxor,chimpinano/fluxxor,hoanglamhuynh/fluxxor,dantman/fluxxor,nagyistoce/fluxxor,demiazz/fluxxor
d0c8e97a68089b2fcd94b9921b976a4ff9619fad
tool/src/main/webapp/static/lib/serverDate.js
tool/src/main/webapp/static/lib/serverDate.js
// Small jQuery plugin to get dates from server. (function($){ var serverDate; var init = function(){ if (!serverDate) { $.ajax({ "url": "/course-signup/rest/user/current", "type": "GET", "async": false, "dataType": "json", "success": function(data){ serverDate = data.date; } }); } }; $.serverDate = function(){ init(); return serverDate; }; })(jQuery);
// Small jQuery plugin to get dates from server. (function($){ // Work out the difference between client time and server time. var adjustment; var init = function(){ if (!adjustment) { $.ajax({ "url": "/course-signup/rest/user/current", "type": "GET", "async": false, "dataType": "json", "success": function(data){ var serverDate = data.date; var clientDate = new Date().getTime(); adjustment = serverDate - clientDate; } }); } }; $.serverDate = function(){ init(); return (new Date().getTime() + adjustment); }; })(jQuery);
Make sure serverdate updates using the client clock.
Make sure serverdate updates using the client clock.
JavaScript
apache-2.0
ox-it/wl-course-signup,ox-it/wl-course-signup,ox-it/wl-course-signup,ox-it/wl-course-signup,ox-it/wl-course-signup
865c601b1b0fb542733e854087581f12b142c59e
src/components/App/components/UserInputError/UserInputError.js
src/components/App/components/UserInputError/UserInputError.js
import styles from './UserInputError.less'; import React, { Component, PropTypes } from 'react'; import { MIN_FONT_SIZE, MAX_FONT_SIZE } from 'flux/constants/config'; export default class UserInputError extends Component { static propTypes = { areColorsValid: PropTypes.bool.isRequired, isFontSizeValid: PropTypes.bool.isRequired }; render() { const { areColorsValid, isFontSizeValid } = this.props; return ( <div className={styles.container}> <div className={styles.innerContainer}> { !areColorsValid && <p> Please enter a valid hexadecimal color </p> } { !isFontSizeValid && <p> Please enter a font size between {MIN_FONT_SIZE}px and {MAX_FONT_SIZE}px </p> } </div> </div> ); } }
import styles from './UserInputError.less'; import React, { Component, PropTypes } from 'react'; import { MIN_FONT_SIZE } from 'flux/constants/config'; export default class UserInputError extends Component { static propTypes = { areColorsValid: PropTypes.bool.isRequired, isFontSizeValid: PropTypes.bool.isRequired }; render() { const { areColorsValid, isFontSizeValid } = this.props; return ( <div className={styles.container}> <div className={styles.innerContainer}> { !areColorsValid && <p> Please enter a valid hexadecimal color </p> } { !isFontSizeValid && <p> Please enter a font size of {MIN_FONT_SIZE}px or above </p> } </div> </div> ); } }
Update font size error message
Update font size error message
JavaScript
mit
moroshko/accessible-colors,moroshko/accessible-colors
29d0e65927d34f8077c56321c4c145b0fd9d87b3
test/gameSpec.js
test/gameSpec.js
var game = require('../game.js'); var chai = require('chai'); chai.should(); describe('Game', function() { describe('createPack', function() { it('has 52 cards', function() { var p = game.createPack(); p.should.have.lengthOf(52); }); }); describe('shuffle', function() { it('should have same number of cards', function() { var p = game.createPack(); var s = game.shuffle(p); p.should.have.lengthOf(s.length); }); }) });
var game = require('../game.js'); var chai = require('chai'); chai.should(); describe('Game', function() { describe('createPack', function() { it('has 52 cards', function() { var p = game.createPack(); p.should.have.lengthOf(52); }); }); describe('shuffle', function() { it('should have same number of cards', function() { var p = game.createPack(); var s = game.shuffle(p); p.should.have.lengthOf(s.length); }); }) describe('draw', function() { describe('one card', function() { it('should draw the requested number', function() { var pack = game.createPack(); var cards = game.draw(pack, 1, [], false); cards.should.have.lengthOf(1); }); }); describe('three cards', function() { it('should draw the requested number', function() { var pack = game.createPack(); var cards = game.draw(pack, 3, [], false); cards.should.have.lengthOf(3); }); }); }); });
Add some tests for drawing cards
Add some tests for drawing cards
JavaScript
mit
psmarshall/500,psmarshall/500
f9f7ba4eb96ff7bcadfd2c7859d315ff3418e084
src/components/LastHarvestStatus/LastHarvestStatus.js
src/components/LastHarvestStatus/LastHarvestStatus.js
import React from 'react' import moment from 'moment' import { theme } from '../../tools' let styles = { chip: {}, } const LastHarvestStatus = ({harvest}) => { const date = new Date(harvest.finished || harvest.finishedAt).getTime() const hoursDifference = moment(date).fromNow() let status if (harvest.status === 'successful') { status = 'Réussi' } else { styles.chip.color = theme.red status = 'En échec' } return ( <div style={styles.chip}> {status} {hoursDifference} </div> ) } export default LastHarvestStatus
import React from 'react' import moment from 'moment' import { theme } from '../../tools' let styles = { chip: {}, } const LastHarvestStatus = ({harvest}) => { const date = new Date(harvest.finished || harvest.finishedAt).getTime() const hoursDifference = moment(date).fromNow() let status if (harvest.status === 'successful') { styles.chip.color = theme.highlightblue status = 'Réussi' } else { styles.chip.color = theme.red status = 'En échec' } return ( <div style={styles.chip}> {status} {hoursDifference} </div> ) } export default LastHarvestStatus
Fix color on last harvested
Fix color on last harvested
JavaScript
mit
sgmap/inspire,sgmap/inspire
b60d3007afcddbe61f1aa3a78bacf284907ffcf6
src/plugins/configure/index.js
src/plugins/configure/index.js
const { next, hookStart, hookEnd } = require('hooter/effects') const assignDefaults = require('./assignDefaults') const validateConfig = require('./validateConfig') const EVENTS_WITH_CONFIG = ['start', 'execute', 'process', 'handle', 'error'] module.exports = function* configurePlugin() { let schema, config function* provideConfig(...args) { let event = this.name if (!config && event !== 'error') { throw new Error( `The config must already be defined at the beginning of "${event}"` ) } return yield next(config, ...args) } yield hookEnd('schema', function* (_schema) { schema = yield next(_schema).or(_schema) return schema }) yield hookStart('configure', function* (_config) { return yield next(schema, _config) }) yield hookStart('configure', function* (_schema, _config) { _config = assignDefaults(_schema, _config) return yield next(_schema, _config) }) yield hookEnd('configure', function* (_schema, _config) { validateConfig(_schema, _config) config = yield next(_schema, _config).or(_config) return config }) for (let event of EVENTS_WITH_CONFIG) { yield hookStart(event, provideConfig) } }
const { next, hook, hookStart, hookEnd } = require('hooter/effects') const assignDefaults = require('./assignDefaults') const validateConfig = require('./validateConfig') const EVENTS_WITH_CONFIG = ['start', 'execute', 'process', 'handle', 'error'] module.exports = function* configurePlugin() { let schema, config function* provideConfig(...args) { let event = this.name if (!config && event !== 'error') { throw new Error( `The config must already be defined at the beginning of "${event}"` ) } return yield next(config, ...args) } yield hookEnd('schema', function* (_schema) { schema = yield next(_schema).or(_schema) return schema }) yield hookStart('configure', function* (_config) { return yield next(schema, _config) }) yield hook('configure', function* (_schema, _config) { _config = assignDefaults(_schema, _config) return yield next(_schema, _config) }) yield hookEnd('configure', function* (_schema, _config) { validateConfig(_schema, _config) config = yield next(_schema, _config).or(_config) return config }) for (let event of EVENTS_WITH_CONFIG) { yield hookStart(event, provideConfig) } }
Use 'hook' to assign defaults
Use 'hook' to assign defaults
JavaScript
isc
alex-shnayder/comanche
6629bedfc4b561b3fbacdb5042b7538f6ad3ac80
app/assets/javascripts/lib/requests.js
app/assets/javascripts/lib/requests.js
import Axios from 'axios'; export function request (url, method, data = {}, options = {scroll: true}) { let promise = Axios.post(url, data, { headers: { 'X-HTTP-Method-Override': method, 'X-CSRF-Token': document.querySelector('meta[name=csrf-token]').getAttribute('content') } }); promise.catch(e => { if (e.response) return e.response; throw e; }) .then(response => { let html = response.data; let location = response.request.responseURL; if ((window.location.href == location) || (method == 'delete')){ window.location.reload(true); // save scroll position for annotations } else { window.location.replace(location); } if (options["modal"]){ options["modal"].destroy(); } }) .done(); return promise; } export var get = (url, data = {}, options = {}) => request(url, 'get', data, options) export var post = (url, data = {}, options = {}) => request(url, 'post', data, options) export var rest_delete = (url, data = {}, options = {}) => request(url, 'delete', data, options) export var patch = (url, data = {}, options = {}) => request(url, 'patch', data, options)
import Axios from 'axios'; export function request (url, method, data = {}, options = {scroll: true}) { let promise = Axios.post(url, data, { headers: { 'X-HTTP-Method-Override': method, 'X-CSRF-Token': document.querySelector('meta[name=csrf-token]').getAttribute('content') } }); promise.catch(e => { if (e.response) return e.response; throw e; }) .then(response => { let html = response.data; let location = response.request.responseURL; if ((window.location.href == location) || (method == 'delete')){ // saving scroll position if (navigator.userAgent.match('Firefox') != null){ window.location.reload(false); } else { window.location.reload(true); } } else { window.location.replace(location); } if (options["modal"]){ options["modal"].destroy(); } }) .done(); return promise; } export var get = (url, data = {}, options = {}) => request(url, 'get', data, options) export var post = (url, data = {}, options = {}) => request(url, 'post', data, options) export var rest_delete = (url, data = {}, options = {}) => request(url, 'delete', data, options) export var patch = (url, data = {}, options = {}) => request(url, 'patch', data, options)
Save scroll position in Firefox.
Save scroll position in Firefox.
JavaScript
agpl-3.0
harvard-lil/h2o,harvard-lil/h2o,harvard-lil/h2o,harvard-lil/h2o
37952efe4b53a791028e72ac9419864fcaf6a4f8
tests/dummy/app/services/store.js
tests/dummy/app/services/store.js
import Ember from 'ember'; import DS from 'ember-data'; import { Offline } from 'ember-flexberry-data'; export default Offline.Store.extend({ init() { this._super(...arguments); let owner = Ember.getOwner(this); let Store = DS.Store; let onlineStore = Store.create(owner.ownerInjection()); this.set('onlineStore', onlineStore); } });
import Ember from 'ember'; import DS from 'ember-data'; import { Offline } from 'ember-flexberry-data'; export default Offline.Store.extend({ init() { this.set('offlineSchema', { TestDB: { 0.1: { 'ember-flexberry-dummy-suggestion': 'id,address,text,date,votes,moderated,type,author,editor1,*files,*userVotes,*comments', 'ember-flexberry-dummy-suggestion-type': 'id,name,moderated,parent,*localizedTypes', 'ember-flexberry-dummy-application-user': 'id,name,eMail,phone1,phone2,phone3,activated,vK,facebook,twitter,birthday,gender,vip,karma', 'ember-flexberry-dummy-vote': 'id,suggestion,voteType,applicationUser', 'ember-flexberry-dummy-comment': 'id,suggestion,text,votes,moderated,author,*userVotes', 'ember-flexberry-dummy-comment-vote': 'id,comment,voteType,applicationUser', } }, }); let owner = Ember.getOwner(this); let Store = DS.Store; let onlineStore = Store.create(owner.ownerInjection()); this.set('onlineStore', onlineStore); this._super(...arguments); } });
Test dummy-app add offline schema for tests
Test dummy-app add offline schema for tests
JavaScript
mit
Flexberry/ember-flexberry-projections,Flexberry/ember-flexberry-data,Flexberry/ember-flexberry-projections,Flexberry/ember-flexberry-data,Flexberry/ember-flexberry-data
a51a480ac80d7123451ed45dca816d445c92d20e
src/routes/control.js
src/routes/control.js
// Manage the SHA of the latest control repository commit. var restify = require('restify'); var storage = require('../storage'); var log = require('../logging').getLogger(); exports.store = function (req, res, next) { if (req.params.sha === undefined) { return next(new restify.InvalidContentError('Missing required "sha" attribute')); } if (!/[0-9a-fA-F]{40}/.test(req.params.sha)) { return next(new restify.InvalidContentError('Not a valid "sha"')); } storage.storeSHA(req.params.sha, function (err) { next.ifError(err); res.send(204); log.info('Stored control repository SHA', { sha: req.params.sha }); next(); }); }; exports.retrieve = function (req, res, next) { storage.getSHA(function (err, sha) { next.ifError(err); res.json(200, {sha: sha}); log.info('Got control repository SHA', { sha: sha }); next(); }); };
// Manage the SHA of the latest control repository commit. var restify = require('restify'); var storage = require('../storage'); var log = require('../logging').getLogger(); exports.store = function (req, res, next) { if (req.params.sha === undefined) { return next(new restify.InvalidContentError('Missing required "sha" attribute')); } if (!/[0-9a-fA-F]{40}/.test(req.params.sha)) { return next(new restify.InvalidContentError('Not a valid "sha"')); } storage.storeSHA(req.params.sha, function (err) { next.ifError(err); res.send(204); log.info('Stored control repository SHA', { sha: req.params.sha }); next(); }); }; exports.retrieve = function (req, res, next) { storage.getSHA(function (err, sha) { next.ifError(err); res.json(200, {sha: sha}); next(); }); };
Remove a misleading log message.
Remove a misleading log message.
JavaScript
mit
deconst/content-service,deconst/content-service
0123500c30cb7acf695d5486b161f3b4ecd3b545
test/trie.js
test/trie.js
var Trie = require('../app/trie'); describe('Trie', function() { var trie; beforeEach(function() { trie = new Trie(); }); it('should be an object', function() { expect(trie).to.be.ok; }); it('should have a root', function() { expect(trie.root).to.be.ok; }); it('should have add method', function() { expect(trie.add).to.be.an.instanceof(Function); }); it('should have search method', function() { expect(trie.search).to.be.an.instanceof(Function); }); it('should have find method', function() { expect(trie.find).to.be.an.instanceof(Function); }); it('should add string to trie', function() { expect(trie.add('test')).to.be.undefined; }); it('should correctly find an added string', function() { trie.add('test'); expect(trie.find('test')).to.be.true; }); });
var Trie = require('../app/trie'); describe('Trie', function() { var trie; beforeEach(function() { trie = new Trie(); }); it('should be an object', function() { expect(trie).to.be.ok; }); it('should have a root', function() { expect(trie.root).to.be.ok; }); it('should have add method', function() { expect(trie.add).to.be.an.instanceof(Function); }); it('should have search method', function() { expect(trie.search).to.be.an.instanceof(Function); }); it('should have find method', function() { expect(trie.find).to.be.an.instanceof(Function); }); it('should add string to trie', function() { expect(trie.add('test')).to.be.undefined; }); it('should correctly find an added string', function() { trie.add('test'); expect(trie.find('test')).to.be.true; }); it('should trim leading/trailing spaces when adding a string', function() { trie.add(' test '); expect(trie.find('test')).to.be.true; }); });
Add test for trimming leading/trailing whitespace
Add test for trimming leading/trailing whitespace
JavaScript
mit
mgarbacz/nordrassil,mgarbacz/nordrassil
21c33458f27ade177cdced1f2f9adba321883274
protractor-demo/conf.js
protractor-demo/conf.js
// An example configuration file. exports.config = { // The address of a running selenium server. //seleniumAddress: 'http://localhost:4444/wd/hub', // Capabilities to be passed to the webdriver instance. capabilities: { 'browserName': 'chrome' }, // Spec patterns are relative to the location of the spec file. They may // include glob patterns. specs: ['*.spec.js'], // Options to be passed to Jasmine-node. jasmineNodeOpts: { showColors: true, // Use colors in the command line report. } };
// An example configuration file. exports.config = { // The address of a running selenium server. //seleniumAddress: 'http://localhost:4444/wd/hub', // Capabilities to be passed to the webdriver instance. capabilities: { 'browserName': 'chrome' }, allScriptsTimeout: 11000, // Spec patterns are relative to the location of the spec file. They may // include glob patterns. specs: ['*.spec.js'], // Options to be passed to Jasmine-node. jasmineNodeOpts: { showColors: true, // Use colors in the command line report. defaultTimeoutInterval: 30000 } };
Add timeouts to protractor demo
Add timeouts to protractor demo
JavaScript
mit
petebacondarwin/angularjs-testing-presentation
802462643c25d33f0632b0a58671094277f8a541
examples/producer.js
examples/producer.js
var starsky = require('..'); setInterval(function () { starsky.publish('starsky.test', { subject: 'test message' }); }, 1000); starsky.connect();
var starsky = require('..'); starsky.configure(__dirname + '/config.yml'); setInterval(function () { starsky.publish('starsky.test', { subject: 'test message' }, confirm); }, 1000); function confirm (err) { if (err) console.error(err.message); } starsky.connect();
Add confirm callback to example
Add confirm callback to example
JavaScript
mit
recurly/starsky
b1e159223635a33ba2c3e5ad239b0dd50baa5bad
src/apps/contacts/middleware/collection.js
src/apps/contacts/middleware/collection.js
const { pick, mapValues, isArray, pickBy, get } = require('lodash') const { search } = require('../../search/services') const { transformApiResponseToSearchCollection } = require('../../search/transformers') const { transformContactToListItem } = require('../transformers') const removeArray = require('../../../lib/remove-array') async function getContactsCollection (req, res, next) { try { res.locals.results = await search({ searchEntity: 'contact', requestBody: req.body, token: req.session.token, page: req.query.page, isAggregation: false, }) .then(transformApiResponseToSearchCollection( { query: req.query }, transformContactToListItem, )) next() } catch (error) { next(error) } } function getRequestBody (req, res, next) { const selectedFiltersQuery = removeArray(pick(req.query, [ 'archived', 'company_name', 'company_sector', 'address_country', 'company_uk_region', ]), 'archived') mapValues(get(selectedFiltersQuery, 'archived'), (value) => { return isArray(value) ? null : value }) const selectedSortBy = req.query.sortby ? { sortby: req.query.sortby } : null req.body = Object.assign({}, req.body, selectedSortBy, pickBy(selectedFiltersQuery)) next() } module.exports = { getContactsCollection, getRequestBody, }
const { pick, mapValues, isArray, pickBy, get } = require('lodash') const { search } = require('../../search/services') const { transformApiResponseToSearchCollection } = require('../../search/transformers') const { transformContactToListItem } = require('../transformers') const removeArray = require('../../../lib/remove-array') async function getContactsCollection (req, res, next) { try { res.locals.results = await search({ searchEntity: 'contact', requestBody: req.body, token: req.session.token, page: req.query.page, isAggregation: false, }) .then(transformApiResponseToSearchCollection( { query: req.query }, transformContactToListItem, )) next() } catch (error) { next(error) } } function getRequestBody (req, res, next) { const selectedFiltersQuery = removeArray(pick(req.query, [ 'archived', 'name', 'company_name', 'company_sector', 'address_country', 'company_uk_region', ]), 'archived') mapValues(get(selectedFiltersQuery, 'archived'), (value) => { return isArray(value) ? null : value }) const selectedSortBy = req.query.sortby ? { sortby: req.query.sortby } : null req.body = Object.assign({}, req.body, selectedSortBy, pickBy(selectedFiltersQuery)) next() } module.exports = { getContactsCollection, getRequestBody, }
Add support to the contact list middleware for contact name
Add support to the contact list middleware for contact name
JavaScript
mit
uktrade/data-hub-fe-beta2,uktrade/data-hub-frontend,uktrade/data-hub-frontend,uktrade/data-hub-fe-beta2,uktrade/data-hub-frontend
e235cdc5790481504b81622b52b9049cb97ef5a0
models/profile.js
models/profile.js
// Profile Model module.exports = function(sequelize, DataTypes) { var Profile = sequelize.define('Profile', { tagLine: { type: DataTypes.STRING, allowNull: false }, description: { type: DataTypes.TEXT, allowNull: false } }, { associate: function(models) { Profile.hasMany(models.ProfileItem); } }); return Profile; }
// Profile Model module.exports = function(sequelize, DataTypes) { var Profile = sequelize.define('Profile', { tagLine: { type: DataTypes.STRING, allowNull: false }, description: { type: DataTypes.TEXT, allowNull: false }, votes: { type: DataTypes.INTEGER, defaultValue: 0 } }, { associate: function(models) { Profile.hasMany(models.ProfileItem); } }); return Profile; }
Add 'votes' field to Profile model
Add 'votes' field to Profile model
JavaScript
mit
kocsenc/nodejs-tutorme,kocsenc/nodejs-tutorme
ca2cbd5b3f051ac74922da0fa7ab7b3d1f5630a8
lib/assert-full-equal/utilities.js
lib/assert-full-equal/utilities.js
'use strict'; function isObject(/* subjects... */) { var index, length = arguments.length, current; if (length < 1) { return false; } for (index = 0; index < length; index += 1) { current = arguments[index]; if (('object' !== typeof current) || (null === current)) { return false; } } return true; } function isInstanceOf(constructor /*, subjects... */) { var index, length = arguments.length; if (length < 2) { return false; } for (index = 1; index < length; index += 1) { if (!(arguments[index] instanceof constructor)) { return false; } } return true; } function xor(left, right) { return (left && !right) || (!left && right); } module.exports.isObject = isObject; module.exports.isInstanceOf = isInstanceOf; module.exports.xor = xor;
'use strict'; function isObject(/* subjects... */) { var index, length = arguments.length, current; if (length < 1) { return false; } for (index = 0; index < length; index += 1) { current = arguments[index]; if (('object' !== typeof current) || (null === current)) { return false; } } return true; } function isInstanceOf(constructor /*, subjects... */) { var index, length = arguments.length; if (length < 2) { return false; } for (index = 1; index < length; index += 1) { if (!(arguments[index] instanceof constructor)) { return false; } } return true; } module.exports.isObject = isObject; module.exports.isInstanceOf = isInstanceOf;
Remove unused `xor` utility function
Remove unused `xor` utility function
JavaScript
mit
dervus/assert-paranoid-equal
57addfba221451214ed59738f528c5febfc5265b
src/types/var-type.js
src/types/var-type.js
const DocumentedItem = require('./item'); class DocumentedVarType extends DocumentedItem { registerMetaInfo(data) { this.directData = data; } serialize() { const names = []; for(const name of this.directData.names) names.push(this.constructor.splitVarName(name)); if(!this.directData.description && !this.directData.nullable) return names; return { types: names, description: this.directData.description, nullable: this.directData.nullable }; } static splitVarName(str) { if(str === '*') return ['*']; const matches = str.match(/([\w*]+)([^\w*]+)/g); const output = []; if(matches) { for(const match of matches) { const groups = match.match(/([\w*]+)([^\w*]+)/); output.push([groups[1], groups[2]]); } } else { output.push([str.match(/([\w*]+)/g)[0]]); } return output; } } /* { "names":[ "String" ] } */ module.exports = DocumentedVarType;
const DocumentedItem = require('./item'); class DocumentedVarType extends DocumentedItem { registerMetaInfo(data) { this.directData = data; } serialize() { const names = []; for(const name of this.directData.names) names.push(this.constructor.splitVarName(name)); if(!this.directData.description && !this.directData.nullable) return names; return { types: names, description: this.directData.description, nullable: this.directData.nullable }; } static splitVarName(str) { if(str === '*') return ['*']; str = str.replace(/\./g, ''); const matches = str.match(/([\w*]+)([^\w*]+)/g); const output = []; if(matches) { for(const match of matches) { const groups = match.match(/([\w*]+)([^\w*]+)/); output.push([groups[1], groups[2]]); } } else { output.push([str.match(/([\w*]+)/g)[0]]); } return output; } } /* { "names":[ "String" ] } */ module.exports = DocumentedVarType;
Remove dots from generic types
Remove dots from generic types
JavaScript
apache-2.0
hydrabolt/discord.js-docgen
fa071535ee1bd3ea9421d98903d39803558405b8
back/routes/city.router.js
back/routes/city.router.js
/** * @fileOverview Routes for City. */ var log = require('logg').getLogger('app.router.city'); var HomeCtrl = require('../controllers/city/index.ctrl'); var StaticsCtrl = require('../controllers/city/statics.ctrl'); var router = module.exports = {}; /** * Initialize routes. * * @param {express} app Express instance. */ router.init = function(app) { log.fine('init() :: initializing routes...'); var homeCtrl = HomeCtrl.getInstance(); var staticsCtrl = StaticsCtrl.getInstance(); app.get('/', homeCtrl.use); app.get('/submit-event/', staticsCtrl.use); };
/** * @fileOverview Routes for City. */ var log = require('logg').getLogger('app.router.city'); var HomeCtrl = require('../controllers/city/index.ctrl'); var StaticsCtrl = require('../controllers/city/statics.ctrl'); var TogetherCtrl = require('../controllers/city/together.ctrl'); var router = module.exports = {}; /** * Initialize routes. * * @param {express} app Express instance. */ router.init = function(app) { log.fine('init() :: initializing routes...'); var homeCtrl = HomeCtrl.getInstance(); var staticsCtrl = StaticsCtrl.getInstance(); var togetherCtrl = TogetherCtrl.getInstance(); app.get('/', homeCtrl.use); app.get('/submit-event', staticsCtrl.use); app.get('/together', togetherCtrl.use); };
Add route for together event
Add route for together event
JavaScript
mpl-2.0
WeAreTech/wearetech.io,WeAreRoots/weareroots.org,WeAreTech/wearetech.io
dcd4c2c790536ee755b42f9cc0a51b5cdb6f04e7
js/chartist2image-with-svg2bitmap.js
js/chartist2image-with-svg2bitmap.js
window.onload = function() { createChart('.ct-chart', true); document.getElementById('button1').onclick = function () { var chartDivNode = document.getElementById('chart'); var chartSvgNode = chartDivNode.children[0]; SVG2Bitmap(chartSvgNode, document.getElementById('canvas')); }; document.getElementById('button2').onclick = function () { var dataURL = document.getElementById('canvas').toDataURL(); document.getElementById('image').src = dataURL; }; }
window.onload = function() { // using true as the second parameter we force chartist.js to use plain SVG not <foreignObject> createChart('.ct-chart', true); document.getElementById('button1').onclick = function () { var chartDivNode = document.getElementById('chart'); var chartSvgNode = chartDivNode.children[0]; // SVG2Bitmap will render the chartist SVG code and create all necessary inline styles SVG2Bitmap(chartSvgNode, document.getElementById('canvas')); }; document.getElementById('button2').onclick = function () { var dataURL = document.getElementById('canvas').toDataURL(); document.getElementById('image').src = dataURL; }; }
Comment added to the JS code
Comment added to the JS code
JavaScript
apache-2.0
giraone/chartist2image,giraone/chartist2image
097e4552a3f47a38bc4ae97eb53993f13106904e
vendor/ember-cli-qunit/test-loader.js
vendor/ember-cli-qunit/test-loader.js
/* globals jQuery,QUnit */ jQuery(document).ready(function() { var TestLoader = require('ember-cli/test-loader')['default']; TestLoader.prototype.shouldLoadModule = function(moduleName) { return moduleName.match(/\/.*[-_]test$/) || (!QUnit.urlParams.nojshint && moduleName.match(/\.jshint$/)); }; TestLoader.prototype.moduleLoadFailure = function(moduleName, error) { QUnit.module('TestLoader Failures'); QUnit.test(moduleName + ': could not be loaded', function() { throw error; }); }; var autostart = QUnit.config.autostart !== false; QUnit.config.autostart = false; setTimeout(function() { TestLoader.load(); if (autostart) { QUnit.start(); } }, 250); });
/* globals jQuery,QUnit */ jQuery(document).ready(function() { var TestLoaderModule = require('ember-cli/test-loader'); var TestLoader = TestLoaderModule['default']; var addModuleIncludeMatcher = TestLoaderModule['addModuleIncludeMatcher']; function moduleMatcher(moduleName) { return moduleName.match(/\/.*[-_]test$/) || (!QUnit.urlParams.nojshint && moduleName.match(/\.jshint$/)); } if (addModuleIncludeMatcher) { addModuleIncludeMatcher(moduleMatcher); } else { TestLoader.prototype.shouldLoadModule = moduleMatcher; } TestLoader.prototype.moduleLoadFailure = function(moduleName, error) { QUnit.module('TestLoader Failures'); QUnit.test(moduleName + ': could not be loaded', function() { throw error; }); }; var autostart = QUnit.config.autostart !== false; QUnit.config.autostart = false; setTimeout(function() { TestLoader.load(); if (autostart) { QUnit.start(); } }, 250); });
Use addModuleIncludeMatcher instead of prototype mutation.
Use addModuleIncludeMatcher instead of prototype mutation.
JavaScript
mit
ember-cli/ember-cli-qunit,nathanhammond/ember-cli-qunit,ember-cli/ember-cli-qunit,nathanhammond/ember-cli-qunit
407de35036baf8aec2cca3f0bf6dede8870fa327
public/javascripts/pluginUpload.js
public/javascripts/pluginUpload.js
var MAX_FILE_SIZE = 1048576; $(function() { $('#pluginFile').on('change', function() { var alert = $('.alert-file'); var fileName = $(this).val().trim(); var fileSize = this.files[0].size; if (!fileName) { alert.fadeOut(1000); return; } if (fileSize > MAX_FILE_SIZE) { alert.find('i').removeClass('fa-upload').addClass('fa-times'); alert.find('.file-upload').find('button') .removeClass('btn-success') .addClass('btn-danger') .prop('disabled', true); alert.find('.file-size').css('color', '#d9534f'); } fileName = fileName.substr(fileName.lastIndexOf('\\') + 1, fileName.length); alert.find('.file-name').text(fileName); alert.find('.file-size').text(filesize(this.files[0].size)); alert.fadeIn('slow'); }); });
var MAX_FILE_SIZE = 1048576; $(function() { $('#pluginFile').on('change', function() { var alert = $('.alert-file'); var fileName = $(this).val().trim(); var fileSize = this.files[0].size; if (!fileName) { alert.fadeOut(1000); return; } if (fileSize > MAX_FILE_SIZE) { alert.find('i').removeClass('fa-upload').addClass('fa-times'); alert.find('.file-upload').find('button') .removeClass('btn-success') .addClass('btn-danger') .prop('disabled', true); alert.find('.file-size').css('color', '#d9534f'); } fileName = fileName.substr(fileName.lastIndexOf('\\') + 1, fileName.length); alert.find('.file-name').text(fileName); alert.find('.file-size').text(filesize(this.files[0].size)); alert.fadeIn('slow'); }); $('.file-upload').find('button').click(function() { $(this).find('i').removeClass('fa-upload').addClass('fa-spinner fa-spin'); }); });
Add spinner to upload button
Add spinner to upload button Signed-off-by: Walker Crouse <a52c6ce3cf7a08dcbb27377aa79f9b994b446d4c@hotmail.com>
JavaScript
mit
SpongePowered/Ore,SpongePowered/Ore,SpongePowered/Ore,SpongePowered/Ore,SpongePowered/Ore
2c8a9fb5fe88c71970af1ad428221251136307eb
functions/helper-intents/ask-for-datetime.js
functions/helper-intents/ask-for-datetime.js
// Copyright 2018, Google, Inc. // 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. const {DateTime} = require('actions-on-google'); module.exports = { 'ask_for_datetime': (conv) => { const options = { prompts: { initial: 'When would you like to schedule the appointment?', date: 'What day was that?', time: 'What time?', }, }; conv.ask(new DateTime(options)); }, 'ask_for_datetime_confirmation': (conv, params, datetime) => { const { month, day } = datetime.date const { hours, minutes } = datetime.time conv.ask(`<speak> Great, we will see you on <say-as interpret-as="date" format="dm">${day}-${month}</say-as> <say-as interpret-as="time" format="hms12" detail="2">${hours}:${minutes || '00'}</say-as> </speak>`); }, };
// Copyright 2018, Google, Inc. // 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. const {DateTime} = require('actions-on-google'); module.exports = { 'ask_for_datetime': (conv) => { const options = { prompts: { initial: 'When would you like to schedule the appointment?', date: 'What day was that?', time: 'What time?', }, }; conv.ask(new DateTime(options)); }, 'ask_for_datetime_confirmation': (conv, params, datetime) => { const { month, day } = datetime.date const { hours, minutes } = datetime.time conv.ask(`<speak>` + `Great, we will see you on ` + `<say-as interpret-as="date" format="dm">${day}-${month}</say-as>` + `<say-as interpret-as="time" format="hms12" detail="2">${hours}:${minutes || '00'}</say-as>` + `</speak>`); }, };
Remove spaces from datetime SSML response.
Remove spaces from datetime SSML response. bug: b/124764992 Change-Id: I846c6e96311350215b2237ebc213c12fc4e79610
JavaScript
apache-2.0
actions-on-google/dialogflow-helper-intents-nodejs
33619ceac4f7453c87c02610ef297af0d76beee9
gulp/tasks/styles.js
gulp/tasks/styles.js
'use strict'; var config = require('../config'); var gulp = require('gulp'); var sass = require('gulp-sass'); var gulpif = require('gulp-if'); var handleErrors = require('../util/handleErrors'); var browserSync = require('browser-sync'); var autoprefixer = require('gulp-autoprefixer'); gulp.task('styles', function () { return gulp.src(config.styles.src) .pipe(sass({ includePaths: [ './node_modules/bootstrap-sass/assets/stylesheets', ], sourceComments: global.isProd ? 'none' : 'map', sourceMap: 'sass', outputStyle: global.isProd ? 'compressed' : 'nested' })) .pipe(autoprefixer("last 2 versions", "> 1%", "ie 8")) .on('error', handleErrors) .pipe(gulp.dest(config.styles.dest)) .pipe(gulpif(browserSync.active, browserSync.reload({ stream: true }))); });
'use strict'; var config = require('../config'); var gulp = require('gulp'); var sass = require('gulp-sass'); var gulpif = require('gulp-if'); var handleErrors = require('../util/handleErrors'); var browserSync = require('browser-sync'); var autoprefixer = require('gulp-autoprefixer'); gulp.task('styles', function () { return gulp.src(config.styles.src) .pipe(sass({ includePaths: [ './node_modules/bootstrap-sass/assets/stylesheets', ], sourceComments: global.isProd ? 'none' : 'map', sourceMap: 'sass', outputStyle: global.isProd ? 'compressed' : 'nested', errLogToConsole: true })) .pipe(autoprefixer("last 2 versions", "> 1%", "ie 8")) .on('error', handleErrors) .pipe(gulp.dest(config.styles.dest)) .pipe(gulpif(browserSync.active, browserSync.reload({ stream: true }))); });
Add option to not break pipe when sass syntax error
Add option to not break pipe when sass syntax error
JavaScript
mit
loklak/loklak_webclient,loklak/loklak_webclient,aayusharora/loklak_webclient,aayusharora/loklak_webclient,codethejason/loklak_webclient,loklak/loklak_webclient,codethejason/loklak_webclient,codethejason/loklak_webclient,aayusharora/loklak_webclient
fe70897411c2109d1cbc725068e96ae177dfdbb9
lib/composition/node/subelm/index.js
lib/composition/node/subelm/index.js
var Deffy = require("deffy") function SubElm(data, parent) { this.name = data.name; this.label = Deffy(data.label, this.name); this.type = data.type; this.id = [this.type, parent.name, this.name].join("_"); } module.exports = SubElm;
var Deffy = require("deffy") , Typpy = require("typpy") ; function SubElm(type, data, parent) { if (Typpy(data, SubElm)) { return data; } this.name = data.name || data.event || data.method; this.label = Deffy(data.label, this.name); this.type = type; this.id = [this.type, parent.name, this.name].join("_"); } module.exports = SubElm;
Set the sub element name
Set the sub element name
JavaScript
mit
jillix/engine-builder
edfeb5b06100df3c2ccc46eb56edc9224624b96b
packages/ember-cli-fastboot/vendor/experimental-render-mode-rehydrate.js
packages/ember-cli-fastboot/vendor/experimental-render-mode-rehydrate.js
(function() { if (typeof FastBoot === 'undefined') { var current = document.getElementById('fastboot-body-start'); if ( current && typeof Ember.ViewUtils.isSerializationFirstNode === 'function' && Ember.ViewUtils.isSerializationFirstNode(current.nextSibling) ) { Ember.ApplicationInstance.reopen({ _bootSync: function(options) { if (options === undefined) { options = { _renderMode: 'rehydrate' }; } return this._super(options); } }); // Prevent clearRender by removing `fastboot-body-start` which is already // guarded for current.parentNode.removeChild(current); var end = document.getElementById('fastboot-body-end'); if (end) { end.parentNode.removeChild(end); } } } })();
(function() { if (typeof FastBoot === 'undefined') { var current = document.getElementById('fastboot-body-start'); var Ember = require('ember').default; if ( current && typeof Ember.ViewUtils.isSerializationFirstNode === 'function' && Ember.ViewUtils.isSerializationFirstNode(current.nextSibling) ) { Ember.ApplicationInstance.reopen({ _bootSync: function(options) { if (options === undefined) { options = { _renderMode: 'rehydrate' }; } return this._super(options); } }); // Prevent clearRender by removing `fastboot-body-start` which is already // guarded for current.parentNode.removeChild(current); var end = document.getElementById('fastboot-body-end'); if (end) { end.parentNode.removeChild(end); } } } })();
Fix use of Ember global
Fix use of Ember global Fixes #827
JavaScript
mit
ember-fastboot/ember-cli-fastboot,ember-fastboot/ember-cli-fastboot
d3ced289507adb4840c6bfdbb53dc015c864e190
website/index.js
website/index.js
/* global window */ /* @jsx createElement */ // @flow // eslint-disable-next-line no-unused-vars import { createElement } from 'jsx-dom'; import { watch } from '../core'; // $FlowFixMe import cardInfoHeader from '../assets/tooltip-header-sprite.png'; // $FlowFixMe import cardInfoBackground from '../assets/tooltip-text-background.png'; // $FlowFixMe import Gwent from '../assets/fonts/hinted-GWENT-ExtraBold.woff2'; // $FlowFixMe import HalisGRRegular from '../assets/fonts/hinted-HalisGR-Regular.woff2'; // $FlowFixMe import HalisGRBold from '../assets/fonts/hinted-HalisGR-Bold.woff2'; // Setup the homepage async function onLoad() { // fetch card data const { cards, dictionary } = await fetchJson('./data.json'); // Start watching the whole body for card names. watch( window.document.body, { cards, dictionary, assets: { cardInfoHeader, cardInfoBackground, Gwent, HalisGRRegular, HalisGRBold } }, { shouldUnderline: true } ); } async function fetchJson(src: string): Promise<Object> { const response = await window.fetch(src); const json = await response.json(); return json; } onLoad();
/* global window */ /* @jsx createElement */ // @flow // eslint-disable-next-line no-unused-vars import { createElement } from 'jsx-dom'; import { watch } from '../core'; // $FlowFixMe import cardInfoHeader from '../assets/tooltip-header-sprite.png'; // $FlowFixMe import cardInfoBackground from '../assets/tooltip-text-background.png'; // $FlowFixMe import Gwent from '../assets/fonts/hinted-GWENT-ExtraBold.woff2'; // $FlowFixMe import HalisGRRegular from '../assets/fonts/hinted-HalisGR-Regular.woff2'; // $FlowFixMe import HalisGRBold from '../assets/fonts/hinted-HalisGR-Bold.woff2'; // $FlowFixMe importing so that it is copied to the font folder import '../assets/fonts/hinted-HalisGR-Book.woff2'; // Setup the homepage async function onLoad() { // fetch card data const { cards, dictionary } = await fetchJson('./data.json'); // Start watching the whole body for card names. watch( window.document.body, { cards, dictionary, assets: { cardInfoHeader, cardInfoBackground, Gwent, HalisGRRegular, HalisGRBold } }, { shouldUnderline: true } ); } async function fetchJson(src: string): Promise<Object> { const response = await window.fetch(src); const json = await response.json(); return json; } onLoad();
Fix missing Halis Book font on website
Fix missing Halis Book font on website
JavaScript
mit
Soreine/hyper-gwent,Soreine/hyper-gwent,Soreine/hyper-gwent
84a40d835cb1f4d6abcfd44db26b342a6ba8dbb3
webpack/build.js
webpack/build.js
const esbuild = require("esbuild"); const isProduction = false; esbuild.buildSync({ entryPoints: ['./src/platform/current/server/serverStartup.ts'], bundle: true, outfile: './build/server/js/bundle2.js', platform: "node", sourcemap: true, minify: false, define: { "process.env.NODE_ENV": isProduction ? "\"production\"" : "\"development\"", "webpackIsServer": true, }, external: [ "akismet-api", "mongodb", "canvas", "express", "mz", "pg", "pg-promise", "mathjax", "mathjax-node", "jsdom", "@sentry/node", "node-fetch", "later", "turndown", "apollo-server", "apollo-server-express", "graphql", "bcrypt", "node-pre-gyp", "@lesswrong", ], }) esbuild.buildSync({ entryPoints: ['./src/platform/current/client/clientStartup.ts'], bundle: true, target: "es6", sourcemap: true, outfile: "./build/client/js/bundle.js", minify: false, define: { "process.env.NODE_ENV": isProduction ? "\"production\"" : "\"development\"", "webpackIsServer": false, "global": "window", }, });
const esbuild = require("esbuild"); const isProduction = false; esbuild.buildSync({ entryPoints: ['./src/platform/current/server/serverStartup.ts'], bundle: true, outfile: './build/server/js/bundle2.js', platform: "node", sourcemap: true, minify: false, define: { "process.env.NODE_ENV": isProduction ? "\"production\"" : "\"development\"", "webpackIsServer": true, }, external: [ "akismet-api", "mongodb", "canvas", "express", "mz", "pg", "pg-promise", "mathjax", "mathjax-node", "mathjax-node-page", "jsdom", "@sentry/node", "node-fetch", "later", "turndown", "apollo-server", "apollo-server-express", "graphql", "bcrypt", "node-pre-gyp", "@lesswrong", "intercom-client", ], }) esbuild.buildSync({ entryPoints: ['./src/platform/current/client/clientStartup.ts'], bundle: true, target: "es6", sourcemap: true, outfile: "./build/client/js/bundle.js", minify: false, define: { "process.env.NODE_ENV": isProduction ? "\"production\"" : "\"development\"", "webpackIsServer": false, "global": "window", }, });
Fix crash in intercom on server navigation events
Fix crash in intercom on server navigation events
JavaScript
mit
Discordius/Lesswrong2,Discordius/Lesswrong2,Discordius/Lesswrong2,Discordius/Lesswrong2
a169d2ecdb6e7d4457eadfc15f33129847c370ec
app/assets/javascripts/angular/common/models/review-model.js
app/assets/javascripts/angular/common/models/review-model.js
(function(){ 'use strict'; angular .module('secondLead') .factory('ReviewModel',['Restangular', 'store', function(Restangular, store) { var currentUser = store.get('user'); return { getAll: function(dramaID){ return Restangular.one('dramas', dramaID).getList('reviews').$object }, getOne: function(dramaID, reviewID) { return Restangular.one('dramas', dramaID).one('reviews', reviewID).get() } }; }]) })();
(function(){ 'use strict'; angular .module('secondLead') .factory('ReviewModel',['Restangular', 'store', function(Restangular, store) { var currentUser = store.get('user'); return { getAll: function(dramaID){ return Restangular.one('dramas', dramaID).getList('reviews').$object }, getOne: function(dramaID, reviewID) { return Restangular.one('dramas', dramaID).one('reviews', reviewID).get() }, create: function(dramaID, userID, review) { return Restangular.one('dramas', dramaID).getList('reviews').post({drama_id: dramaID, body: review, reviewer_id: userID}) }, update: function(dramaID, reviewID,review){ return Restangular.one('dramas', dramaID).one('reviews', reviewID).put({body: review}) } }; }]) })();
Add create and update functions to ang review model
Add create and update functions to ang review model
JavaScript
mit
ac-adekunle/secondlead,ac-adekunle/secondlead,ac-adekunle/secondlead
c210a34a20955ac96f5d8bc0913f5aa8e2aa6634
blueprints/ember-cli-mirage/files/app/mirage/factories/contact.js
blueprints/ember-cli-mirage/files/app/mirage/factories/contact.js
/* This is an example factory definition. Factories are used inside acceptance tests. Create more files in this directory to define additional factories. */ import Mirage from 'ember-cli-mirage'; export default Mirage.Factory.extend({ name: 'Pete', age: 20, email: (i) => `person${i}@test.com`, admin: function() { return this.age > 30; } });
/* This is an example factory definition. Factories are used inside acceptance tests. Create more files in this directory to define additional factories. */ import Mirage from 'ember-cli-mirage'; export default Mirage.Factory.extend({ // name: 'Pete', // strings // age: 20, // numbers // tall: true, // booleans // email: (i) => `person${i}@test.com`, // and functions // admin: function() { // return this.age > 30; // } });
Update blueprint to use comments
Update blueprint to use comments
JavaScript
mit
unchartedcode/ember-cli-mirage,martinmaillard/ember-cli-mirage,PrecisionNutrition/ember-cli-mirage,mixonic/ember-cli-mirage,kategengler/ember-cli-mirage,flexyford/ember-cli-mirage,rubygiulioni/testing-waffle,lazybensch/ember-cli-mirage,andrei1089/ember-cli-mirage,samselikoff/ember-cli-mirage,alecho/ember-cli-mirage,makepanic/ember-cli-mirage,mixonic/ember-cli-mirage,oliverbarnes/ember-cli-mirage,andrei1089/ember-cli-mirage,HeroicEric/ember-cli-mirage,ronco/ember-cli-mirage,IAmJulianAcosta/ember-cli-mirage,flexyford/ember-cli-mirage,cibernox/ember-cli-mirage,samselikoff/ember-cli-mirage,samselikoff/ember-cli-mirage,oliverbarnes/ember-cli-mirage,jamesdixon/ember-cli-mirage,PrecisionNutrition/ember-cli-mirage,alecho/ember-cli-mirage,jamesdixon/ember-cli-mirage,maxcal/ember-cli-mirage,LevelbossMike/ember-cli-mirage,HeroicEric/ember-cli-mirage,escobera/ember-cli-mirage,samselikoff/ember-cli-mirage,cs3b/ember-cli-mirage,jerel/ember-cli-mirage,ibroadfo/ember-cli-mirage,alvinvogelzang/ember-cli-mirage,seawatts/ember-cli-mirage,rubygiulioni/testing-waffle,ronco/ember-cli-mirage,lazybensch/ember-cli-mirage,ballPointPenguin/ember-cli-mirage,blimmer/ember-cli-mirage,mrandre/ember-cli-mirage,kategengler/ember-cli-mirage,jherdman/ember-cli-mirage,martinmaillard/ember-cli-mirage,lependu/ember-cli-mirage,makepanic/ember-cli-mirage,mydea/ember-cli-mirage,mydea/ember-cli-mirage,bantic/ember-cli-mirage,constantm/ember-cli-mirage,unchartedcode/ember-cli-mirage,unchartedcode/ember-cli-mirage,alvinvogelzang/ember-cli-mirage,cibernox/ember-cli-mirage,jherdman/ember-cli-mirage,mfeckie/ember-cli-mirage,bantic/ember-cli-mirage,mfeckie/ember-cli-mirage,lependu/ember-cli-mirage,seawatts/ember-cli-mirage,kagemusha/ember-cli-mirage,escobera/ember-cli-mirage,jerel/ember-cli-mirage,maxcal/ember-cli-mirage,IAmJulianAcosta/ember-cli-mirage,cs3b/ember-cli-mirage,blimmer/ember-cli-mirage,ghedamat/ember-cli-mirage,jherdman/ember-cli-mirage,LevelbossMike/ember-cli-mirage,jherdman/ember-cli-mirage,unchartedcode/ember-cli-mirage,mrandre/ember-cli-mirage,kagemusha/ember-cli-mirage,ibroadfo/ember-cli-mirage,ghedamat/ember-cli-mirage,ballPointPenguin/ember-cli-mirage,constantm/ember-cli-mirage
eb26baf49634cc1547b2a8a9be0befac551c11ac
src/app-webapp/app/components/new-question/new-question.js
src/app-webapp/app/components/new-question/new-question.js
import React from 'react' class NewQuestion extends React.Component { render () { return <div> <h2>Create a New Question</h2> </div> } } export default NewQuestion
import React from 'react' import { Form, FormGroup, ControlLabel, FormControl, Col } from 'react-bootstrap' import Button from 'react-bootstrap-button-loader' class NewQuestion extends React.Component { constructor (props) { super(props) this.state = { question: '', answer: '', isLoading: false } this.handleChange = this.handleChange.bind(this) this.onSubmit = this.onSubmit.bind(this) } render () { return <div> <h2>Create a New Question</h2> <Form horizontal> <FormGroup> <Col sm={2} componentClass={ControlLabel}>Question</Col> <Col sm={10}> <FormControl componentClass='textarea' name='question' value={this.state.question} placeholder='Enter your question here...' onChange={this.handleChange} /> </Col> </FormGroup> <FormGroup> <Col sm={2} componentClass={ControlLabel}>Answer</Col> <Col sm={10}> <FormControl type='text' name='answer' value={this.state.answer} placeholder='Enter the correct answer here...' onChange={this.handleChange} /> </Col> </FormGroup> <FormGroup> <Col smOffset={2} sm={10}> <Button bsStyle='primary' bsSize='large' loading={this.state.isLoading} disabled={!this.validFormInput()} onClick={this.onSubmit} > Create </Button> </Col> </FormGroup> </Form> </div> } handleChange (event) { let target = event.target this.setState({ [target.name]: target.value }) } onSubmit () { this.setState({ isLoading: true }) } validFormInput () { return this.state.question !== '' && this.state.answer !== '' } } export default NewQuestion
Add form for for creating a new question.
Add form for for creating a new question.
JavaScript
mit
Charterhouse/NextBuild2017,Charterhouse/NextBuild2017,Charterhouse/NextBuild2017
5f80a1d7d6737168e211e8e04f70a0baaf2864b5
app/aptible/torii-provider.js
app/aptible/torii-provider.js
import BaseProvider from "torii/providers/base"; import ajax from "../utils/ajax"; import config from "../config/environment"; export default BaseProvider.extend({ open: function(credentials){ return ajax(config.authBaseUri+'/tokens', { type: 'POST', data: credentials }).catch(function(jqXHR){ if (jqXHR.responseJSON) { throw new Error(jqXHR.responseJSON.message); } else if (jqXHR.responseText) { throw new Error(jqXHR.responseText); } else { throw new Error("Unknown error from the server."); } }); } });
import BaseProvider from "torii/providers/base"; import ajax from "../utils/ajax"; import config from "../config/environment"; export default BaseProvider.extend({ open: function(credentials){ return ajax(config.authBaseUri+'/tokens', { type: 'POST', data: credentials, xhrFields: { withCredentials: true } }).catch(function(jqXHR){ if (jqXHR.responseJSON) { throw new Error(jqXHR.responseJSON.message); } else if (jqXHR.responseText) { throw new Error(jqXHR.responseText); } else { throw new Error("Unknown error from the server."); } }); } });
Send the cookies with the request
Send the cookies with the request
JavaScript
mit
blakepettersson/dashboard.aptible.com,blakepettersson/dashboard.aptible.com,aptible/dashboard.aptible.com,aptible/dashboard.aptible.com,aptible/dashboard.aptible.com,blakepettersson/dashboard.aptible.com,chasballew/dashboard.aptible.com,chasballew/dashboard.aptible.com,chasballew/dashboard.aptible.com
7e950ec73d741059adb354a6d65d564a7b27ab5a
scripts/clients/git_diff.js
scripts/clients/git_diff.js
const { spawn } = require("child_process"); const gitCommand = "git"; const gitDiff = "diff"; const statOption = "--numstat"; function promisify(child_process) { return new Promise((resolve, reject) => { const result = ""; child_process.stdout.on('data', data => { result.push(data.toString()); }); child_process.on('error', (err) => { reject(err); }) child_process.on('close', () => { resolve(result); }); }); } module.exports = { getDiff: function (commit1, commit2, options) { const gitProcess = spawn(gitCommand, [gitDiff, statOption, commit1, commit2], { cwd: options.cwd }); return promisify(gitProcess); } }
const { spawn } = require("child_process"); const Promise = require("bluebird").Promise; const gitCommand = "git"; const gitDiff = "diff"; const statOption = "--numstat"; function promisify(child) { return new Promise((resolve, reject) => { let result = ""; child.stdout.on('data', data => { console.log(data.toString()); result += data; }); child.stderr.on('data', data => { console.error(data.toString()); }); child.on('error', (err) => { reject(err); }); child.on('exit', () => { resolve(result); }); }); } module.exports = { getDiff: function (commit1, commit2, options) { const gitProcess = spawn(gitCommand, [gitDiff, statOption, commit1, commit2], { // stdio: "inherit", cwd: options.cwd }); return promisify(gitProcess); } }
Return output from child process git diff
Return output from child process git diff
JavaScript
mit
ovidiup13/L5-ProjectSource
07a30d57ac292bbb630a78eb58f4995c702222f2
test/conversorTest.js
test/conversorTest.js
const chai = require('chai') const exec = require('child_process').exec var assert = chai.assert console.log('Testing the app') describe('Conversion Params', function () { // Further code for tests goes here it('If no params', function (done) { // Test implementation goes here exec('currencyconv', function (err, stdout, stderr) { assert.isNotNull(err) done() }) }) it('If no amount', function (done) { exec('currencyconv --f=USD --to=EUR --ouput=fulls', function (err, stdout, stderr) { assert.isNull(err) assert.strictEqual(stdout, 'Amount param should be defined\n') done() }) }) }) describe('Conversion Logic', function () { it('If currency does not exist', function (done) { exec('currencyconv --f=USDG --to=EURs --ouput=fulls 1', function (err, stdout, stderr) { assert.isNull(err) assert.strictEqual(stdout, 'Currency no supported or bad spell\n') done() }) }) it('If conversion is good', function (done) { exec('currencyconv --f=USD --to=EUR --ouput=fulls 1', function (err, stdout, stderr) { assert.isNull(err) var result = stdout.split(' ') assert.isNotNull(result[0]) assert.isNumber(parseInt(result[0])) done() }) }) })
/* global describe global it */ const chai = require('chai') const exec = require('child_process').exec const path = require('path') var assert = chai.assert console.log('Testing the app') var cmd = 'node ' + path.join(__dirname, '../index.js') + ' ' describe('Conversion Params', function () { // Further code for tests goes here it('If no params', function (done) { // Test implementation goes here exec(`${cmd}`, function (err, stdout, stderr) { assert.isNotNull(err) done() }) }) it('If no amount', function (done) { exec(`${cmd} --f=USD --to=EUR --ouput=fulls`, function (err, stdout, stderr) { assert.isNull(err) assert.strictEqual(stdout, 'Amount param should be defined\n') done() }) }) }) describe('Conversion Logic', function () { it('If currency does not exist', function (done) { exec(`${cmd} --f=USDG --to=EURs --ouput=fulls 1`, function (err, stdout, stderr) { assert.isNull(err) assert.strictEqual(stdout, 'Currency no supported or bad spell\n') done() }) }) it('If conversion is good', function (done) { exec(`${cmd} --f=USD --to=EUR --ouput=fulls 1`, function (err, stdout, stderr) { assert.isNull(err) var result = stdout.split(' ') assert.isNotNull(result[0]) assert.isNumber(parseInt(result[0])) done() }) }) })
Change the way the test works with the command
Change the way the test works with the command
JavaScript
mit
duvanmonsa/currency_conversor_cli
f5822d9e9fd386b46194fd719e6b4b6f8dfcec42
test/lib/dashycode.js
test/lib/dashycode.js
'use strict'; const assert = require('assert'); const Dashycode = require('./../../.lib-dist/dashycode'); describe('Dashycode', function () { // Technically we should be testing for values up to 0x10FFFF, but we will // never see any above 0xFFFF because of how SockJS works. const codepoints = Array.from({length: 0x10000}, (v, k) => k); const encoded = new Map(); const encode = (codepoint, allowCaps) => { const character = String.fromCodePoint(codepoint); const dashycode = Dashycode.encode(character); assert.strictEqual(encoded.has(dashycode), false); encoded.set(dashycode, character); }; const decode = (dashycode) => { const character = Dashycode.decode(dashycode); assert.strictEqual(encoded.get(dashycode), character); }; it('should encode all codepoints uniquely', function () { return codepoints.reduce((p, codepoint) => ( p.then(v => encode(codepoint)) ), Promise.resolve()); }); it('should decode all codepoints accurately', function () { return [...encoded.keys()].reduce((p, dashycode) => ( p.then(v => decode(dashycode)) ), Promise.resolve()); }); after(function () { encoded.clear(); }); });
'use strict'; const assert = require('assert'); const Dashycode = require('./../../.lib-dist/dashycode'); describe('Dashycode', function () { // Technically we should be testing for values up to 0x10FFFF, but we will // never see any above 0xFFFF because of how SockJS works. const codepoints = Array.from({length: 0x10000}, (v, k) => k); const encoded = new Map(); const encode = (codepoint) => { const character = String.fromCodePoint(codepoint); const dashycode = Dashycode.encode(character); assert.strictEqual(encoded.has(dashycode), false); encoded.set(dashycode, character); }; const decode = (dashycode) => { const character = Dashycode.decode(dashycode); assert.strictEqual(encoded.get(dashycode), character); }; it('should encode all codepoints uniquely', function () { return codepoints.reduce((p, codepoint) => ( p.then(v => encode(codepoint)) ), Promise.resolve()); }); it('should decode all codepoints accurately', function () { return [...encoded.keys()].reduce((p, dashycode) => ( p.then(v => decode(dashycode)) ), Promise.resolve()); }); after(function () { encoded.clear(); }); });
Remove unused parameter from function in Dashycode's unit tests
Remove unused parameter from function in Dashycode's unit tests
JavaScript
mit
sirDonovan/Pokemon-Showdown,sirDonovan/Pokemon-Showdown,svivian/Pokemon-Showdown,QuiteQuiet/Pokemon-Showdown,xfix/Pokemon-Showdown,urkerab/Pokemon-Showdown,panpawn/Gold-Server,Zarel/Pokemon-Showdown,urkerab/Pokemon-Showdown,jumbowhales/Pokemon-Showdown,Enigami/Pokemon-Showdown,Zarel/Pokemon-Showdown,Zarel/Pokemon-Showdown,xfix/Pokemon-Showdown,panpawn/Gold-Server,xfix/Pokemon-Showdown,urkerab/Pokemon-Showdown,sirDonovan/Pokemon-Showdown,jumbowhales/Pokemon-Showdown,QuiteQuiet/Pokemon-Showdown,svivian/Pokemon-Showdown,panpawn/Gold-Server,svivian/Pokemon-Showdown,xfix/Pokemon-Showdown,svivian/Pokemon-Showdown,AustinXII/Pokemon-Showdown,Enigami/Pokemon-Showdown,AustinXII/Pokemon-Showdown,Enigami/Pokemon-Showdown,Enigami/Pokemon-Showdown,jumbowhales/Pokemon-Showdown,QuiteQuiet/Pokemon-Showdown,svivian/Pokemon-Showdown,xfix/Pokemon-Showdown,AustinXII/Pokemon-Showdown
3223750e3abc0b941331c960b6c3afa027ef31dc
find-core/src/main/public/static/js/find/app/page/search/results/query-strategy.js
find-core/src/main/public/static/js/find/app/page/search/results/query-strategy.js
/* * Copyright 2015 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([], function () { "use strict"; function displayPromotions() { return true; } function requestParams(queryModel, infiniteScroll) { return { text: queryModel.get('queryText'), auto_correct: infiniteScroll ? false : queryModel.get('autoCorrect') }; } function validateQuery(queryModel) { return queryModel.get('queryText'); } function waitForIndexes(queryModel) { return _.isEmpty(queryModel.get('indexes')); } return { colourboxGrouping: 'results', displayPromotions: displayPromotions, requestParams: requestParams, validateQuery: validateQuery, waitForIndexes: waitForIndexes } });
/* * Copyright 2015 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([], function () { "use strict"; function displayPromotions() { return true; } function requestParams(queryModel, infiniteScroll) { return { text: queryModel.get('queryText'), auto_correct: false }; } function validateQuery(queryModel) { return queryModel.get('queryText'); } function waitForIndexes(queryModel) { return _.isEmpty(queryModel.get('indexes')); } return { colourboxGrouping: 'results', displayPromotions: displayPromotions, requestParams: requestParams, validateQuery: validateQuery, waitForIndexes: waitForIndexes } });
Disable spellcheck/auto correct as there are platform issues with it
Disable spellcheck/auto correct as there are platform issues with it
JavaScript
mit
LinkPowerHK/find,hpe-idol/find,LinkPowerHK/find,LinkPowerHK/find,hpe-idol/java-powerpoint-report,hpautonomy/find,hpautonomy/find,LinkPowerHK/find,hpautonomy/find,hpautonomy/find,hpe-idol/java-powerpoint-report,hpe-idol/find,hpe-idol/find,LinkPowerHK/find,hpe-idol/find,hpe-idol/find,hpautonomy/find
bc077131bfdef8a35e54bdb61089914d376fdc59
src/middleware.js
src/middleware.js
class Middleware { constructor() { } before(event) { } after(event) { } } module.exports = Middleware
class Middleware { constructor() { } before(event) { return event } after(event) { return event } } module.exports = Middleware
Make sure stub methods return event.
Make sure stub methods return event.
JavaScript
mit
surebot/Eventline,surebot/Eventline
7050035874fdd5d42d5e74617011201f9595065d
native/components/thread-visibility.react.js
native/components/thread-visibility.react.js
// @flow import * as React from 'react'; import { View, Text, StyleSheet } from 'react-native'; import Icon from 'react-native-vector-icons/MaterialIcons'; import { threadTypes, type ThreadType } from 'lib/types/thread-types'; type Props = {| +threadType: ThreadType, +color: string, |}; function ThreadVisibility(props: Props) { const { threadType, color } = props; const visLabelStyle = [styles.visibilityLabel, { color }]; if (threadType === threadTypes.CHAT_SECRET) { return ( <View style={styles.container}> <Icon name="lock-outline" size={18} color={color} /> <Text style={visLabelStyle}>Secret</Text> </View> ); } else if (threadType === threadTypes.PRIVATE) { return ( <View style={styles.container}> <Icon name="person" size={18} color={color} /> <Text style={visLabelStyle}>Private</Text> </View> ); } else { return ( <View style={styles.container}> <Icon name="public" size={18} color={color} /> <Text style={visLabelStyle}>Open</Text> </View> ); } } const styles = StyleSheet.create({ container: { alignItems: 'center', flexDirection: 'row', }, visibilityLabel: { fontSize: 16, fontWeight: 'bold', paddingLeft: 4, }, }); export default ThreadVisibility;
// @flow import * as React from 'react'; import { View, Text, StyleSheet } from 'react-native'; import { threadTypes, type ThreadType } from 'lib/types/thread-types'; import ThreadIcon from './thread-icon.react'; type Props = {| +threadType: ThreadType, +color: string, |}; function ThreadVisibility(props: Props) { const { threadType, color } = props; const visLabelStyle = [styles.visibilityLabel, { color }]; let label; if (threadType === threadTypes.CHAT_SECRET) { label = 'Secret'; } else if (threadType === threadTypes.PRIVATE) { label = 'Private'; } else { label = 'Open'; } return ( <View style={styles.container}> <ThreadIcon threadType={threadType} color={color} /> <Text style={visLabelStyle}>{label}</Text> </View> ); } const styles = StyleSheet.create({ container: { alignItems: 'center', flexDirection: 'row', }, visibilityLabel: { fontSize: 16, fontWeight: 'bold', paddingLeft: 4, }, }); export default ThreadVisibility;
Make thread-visiblity icon use thread-icon
Make thread-visiblity icon use thread-icon Summary: Made it so thread-visiblity uses thread-icon.react.js instead of its own icon. Test Plan: Checked in thread settings to see if icon still worked. Also checked private threads before and after updates to make sure they still work. And also made sure normal threads still work Reviewers: ashoat, palys-swm Reviewed By: ashoat Subscribers: KatPo, zrebcu411, Adrian, atul Differential Revision: https://phabricator.ashoat.com/D626
JavaScript
bsd-3-clause
Ashoat/squadcal,Ashoat/squadcal,Ashoat/squadcal,Ashoat/squadcal,Ashoat/squadcal,Ashoat/squadcal,Ashoat/squadcal
b4181ef46197cdaf830014e57f42d97efdebec92
src/components/FormViewerContainer.js
src/components/FormViewerContainer.js
import { connect } from "react-redux"; import FormViewer from "./FormViewer"; const mapStateToProps = (state) => { const points = state.waterlines.filter((offset) => { return offset && offset.x != undefined && offset.y != undefined; }); points.push(...state.buttocks.filter((offset) => { return offset && offset.x !== undefined && offset.y != undefined; })); return { points: points }; }, mapDispatchToProps = (dispatch) => { return {}; }; export default connect(mapStateToProps, mapDispatchToProps)(FormViewer);
import { connect } from "react-redux"; import FormViewer from "./FormViewer"; const mapStateToProps = (state) => { const points = state.waterlines.filter((offset) => { return offset && offset.x !== undefined && offset.y !== undefined; }); points.push(...state.buttocks.filter((offset) => { return offset && offset.x !== undefined && offset.y !== undefined; })); points.sort((a, b) => { if (a.order < b.order) { return -1; } if (a.order > b.order) { return 1; } // a must be equal to b return 0; }); return { points: points }; }, mapDispatchToProps = (dispatch) => { return {}; }; export default connect(mapStateToProps, mapDispatchToProps)(FormViewer);
Sort points based on order, waterlines and buttocks fully integrated now
Sort points based on order, waterlines and buttocks fully integrated now
JavaScript
apache-2.0
sel129/lofter,sel129/lofter
dc51280c20545b07c9dc7bb0cd11dd60384e9b79
test/exceptions/minified_code.spec.js
test/exceptions/minified_code.spec.js
var context = require('../../src/exceptions/context') describe("Minified code detection", function() { it("Empty source returns false", function() { expect(context.isSourceMinified('')).toBe(false) }) it("Minified JS Bundle returns true", function() { var source = require('./data/bundle.js') expect(context.isSourceMinified(source)).toBe(true) }) })
var context = require('../../src/exceptions/context') describe("isSourceMinified", function() { it("Empty source returns false", function() { expect(context.isSourceMinified('')).toBe(false) }) it("Minified JS Bundle returns true", function() { var source = require('./data/bundle.js') expect(context.isSourceMinified(source)).toBe(true) }) })
Add tests of minified code detection logic
Add tests of minified code detection logic
JavaScript
mit
opbeat/opbeat-angular,opbeat/opbeat-react,opbeat/opbeat-angular,jahtalab/opbeat-js,opbeat/opbeat-angular,opbeat/opbeat-react,opbeat/opbeat-react,opbeat/opbeat-js-core,opbeat/opbeat-js-core,jahtalab/opbeat-js,jahtalab/opbeat-js
ee7042ed28b7e15087543b59609e74276bf5befa
nodejs_projects/basic_nodejs_samples/read.js
nodejs_projects/basic_nodejs_samples/read.js
logMessage("Script Begins!"); var Galileo = require("galileo-io"); var board = new Galileo(); var previousData = 0; logMessage("Setting Ready event for the Galileo Board"); board.on("ready", galileoReadyHandler); logMessage("Root Execution Complete!"); /* * Contains the logic for when the Galileo Board is Ready * @returns {undefined} */ function galileoReadyHandler() { /*** * This line sets a Digital Read event handler. Every time the Galileo Board completes a read operation * it will call the readHandler function to process it. **/ logMessage("Galileo Ready Handler Begins! - Setting a Digital Read Handler..."); board.digitalRead(10, readHandler); logMessage("Galileo Ready Handler Complete!"); } /*** * Receives DATA from a read event and uses it. * @param data * @returns {undefined} */ function readHandler(data) { logMessage("Read Handler Begins!"); if (previousData !== data) { logMessage("Data Changed!"); previousData = data; logMessage("New Data: " + data); } } /*** * Logs messages into the console including a milliseconds timestamp * @param {type} message * @returns {undefined} */ function logMessage(message) { var d = new Date().getTime(); console.log(d + " - " + message); }
logMessage("Script Begins!"); var Galileo = require("galileo-io"); var board = new Galileo(); var previousData = 0; logMessage("Setting Ready event for the Galileo Board"); board.on("ready", galileoReadyHandler); logMessage("Root Execution Complete!"); /* * Contains the logic for when the Galileo Board is Ready * @returns {undefined} */ function galileoReadyHandler() { /*** * This line sets a Digital Read event handler. Every time the Galileo Board completes a read operation * it will call the readHandler function to process it. **/ logMessage("Galileo Ready Handler Begins! - Setting a Digital Read Handler..."); board.digitalRead(10, readHandler); logMessage("Galileo Ready Handler Complete!"); } /*** * Receives DATA from a read event and uses it. * @param data * @returns {undefined} */ var readtimes = 0; function readHandler(data) { if (readtimes<5) { readtimes++; logMessage("Read Handler Begins!"); } if (previousData !== data) { logMessage("Data Changed!"); previousData = data; logMessage("New Data: " + data); } if (readtimes<5) { logMessage("Read Handler END!"); } } /*** * Logs messages into the console including a milliseconds timestamp * @param {type} message * @returns {undefined} */ function logMessage(message) { var d = new Date().getTime(); console.log(d + " - " + message); }
Tidy code for basic examples on NodeJS
Tidy code for basic examples on NodeJS
JavaScript
mit
janunezc/GALILEO,janunezc/GALILEO,janunezc/GALILEO
5897c870fa46c8844c3f0bc92d8888377eb0f2ce
ui/src/registrator/PrihlaskyDohlasky/Input/InputActions.js
ui/src/registrator/PrihlaskyDohlasky/Input/InputActions.js
// eslint-disable-next-line import/prefer-default-export export const createInputChanged = actionPrefix => (name, event) => ({ type: `${actionPrefix}_INPUT_CHANGED`, name, id: event.target.id, startovne: event.target.nonce, value: event.target.type === 'checkbox' ? event.target.checked : event.target.value });
// eslint-disable-next-line import/prefer-default-export export const createInputChanged = actionPrefix => (name, event) => { const action = { type: `${actionPrefix}_INPUT_CHANGED`, name, id: event.target.id, value: event.target.type === 'checkbox' ? event.target.checked : event.target.value }; if (event.target.nonce) { const startovne = parseInt(event.target.nonce, 10); if (!Number.isNaN(startovne)) { action.startovne = startovne; } } return action; };
Convert startovne to a number.
Convert startovne to a number.
JavaScript
mit
ivosh/jcm2018,ivosh/jcm2018,ivosh/jcm2018